From 68272cd77d76a58b5de1ae89c274e5cb6f7b2eb9 Mon Sep 17 00:00:00 2001 From: "Christopher S. Aondona" Date: Sun, 29 Nov 2026 17:09:46 +0100 Subject: [PATCH 1/5] feat: implement RV-I03 review scheduling and advisory readiness --- CHANGELOG.md | 1 + README.md | 8 +- docs/architecture.md | 16 +- docs/events.md | 2 +- docs/policies.md | 8 +- docs/replay.md | 23 ++- scripts/verify-dist.mjs | 22 +- src/contracts/projections.ts | 86 ++++++++ src/contracts/results.ts | 1 + src/contracts/time.ts | 2 + src/explanation/reasons.ts | 51 +++++ src/index.ts | 18 ++ src/readiness/candidate.ts | 58 ++++++ src/replay/advance.ts | 75 +++++++ src/replay/explain.ts | 125 ++++++++++++ src/replay/rebuild.ts | 103 ++++++++++ src/replay/reconcile.ts | 6 + src/scheduling/intervals.ts | 10 + src/scheduling/transitions.ts | 117 +++++++++++ src/time/elapsed.ts | 3 +- tests/unit/foundation.test.ts | 9 +- tests/unit/reconcile.test.ts | 1 + tests/unit/review.test.ts | 366 ++++++++++++++++++++++++++++++++++ 23 files changed, 1091 insertions(+), 20 deletions(-) create mode 100644 src/contracts/projections.ts create mode 100644 src/contracts/time.ts create mode 100644 src/explanation/reasons.ts create mode 100644 src/readiness/candidate.ts create mode 100644 src/replay/advance.ts create mode 100644 src/replay/explain.ts create mode 100644 src/replay/rebuild.ts create mode 100644 src/scheduling/intervals.ts create mode 100644 src/scheduling/transitions.ts create mode 100644 tests/unit/review.test.ts diff --git a/CHANGELOG.md b/CHANGELOG.md index d5eef7c..fcd1e64 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -13,3 +13,4 @@ Notable changes to Retention are recorded here. The format follows [Keep a Chang - Current-version scoped event contracts, bounded validation and canonical duplicate/conflict detection. - Internal full-history reconciliation, including credited decision replacement and revocation, deletion controls, deterministic replay ordering and canonical history watermarks. - Optional versioned eligibility-policy validation and internal eligible-only qualification with reset or ignore classification. +- Public full-history review rebuild and complete-prefix advance, practice scheduling, eligible-only candidate readiness and structured explanations. diff --git a/README.md b/README.md index de6fbf4..be8b183 100644 --- a/README.md +++ b/README.md @@ -60,7 +60,7 @@ flowchart LR Identical duplicate events have no effect. Conflicting identities and invalid correction chains produce typed failures. A correction replaces the original observation and contributes no extra success. Deletion controls suppress affected history during replay; the application remains responsible for physical erasure and preventing obsolete histories from returning. -Full replay is the reference calculation. The planned advance operation verifies the previous projection identity and complete event prefix before rebuilding. Policy changes require explicit replay. +Full replay is the reference calculation. The advance operation verifies the previous projection identity and complete event prefix before rebuilding. Policy changes require explicit replay. ### Readiness and evidence @@ -87,16 +87,16 @@ Retention cannot establish whether evidence is authentic. The application admits | `rebuildReview` | Reconstruct review projections from complete history. | | `advanceReview` | Verify the prior identity and event prefix, then rebuild with new events. | | `evaluateReadiness` | Calculate advisory readiness from reconciled eligible evidence. | -| `scheduleDue` | Select and rank due concepts. | +| `scheduleDue` | Planned: select and rank due concepts. | | `explainReview` | Return structured reasons for a recommendation. | -The remaining public operations are planned. See [policy validation](docs/policies.md), [event validation](docs/events.md) and [internal reconciliation](docs/replay.md) for implemented behavior and limitations. +Due ranking is the remaining planned public operation. See [policy validation](docs/policies.md), [event validation](docs/events.md) and [replay and readiness](docs/replay.md) for implemented behavior and limitations. The [review scheduling specification](https://github.com/0xbuffdev/context/blob/main/repos/retention/specs/0001-review-scheduling.md) defines the event schemas, policy fields, transition rules, resource limits and error behavior. ## Development -The repository has an ESM package foundation with policy and event validation, internal time arithmetic, canonical history reconciliation and eligible-only qualification; scheduler and candidate aggregation are pending. Install Node.js 24+ and pnpm 11.2.2, then run: +The repository has an ESM package foundation with policy and event validation, checked time arithmetic, canonical history reconciliation, practice scheduling and eligible-only readiness; due ranking is pending. Install Node.js 24+ and pnpm 11.2.2, then run: ```sh corepack enable diff --git a/docs/architecture.md b/docs/architecture.md index 4401bcf..bbb23a0 100644 --- a/docs/architecture.md +++ b/docs/architecture.md @@ -1,24 +1,26 @@ # Architecture -Retention is a standalone review-scheduling engine. The planned engine takes an explicit policy, clock and bounded history for one scope and returns advisory projections without side effects. Consumers own admission, persistence, authorization and official decisions. +Retention is a standalone review-scheduling engine. The engine takes an explicit policy, clock and bounded history for one scope and returns advisory projections without side effects. Consumers own admission, persistence, authorization and official decisions. ## Current layout -- `src/index.ts`: explicit policy and event validation and contract types. +- `src/index.ts`: explicit validation, replay, readiness and explanation operations and contract types. - `src/contracts/` and `src/errors.ts`: versioned policy and event shapes and result envelopes. - `src/validation/`: bounded own-data shape checks, scheduling and eligibility policy validation, and scoped event validation. - `src/time/`: checked elapsed days and explicit calendar segments, without runtime timezone data. - `src/events/`: canonical identity, ordering, indexed correction chains and deletion resolution. -- `src/replay/`: internal full-history reconciliation and canonical watermark. -- `src/readiness/`: internal eligible-only qualification and reset/ignore classification. +- `src/replay/`: full-history reconciliation, canonical watermark, public rebuild, advance and readiness orchestration. +- `src/scheduling/`: practice transitions and interval arithmetic. +- `src/explanation/`: fixed reason codes and lifecycle explanations. +- `src/readiness/`: internal eligible-only qualification and candidate streak aggregation. - `tests/unit/` and `tests/fixtures/`: policy, time, event, lifecycle, qualification, identity and export-boundary tests. - `scripts/`: architecture and distribution checks. - Root configuration and CI: strict TypeScript, Vitest, tsdown, Biome and frozen pnpm dependencies. -## Planned layers +## Replay and projection layers -The internal replay layer validates and reconciles events. Future orchestration will calculate practice schedules and eligible-only readiness separately from that result. Due ranking consumes compatible projections. Time arithmetic consumes explicit calendar rules or elapsed milliseconds. Explanations are structured and do not run the scheduler. +The internal replay layer validates and reconciles events. Public orchestration calculates practice schedules and eligible-only readiness separately from that result. Planned due ranking will consume compatible projections. Time arithmetic consumes explicit calendar rules or elapsed milliseconds. Explanations are structured and do not run the scheduler. Keep lower layers independent of public orchestration and the root entry. No runtime dependencies, hidden clocks, randomness, locale services, network or filesystem. Do not add empty directories or speculative exports. -The [canonical architecture](https://github.com/0xbuffdev/context/blob/main/repos/retention/architecture.md), [specification](https://github.com/0xbuffdev/context/blob/main/repos/retention/specs/0001-review-scheduling.md) and [tickets](https://github.com/0xbuffdev/context/blob/main/repos/retention/tickets.md) contain the target layout and contract; these planning documents may require organization access. Policy, time, event validation, internal reconciliation and eligible-only qualification are implemented; public replay, scheduling, candidate aggregation and ranking are not implemented. +The [canonical architecture](https://github.com/0xbuffdev/context/blob/main/repos/retention/architecture.md), [specification](https://github.com/0xbuffdev/context/blob/main/repos/retention/specs/0001-review-scheduling.md) and [tickets](https://github.com/0xbuffdev/context/blob/main/repos/retention/tickets.md) contain the target layout and contract; these planning documents may require organization access. Policy, time, event validation, reconciliation, scheduling, candidate aggregation, public replay and explanations are implemented; due ranking is not implemented. diff --git a/docs/events.md b/docs/events.md index e995de4..2fb085b 100644 --- a/docs/events.md +++ b/docs/events.md @@ -1,6 +1,6 @@ # Event validation -Use `validateEvents(scopeId, events)` to check a history before passing it to the scheduler once the public replay API is available. The scope is an opaque identifier supplied by the caller; it does not establish authorization. +Use `validateEvents(scopeId, events)` to check a history before passing it to the scheduler. The scope is an opaque identifier supplied by the caller; it does not establish authorization. ```ts import { validateEvents } from "@0xbuff/retention"; diff --git a/docs/policies.md b/docs/policies.md index 759cc3f..1920771 100644 --- a/docs/policies.md +++ b/docs/policies.md @@ -1,6 +1,6 @@ # Policy validation -`validatePolicy(input)` returns a discriminated result with a detached, immutable normalized policy or safe structured diagnostics. It does not schedule a review yet. +`validatePolicy(input)` returns a discriminated result with a detached, immutable normalized policy or safe structured diagnostics. Use the normalized policy with the public replay operations. ```ts import { validatePolicy } from "@0xbuff/retention"; @@ -25,11 +25,11 @@ All scheduling fields are required. Interval order is preserved. Intervals, retr For `local_calendar_days`, include `scheduling.calendarProfile` with `zoneId`, `rulesVersion`, `coverageStartMs`, `coverageEndMs`, `initialOffsetMinutes` and `transitions`. Each transition has `atMs` and `offsetMinutes`. Coverage ends exclusively. Offsets are integer minutes in ±1440; transitions are strictly ordered and inside coverage. The caller supplies the rules; no system timezone data is consulted. The entire possible target window must be covered, including the shifted target when resolving a gap. Folds choose the earliest valid instant. -Elapsed arithmetic uses exactly 86,400,000 milliseconds per day. Local arithmetic adds civil days to a local wall-time scalar before resolving the offset. Internal time helpers are not public APIs. Public replay, policy-change rebuild enforcement and ranking remain planned. +Elapsed arithmetic uses exactly 86,400,000 milliseconds per day. Local arithmetic adds civil days to a local wall-time scalar before resolving the offset. Internal time helpers are not public APIs. Public replay enforces policy identity when advancing. Ranking remains planned. ## Optional eligibility -Omit `eligibility` for practice-only use. To configure the planned separate advisory candidate projection, supply all of these fields alongside `scheduling`: +Omit `eligibility` for practice-only use. To configure the separate advisory candidate projection, supply all of these fields alongside `scheduling`: ```ts const eligibility = { @@ -47,7 +47,7 @@ const eligibility = { These values are illustrative, not defaults. Successes range from 1 to 1000, sessions from 1 to `minSuccesses`, span from zero to the largest safe integer in milliseconds, and hint and ladder thresholds from zero to 1000. The version is a bounded ASCII identifier. Freshness must be a boolean; both actions must be `reset` or `ignore`. -The internal qualification step considers only surviving credited observations from reconciliation. A matching-version pass qualifies when freshness (if required), maximum hints and minimum ladder are satisfied. A matching-version failure uses `onFailure`; a version mismatch or nonqualifying pass uses `onNonqualifying`. Practice observations never enter this classification, even with equivalent metadata. Validation and qualification cannot authenticate a credited tag or model claim. The host must independently admit evidence before supplying a history. Streak, session and span aggregation and the public readiness operation are not implemented yet. +The internal qualification step considers only surviving credited observations from reconciliation. A matching-version pass qualifies when freshness (if required), maximum hints and minimum ladder are satisfied. A matching-version failure uses `onFailure`; a version mismatch or nonqualifying pass uses `onNonqualifying`. Practice observations never enter this classification, even with equivalent metadata. Validation and qualification cannot authenticate a credited tag or model claim. The host must independently admit evidence before supplying a history. Streaks count qualifying successes and distinct sessions from the first qualifying instant; reset clears the entire streak. See [replay and readiness](replay.md). The validator accepts only the closed current schema, including dense ordinary arrays and own enumerable data properties. It does not invoke getters or support arbitrary executable objects and proxies. diff --git a/docs/replay.md b/docs/replay.md index f39ef9c..cc1feee 100644 --- a/docs/replay.md +++ b/docs/replay.md @@ -1,6 +1,6 @@ # History reconciliation -The internal reconciliation layer prepares a complete scoped history for the scheduler. The public replay operations are not available yet; `validateEvents` remains the public event-validation entry point. +The internal reconciliation layer prepares a complete scoped history for the scheduler. Public replay validates the policy and reconciles the complete scope before computing schedules and advisory readiness. Reconciliation validates and deduplicates every input event, validates the explicit clock and sorts the distinct records by durable sequence. It then indexes each credited decision, resolves its replacements and revocations, and applies event and scope deletion controls. Surviving observations are sorted by effective time, root sequence and ASCII event ID. @@ -13,3 +13,24 @@ Future observations are validated but excluded until their effective time. Futur The internal result contains immutable active observations, their applied event IDs in replay order, the controls and their IDs in sequence order, scope, evaluation clock and watermark. The version-one watermark is the canonical JSON array of **all distinct validated events in ascending sequence**, including inactive, future and suppressed events and unresolved tombstones. It is independent of input order, duplicate entries and evaluation time. It is content identity, not evidence of authenticity or completeness; it contains event data and must be handled as such. The host supplies complete relevant history and owns authorization, durable sequence, physical erasure and stale-generation protection. The library neither persists data nor grants credit. See [event validation](events.md) for shape and input limits. + +## Public review operations + +```ts +import { advanceReview, evaluateReadiness, explainReview, rebuildReview } from "@0xbuff/retention"; + +const first = rebuildReview(policy, scopeId, events, nowMs); +if (first.ok) { + const explanation = explainReview(first.value); + const next = advanceReview(policy, scopeId, first.value.identity, events, appendedEvents, nextMs); +} +const candidate = evaluateReadiness(policy, scopeId, conceptId, events, nowMs); +``` + +The example assumes the application supplies a policy, complete scoped events and explicit clocks. All operations return discriminated results. Rebuild returns an identity, ordered applied/control event IDs, lifecycle reasons, and concept projections in ASCII concept-ID order. Concepts named in the history but with no surviving observation have an unobserved practice projection; an empty history names no concepts. No eligibility policy means no candidate field, and the single-concept readiness query returns null. With eligibility configured, querying a concept without active credited observations returns unknown. + +Practice scheduling uses all active observations. Candidate aggregation uses only reconciled credited evidence, independent of practice. The qualifying span runs from the first to last qualifying success, never the evaluation clock. A reset clears all streak counters and timestamps. A candidate is advisory, not mastery or an official decision. + +Advance requires the exact prior identity and complete prior history, including suppressed and future events. A changed policy, incompatible identity, missing history or backward clock requires explicit rebuild. The appended records may include late effective observations or identical duplicates; the combined history is validated and replayed from scratch. A supplied identity is not authenticated evidence. Both input arrays count toward the raw-entry limit, including duplicates. + +Explain accepts a successful rebuild or advance value and returns only fixed reason codes, bounded numeric arguments and concept identifiers. It does not interpret raw correction reason strings, revalidate evidence or rerun scheduling. It checks the reason-bearing shape and bounds; it is not a projection authenticity check. diff --git a/scripts/verify-dist.mjs b/scripts/verify-dist.mjs index 13ab8e8..4445efe 100644 --- a/scripts/verify-dist.mjs +++ b/scripts/verify-dist.mjs @@ -19,7 +19,12 @@ for (const name of expected) { } const runtime = await import(pathToFileURL(resolve(entry.import)).href); if ( - Object.keys(runtime).sort().join() !== "validateEvents,validatePolicy" || + Object.keys(runtime).sort().join() !== + "advanceReview,evaluateReadiness,explainReview,rebuildReview,validateEvents,validatePolicy" || + typeof runtime.advanceReview !== "function" || + typeof runtime.evaluateReadiness !== "function" || + typeof runtime.explainReview !== "function" || + typeof runtime.rebuildReview !== "function" || typeof runtime.validateEvents !== "function" || typeof runtime.validatePolicy !== "function" ) { @@ -75,4 +80,19 @@ const events = runtime.validateEvents("smoke", [ if (!events.ok || events.value.length !== 1 || events.value[0].kind !== "practice_observation") { throw new Error("Built event validation failed."); } +const replay = runtime.rebuildReview(result.value, "smoke", events.value, 0); +if (!replay.ok || replay.value.concepts[0]?.dueAtMs !== 259_200_000) { + throw new Error("Built replay failed."); +} +const advanced = runtime.advanceReview(result.value, "smoke", replay.value.identity, events.value, [], 0); +if (!advanced.ok || JSON.stringify(advanced.value) !== JSON.stringify(replay.value)) { + throw new Error("Built advance failed."); +} +const candidate = runtime.evaluateReadiness(candidatePolicy.value, "smoke", "concept-1", events.value, 0); +if (!candidate.ok || candidate.value?.readiness !== "unknown") { + throw new Error("Built readiness failed."); +} +if (!runtime.explainReview(replay.value).ok) { + throw new Error("Built explanation failed."); +} console.log("Distribution exports and ESM import verified."); diff --git a/src/contracts/projections.ts b/src/contracts/projections.ts new file mode 100644 index 0000000..d25e5ed --- /dev/null +++ b/src/contracts/projections.ts @@ -0,0 +1,86 @@ +import type { AlgorithmVersion, SchemaVersion } from "./versions"; + +export type ScheduleState = "unobserved" | "learning" | "reviewing" | "review_ready"; +export type PracticeReadiness = "unknown" | "developing" | "review_ready"; +export type CandidateReadiness = "unknown" | "developing" | "candidate_ready"; +export type RecommendationKind = "ordinary" | "delayed_retrieval" | "transfer" | "support"; + +export type ReasonCode = + | "FIRST_PASS" + | "EARLY_PASS" + | "DUE_PASS" + | "MISS" + | "RESTART" + | "SUPPORT_THRESHOLD" + | "FORCED_SUPPORT" + | "DELAYED_PROBE" + | "MAINTENANCE" + | "NO_OBSERVATION" + | "CREDIT_CORRECTION" + | "CREDIT_REVOCATION" + | "EVENT_DELETION" + | "SCOPE_DELETION" + | "QUALIFYING_SUCCESS" + | "CANDIDATE_RESET" + | "CANDIDATE_IGNORE"; + +export type ReviewReason = { + readonly code: ReasonCode; + readonly value?: number; +}; + +export type ProjectionIdentity = { + readonly schemaVersion: SchemaVersion; + readonly algorithmVersion: AlgorithmVersion; + readonly scopeId: string; + readonly policyIdentity: string; + readonly evaluatedAtMs: number; + readonly watermark: string; +}; + +export type PracticeProjection = { + readonly scheduleState: ScheduleState; + readonly stageIndex: number | null; + readonly dueAtMs: number | null; + readonly lastSeenAtMs: number | null; + readonly consecutiveMisses: number; + readonly advisorySuccesses: number; + readonly needsSupport: boolean; + readonly recommendationKind: RecommendationKind; + readonly readiness: PracticeReadiness; + readonly reasons: readonly ReviewReason[]; +}; + +export type CandidateProjection = { + readonly readiness: CandidateReadiness; + readonly qualifyingSuccesses: number; + readonly distinctSessions: number; + readonly firstQualifyingAtMs: number | null; + readonly lastQualifyingAtMs: number | null; + readonly qualifyingSpanMs: number; + readonly reasons: readonly ReviewReason[]; +}; + +export type ConceptProjection = PracticeProjection & { + readonly conceptId: string; + readonly candidate?: CandidateProjection; +}; + +export type ReviewResult = { + readonly identity: ProjectionIdentity; + readonly concepts: readonly ConceptProjection[]; + readonly appliedEventIds: readonly string[]; + readonly controlEventIds: readonly string[]; + readonly lifecycleReasons: readonly ReviewReason[]; +}; + +export type ConceptExplanation = { + readonly conceptId: string; + readonly practiceReasons: readonly ReviewReason[]; + readonly candidateReasons?: readonly ReviewReason[]; +}; + +export type ReviewExplanation = { + readonly lifecycleReasons: readonly ReviewReason[]; + readonly concepts: readonly ConceptExplanation[]; +}; diff --git a/src/contracts/results.ts b/src/contracts/results.ts index 79b3186..e022b26 100644 --- a/src/contracts/results.ts +++ b/src/contracts/results.ts @@ -8,6 +8,7 @@ export type ErrorCode = | "INVALID_POLICY" | "INVALID_TIMESTAMP" | "UNSUPPORTED_VERSION" + | "REBUILD_REQUIRED" | "CALENDAR_PROFILE_MISMATCH" | "RESOURCE_LIMIT_EXCEEDED"; diff --git a/src/contracts/time.ts b/src/contracts/time.ts new file mode 100644 index 0000000..2f67d23 --- /dev/null +++ b/src/contracts/time.ts @@ -0,0 +1,2 @@ +// Shared numeric boundary for instants and checked millisecond arithmetic. +export const MAX_INSTANT_MS = 8_640_000_000_000_000; diff --git a/src/explanation/reasons.ts b/src/explanation/reasons.ts new file mode 100644 index 0000000..0bb3f17 --- /dev/null +++ b/src/explanation/reasons.ts @@ -0,0 +1,51 @@ +import type { ReviewControl } from "../contracts/events"; +import type { ReasonCode, ReviewReason } from "../contracts/projections"; + +export function lifecycleReasons(controls: readonly ReviewControl[]): readonly ReviewReason[] { + return Object.freeze( + controls.map((control): ReviewReason => { + switch (control.kind) { + case "credited_decision_correction": + return Object.freeze({ code: "CREDIT_CORRECTION" }); + case "credited_decision_revocation": + return Object.freeze({ code: "CREDIT_REVOCATION" }); + case "review_event_deletion": + return Object.freeze({ code: "EVENT_DELETION" }); + case "review_scope_deletion": + return Object.freeze({ code: "SCOPE_DELETION" }); + } + }), + ); +} + +// Only fixed codes and their documented numeric arguments can leave the explanation boundary. +export function reasonBound(code: unknown): number | null | undefined { + switch (code) { + case "FIRST_PASS": + case "EARLY_PASS": + case "DUE_PASS": + return 63; + case "MISS": + case "SUPPORT_THRESHOLD": + case "QUALIFYING_SUCCESS": + return 10_000; + case "RESTART": + case "FORCED_SUPPORT": + case "DELAYED_PROBE": + case "MAINTENANCE": + case "NO_OBSERVATION": + case "CREDIT_CORRECTION": + case "CREDIT_REVOCATION": + case "EVENT_DELETION": + case "SCOPE_DELETION": + case "CANDIDATE_RESET": + case "CANDIDATE_IGNORE": + return null; + default: + return undefined; + } +} + +export function normalizedReason(code: ReasonCode, value?: number): ReviewReason { + return Object.freeze({ code, ...(value === undefined ? {} : { value: value + 0 }) }); +} diff --git a/src/index.ts b/src/index.ts index b275a41..4b81622 100644 --- a/src/index.ts +++ b/src/index.ts @@ -22,7 +22,25 @@ export type { PriorityWeights, SchedulingPolicy, } from "./contracts/policies"; +export type { + CandidateProjection, + CandidateReadiness, + ConceptExplanation, + ConceptProjection, + PracticeProjection, + PracticeReadiness, + ProjectionIdentity, + ReasonCode, + RecommendationKind, + ReviewExplanation, + ReviewReason, + ReviewResult, + ScheduleState, +} from "./contracts/projections"; export type { Diagnostic, ErrorCode, Result } from "./contracts/results"; export type { AlgorithmVersion, SchemaVersion } from "./contracts/versions"; +export { advanceReview } from "./replay/advance"; +export { explainReview } from "./replay/explain"; +export { evaluateReadiness, rebuildReview } from "./replay/rebuild"; export { validateEvents } from "./validation/events"; export { validatePolicy } from "./validation/policies"; diff --git a/src/readiness/candidate.ts b/src/readiness/candidate.ts new file mode 100644 index 0000000..327528e --- /dev/null +++ b/src/readiness/candidate.ts @@ -0,0 +1,58 @@ +import type { ReconciledCreditedObservation } from "../contracts/events"; +import type { EligibilityPolicy } from "../contracts/policies"; +import type { CandidateProjection, ReviewReason } from "../contracts/projections"; +import type { Result } from "../contracts/results"; +import { MAX_INSTANT_MS } from "../contracts/time"; +import { failure, success } from "../errors"; +import { classifyQualification } from "./qualification"; + +export function projectCandidate( + policy: EligibilityPolicy, + observations: readonly ReconciledCreditedObservation[], +): Result { + let qualifyingSuccesses = 0; + const sessions = new Set(); + let firstQualifyingAtMs: number | null = null; + let lastQualifyingAtMs: number | null = null; + let qualifyingSpanMs = 0; + const reasons: ReviewReason[] = []; + for (const observation of observations) { + const classification = classifyQualification(policy, observation); + if (classification === "reset") { + qualifyingSuccesses = 0; + sessions.clear(); + firstQualifyingAtMs = null; + lastQualifyingAtMs = null; + qualifyingSpanMs = 0; + reasons.push({ code: "CANDIDATE_RESET" }); + } else if (classification === "ignore") { + reasons.push({ code: "CANDIDATE_IGNORE" }); + } else { + qualifyingSuccesses += 1; + sessions.add(observation.sessionId); + firstQualifyingAtMs ??= observation.atMs; + lastQualifyingAtMs = observation.atMs; + qualifyingSpanMs = lastQualifyingAtMs - firstQualifyingAtMs; + if (!Number.isSafeInteger(qualifyingSpanMs) || qualifyingSpanMs > MAX_INSTANT_MS) { + return failure("INVALID_TIMESTAMP", "qualifyingSpanMs"); + } + reasons.push({ code: "QUALIFYING_SUCCESS", value: qualifyingSuccesses }); + } + } + + const ready = + qualifyingSuccesses >= policy.minSuccesses && + sessions.size >= policy.minSessions && + qualifyingSpanMs >= policy.minSpanMs; + return success( + Object.freeze({ + readiness: observations.length === 0 ? "unknown" : ready ? "candidate_ready" : "developing", + qualifyingSuccesses, + distinctSessions: sessions.size, + firstQualifyingAtMs, + lastQualifyingAtMs, + qualifyingSpanMs, + reasons: Object.freeze(reasons.map((reason) => Object.freeze(reason))), + }), + ); +} diff --git a/src/replay/advance.ts b/src/replay/advance.ts new file mode 100644 index 0000000..79c1900 --- /dev/null +++ b/src/replay/advance.ts @@ -0,0 +1,75 @@ +import type { ReviewResult } from "../contracts/projections"; +import type { Result } from "../contracts/results"; +import { failure } from "../errors"; +import { policyIdentity } from "../events/identity"; +import { validateClock } from "../validation/clock"; +import { array, arrayLength, LIMITS, record } from "../validation/limits"; +import { validatePolicy } from "../validation/policies"; +import { rebuildReview } from "./rebuild"; + +export function advanceReview( + inputPolicy: unknown, + scopeId: unknown, + previousIdentity: unknown, + previousEvents: unknown, + appendedEvents: unknown, + nowMs: unknown, +): Result { + const policy = validatePolicy(inputPolicy); + if (!policy.ok) { + return policy; + } + const clock = validateClock(nowMs); + if (!clock.ok) { + return clock; + } + const previous = record(previousIdentity, [ + "schemaVersion", + "algorithmVersion", + "scopeId", + "policyIdentity", + "evaluatedAtMs", + "watermark", + ]); + if ( + !previous || + previous.schemaVersion !== policy.value.schemaVersion || + previous.algorithmVersion !== policy.value.algorithmVersion || + previous.scopeId !== scopeId || + previous.policyIdentity !== policyIdentity(policy.value) || + typeof previous.watermark !== "string" + ) { + return failure("REBUILD_REQUIRED", "previousIdentity"); + } + const previousClock = validateClock(previous.evaluatedAtMs); + if (!previousClock.ok || previousClock.value > clock.value) { + return failure("REBUILD_REQUIRED", "evaluatedAtMs"); + } + const priorLength = arrayLength(previousEvents); + const addedLength = arrayLength(appendedEvents); + if (priorLength === null) { + return failure("REBUILD_REQUIRED", "previousEvents"); + } + if (addedLength === null) { + return failure("INVALID_EVENT", "appendedEvents"); + } + if (priorLength + addedLength > LIMITS.rawEvents) { + return failure("RESOURCE_LIMIT_EXCEEDED", "events", LIMITS.rawEvents); + } + const prior = array(previousEvents, LIMITS.rawEvents); + const added = array(appendedEvents, LIMITS.rawEvents); + if (!prior) { + return failure("REBUILD_REQUIRED", "previousEvents"); + } + if (!added) { + return failure("INVALID_EVENT", "appendedEvents"); + } + + // Reconstruct the prior result rather than trusting its projection or an opaque snapshot. + const reconstructed = rebuildReview(policy.value, scopeId, prior, previousClock.value); + if (!reconstructed.ok || reconstructed.value.identity.watermark !== previous.watermark) { + return failure("REBUILD_REQUIRED", "previousEvents"); + } + // Validate raw combined bounds, identities and lifecycle again using the reference operation. + return rebuildReview(policy.value, scopeId, [...prior, ...added], clock.value); +} diff --git a/src/replay/explain.ts b/src/replay/explain.ts new file mode 100644 index 0000000..1a91ff6 --- /dev/null +++ b/src/replay/explain.ts @@ -0,0 +1,125 @@ +import type { + ConceptExplanation, + ReasonCode, + ReviewExplanation, + ReviewReason, +} from "../contracts/projections"; +import type { Result } from "../contracts/results"; +import { failure, success } from "../errors"; +import { normalizedReason, reasonBound } from "../explanation/reasons"; +import { array, arrayLength, identifier, integer, LIMITS, record } from "../validation/limits"; + +const maxReasons = LIMITS.distinctEvents * 5; + +function readReasons(input: unknown, remaining: number): Result { + const length = arrayLength(input); + if (length !== null && length > remaining) { + return failure("RESOURCE_LIMIT_EXCEEDED", "reasons", maxReasons); + } + const entries = array(input, remaining); + if (!entries) { + return failure("INVALID_EVENT", "reasons"); + } + const reasons: ReviewReason[] = []; + for (const entry of entries) { + const fields = record(entry, ["code"], ["value"]); + if (!fields) { + return failure("INVALID_EVENT", "reasons"); + } + const bound = reasonBound(fields.code); + if (bound === undefined) { + return failure("INVALID_EVENT", "code"); + } + if (bound === null) { + if (Object.hasOwn(fields, "value")) { + return failure("INVALID_EVENT", "value"); + } + reasons.push(normalizedReason(fields.code as ReasonCode)); + } else { + if (!integer(fields.value, 0, bound)) { + return failure("INVALID_EVENT", "value"); + } + reasons.push(normalizedReason(fields.code as ReasonCode, fields.value)); + } + } + return success(Object.freeze(reasons)); +} + +/** Explain a successful replay value; this does not revalidate evidence or run scheduling. */ +export function explainReview(input: unknown): Result { + const fields = record(input, [ + "identity", + "concepts", + "appliedEventIds", + "controlEventIds", + "lifecycleReasons", + ]); + if (!fields) { + return failure("INVALID_EVENT", "review"); + } + const concepts = array(fields.concepts, LIMITS.concepts); + if (!concepts) { + return failure("INVALID_EVENT", "concepts"); + } + const lifecycle = readReasons(fields.lifecycleReasons, maxReasons); + if (!lifecycle.ok) { + return lifecycle; + } + let remaining = maxReasons - lifecycle.value.length; + const explanations: ConceptExplanation[] = []; + const seen = new Set(); + for (const concept of concepts) { + const projection = record( + concept, + [ + "conceptId", + "scheduleState", + "stageIndex", + "dueAtMs", + "lastSeenAtMs", + "consecutiveMisses", + "advisorySuccesses", + "needsSupport", + "recommendationKind", + "readiness", + "reasons", + ], + ["candidate"], + ); + if (!projection || !identifier(projection.conceptId) || seen.has(projection.conceptId)) { + return failure("INVALID_EVENT", "conceptId"); + } + seen.add(projection.conceptId); + const practice = readReasons(projection.reasons, remaining); + if (!practice.ok) { + return practice; + } + remaining -= practice.value.length; + const base = { conceptId: projection.conceptId, practiceReasons: practice.value }; + if (Object.hasOwn(projection, "candidate")) { + const candidate = record(projection.candidate, [ + "readiness", + "qualifyingSuccesses", + "distinctSessions", + "firstQualifyingAtMs", + "lastQualifyingAtMs", + "qualifyingSpanMs", + "reasons", + ]); + if (!candidate) { + return failure("INVALID_EVENT", "candidate"); + } + const reasons = readReasons(candidate.reasons, remaining); + if (!reasons.ok) { + return reasons; + } + remaining -= reasons.value.length; + explanations.push(Object.freeze({ ...base, candidateReasons: reasons.value })); + } else { + explanations.push(Object.freeze(base)); + } + } + return success( + Object.freeze({ lifecycleReasons: lifecycle.value, concepts: Object.freeze(explanations) }), + ); +} diff --git a/src/replay/rebuild.ts b/src/replay/rebuild.ts new file mode 100644 index 0000000..00a88a3 --- /dev/null +++ b/src/replay/rebuild.ts @@ -0,0 +1,103 @@ +import type { ReconciledObservation } from "../contracts/events"; +import type { CandidateProjection, ConceptProjection, ReviewResult } from "../contracts/projections"; +import type { Result } from "../contracts/results"; +import { failure, success } from "../errors"; +import { policyIdentity } from "../events/identity"; +import { lifecycleReasons } from "../explanation/reasons"; +import { projectCandidate } from "../readiness/candidate"; +import { isEligibleObservation } from "../readiness/qualification"; +import { projectPractice } from "../scheduling/transitions"; +import { identifier } from "../validation/limits"; +import { validatePolicy } from "../validation/policies"; +import { reconcile } from "./reconcile"; + +export function rebuildReview( + inputPolicy: unknown, + scopeId: unknown, + events: unknown, + nowMs: unknown, +): Result { + const policy = validatePolicy(inputPolicy); + if (!policy.ok) { + return policy; + } + const history = reconcile(scopeId, events, nowMs); + if (!history.ok) { + return history; + } + const grouped = new Map(); + for (const observation of history.value.observations) { + const group = grouped.get(observation.conceptId); + if (group) { + group.push(observation); + } else { + grouped.set(observation.conceptId, [observation]); + } + } + const concepts: ConceptProjection[] = []; + for (const conceptId of history.value.conceptIds) { + const observations = grouped.get(conceptId) ?? []; + const practice = projectPractice(policy.value.scheduling, observations); + if (!practice.ok) { + return practice; + } + if (policy.value.eligibility) { + const candidate = projectCandidate( + policy.value.eligibility, + observations.filter(isEligibleObservation), + ); + if (!candidate.ok) { + return candidate; + } + concepts.push(Object.freeze({ conceptId, ...practice.value, candidate: candidate.value })); + } else { + concepts.push(Object.freeze({ conceptId, ...practice.value })); + } + } + return success( + Object.freeze({ + identity: Object.freeze({ + schemaVersion: policy.value.schemaVersion, + algorithmVersion: policy.value.algorithmVersion, + scopeId: history.value.scopeId, + policyIdentity: policyIdentity(policy.value), + evaluatedAtMs: history.value.evaluatedAtMs, + watermark: history.value.watermark, + }), + concepts: Object.freeze(concepts), + appliedEventIds: history.value.appliedEventIds, + controlEventIds: history.value.controlEventIds, + lifecycleReasons: lifecycleReasons(history.value.controls), + }), + ); +} + +// A single-concept query still reconciles the complete scope before selecting evidence. +export function evaluateReadiness( + inputPolicy: unknown, + scopeId: unknown, + conceptId: unknown, + events: unknown, + nowMs: unknown, +): Result { + const policy = validatePolicy(inputPolicy); + if (!policy.ok) { + return policy; + } + if (!identifier(conceptId)) { + return failure("INVALID_EVENT", "conceptId"); + } + const history = reconcile(scopeId, events, nowMs); + if (!history.ok) { + return history; + } + if (!policy.value.eligibility) { + return success(null); + } + return projectCandidate( + policy.value.eligibility, + history.value.observations + .filter(isEligibleObservation) + .filter((observation) => observation.conceptId === conceptId), + ); +} diff --git a/src/replay/reconcile.ts b/src/replay/reconcile.ts index 770dad8..9157d55 100644 --- a/src/replay/reconcile.ts +++ b/src/replay/reconcile.ts @@ -12,6 +12,7 @@ import { historyWatermark } from "./watermark"; export type ReconciledHistory = { readonly scopeId: string; readonly evaluatedAtMs: number; + readonly conceptIds: readonly string[]; readonly observations: readonly ReconciledObservation[]; readonly appliedEventIds: readonly string[]; readonly controls: readonly ReviewControl[]; @@ -49,6 +50,7 @@ export function reconcile( return deletion; } const { rootEventIds, throughSequence } = deletion.value; + const conceptIds = new Set(); const observations: ReconciledObservation[] = []; const controls: ReviewControl[] = []; @@ -63,6 +65,9 @@ export function reconcile( } for (const event of events) { + if ("conceptId" in event) { + conceptIds.add(event.conceptId); + } if (event.kind === "practice_observation") { append(event.eventId, event); } else if (event.kind !== "eligible_credited_retrieval") { @@ -78,6 +83,7 @@ export function reconcile( Object.freeze({ scopeId, evaluatedAtMs, + conceptIds: Object.freeze([...conceptIds].sort()), observations: Object.freeze(observations), appliedEventIds: Object.freeze(observations.map((event) => event.eventId)), controls: Object.freeze(controls), diff --git a/src/scheduling/intervals.ts b/src/scheduling/intervals.ts new file mode 100644 index 0000000..f77e033 --- /dev/null +++ b/src/scheduling/intervals.ts @@ -0,0 +1,10 @@ +import type { SchedulingPolicy } from "../contracts/policies"; +import type { Result } from "../contracts/results"; +import { addCalendarDays } from "../time/calendar"; +import { addElapsedDays } from "../time/elapsed"; + +export function dueAfter(policy: SchedulingPolicy, anchorMs: number, days: number): Result { + return policy.dateArithmetic === "local_calendar_days" + ? addCalendarDays(anchorMs, days, policy.calendarProfile) + : addElapsedDays(anchorMs, days); +} diff --git a/src/scheduling/transitions.ts b/src/scheduling/transitions.ts new file mode 100644 index 0000000..f308900 --- /dev/null +++ b/src/scheduling/transitions.ts @@ -0,0 +1,117 @@ +import type { ReconciledObservation } from "../contracts/events"; +import type { SchedulingPolicy } from "../contracts/policies"; +import type { + PracticeProjection, + PracticeReadiness, + RecommendationKind, + ReviewReason, + ScheduleState, +} from "../contracts/projections"; +import type { Result } from "../contracts/results"; +import { success } from "../errors"; +import { dueAfter } from "./intervals"; + +export function projectPractice( + policy: SchedulingPolicy, + observations: readonly ReconciledObservation[], +): Result { + let scheduleState: ScheduleState = "unobserved"; + let stageIndex: number | null = null; + let dueAtMs: number | null = null; + let lastSeenAtMs: number | null = null; + let consecutiveMisses = 0; + let advisorySuccesses = 0; + let forcedSupport = false; + let observed = false; + const reasons: ReviewReason[] = []; + const lastStage = policy.intervalsDays.length - 1; + + for (const observation of observations) { + lastSeenAtMs = observation.atMs; + if (observation.outcome === "not_observed") { + if (scheduleState === "unobserved") { + scheduleState = "learning"; + } + reasons.push({ code: "NO_OBSERVATION" }); + continue; + } + observed = true; + let days: number; + if (observation.outcome === "pass") { + advisorySuccesses += 1; + consecutiveMisses = 0; + forcedSupport = false; + if (stageIndex === null) { + stageIndex = 0; + scheduleState = "reviewing"; + days = policy.intervalsDays[0] as number; + reasons.push({ code: "FIRST_PASS", value: stageIndex }); + } else if (dueAtMs !== null && observation.atMs < dueAtMs) { + reasons.push({ code: "EARLY_PASS", value: stageIndex }); + continue; + } else { + reasons.push({ code: "DUE_PASS", value: stageIndex }); + if (stageIndex === lastStage) { + scheduleState = "review_ready"; + days = policy.maintenanceDays; + } else { + stageIndex += 1; + days = policy.intervalsDays[stageIndex] as number; + } + } + } else { + consecutiveMisses += 1; + reasons.push({ code: "MISS", value: consecutiveMisses }); + if (stageIndex !== lastStage || policy.longProbeAction === "restart") { + stageIndex = null; + scheduleState = "learning"; + reasons.push({ code: "RESTART" }); + } else if (policy.longProbeAction === "support") { + forcedSupport = true; + reasons.push({ code: "FORCED_SUPPORT" }); + } + if (consecutiveMisses >= policy.supportAfterMisses) { + reasons.push({ code: "SUPPORT_THRESHOLD", value: consecutiveMisses }); + } + days = policy.retryDays; + } + const due = dueAfter(policy, observation.atMs, days); + if (!due.ok) { + return due; + } + dueAtMs = due.value; + if (scheduleState === "review_ready") { + reasons.push({ code: "MAINTENANCE" }); + } else if (stageIndex === lastStage) { + reasons.push({ code: "DELAYED_PROBE" }); + } + } + + const needsSupport = forcedSupport || consecutiveMisses >= policy.supportAfterMisses; + const recommendationKind: RecommendationKind = needsSupport + ? "support" + : scheduleState === "review_ready" + ? "transfer" + : stageIndex === lastStage + ? "delayed_retrieval" + : "ordinary"; + const readiness: PracticeReadiness = !observed + ? "unknown" + : scheduleState === "review_ready" + ? "review_ready" + : "developing"; + return success( + Object.freeze({ + scheduleState, + stageIndex, + dueAtMs, + lastSeenAtMs, + consecutiveMisses, + advisorySuccesses, + needsSupport, + recommendationKind, + readiness, + reasons: Object.freeze(reasons.map((reason) => Object.freeze(reason))), + }), + ); +} diff --git a/src/time/elapsed.ts b/src/time/elapsed.ts index 4a07dd4..052fed2 100644 --- a/src/time/elapsed.ts +++ b/src/time/elapsed.ts @@ -1,9 +1,10 @@ import type { Result } from "../contracts/results"; +import { MAX_INSTANT_MS } from "../contracts/time"; import { failure, success } from "../errors"; export const DAY_MS = 86_400_000; export const MINUTE_MS = 60_000; -export const MAX_INSTANT_MS = 8_640_000_000_000_000; +export { MAX_INSTANT_MS }; export function isInstant(value: unknown): value is number { return ( diff --git a/tests/unit/foundation.test.ts b/tests/unit/foundation.test.ts index c1729a7..78824af 100644 --- a/tests/unit/foundation.test.ts +++ b/tests/unit/foundation.test.ts @@ -3,6 +3,13 @@ import * as retention from "../../src/index"; describe("public entry point", () => { it("exports only implemented operations", () => { - expect(Object.keys(retention)).toEqual(["validateEvents", "validatePolicy"]); + expect(Object.keys(retention).sort()).toEqual([ + "advanceReview", + "evaluateReadiness", + "explainReview", + "rebuildReview", + "validateEvents", + "validatePolicy", + ]); }); }); diff --git a/tests/unit/reconcile.test.ts b/tests/unit/reconcile.test.ts index 552b7e4..6dc094a 100644 --- a/tests/unit/reconcile.test.ts +++ b/tests/unit/reconcile.test.ts @@ -116,6 +116,7 @@ describe("canonical reconciliation", () => { expect(history).toEqual({ scopeId, evaluatedAtMs: 0, + conceptIds: [], observations: [], appliedEventIds: [], controls: [], diff --git a/tests/unit/review.test.ts b/tests/unit/review.test.ts new file mode 100644 index 0000000..e3061d7 --- /dev/null +++ b/tests/unit/review.test.ts @@ -0,0 +1,366 @@ +import { describe, expect, it } from "vitest"; +import type { EligibleCreditedRetrieval, PracticeObservation } from "../../src/index"; +import { advanceReview, evaluateReadiness, explainReview, rebuildReview } from "../../src/index"; +import { elapsedPolicy, localPolicy } from "../fixtures/policy"; + +const day = 86_400_000; +const scope = "scope"; +const concept = "concept"; + +function policy(intervalsDays = [1, 3, 7, 16, 35]) { + const input = elapsedPolicy(); + return { ...input, scheduling: { ...input.scheduling, intervalsDays } }; +} + +function withEligibility() { + return { + ...policy(), + eligibility: { + eligibilityPolicyVersion: "v1", + minSuccesses: 3, + minSessions: 2, + minSpanMs: day, + requireFresh: true, + maxHints: 0, + minLadder: 3, + onFailure: "reset", + onNonqualifying: "ignore", + }, + }; +} + +function practice( + sequence: number, + atMs: number, + outcome: PracticeObservation["outcome"] = "pass", +): PracticeObservation { + return { + schemaVersion: 1, + scopeId: scope, + conceptId: concept, + eventId: `practice-${sequence}`, + sequence, + atMs, + kind: "practice_observation", + sessionId: "practice", + outcome, + }; +} + +function credit(sequence: number, atMs: number, sessionId = "session"): EligibleCreditedRetrieval { + return { + schemaVersion: 1, + scopeId: scope, + conceptId: concept, + eventId: `credit-${sequence}`, + sequence, + atMs, + kind: "eligible_credited_retrieval", + sessionId, + outcome: "pass", + fresh: true, + hints: 0, + ladder: 3, + eligibilityPolicyVersion: "v1", + creditDecisionId: `decision-${sequence}`, + decisionVersion: 1, + }; +} + +function value( + result: { readonly ok: true; readonly value: T } | { readonly ok: false; readonly errors: readonly unknown[] }, +): T { + if (!result.ok) { + throw new Error(JSON.stringify(result.errors)); + } + return result.value; +} + +function projection(events: unknown, nowMs = 100 * day, input: unknown = policy()) { + const result = value(rebuildReview(input, scope, events, nowMs)); + const first = result.concepts[0]; + if (!first) { + throw new Error("expected concept"); + } + return first; +} + +describe("practice review transitions", () => { + it("follows the independently derived progression and renews maintenance", () => { + const history = [0, 1, 4, 11, 27, 62, 92].map((at, sequence) => + practice(sequence, at * day), + ); + for (const [index, due] of [1, 4, 11, 27, 62, 92, 122].entries()) { + const result = projection(history.slice(0, index + 1)); + expect(result.dueAtMs).toBe(due * day); + expect(result.stageIndex).toBe(Math.min(index, 4)); + expect(result.scheduleState).toBe(index < 5 ? "reviewing" : "review_ready"); + expect(result.recommendationKind).toBe( + index < 4 ? "ordinary" : index === 4 ? "delayed_retrieval" : "transfer", + ); + } + expect(projection([practice(0, 0)], 0, policy([2, 8])).dueAtMs).toBe(2 * day); + }); + + it("retains early due and stage, counts advisory passes and tracks unobserved attempts", () => { + const result = projection([ + practice(0, 0), + practice(1, 1), + practice(2, 2, "not_observed"), + ]); + expect(result).toMatchObject({ + stageIndex: 0, + dueAtMs: day, + lastSeenAtMs: 2, + advisorySuccesses: 2, + consecutiveMisses: 0, + readiness: "developing", + }); + expect(result.reasons.map((reason) => reason.code)).toEqual([ + "FIRST_PASS", + "EARLY_PASS", + "NO_OBSERVATION", + ]); + expect(projection([practice(0, 0, "not_observed")])).toMatchObject({ + scheduleState: "learning", + readiness: "unknown", + dueAtMs: null, + lastSeenAtMs: 0, + }); + expect(projection([practice(0, day)], 0)).toMatchObject({ + scheduleState: "unobserved", + readiness: "unknown", + dueAtMs: null, + lastSeenAtMs: null, + }); + expect(value(rebuildReview(policy(), scope, [], 0)).concepts).toEqual([]); + }); + + it("restarts on short misses, recommends support at threshold and resets on pass", () => { + const events = [ + practice(0, 0), + practice(1, 1, "fail"), + practice(2, 2, "fail"), + ]; + expect(projection(events)).toMatchObject({ + scheduleState: "learning", + stageIndex: null, + dueAtMs: day + 2, + consecutiveMisses: 2, + needsSupport: true, + recommendationKind: "support", + }); + expect(projection([...events, practice(3, 3)])).toMatchObject({ + stageIndex: 0, + dueAtMs: day + 3, + consecutiveMisses: 0, + needsSupport: false, + advisorySuccesses: 2, + }); + }); + + it.each(["restart", "support", "keep"] as const)("applies %s at final stage and maintenance", (action) => { + const input = policy([1]); + input.scheduling.longProbeAction = action; + for (const maintained of [false, true]) { + const events = maintained + ? [practice(0, 0), practice(1, day)] + : [practice(0, 0)]; + const failed = [...events, practice(2, day + 1, "fail")]; + expect(projection(failed, 100 * day, input)).toMatchObject({ + stageIndex: action === "restart" ? null : 0, + scheduleState: action === "restart" ? "learning" : maintained ? "review_ready" : "reviewing", + dueAtMs: 2 * day + 1, + needsSupport: action === "support", + }); + expect(projection([...failed, practice(3, day + 2)], 100 * day, input).needsSupport).toBe(false); + } + }); + + it("uses explicit calendar rules and rejects overflow without a partial projection", () => { + const input = localPolicy(); + input.scheduling.intervalsDays = [1]; + const start = Date.UTC(2024, 2, 9, 7, 30); + expect(projection([practice(0, start)], start, input).dueAtMs).toBe( + Date.UTC(2024, 2, 10, 7, 30), + ); + const edge = 8_640_000_000_000_000; + expect(rebuildReview(policy(), scope, [practice(0, edge)], edge)).toEqual({ + ok: false, + errors: [{ code: "INVALID_TIMESTAMP", field: "dueAtMs" }], + }); + }); +}); + +describe("eligible-only readiness", () => { + it("counts qualifying streak sessions and span without using practice or evaluation time", () => { + const input = withEligibility(); + const early = { ...credit(0, 0), fresh: false }; + const first = credit(2, day); + const second = credit(3, day + 1); + const third = credit(4, day + 2, "second"); + const history = [early, practice(1, 1), first, second, third]; + const result = projection(history, 100 * day, input); + expect(result.candidate).toMatchObject({ + readiness: "developing", + qualifyingSuccesses: 3, + distinctSessions: 2, + firstQualifyingAtMs: day, + lastQualifyingAtMs: day + 2, + qualifyingSpanMs: 2, + }); + expect(projection([first], 100 * day, input).candidate?.readiness).toBe("developing"); + expect( + projection([first, second, credit(4, 2 * day)], 100 * day, input).candidate?.readiness, + ).toBe("developing"); + const complete = [...history.slice(0, 4), credit(4, 2 * day, "second")]; + const ready = projection(complete, 100 * day, input); + expect(ready.candidate?.readiness).toBe("candidate_ready"); + expect(ready.readiness).toBe("developing"); + expect(value(evaluateReadiness(input, scope, concept, complete, 100 * day))).toEqual( + ready.candidate, + ); + expect(projection([practice(0, 0)], 0, input).candidate?.readiness).toBe("unknown"); + expect(projection([practice(0, 0)], 0)).not.toHaveProperty("candidate"); + expect(value(evaluateReadiness(policy(), scope, concept, [], 0))).toBeNull(); + }); + + it("resets counts, timestamps and distinct sessions; ignores nonqualifying evidence", () => { + const input = withEligibility(); + const events = [credit(0, 0), credit(1, day, "second"), { ...credit(2, 2 * day), outcome: "fail" }, credit(3, 3 * day)]; + expect(projection(events, 100 * day, input).candidate).toMatchObject({ + qualifyingSuccesses: 1, + distinctSessions: 1, + firstQualifyingAtMs: 3 * day, + lastQualifyingAtMs: 3 * day, + qualifyingSpanMs: 0, + }); + const hinted = { ...credit(2, 2 * day), hints: 1 }; + expect(projection([events[0], events[1], hinted], 100 * day, input).candidate?.qualifyingSuccesses).toBe(2); + input.eligibility.onNonqualifying = "reset"; + expect(projection([events[0], events[1], hinted], 100 * day, input).candidate).toMatchObject({ + qualifyingSuccesses: 0, + distinctSessions: 0, + firstQualifyingAtMs: null, + lastQualifyingAtMs: null, + qualifyingSpanMs: 0, + }); + }); + + it("reconciles the whole scope before returning readiness, even without eligibility", () => { + const invalid = { + schemaVersion: 1, + scopeId: scope, + conceptId: "other", + eventId: "revocation", + sequence: 3, + atMs: 0, + kind: "credited_decision_revocation", + supersedesDecisionId: "missing", + reasonCode: "revoked", + }; + for (const input of [policy(), withEligibility()]) { + expect(evaluateReadiness(input, scope, concept, [credit(1, 0), invalid], 0)).toEqual({ + ok: false, + errors: [{ code: "MISSING_CORRECTION_TARGET", field: "supersedesDecisionId" }], + }); + } + }); +}); + +describe("full replay, advance and explanations", () => { + it("replays correction and deletion effects on both projections", () => { + const input = withEligibility(); + const root = credit(0, 0); + const correction = { + schemaVersion: 1, + scopeId: scope, + conceptId: concept, + eventId: "correction", + sequence: 1, + atMs: day, + kind: "credited_decision_correction", + supersedesDecisionId: "decision-0", + replacementDecisionId: "decision-new", + decisionVersion: 2, + reasonCode: "private-canary", + replacement: { + sessionId: "session", + outcome: "fail", + fresh: true, + hints: 0, + ladder: 3, + eligibilityPolicyVersion: "v1", + }, + }; + const deletion = { + schemaVersion: 1, + scopeId: scope, + conceptId: concept, + eventId: "deletion", + sequence: 2, + atMs: day, + kind: "review_event_deletion", + targetEventId: "correction", + }; + const corrected = value(rebuildReview(input, scope, [root, correction], day)); + expect(corrected.appliedEventIds).toEqual(["correction"]); + expect(corrected.concepts[0]).toMatchObject({ + advisorySuccesses: 0, + consecutiveMisses: 1, + candidate: { readiness: "developing", qualifyingSuccesses: 0 }, + }); + const deleted = value(rebuildReview(input, scope, [deletion, correction, root], day)); + expect(deleted.appliedEventIds).toEqual([]); + expect(deleted.concepts[0]).toMatchObject({ + scheduleState: "unobserved", + candidate: { readiness: "unknown" }, + }); + const explanation = value(explainReview(deleted)); + expect(explanation.lifecycleReasons).toEqual([ + { code: "CREDIT_CORRECTION" }, + { code: "EVENT_DELETION" }, + ]); + expect(JSON.stringify(explanation)).not.toContain("private-canary"); + expect(explainReview({ ...deleted, lifecycleReasons: [{ code: "private-canary" }] }).ok).toBe(false); + }); + + it("matches reference replay on permutations, duplicates and a late effective append", () => { + const input = withEligibility(); + const previous = [credit(0, day), practice(1, 2 * day)]; + const added = [credit(2, 0, "second"), practice(3, 4 * day)]; + const first = value(rebuildReview(input, scope, previous, 2 * day)); + const expected = value(rebuildReview(input, scope, [...previous, ...added], 4 * day)); + expect(value(advanceReview(input, scope, first.identity, previous, added, 4 * day))).toEqual(expected); + expect(value(rebuildReview(input, scope, [...added, ...previous, ...previous], 4 * day))).toEqual(expected); + expect(Object.isFrozen(expected.concepts)).toBe(true); + expect(Object.isFrozen(expected.concepts[0]?.reasons)).toBe(true); + }); + + it("refuses mismatched identity, prefix, backward time and opaque snapshots", () => { + const input = policy(); + const previous = [practice(0, 0)]; + const first = value(rebuildReview(input, scope, previous, day)); + for (const [identity, prefix, clock] of [ + [first, previous, day], + [first.identity, [], day], + [{ ...first.identity, schemaVersion: 2 }, previous, day], + [{ ...first.identity, algorithmVersion: "2" }, previous, day], + [{ ...first.identity, scopeId: "other" }, previous, day], + [{ ...first.identity, watermark: "[]" }, previous, day], + [first.identity, undefined, day], + [first.identity, previous, 0], + ] as const) { + const result = advanceReview(input, scope, identity, prefix, [], clock); + expect(result.ok).toBe(false); + if (!result.ok) { + expect(result.errors[0]?.code).toBe("REBUILD_REQUIRED"); + } + } + expect(advanceReview(policy([2]), scope, first.identity, previous, [], day).ok).toBe(false); + expect(advanceReview(input, scope, first.identity, previous, Array(20_000), day)).toEqual({ + ok: false, + errors: [{ code: "RESOURCE_LIMIT_EXCEEDED", field: "events", limit: 20_000 }], + }); + }); +}); From d36f0e96899ff7fe92c667062f187db0706e3007 Mon Sep 17 00:00:00 2001 From: "Christopher S. Aondona" Date: Sun, 29 Nov 2026 17:11:02 +0100 Subject: [PATCH 2/5] fix: satisfy RV-I03 pinned Biome checks --- README.md | 2 +- scripts/verify-dist.mjs | 17 +++++++- src/explanation/reasons.ts | 21 ++++------ src/replay/rebuild.ts | 6 ++- tests/unit/review.test.ts | 81 +++++++++++++++++++++----------------- 5 files changed, 73 insertions(+), 54 deletions(-) diff --git a/README.md b/README.md index be8b183..21a3b24 100644 --- a/README.md +++ b/README.md @@ -87,7 +87,7 @@ Retention cannot establish whether evidence is authentic. The application admits | `rebuildReview` | Reconstruct review projections from complete history. | | `advanceReview` | Verify the prior identity and event prefix, then rebuild with new events. | | `evaluateReadiness` | Calculate advisory readiness from reconciled eligible evidence. | -| `scheduleDue` | Planned: select and rank due concepts. | +| `scheduleDue` | Planned: select and rank due concepts. | | `explainReview` | Return structured reasons for a recommendation. | Due ranking is the remaining planned public operation. See [policy validation](docs/policies.md), [event validation](docs/events.md) and [replay and readiness](docs/replay.md) for implemented behavior and limitations. diff --git a/scripts/verify-dist.mjs b/scripts/verify-dist.mjs index 4445efe..b7cc3ca 100644 --- a/scripts/verify-dist.mjs +++ b/scripts/verify-dist.mjs @@ -84,11 +84,24 @@ const replay = runtime.rebuildReview(result.value, "smoke", events.value, 0); if (!replay.ok || replay.value.concepts[0]?.dueAtMs !== 259_200_000) { throw new Error("Built replay failed."); } -const advanced = runtime.advanceReview(result.value, "smoke", replay.value.identity, events.value, [], 0); +const advanced = runtime.advanceReview( + result.value, + "smoke", + replay.value.identity, + events.value, + [], + 0, +); if (!advanced.ok || JSON.stringify(advanced.value) !== JSON.stringify(replay.value)) { throw new Error("Built advance failed."); } -const candidate = runtime.evaluateReadiness(candidatePolicy.value, "smoke", "concept-1", events.value, 0); +const candidate = runtime.evaluateReadiness( + candidatePolicy.value, + "smoke", + "concept-1", + events.value, + 0, +); if (!candidate.ok || candidate.value?.readiness !== "unknown") { throw new Error("Built readiness failed."); } diff --git a/src/explanation/reasons.ts b/src/explanation/reasons.ts index 0bb3f17..70c3982 100644 --- a/src/explanation/reasons.ts +++ b/src/explanation/reasons.ts @@ -2,20 +2,13 @@ import type { ReviewControl } from "../contracts/events"; import type { ReasonCode, ReviewReason } from "../contracts/projections"; export function lifecycleReasons(controls: readonly ReviewControl[]): readonly ReviewReason[] { - return Object.freeze( - controls.map((control): ReviewReason => { - switch (control.kind) { - case "credited_decision_correction": - return Object.freeze({ code: "CREDIT_CORRECTION" }); - case "credited_decision_revocation": - return Object.freeze({ code: "CREDIT_REVOCATION" }); - case "review_event_deletion": - return Object.freeze({ code: "EVENT_DELETION" }); - case "review_scope_deletion": - return Object.freeze({ code: "SCOPE_DELETION" }); - } - }), - ); + const codes = { + credited_decision_correction: "CREDIT_CORRECTION", + credited_decision_revocation: "CREDIT_REVOCATION", + review_event_deletion: "EVENT_DELETION", + review_scope_deletion: "SCOPE_DELETION", + } as const; + return Object.freeze(controls.map((control) => normalizedReason(codes[control.kind]))); } // Only fixed codes and their documented numeric arguments can leave the explanation boundary. diff --git a/src/replay/rebuild.ts b/src/replay/rebuild.ts index 00a88a3..6ba538e 100644 --- a/src/replay/rebuild.ts +++ b/src/replay/rebuild.ts @@ -1,5 +1,9 @@ import type { ReconciledObservation } from "../contracts/events"; -import type { CandidateProjection, ConceptProjection, ReviewResult } from "../contracts/projections"; +import type { + CandidateProjection, + ConceptProjection, + ReviewResult, +} from "../contracts/projections"; import type { Result } from "../contracts/results"; import { failure, success } from "../errors"; import { policyIdentity } from "../events/identity"; diff --git a/tests/unit/review.test.ts b/tests/unit/review.test.ts index e3061d7..f91a081 100644 --- a/tests/unit/review.test.ts +++ b/tests/unit/review.test.ts @@ -68,7 +68,9 @@ function credit(sequence: number, atMs: number, sessionId = "session"): Eligible } function value( - result: { readonly ok: true; readonly value: T } | { readonly ok: false; readonly errors: readonly unknown[] }, + result: + | { readonly ok: true; readonly value: T } + | { readonly ok: false; readonly errors: readonly unknown[] }, ): T { if (!result.ok) { throw new Error(JSON.stringify(result.errors)); @@ -87,9 +89,7 @@ function projection(events: unknown, nowMs = 100 * day, input: unknown = policy( describe("practice review transitions", () => { it("follows the independently derived progression and renews maintenance", () => { - const history = [0, 1, 4, 11, 27, 62, 92].map((at, sequence) => - practice(sequence, at * day), - ); + const history = [0, 1, 4, 11, 27, 62, 92].map((at, sequence) => practice(sequence, at * day)); for (const [index, due] of [1, 4, 11, 27, 62, 92, 122].entries()) { const result = projection(history.slice(0, index + 1)); expect(result.dueAtMs).toBe(due * day); @@ -103,11 +103,7 @@ describe("practice review transitions", () => { }); it("retains early due and stage, counts advisory passes and tracks unobserved attempts", () => { - const result = projection([ - practice(0, 0), - practice(1, 1), - practice(2, 2, "not_observed"), - ]); + const result = projection([practice(0, 0), practice(1, 1), practice(2, 2, "not_observed")]); expect(result).toMatchObject({ stageIndex: 0, dueAtMs: day, @@ -137,11 +133,7 @@ describe("practice review transitions", () => { }); it("restarts on short misses, recommends support at threshold and resets on pass", () => { - const events = [ - practice(0, 0), - practice(1, 1, "fail"), - practice(2, 2, "fail"), - ]; + const events = [practice(0, 0), practice(1, 1, "fail"), practice(2, 2, "fail")]; expect(projection(events)).toMatchObject({ scheduleState: "learning", stageIndex: null, @@ -159,23 +151,27 @@ describe("practice review transitions", () => { }); }); - it.each(["restart", "support", "keep"] as const)("applies %s at final stage and maintenance", (action) => { - const input = policy([1]); - input.scheduling.longProbeAction = action; - for (const maintained of [false, true]) { - const events = maintained - ? [practice(0, 0), practice(1, day)] - : [practice(0, 0)]; - const failed = [...events, practice(2, day + 1, "fail")]; - expect(projection(failed, 100 * day, input)).toMatchObject({ - stageIndex: action === "restart" ? null : 0, - scheduleState: action === "restart" ? "learning" : maintained ? "review_ready" : "reviewing", - dueAtMs: 2 * day + 1, - needsSupport: action === "support", - }); - expect(projection([...failed, practice(3, day + 2)], 100 * day, input).needsSupport).toBe(false); - } - }); + it.each(["restart", "support", "keep"] as const)( + "applies %s at final stage and maintenance", + (action) => { + const input = policy([1]); + input.scheduling.longProbeAction = action; + for (const maintained of [false, true]) { + const events = maintained ? [practice(0, 0), practice(1, day)] : [practice(0, 0)]; + const failed = [...events, practice(2, day + 1, "fail")]; + expect(projection(failed, 100 * day, input)).toMatchObject({ + stageIndex: action === "restart" ? null : 0, + scheduleState: + action === "restart" ? "learning" : maintained ? "review_ready" : "reviewing", + dueAtMs: 2 * day + 1, + needsSupport: action === "support", + }); + expect(projection([...failed, practice(3, day + 2)], 100 * day, input).needsSupport).toBe( + false, + ); + } + }, + ); it("uses explicit calendar rules and rejects overflow without a partial projection", () => { const input = localPolicy(); @@ -227,7 +223,12 @@ describe("eligible-only readiness", () => { it("resets counts, timestamps and distinct sessions; ignores nonqualifying evidence", () => { const input = withEligibility(); - const events = [credit(0, 0), credit(1, day, "second"), { ...credit(2, 2 * day), outcome: "fail" }, credit(3, 3 * day)]; + const events = [ + credit(0, 0), + credit(1, day, "second"), + { ...credit(2, 2 * day), outcome: "fail" }, + credit(3, 3 * day), + ]; expect(projection(events, 100 * day, input).candidate).toMatchObject({ qualifyingSuccesses: 1, distinctSessions: 1, @@ -236,7 +237,9 @@ describe("eligible-only readiness", () => { qualifyingSpanMs: 0, }); const hinted = { ...credit(2, 2 * day), hints: 1 }; - expect(projection([events[0], events[1], hinted], 100 * day, input).candidate?.qualifyingSuccesses).toBe(2); + expect( + projection([events[0], events[1], hinted], 100 * day, input).candidate?.qualifyingSuccesses, + ).toBe(2); input.eligibility.onNonqualifying = "reset"; expect(projection([events[0], events[1], hinted], 100 * day, input).candidate).toMatchObject({ qualifyingSuccesses: 0, @@ -322,7 +325,9 @@ describe("full replay, advance and explanations", () => { { code: "EVENT_DELETION" }, ]); expect(JSON.stringify(explanation)).not.toContain("private-canary"); - expect(explainReview({ ...deleted, lifecycleReasons: [{ code: "private-canary" }] }).ok).toBe(false); + expect(explainReview({ ...deleted, lifecycleReasons: [{ code: "private-canary" }] }).ok).toBe( + false, + ); }); it("matches reference replay on permutations, duplicates and a late effective append", () => { @@ -331,8 +336,12 @@ describe("full replay, advance and explanations", () => { const added = [credit(2, 0, "second"), practice(3, 4 * day)]; const first = value(rebuildReview(input, scope, previous, 2 * day)); const expected = value(rebuildReview(input, scope, [...previous, ...added], 4 * day)); - expect(value(advanceReview(input, scope, first.identity, previous, added, 4 * day))).toEqual(expected); - expect(value(rebuildReview(input, scope, [...added, ...previous, ...previous], 4 * day))).toEqual(expected); + expect(value(advanceReview(input, scope, first.identity, previous, added, 4 * day))).toEqual( + expected, + ); + expect( + value(rebuildReview(input, scope, [...added, ...previous, ...previous], 4 * day)), + ).toEqual(expected); expect(Object.isFrozen(expected.concepts)).toBe(true); expect(Object.isFrozen(expected.concepts[0]?.reasons)).toBe(true); }); From c5ff219a34f16d79c9a3d556c1a524932e240071 Mon Sep 17 00:00:00 2001 From: "Christopher S. Aondona" Date: Sun, 29 Nov 2026 17:19:55 +0100 Subject: [PATCH 3/5] fix: validate review projections and cover public lifecycle replay --- docs/replay.md | 2 +- src/explanation/reasons.ts | 28 --- src/replay/advance.ts | 29 +-- src/replay/explain.ts | 135 ++--------- src/validation/projections.ts | 416 ++++++++++++++++++++++++++++++++++ tests/unit/explain.test.ts | 161 +++++++++++++ tests/unit/review.test.ts | 104 ++++++++- 7 files changed, 709 insertions(+), 166 deletions(-) create mode 100644 src/validation/projections.ts create mode 100644 tests/unit/explain.test.ts diff --git a/docs/replay.md b/docs/replay.md index cc1feee..e57369a 100644 --- a/docs/replay.md +++ b/docs/replay.md @@ -33,4 +33,4 @@ Practice scheduling uses all active observations. Candidate aggregation uses onl Advance requires the exact prior identity and complete prior history, including suppressed and future events. A changed policy, incompatible identity, missing history or backward clock requires explicit rebuild. The appended records may include late effective observations or identical duplicates; the combined history is validated and replayed from scratch. A supplied identity is not authenticated evidence. Both input arrays count toward the raw-entry limit, including duplicates. -Explain accepts a successful rebuild or advance value and returns only fixed reason codes, bounded numeric arguments and concept identifiers. It does not interpret raw correction reason strings, revalidate evidence or rerun scheduling. It checks the reason-bearing shape and bounds; it is not a projection authenticity check. +Explain accepts a successful rebuild or advance value and returns only fixed reason codes, bounded numeric arguments and concept identifiers. It does not interpret raw correction reason strings, revalidate evidence or rerun scheduling. It validates the closed result envelope, identity, event IDs, projection states, counts, timestamps and reason bounds. The canonical identity strings have separate derived size limits and are treated as opaque content identifiers here; only advance verifies them against replayed input. Explanation is not a projection authenticity check. diff --git a/src/explanation/reasons.ts b/src/explanation/reasons.ts index 70c3982..5885605 100644 --- a/src/explanation/reasons.ts +++ b/src/explanation/reasons.ts @@ -11,34 +11,6 @@ export function lifecycleReasons(controls: readonly ReviewControl[]): readonly R return Object.freeze(controls.map((control) => normalizedReason(codes[control.kind]))); } -// Only fixed codes and their documented numeric arguments can leave the explanation boundary. -export function reasonBound(code: unknown): number | null | undefined { - switch (code) { - case "FIRST_PASS": - case "EARLY_PASS": - case "DUE_PASS": - return 63; - case "MISS": - case "SUPPORT_THRESHOLD": - case "QUALIFYING_SUCCESS": - return 10_000; - case "RESTART": - case "FORCED_SUPPORT": - case "DELAYED_PROBE": - case "MAINTENANCE": - case "NO_OBSERVATION": - case "CREDIT_CORRECTION": - case "CREDIT_REVOCATION": - case "EVENT_DELETION": - case "SCOPE_DELETION": - case "CANDIDATE_RESET": - case "CANDIDATE_IGNORE": - return null; - default: - return undefined; - } -} - export function normalizedReason(code: ReasonCode, value?: number): ReviewReason { return Object.freeze({ code, ...(value === undefined ? {} : { value: value + 0 }) }); } diff --git a/src/replay/advance.ts b/src/replay/advance.ts index 79c1900..00bc3c0 100644 --- a/src/replay/advance.ts +++ b/src/replay/advance.ts @@ -3,8 +3,9 @@ import type { Result } from "../contracts/results"; import { failure } from "../errors"; import { policyIdentity } from "../events/identity"; import { validateClock } from "../validation/clock"; -import { array, arrayLength, LIMITS, record } from "../validation/limits"; +import { array, arrayLength, LIMITS } from "../validation/limits"; import { validatePolicy } from "../validation/policies"; +import { validateProjectionIdentity } from "../validation/projections"; import { rebuildReview } from "./rebuild"; export function advanceReview( @@ -23,26 +24,16 @@ export function advanceReview( if (!clock.ok) { return clock; } - const previous = record(previousIdentity, [ - "schemaVersion", - "algorithmVersion", - "scopeId", - "policyIdentity", - "evaluatedAtMs", - "watermark", - ]); + const previous = validateProjectionIdentity(previousIdentity); if ( - !previous || - previous.schemaVersion !== policy.value.schemaVersion || - previous.algorithmVersion !== policy.value.algorithmVersion || - previous.scopeId !== scopeId || - previous.policyIdentity !== policyIdentity(policy.value) || - typeof previous.watermark !== "string" + !previous.ok || + previous.value.scopeId !== scopeId || + previous.value.policyIdentity !== policyIdentity(policy.value) ) { return failure("REBUILD_REQUIRED", "previousIdentity"); } - const previousClock = validateClock(previous.evaluatedAtMs); - if (!previousClock.ok || previousClock.value > clock.value) { + const previousClock = previous.value.evaluatedAtMs; + if (previousClock > clock.value) { return failure("REBUILD_REQUIRED", "evaluatedAtMs"); } const priorLength = arrayLength(previousEvents); @@ -66,8 +57,8 @@ export function advanceReview( } // Reconstruct the prior result rather than trusting its projection or an opaque snapshot. - const reconstructed = rebuildReview(policy.value, scopeId, prior, previousClock.value); - if (!reconstructed.ok || reconstructed.value.identity.watermark !== previous.watermark) { + const reconstructed = rebuildReview(policy.value, scopeId, prior, previousClock); + if (!reconstructed.ok || reconstructed.value.identity.watermark !== previous.value.watermark) { return failure("REBUILD_REQUIRED", "previousEvents"); } // Validate raw combined bounds, identities and lifecycle again using the reference operation. diff --git a/src/replay/explain.ts b/src/replay/explain.ts index 1a91ff6..8fe2cad 100644 --- a/src/replay/explain.ts +++ b/src/replay/explain.ts @@ -1,125 +1,26 @@ -import type { - ConceptExplanation, - ReasonCode, - ReviewExplanation, - ReviewReason, -} from "../contracts/projections"; +import type { ConceptExplanation, ReviewExplanation } from "../contracts/projections"; import type { Result } from "../contracts/results"; -import { failure, success } from "../errors"; -import { normalizedReason, reasonBound } from "../explanation/reasons"; -import { array, arrayLength, identifier, integer, LIMITS, record } from "../validation/limits"; - -const maxReasons = LIMITS.distinctEvents * 5; - -function readReasons(input: unknown, remaining: number): Result { - const length = arrayLength(input); - if (length !== null && length > remaining) { - return failure("RESOURCE_LIMIT_EXCEEDED", "reasons", maxReasons); - } - const entries = array(input, remaining); - if (!entries) { - return failure("INVALID_EVENT", "reasons"); - } - const reasons: ReviewReason[] = []; - for (const entry of entries) { - const fields = record(entry, ["code"], ["value"]); - if (!fields) { - return failure("INVALID_EVENT", "reasons"); - } - const bound = reasonBound(fields.code); - if (bound === undefined) { - return failure("INVALID_EVENT", "code"); - } - if (bound === null) { - if (Object.hasOwn(fields, "value")) { - return failure("INVALID_EVENT", "value"); - } - reasons.push(normalizedReason(fields.code as ReasonCode)); - } else { - if (!integer(fields.value, 0, bound)) { - return failure("INVALID_EVENT", "value"); - } - reasons.push(normalizedReason(fields.code as ReasonCode, fields.value)); - } - } - return success(Object.freeze(reasons)); -} +import { success } from "../errors"; +import { validateReviewResult } from "../validation/projections"; /** Explain a successful replay value; this does not revalidate evidence or run scheduling. */ export function explainReview(input: unknown): Result { - const fields = record(input, [ - "identity", - "concepts", - "appliedEventIds", - "controlEventIds", - "lifecycleReasons", - ]); - if (!fields) { - return failure("INVALID_EVENT", "review"); - } - const concepts = array(fields.concepts, LIMITS.concepts); - if (!concepts) { - return failure("INVALID_EVENT", "concepts"); - } - const lifecycle = readReasons(fields.lifecycleReasons, maxReasons); - if (!lifecycle.ok) { - return lifecycle; - } - let remaining = maxReasons - lifecycle.value.length; - const explanations: ConceptExplanation[] = []; - const seen = new Set(); - for (const concept of concepts) { - const projection = record( - concept, - [ - "conceptId", - "scheduleState", - "stageIndex", - "dueAtMs", - "lastSeenAtMs", - "consecutiveMisses", - "advisorySuccesses", - "needsSupport", - "recommendationKind", - "readiness", - "reasons", - ], - ["candidate"], - ); - if (!projection || !identifier(projection.conceptId) || seen.has(projection.conceptId)) { - return failure("INVALID_EVENT", "conceptId"); - } - seen.add(projection.conceptId); - const practice = readReasons(projection.reasons, remaining); - if (!practice.ok) { - return practice; - } - remaining -= practice.value.length; - const base = { conceptId: projection.conceptId, practiceReasons: practice.value }; - if (Object.hasOwn(projection, "candidate")) { - const candidate = record(projection.candidate, [ - "readiness", - "qualifyingSuccesses", - "distinctSessions", - "firstQualifyingAtMs", - "lastQualifyingAtMs", - "qualifyingSpanMs", - "reasons", - ]); - if (!candidate) { - return failure("INVALID_EVENT", "candidate"); - } - const reasons = readReasons(candidate.reasons, remaining); - if (!reasons.ok) { - return reasons; - } - remaining -= reasons.value.length; - explanations.push(Object.freeze({ ...base, candidateReasons: reasons.value })); - } else { - explanations.push(Object.freeze(base)); - } + const result = validateReviewResult(input); + if (!result.ok) { + return result; } + const concepts = result.value.concepts.map( + (concept): ConceptExplanation => + Object.freeze({ + conceptId: concept.conceptId, + practiceReasons: concept.reasons, + ...(concept.candidate ? { candidateReasons: concept.candidate.reasons } : {}), + }), + ); return success( - Object.freeze({ lifecycleReasons: lifecycle.value, concepts: Object.freeze(explanations) }), + Object.freeze({ + lifecycleReasons: result.value.lifecycleReasons, + concepts: Object.freeze(concepts), + }), ); } diff --git a/src/validation/projections.ts b/src/validation/projections.ts new file mode 100644 index 0000000..9b8a737 --- /dev/null +++ b/src/validation/projections.ts @@ -0,0 +1,416 @@ +import type { + CandidateProjection, + ConceptProjection, + ProjectionIdentity, + ReasonCode, + ReviewReason, + ReviewResult, +} from "../contracts/projections"; +import type { Result } from "../contracts/results"; +import { failure, success } from "../errors"; +import { isInstant, MAX_INSTANT_MS } from "../time/elapsed"; +import { array, arrayLength, identifier, integer, LIMITS, record } from "./limits"; + +const maxReasons = LIMITS.distinctEvents * 5; +// Derived canonical strings are not individual input labels. Allow worst-case JSON escaping, +// fixed record keys and numeric fields, including all bounded calendar transitions and events. +const maxPolicyIdentity = LIMITS.calendarTransitions * 128 + 4096; +const maxWatermark = LIMITS.aggregateStringLength * 6 + LIMITS.distinctEvents * 1024 + 2; + +function invalid(field: string): Result { + return failure("INVALID_EVENT", field); +} + +function derivedString(value: unknown, max: number, start: string, end: string): value is string { + return ( + typeof value === "string" && + value.length <= max && + value.startsWith(start) && + value.endsWith(end) + ); +} + +// Identity strings are bounded opaque encodings here, not trusted proof of the underlying +// history or policy. Advance verifies exact content by reconstruction. +export function validateProjectionIdentity(input: unknown): Result { + const fields = record(input, [ + "schemaVersion", + "algorithmVersion", + "scopeId", + "policyIdentity", + "evaluatedAtMs", + "watermark", + ]); + if (!fields) { + return invalid("identity"); + } + const { schemaVersion, algorithmVersion, scopeId, policyIdentity, evaluatedAtMs, watermark } = + fields; + if (schemaVersion !== 1 || algorithmVersion !== "1") { + return failure("UNSUPPORTED_VERSION", "identity"); + } + if (!identifier(scopeId)) { + return invalid("scopeId"); + } + if (!isInstant(evaluatedAtMs)) { + return failure("INVALID_TIMESTAMP", "evaluatedAtMs"); + } + if (!derivedString(policyIdentity, maxPolicyIdentity, '{"algorithmVersion":"1",', "}")) { + return invalid("policyIdentity"); + } + if (!derivedString(watermark, maxWatermark, "[", "]")) { + return invalid("watermark"); + } + return success( + Object.freeze({ + schemaVersion, + algorithmVersion, + scopeId, + policyIdentity, + evaluatedAtMs: evaluatedAtMs + 0, + watermark, + }), + ); +} + +// Only fixed codes and their documented numeric arguments can leave the explanation boundary. +function reasonBound(code: unknown): number | null | undefined { + switch (code) { + case "FIRST_PASS": + case "EARLY_PASS": + case "DUE_PASS": + return 63; + case "MISS": + case "SUPPORT_THRESHOLD": + case "QUALIFYING_SUCCESS": + return 10_000; + case "RESTART": + case "FORCED_SUPPORT": + case "DELAYED_PROBE": + case "MAINTENANCE": + case "NO_OBSERVATION": + case "CREDIT_CORRECTION": + case "CREDIT_REVOCATION": + case "EVENT_DELETION": + case "SCOPE_DELETION": + case "CANDIDATE_RESET": + case "CANDIDATE_IGNORE": + return null; + default: + return undefined; + } +} + +function readReasons(input: unknown, remaining: number): Result { + const length = arrayLength(input); + if (length !== null && length > remaining) { + return failure("RESOURCE_LIMIT_EXCEEDED", "reasons", maxReasons); + } + const entries = array(input, remaining); + if (!entries) { + return invalid("reasons"); + } + const reasons: ReviewReason[] = []; + for (const entry of entries) { + const fields = record(entry, ["code"], ["value"]); + if (!fields) { + return invalid("reasons"); + } + const bound = reasonBound(fields.code); + if (bound === undefined) { + return invalid("code"); + } + const code = fields.code as ReasonCode; + if (bound === null) { + if (Object.hasOwn(fields, "value")) { + return invalid("value"); + } + reasons.push(Object.freeze({ code })); + } else { + if (!integer(fields.value, 0, bound)) { + return invalid("value"); + } + reasons.push(Object.freeze({ code, value: fields.value + 0 })); + } + } + return success(Object.freeze(reasons)); +} + +function readIds(input: unknown, field: "appliedEventIds" | "controlEventIds"): Result { + const length = arrayLength(input); + if (length !== null && length > LIMITS.distinctEvents) { + return failure("RESOURCE_LIMIT_EXCEEDED", field, LIMITS.distinctEvents); + } + const entries = array(input, LIMITS.distinctEvents); + if (!entries) { + return invalid(field); + } + const ids = new Set(); + for (const entry of entries) { + if (!identifier(entry) || ids.has(entry)) { + return invalid(field); + } + ids.add(entry); + } + return success(Object.freeze([...ids])); +} + +function count(value: unknown): value is number { + return integer(value, 0, LIMITS.distinctEvents); +} + +function nullableInstant(value: unknown): value is number | null { + return value === null || isInstant(value); +} + +function readCandidate( + input: unknown, + evaluatedAtMs: number, + remaining: number, +): Result { + const fields = record(input, [ + "readiness", + "qualifyingSuccesses", + "distinctSessions", + "firstQualifyingAtMs", + "lastQualifyingAtMs", + "qualifyingSpanMs", + "reasons", + ]); + if (!fields) { + return invalid("candidate"); + } + const { + readiness, + qualifyingSuccesses, + distinctSessions, + firstQualifyingAtMs, + lastQualifyingAtMs, + qualifyingSpanMs, + } = fields; + if (readiness !== "unknown" && readiness !== "developing" && readiness !== "candidate_ready") { + return invalid("readiness"); + } + if (!count(qualifyingSuccesses) || !count(distinctSessions) || distinctSessions > qualifyingSuccesses) { + return invalid("qualifyingSuccesses"); + } + if ( + !nullableInstant(firstQualifyingAtMs) || + !nullableInstant(lastQualifyingAtMs) || + (lastQualifyingAtMs !== null && lastQualifyingAtMs > evaluatedAtMs) + ) { + return failure("INVALID_TIMESTAMP", "qualifyingAtMs"); + } + if (!integer(qualifyingSpanMs, 0, MAX_INSTANT_MS)) { + return invalid("qualifyingSpanMs"); + } + if (qualifyingSuccesses === 0) { + if ( + distinctSessions !== 0 || + firstQualifyingAtMs !== null || + lastQualifyingAtMs !== null || + qualifyingSpanMs !== 0 || + readiness === "candidate_ready" + ) { + return invalid("candidate"); + } + } else if ( + readiness === "unknown" || + distinctSessions === 0 || + firstQualifyingAtMs === null || + lastQualifyingAtMs === null || + lastQualifyingAtMs - firstQualifyingAtMs !== qualifyingSpanMs + ) { + return invalid("candidate"); + } + const reasons = readReasons(fields.reasons, remaining); + if (!reasons.ok) { + return reasons; + } + return success( + Object.freeze({ + readiness, + qualifyingSuccesses: qualifyingSuccesses + 0, + distinctSessions: distinctSessions + 0, + firstQualifyingAtMs, + lastQualifyingAtMs, + qualifyingSpanMs: qualifyingSpanMs + 0, + reasons: reasons.value, + }), + ); +} + +function readConcept( + input: unknown, + evaluatedAtMs: number, + remaining: number, +): Result { + const fields = record( + input, + [ + "conceptId", + "scheduleState", + "stageIndex", + "dueAtMs", + "lastSeenAtMs", + "consecutiveMisses", + "advisorySuccesses", + "needsSupport", + "recommendationKind", + "readiness", + "reasons", + ], + ["candidate"], + ); + if (!fields) { + return invalid("concepts"); + } + const { + conceptId, + scheduleState, + stageIndex, + dueAtMs, + lastSeenAtMs, + consecutiveMisses, + advisorySuccesses, + needsSupport, + recommendationKind, + readiness, + } = fields; + if (!identifier(conceptId)) { + return invalid("conceptId"); + } + if ( + scheduleState !== "unobserved" && + scheduleState !== "learning" && + scheduleState !== "reviewing" && + scheduleState !== "review_ready" + ) { + return invalid("scheduleState"); + } + if (stageIndex !== null && !integer(stageIndex, 0, LIMITS.intervals - 1)) { + return invalid("stageIndex"); + } + if (!nullableInstant(dueAtMs)) { + return failure("INVALID_TIMESTAMP", "dueAtMs"); + } + if (!nullableInstant(lastSeenAtMs) || (lastSeenAtMs !== null && lastSeenAtMs > evaluatedAtMs)) { + return failure("INVALID_TIMESTAMP", "lastSeenAtMs"); + } + if (!count(consecutiveMisses) || !count(advisorySuccesses) || consecutiveMisses + advisorySuccesses > LIMITS.distinctEvents) { + return invalid("advisorySuccesses"); + } + if (typeof needsSupport !== "boolean") { + return invalid("needsSupport"); + } + if ( + recommendationKind !== "ordinary" && + recommendationKind !== "delayed_retrieval" && + recommendationKind !== "transfer" && + recommendationKind !== "support" + ) { + return invalid("recommendationKind"); + } + if (readiness !== "unknown" && readiness !== "developing" && readiness !== "review_ready") { + return invalid("readiness"); + } + if ( + (scheduleState === "reviewing" || scheduleState === "review_ready") !== (stageIndex !== null) || + (scheduleState === "unobserved") !== (lastSeenAtMs === null) || + (scheduleState === "review_ready") !== (readiness === "review_ready") || + (recommendationKind === "support") !== needsSupport || + (stageIndex !== null && dueAtMs === null) || + (dueAtMs !== null && lastSeenAtMs === null) + ) { + return invalid("concepts"); + } + const reasons = readReasons(fields.reasons, remaining); + if (!reasons.ok) { + return reasons; + } + const base = { + conceptId, + scheduleState, + stageIndex, + dueAtMs, + lastSeenAtMs, + consecutiveMisses: consecutiveMisses + 0, + advisorySuccesses: advisorySuccesses + 0, + needsSupport, + recommendationKind, + readiness, + reasons: reasons.value, + }; + if (!Object.hasOwn(fields, "candidate")) { + return success(Object.freeze(base)); + } + const candidate = readCandidate(fields.candidate, evaluatedAtMs, remaining - reasons.value.length); + return candidate.ok ? success(Object.freeze({ ...base, candidate: candidate.value })) : candidate; +} + +/** Validate closed result shapes and bounded derived values, not evidence or replay correctness. */ +export function validateReviewResult(input: unknown): Result { + const fields = record(input, [ + "identity", + "concepts", + "appliedEventIds", + "controlEventIds", + "lifecycleReasons", + ]); + if (!fields) { + return invalid("review"); + } + const identity = validateProjectionIdentity(fields.identity); + if (!identity.ok) { + return identity; + } + const applied = readIds(fields.appliedEventIds, "appliedEventIds"); + if (!applied.ok) { + return applied; + } + const controls = readIds(fields.controlEventIds, "controlEventIds"); + if (!controls.ok) { + return controls; + } + // An active correction ID occurs in both lists, so bound the union, not their sum. + if (new Set([...applied.value, ...controls.value]).size > LIMITS.distinctEvents) { + return failure("RESOURCE_LIMIT_EXCEEDED", "events", LIMITS.distinctEvents); + } + const length = arrayLength(fields.concepts); + if (length !== null && length > LIMITS.concepts) { + return failure("RESOURCE_LIMIT_EXCEEDED", "concepts", LIMITS.concepts); + } + const entries = array(fields.concepts, LIMITS.concepts); + if (!entries) { + return invalid("concepts"); + } + const lifecycle = readReasons(fields.lifecycleReasons, maxReasons); + if (!lifecycle.ok) { + return lifecycle; + } + let remaining = maxReasons - lifecycle.value.length; + const concepts: ConceptProjection[] = []; + let previousId: string | null = null; + for (const entry of entries) { + const result = readConcept(entry, identity.value.evaluatedAtMs, remaining); + if (!result.ok) { + return result; + } + const concept = result.value; + if (previousId !== null && concept.conceptId <= previousId) { + return invalid("conceptId"); + } + previousId = concept.conceptId; + remaining -= concept.reasons.length + (concept.candidate?.reasons.length ?? 0); + concepts.push(concept); + } + return success( + Object.freeze({ + identity: identity.value, + concepts: Object.freeze(concepts), + appliedEventIds: applied.value, + controlEventIds: controls.value, + lifecycleReasons: lifecycle.value, + }), + ); +} diff --git a/tests/unit/explain.test.ts b/tests/unit/explain.test.ts new file mode 100644 index 0000000..7aeb17c --- /dev/null +++ b/tests/unit/explain.test.ts @@ -0,0 +1,161 @@ +import { describe, expect, it } from "vitest"; +import { explainReview, rebuildReview } from "../../src/index"; +import { elapsedPolicy, localPolicy } from "../fixtures/policy"; + +function fixture() { + const policy = { + ...elapsedPolicy(), + eligibility: { + eligibilityPolicyVersion: "v1", + minSuccesses: 1, + minSessions: 1, + minSpanMs: 0, + requireFresh: true, + maxHints: 0, + minLadder: 0, + onFailure: "reset", + onNonqualifying: "ignore", + }, + }; + const result = rebuildReview( + policy, + "scope", + [ + { + schemaVersion: 1, + scopeId: "scope", + conceptId: "concept", + eventId: "credit", + sequence: 0, + atMs: 0, + kind: "eligible_credited_retrieval", + sessionId: "session", + outcome: "pass", + fresh: true, + hints: 0, + ladder: 1, + eligibilityPolicyVersion: "v1", + creditDecisionId: "decision", + decisionVersion: 1, + }, + ], + 0, + ); + if (!result.ok || !result.value.concepts[0]?.candidate) { + throw new Error("fixture must rebuild"); + } + return { + result: result.value, + concept: result.value.concepts[0], + candidate: result.value.concepts[0].candidate, + }; +} + +describe("public explanation validation", () => { + it("accepts immutable and serialized replay values including long canonical identities", () => { + const { result } = fixture(); + expect(result.identity.policyIdentity.length).toBeGreaterThan(256); + expect(result.identity.watermark.length).toBeGreaterThan(256); + const explanation = explainReview(result); + expect(explanation.ok).toBe(true); + expect(explainReview(JSON.parse(JSON.stringify(result)))).toEqual(explanation); + const calendar = rebuildReview(localPolicy(), "scope", [], 0); + if (!calendar.ok) { + throw new Error("fixture must rebuild"); + } + expect(explainReview(calendar.value).ok).toBe(true); + }); + + it("rejects malformed identities, event ID arrays and concept arrays", () => { + const { result } = fixture(); + const identity = result.identity; + const cases = [ + { identity: null, appliedEventIds: false, controlEventIds: 42, concepts: [] }, + { identity: { ...identity, schemaVersion: 2 } }, + { identity: { ...identity, algorithmVersion: "2" } }, + { identity: { ...identity, scopeId: "invalid id" } }, + { identity: { ...identity, evaluatedAtMs: Number.NaN } }, + { identity: { ...identity, policyIdentity: false } }, + { identity: { ...identity, policyIdentity: "private-canary" } }, + { identity: { ...identity, policyIdentity: "x".repeat(1_000_000) } }, + { identity: { ...identity, watermark: null } }, + { identity: { ...identity, watermark: "x".repeat(35_000_000) } }, + { identity: { ...identity, unknown: "private-canary" } }, + { appliedEventIds: false }, + { appliedEventIds: ["x".repeat(129)] }, + { appliedEventIds: ["credit", "credit"] }, + { controlEventIds: 42 }, + { controlEventIds: new Array(10_001) }, + { concepts: new Array(1001) }, + { concepts: [result.concepts[0], result.concepts[0]] }, + ]; + for (const fields of cases) { + const invalid = explainReview({ ...result, ...fields }); + expect(invalid.ok).toBe(false); + expect(JSON.stringify(invalid)).not.toContain("private-canary"); + } + }); + + it("rejects malformed practice and candidate scalar values", () => { + const { result, concept, candidate } = fixture(); + for (const fields of [ + { conceptId: "invalid id" }, + { scheduleState: "bogus" }, + { stageIndex: 64 }, + { dueAtMs: Number.NaN }, + { lastSeenAtMs: 1 }, + { consecutiveMisses: -1 }, + { advisorySuccesses: 10_001 }, + { needsSupport: 1 }, + { recommendationKind: "bogus" }, + { readiness: "candidate_ready" }, + { candidate: undefined }, + { unknown: "private-canary" }, + ]) { + expect(explainReview({ ...result, concepts: [{ ...concept, ...fields }] }).ok).toBe(false); + } + for (const fields of [ + { readiness: "review_ready" }, + { qualifyingSuccesses: 0.5 }, + { distinctSessions: 2 }, + { firstQualifyingAtMs: Number.POSITIVE_INFINITY }, + { lastQualifyingAtMs: 1 }, + { qualifyingSpanMs: -1 }, + { qualifyingSpanMs: 1 }, + { reasons: [{ code: "QUALIFYING_SUCCESS", value: 10_001 }] }, + ]) { + const projection = { ...concept, candidate: { ...candidate, ...fields } }; + expect(explainReview({ ...result, concepts: [projection] }).ok).toBe(false); + } + }); + + it("refuses nested accessors, hidden fields and sparse arrays without executing getters", () => { + const { result, concept, candidate } = fixture(); + let calls = 0; + function getter() { + calls += 1; + return 0; + } + const identity = Object.defineProperty({ ...result.identity }, "evaluatedAtMs", { + enumerable: true, + get: getter, + }); + const ids = Object.defineProperty(["credit"], "0", { enumerable: true, get: getter }); + const practice = Object.defineProperty({ ...concept }, "dueAtMs", { + enumerable: true, + get: getter, + }); + const credit = Object.defineProperty({ ...candidate }, "hidden", { get: getter }); + for (const fields of [ + { identity }, + { appliedEventIds: ids }, + { appliedEventIds: new Array(1) }, + { concepts: [practice] }, + { concepts: [{ ...concept, candidate: credit }] }, + { concepts: [{ ...concept, [Symbol("hidden")]: true }] }, + ]) { + expect(explainReview({ ...result, ...fields }).ok).toBe(false); + } + expect(calls).toBe(0); + }); +}); diff --git a/tests/unit/review.test.ts b/tests/unit/review.test.ts index f91a081..55204b7 100644 --- a/tests/unit/review.test.ts +++ b/tests/unit/review.test.ts @@ -1,5 +1,9 @@ import { describe, expect, it } from "vitest"; -import type { EligibleCreditedRetrieval, PracticeObservation } from "../../src/index"; +import type { + EligibleCreditedRetrieval, + PracticeObservation, + ReviewEvent, +} from "../../src/index"; import { advanceReview, evaluateReadiness, explainReview, rebuildReview } from "../../src/index"; import { elapsedPolicy, localPolicy } from "../fixtures/policy"; @@ -330,6 +334,104 @@ describe("full replay, advance and explanations", () => { ); }); + it("recomputes both projections after revocation, scope cutoff and late suppressed history", () => { + const input = withEligibility(); + const now = 6 * day; + let events: ReviewEvent[] = [ + credit(0, 0), + credit(2, day, "second"), + credit(4, 4 * day, "second"), + practice(5, 5 * day), + ]; + let result = value(rebuildReview(input, scope, events, now)); + function check(ids: string[], successes: number, state: string, qualifying: number, readiness: string) { + expect(result.appliedEventIds).toEqual(ids); + expect(result.concepts[0]).toMatchObject({ + advisorySuccesses: successes, + scheduleState: state, + candidate: { qualifyingSuccesses: qualifying, readiness }, + }); + expect(value(evaluateReadiness(input, scope, concept, events, now))).toEqual( + result.concepts[0]?.candidate, + ); + } + function append(added: ReviewEvent[]) { + const next = value(advanceReview(input, scope, result.identity, events, added, now)); + events = [...events, ...added]; + expect(next).toEqual(value(rebuildReview(input, scope, events, now))); + result = next; + } + check(["credit-0", "credit-2", "credit-4", "practice-5"], 4, "reviewing", 3, "candidate_ready"); + append([ + { + schemaVersion: 1, + scopeId: scope, + conceptId: concept, + eventId: "revocation", + sequence: 6, + atMs: now, + kind: "credited_decision_revocation", + supersedesDecisionId: "decision-4", + reasonCode: "revoked", + }, + ]); + check(["credit-0", "credit-2", "practice-5"], 3, "reviewing", 2, "developing"); + expect(result.concepts[0]?.dueAtMs).toBe(12 * day); + append([ + { + schemaVersion: 1, + scopeId: scope, + eventId: "cutoff", + sequence: 7, + atMs: now + day, + kind: "review_scope_deletion", + throughSequence: 4, + }, + ]); + check(["practice-5"], 1, "reviewing", 0, "unknown"); + expect(result.concepts[0]?.dueAtMs).toBe(6 * day); + append([ + { + schemaVersion: 1, + scopeId: scope, + conceptId: concept, + eventId: "correction", + sequence: 8, + atMs: now, + kind: "credited_decision_correction", + supersedesDecisionId: "decision-0", + replacementDecisionId: "decision-new", + decisionVersion: 2, + reasonCode: "corrected", + replacement: { + sessionId: "third", + outcome: "pass", + fresh: true, + hints: 0, + ladder: 3, + eligibilityPolicyVersion: "v1", + }, + }, + credit(1, 1, "late"), + ]); + check(["practice-5"], 1, "reviewing", 0, "unknown"); + append([ + { + schemaVersion: 1, + scopeId: scope, + conceptId: concept, + eventId: "deletion", + sequence: 9, + atMs: now, + kind: "review_event_deletion", + targetEventId: "practice-5", + }, + ]); + check([], 0, "unobserved", 0, "unknown"); + expect(result.concepts[0]?.dueAtMs).toBeNull(); + expect(result.controlEventIds).toEqual(["revocation", "cutoff", "correction", "deletion"]); + }); + it("matches reference replay on permutations, duplicates and a late effective append", () => { const input = withEligibility(); const previous = [credit(0, day), practice(1, 2 * day)]; From 220645ba0f75d43bb88357b1510991853fa2f1f3 Mon Sep 17 00:00:00 2001 From: "Christopher S. Aondona" Date: Sun, 29 Nov 2026 17:20:32 +0100 Subject: [PATCH 4/5] fix: preserve validated projection enum types --- src/validation/projections.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/validation/projections.ts b/src/validation/projections.ts index 9b8a737..fe9bd43 100644 --- a/src/validation/projections.ts +++ b/src/validation/projections.ts @@ -328,7 +328,7 @@ function readConcept( if (!reasons.ok) { return reasons; } - const base = { + const base: ConceptProjection = { conceptId, scheduleState, stageIndex, From c284ed1d7c64c111bab39c01f02ea60b21b726bd Mon Sep 17 00:00:00 2001 From: "Christopher S. Aondona" Date: Sun, 29 Nov 2026 17:21:37 +0100 Subject: [PATCH 5/5] style: apply pinned Biome formatting to review fixes --- src/validation/projections.ts | 23 +++++++++++++++++++---- tests/unit/review.test.ts | 14 ++++++++------ 2 files changed, 27 insertions(+), 10 deletions(-) diff --git a/src/validation/projections.ts b/src/validation/projections.ts index fe9bd43..6f07f41 100644 --- a/src/validation/projections.ts +++ b/src/validation/projections.ts @@ -136,7 +136,10 @@ function readReasons(input: unknown, remaining: number): Result { +function readIds( + input: unknown, + field: "appliedEventIds" | "controlEventIds", +): Result { const length = arrayLength(input); if (length !== null && length > LIMITS.distinctEvents) { return failure("RESOURCE_LIMIT_EXCEEDED", field, LIMITS.distinctEvents); @@ -191,7 +194,11 @@ function readCandidate( if (readiness !== "unknown" && readiness !== "developing" && readiness !== "candidate_ready") { return invalid("readiness"); } - if (!count(qualifyingSuccesses) || !count(distinctSessions) || distinctSessions > qualifyingSuccesses) { + if ( + !count(qualifyingSuccesses) || + !count(distinctSessions) || + distinctSessions > qualifyingSuccesses + ) { return invalid("qualifyingSuccesses"); } if ( @@ -297,7 +304,11 @@ function readConcept( if (!nullableInstant(lastSeenAtMs) || (lastSeenAtMs !== null && lastSeenAtMs > evaluatedAtMs)) { return failure("INVALID_TIMESTAMP", "lastSeenAtMs"); } - if (!count(consecutiveMisses) || !count(advisorySuccesses) || consecutiveMisses + advisorySuccesses > LIMITS.distinctEvents) { + if ( + !count(consecutiveMisses) || + !count(advisorySuccesses) || + consecutiveMisses + advisorySuccesses > LIMITS.distinctEvents + ) { return invalid("advisorySuccesses"); } if (typeof needsSupport !== "boolean") { @@ -344,7 +355,11 @@ function readConcept( if (!Object.hasOwn(fields, "candidate")) { return success(Object.freeze(base)); } - const candidate = readCandidate(fields.candidate, evaluatedAtMs, remaining - reasons.value.length); + const candidate = readCandidate( + fields.candidate, + evaluatedAtMs, + remaining - reasons.value.length, + ); return candidate.ok ? success(Object.freeze({ ...base, candidate: candidate.value })) : candidate; } diff --git a/tests/unit/review.test.ts b/tests/unit/review.test.ts index 55204b7..afae6d4 100644 --- a/tests/unit/review.test.ts +++ b/tests/unit/review.test.ts @@ -1,9 +1,5 @@ import { describe, expect, it } from "vitest"; -import type { - EligibleCreditedRetrieval, - PracticeObservation, - ReviewEvent, -} from "../../src/index"; +import type { EligibleCreditedRetrieval, PracticeObservation, ReviewEvent } from "../../src/index"; import { advanceReview, evaluateReadiness, explainReview, rebuildReview } from "../../src/index"; import { elapsedPolicy, localPolicy } from "../fixtures/policy"; @@ -344,7 +340,13 @@ describe("full replay, advance and explanations", () => { practice(5, 5 * day), ]; let result = value(rebuildReview(input, scope, events, now)); - function check(ids: string[], successes: number, state: string, qualifying: number, readiness: string) { + function check( + ids: string[], + successes: number, + state: string, + qualifying: number, + readiness: string, + ) { expect(result.appliedEventIds).toEqual(ids); expect(result.concepts[0]).toMatchObject({ advisorySuccesses: successes,