diff --git a/CHANGELOG.md b/CHANGELOG.md index fcd1e64..587b556 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -14,3 +14,4 @@ Notable changes to Retention are recorded here. The format follows [Keep a Chang - 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. +- Public due ranking with bounded weighted features, validated concept relations and deterministic limits. diff --git a/README.md b/README.md index 21a3b24..d46c5d0 100644 --- a/README.md +++ b/README.md @@ -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` | Planned: select and rank due concepts. | +| `scheduleDue` | 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. +See [due ranking](docs/priority.md), [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, 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: +The repository has an ESM package foundation with policy and event validation, checked time arithmetic, canonical history reconciliation, practice scheduling and eligible-only readiness and due ranking. 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 bbb23a0..28f312f 100644 --- a/docs/architecture.md +++ b/docs/architecture.md @@ -4,13 +4,14 @@ Retention is a standalone review-scheduling engine. The engine takes an explicit ## Current layout -- `src/index.ts`: explicit validation, replay, readiness and explanation operations and contract types. +- `src/index.ts`: explicit validation, replay, readiness, ranking 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/`: full-history reconciliation, canonical watermark, public rebuild, advance and readiness orchestration. - `src/scheduling/`: practice transitions and interval arithmetic. +- `src/priority/`: due selection, bounded features, relation graph checks and deterministic ranking. - `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. @@ -19,8 +20,8 @@ Retention is a standalone review-scheduling engine. The engine takes an explicit ## Replay and projection layers -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. +The internal replay layer validates and reconciles events. Public orchestration calculates 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. 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, reconciliation, scheduling, candidate aggregation, public replay and explanations are implemented; due ranking is 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, explanations and due ranking are implemented. diff --git a/docs/policies.md b/docs/policies.md index 1920771..3895afe 100644 --- a/docs/policies.md +++ b/docs/policies.md @@ -21,11 +21,11 @@ const result = validatePolicy({ }); ``` -All scheduling fields are required. Interval order is preserved. Intervals, retry and maintenance are integers from 1 to 3650 days; there must be 1 to 64 intervals. Support activates at the authored miss threshold (1 to 1000). The optional `priority` object accepts all four integer weights `overdue`, `support`, `relation`, and `stage` (0 to 1000). Ranking is not implemented yet. Policy identifiers and version identifiers are bounded ASCII identifiers. +All scheduling fields are required. Interval order is preserved. Intervals, retry and maintenance are integers from 1 to 3650 days; there must be 1 to 64 intervals. Support activates at the authored miss threshold (1 to 1000). The optional `priority` object accepts all four integer weights `overdue`, `support`, `relation`, and `stage` (0 to 1000). Omitting priority sets all ranking weights to zero. See [due ranking](priority.md). Policy identifiers and version identifiers are bounded ASCII identifiers. 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 enforces policy identity when advancing. Ranking remains 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. ## Optional eligibility diff --git a/docs/priority.md b/docs/priority.md new file mode 100644 index 0000000..fbfd968 --- /dev/null +++ b/docs/priority.md @@ -0,0 +1,30 @@ +# Due ranking + +Call `scheduleDue(policy, scopeId, review, nowMs, relations?, limit?)` with a successful rebuild or advance value and the same explicit clock, scope and complete policy. The review carries one scope-level identity; concept entries may be in any order, but must be unique. A stale clock or changed policy requires a fresh rebuild. The operation does not replay or authenticate the history. + +```ts +import { rebuildReview, scheduleDue } from "@0xbuff/retention"; + +const review = rebuildReview(policy, scopeId, events, nowMs); +if (review.ok) { + const due = scheduleDue(policy, scopeId, review.value, nowMs, [], 10); + if (due.ok) { + // Present due.value to the learner. + } +} +``` + +Only concepts whose due time is at or before the clock are selected. Each recommendation contains its concept ID, due time, recommendation kind, integer score, four features and fixed numeric reasons in feature order: + +| Feature | Value | +| -------- | --------------------------------------------- | +| overdue | Whole elapsed days overdue, capped at 3650 | +| support | 1 if support is needed; otherwise 0 | +| relation | Distinct related due concepts, capped at 1000 | +| stage | Stage index plus one, or 0 before a stage | + +The score is the sum of each feature multiplied by its policy weight. Omitting priority gives all four weights zero. Results sort by descending score, ascending due time, then ascending ASCII concept ID. The optional limit (0–1000) applies after ranking; omitted means all due. + +A relation has `kind` (`prerequisite` or `confusable`), `fromConceptId` and `toConceptId`. A prerequisite points from prerequisite to dependent and only counts outgoing due dependents. A confusable pair counts in both directions. Duplicate edges and reversed confusable pairs count once; overlapping relation kinds do not double-count a neighbor. All endpoints must be present in the review, including non-due concepts. Self-relations and directed prerequisite cycles are rejected; confusable cycles are valid. At most 10,000 raw relations are accepted. The policy, scope, review and raw relations share a 4,000,000 UTF-16 code-unit budget for ordinary string values, including duplicate relation entries. Derived policy identity and watermark encodings retain separate size bounds. + +A relation changes only the ranking score. It does not block a due review, establish mastery or change eligibility. Zero limit still validates every input. Support and recommendation kinds must agree with the supplied scheduling policy and projection state. Malformed or incompatible inputs produce a typed failure without a partial queue. The host remains responsible for trustworthy current projections, history completeness, authorization, stale-generation rejection and delivery. diff --git a/docs/replay.md b/docs/replay.md index e57369a..4eb3010 100644 --- a/docs/replay.md +++ b/docs/replay.md @@ -34,3 +34,5 @@ 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 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. + +Use [due ranking](priority.md) to select recommendations from a current review result without replaying its history. diff --git a/scripts/verify-dist.mjs b/scripts/verify-dist.mjs index b7cc3ca..6876ba5 100644 --- a/scripts/verify-dist.mjs +++ b/scripts/verify-dist.mjs @@ -20,11 +20,12 @@ for (const name of expected) { const runtime = await import(pathToFileURL(resolve(entry.import)).href); if ( Object.keys(runtime).sort().join() !== - "advanceReview,evaluateReadiness,explainReview,rebuildReview,validateEvents,validatePolicy" || + "advanceReview,evaluateReadiness,explainReview,rebuildReview,scheduleDue,validateEvents,validatePolicy" || typeof runtime.advanceReview !== "function" || typeof runtime.evaluateReadiness !== "function" || typeof runtime.explainReview !== "function" || typeof runtime.rebuildReview !== "function" || + typeof runtime.scheduleDue !== "function" || typeof runtime.validateEvents !== "function" || typeof runtime.validatePolicy !== "function" ) { @@ -108,4 +109,12 @@ if (!candidate.ok || candidate.value?.readiness !== "unknown") { if (!runtime.explainReview(replay.value).ok) { throw new Error("Built explanation failed."); } +const dueReview = runtime.rebuildReview(result.value, "smoke", events.value, 259_200_000); +if (!dueReview.ok) { + throw new Error("Built due replay failed."); +} +const due = runtime.scheduleDue(result.value, "smoke", dueReview.value, 259_200_000); +if (!due.ok || due.value[0]?.conceptId !== "concept-1" || due.value[0]?.score !== 0) { + throw new Error("Built ranking failed."); +} console.log("Distribution exports and ESM import verified."); diff --git a/src/contracts/priority.ts b/src/contracts/priority.ts new file mode 100644 index 0000000..f0c9462 --- /dev/null +++ b/src/contracts/priority.ts @@ -0,0 +1,28 @@ +import type { RecommendationKind } from "./projections"; + +export type ConceptRelation = { + readonly kind: "prerequisite" | "confusable"; + readonly fromConceptId: string; + readonly toConceptId: string; +}; + +export type PriorityFeatures = { + readonly overdue: number; + readonly support: number; + readonly relation: number; + readonly stage: number; +}; + +export type PriorityReason = { + readonly code: "OVERDUE_DAYS" | "SUPPORT_NEEDED" | "RELATED_DUE" | "REVIEW_STAGE"; + readonly value: number; +}; + +export type DueRecommendation = { + readonly conceptId: string; + readonly dueAtMs: number; + readonly recommendationKind: RecommendationKind; + readonly score: number; + readonly features: PriorityFeatures; + readonly reasons: readonly PriorityReason[]; +}; diff --git a/src/contracts/results.ts b/src/contracts/results.ts index e022b26..2f6a9b3 100644 --- a/src/contracts/results.ts +++ b/src/contracts/results.ts @@ -6,6 +6,8 @@ export type ErrorCode = | "INVALID_CORRECTION" | "MISSING_CORRECTION_TARGET" | "INVALID_POLICY" + | "POLICY_MISMATCH" + | "INVALID_RELATION" | "INVALID_TIMESTAMP" | "UNSUPPORTED_VERSION" | "REBUILD_REQUIRED" diff --git a/src/index.ts b/src/index.ts index 4b81622..602a820 100644 --- a/src/index.ts +++ b/src/index.ts @@ -22,6 +22,12 @@ export type { PriorityWeights, SchedulingPolicy, } from "./contracts/policies"; +export type { + ConceptRelation, + DueRecommendation, + PriorityFeatures, + PriorityReason, +} from "./contracts/priority"; export type { CandidateProjection, CandidateReadiness, @@ -39,6 +45,7 @@ export type { } from "./contracts/projections"; export type { Diagnostic, ErrorCode, Result } from "./contracts/results"; export type { AlgorithmVersion, SchemaVersion } from "./contracts/versions"; +export { scheduleDue } from "./priority/rank"; export { advanceReview } from "./replay/advance"; export { explainReview } from "./replay/explain"; export { evaluateReadiness, rebuildReview } from "./replay/rebuild"; diff --git a/src/priority/features.ts b/src/priority/features.ts new file mode 100644 index 0000000..d55f376 --- /dev/null +++ b/src/priority/features.ts @@ -0,0 +1,52 @@ +import type { PriorityWeights } from "../contracts/policies"; +import type { DueRecommendation, PriorityFeatures, PriorityReason } from "../contracts/priority"; +import type { ConceptProjection } from "../contracts/projections"; +import { MAX_INSTANT_MS } from "../contracts/time"; + +const dayMs = 86_400_000; +const capDays = 3650; +const capMs = capDays * dayMs; + +// Both instants have been validated and due <= now. Compare against the cap before +// subtraction so even opposite-end instants never produce an unsafe integer. +function overdueDays(nowMs: number, dueAtMs: number): number { + if (nowMs >= -MAX_INSTANT_MS + capMs && dueAtMs <= nowMs - capMs) { + return capDays; + } + return Math.floor((nowMs - dueAtMs) / dayMs); +} + +export function dueRecommendation( + concept: ConceptProjection, + dueAtMs: number, + nowMs: number, + relation: number, + weights: PriorityWeights | undefined, +): DueRecommendation { + const features: PriorityFeatures = Object.freeze({ + overdue: overdueDays(nowMs, dueAtMs), + support: concept.needsSupport ? 1 : 0, + relation, + stage: concept.stageIndex === null ? 0 : concept.stageIndex + 1, + }); + // Bounded features and weights keep the sum <= 4,715,000. + const score = + features.overdue * (weights?.overdue ?? 0) + + features.support * (weights?.support ?? 0) + + features.relation * (weights?.relation ?? 0) + + features.stage * (weights?.stage ?? 0); + const reasons: PriorityReason[] = [ + { code: "OVERDUE_DAYS", value: features.overdue }, + { code: "SUPPORT_NEEDED", value: features.support }, + { code: "RELATED_DUE", value: features.relation }, + { code: "REVIEW_STAGE", value: features.stage }, + ]; + return Object.freeze({ + conceptId: concept.conceptId, + dueAtMs, + recommendationKind: concept.recommendationKind, + score, + features, + reasons: Object.freeze(reasons.map((reason) => Object.freeze(reason))), + }); +} diff --git a/src/priority/rank.ts b/src/priority/rank.ts new file mode 100644 index 0000000..c1b155d --- /dev/null +++ b/src/priority/rank.ts @@ -0,0 +1,74 @@ +import type { DueRecommendation } from "../contracts/priority"; +import type { Result } from "../contracts/results"; +import { success } from "../errors"; +import { validatePolicy } from "../validation/policies"; +import { + validateRankingLimit, + validateRankingReview, + validateRelations, +} from "../validation/priority"; +import { StringBudget } from "../validation/string-budget"; +import { dueRecommendation } from "./features"; +import { relatedDueCounts } from "./relations"; + +export function scheduleDue( + inputPolicy: unknown, + scopeId: unknown, + inputReview: unknown, + nowMs: unknown, + relations?: unknown, + limit?: unknown, +): Result { + const policy = validatePolicy(inputPolicy); + if (!policy.ok) { + return policy; + } + const budget = new StringBudget(); + const review = validateRankingReview(policy.value, scopeId, inputReview, nowMs, budget); + if (!review.ok) { + return review; + } + const maximum = validateRankingLimit(limit); + if (!maximum.ok) { + return maximum; + } + const clock = review.value.identity.evaluatedAtMs; + const concepts = new Set(review.value.concepts.map((concept) => concept.conceptId)); + const due = new Set( + review.value.concepts + .filter((concept) => concept.dueAtMs !== null && concept.dueAtMs <= clock) + .map((concept) => concept.conceptId), + ); + const edges = validateRelations(relations, concepts, budget); + if (!edges.ok) { + return edges; + } + const counts = relatedDueCounts(concepts, due, edges.value); + if (!counts.ok) { + return counts; + } + const ranked: DueRecommendation[] = []; + for (const concept of review.value.concepts) { + if (concept.dueAtMs !== null && concept.dueAtMs <= clock) { + ranked.push( + dueRecommendation( + concept, + concept.dueAtMs, + clock, + counts.value.get(concept.conceptId) ?? 0, + policy.value.priority, + ), + ); + } + } + ranked.sort((left, right) => { + if (left.score !== right.score) { + return right.score - left.score; + } + if (left.dueAtMs !== right.dueAtMs) { + return left.dueAtMs < right.dueAtMs ? -1 : 1; + } + return left.conceptId < right.conceptId ? -1 : left.conceptId > right.conceptId ? 1 : 0; + }); + return success(Object.freeze(ranked.slice(0, maximum.value))); +} diff --git a/src/priority/relations.ts b/src/priority/relations.ts new file mode 100644 index 0000000..03b7945 --- /dev/null +++ b/src/priority/relations.ts @@ -0,0 +1,60 @@ +import type { ConceptRelation } from "../contracts/priority"; +import type { Result } from "../contracts/results"; +import { failure, success } from "../errors"; + +function add(index: Map>, from: string, to: string): boolean { + const existing = index.get(from); + if (!existing) { + index.set(from, new Set([to])); + return true; + } + if (existing.has(to)) { + return false; + } + existing.add(to); + return true; +} + +// Sets normalize duplicate edges, including reversed confusable pairs, and count each +// due neighbor once even when two relation kinds connect the same concepts. +export function relatedDueCounts( + concepts: ReadonlySet, + due: ReadonlySet, + relations: readonly ConceptRelation[], +): Result> { + const outgoing = new Map>(); + const indegree = new Map(); + const neighbors = new Map>(); + for (const { kind, fromConceptId: from, toConceptId: to } of relations) { + if (kind === "prerequisite" && add(outgoing, from, to)) { + indegree.set(to, (indegree.get(to) ?? 0) + 1); + } + if (due.has(from) && due.has(to)) { + add(neighbors, from, to); + if (kind === "confusable") { + add(neighbors, to, from); + } + } + } + // Kahn's algorithm checks the entire prerequisite graph, including non-due concepts. + const queue = [...concepts].filter((id) => !indegree.has(id)); + let visited = 0; + for (const id of queue) { + visited += 1; + for (const dependent of outgoing.get(id) ?? []) { + const remaining = (indegree.get(dependent) ?? 0) - 1; + indegree.set(dependent, remaining); + if (remaining === 0) { + queue.push(dependent); + } + } + } + if (visited !== concepts.size) { + return failure("INVALID_RELATION", "relations"); + } + const counts = new Map(); + for (const [id, related] of neighbors) { + counts.set(id, Math.min(1000, related.size)); + } + return success(counts); +} diff --git a/src/validation/priority.ts b/src/validation/priority.ts new file mode 100644 index 0000000..3fa6e0c --- /dev/null +++ b/src/validation/priority.ts @@ -0,0 +1,148 @@ +import type { Policy } from "../contracts/policies"; +import type { ConceptRelation } from "../contracts/priority"; +import type { ReviewResult } from "../contracts/projections"; +import type { Result } from "../contracts/results"; +import { failure, success } from "../errors"; +import { policyIdentity } from "../events/identity"; +import { isInstant } from "../time/elapsed"; +import { array, arrayLength, identifier, integer, LIMITS, record } from "./limits"; +import { validateReviewResult } from "./projections"; +import type { StringBudget } from "./string-budget"; + +export function validateRankingReview( + policy: Policy, + scopeId: unknown, + input: unknown, + nowMs: unknown, + budget: StringBudget, +): Result { + if (!identifier(scopeId)) { + return failure("INVALID_EVENT", "scopeId"); + } + if (!isInstant(nowMs)) { + return failure("INVALID_TIMESTAMP", "nowMs"); + } + const { scheduling, eligibility } = policy; + if ( + !budget.consume( + scopeId, + policy.algorithmVersion, + policy.policyId, + policy.policyVersion, + scheduling.longProbeAction, + scheduling.dateArithmetic, + ) || + (scheduling.dateArithmetic === "local_calendar_days" && + !budget.consume( + scheduling.calendarProfile.zoneId, + scheduling.calendarProfile.rulesVersion, + )) || + (eligibility && + !budget.consume( + eligibility.eligibilityPolicyVersion, + eligibility.onFailure, + eligibility.onNonqualifying, + )) + ) { + return failure("RESOURCE_LIMIT_EXCEEDED", "policy", LIMITS.aggregateStringLength); + } + const review = validateReviewResult(input, true, budget); + if (!review.ok) { + return review; + } + const { identity, concepts } = review.value; + if (identity.scopeId !== scopeId) { + return failure("SCOPE_MISMATCH", "scopeId"); + } + if (identity.policyIdentity !== policyIdentity(policy)) { + return failure("POLICY_MISMATCH", "policyIdentity"); + } + if (identity.evaluatedAtMs !== nowMs) { + return failure("REBUILD_REQUIRED", "evaluatedAtMs"); + } + const lastStage = policy.scheduling.intervalsDays.length - 1; + for (const concept of concepts) { + // A final-stage miss under the support action forces support until a pass. + // A pass clears both consecutive misses and the forced-support flag, so the + // expected support state is derivable without replaying the observations. + const forcedSupport = + concept.consecutiveMisses > 0 && + concept.stageIndex === lastStage && + scheduling.longProbeAction === "support"; + const expectedSupport = + forcedSupport || concept.consecutiveMisses >= scheduling.supportAfterMisses; + if ( + concept.needsSupport !== expectedSupport || + (!expectedSupport && + ((concept.recommendationKind === "transfer") !== + (concept.scheduleState === "review_ready") || + (concept.recommendationKind === "delayed_retrieval") !== + (concept.scheduleState !== "review_ready" && concept.stageIndex === lastStage))) || + (concept.consecutiveMisses > 0 && + concept.stageIndex !== null && + (concept.stageIndex !== lastStage || scheduling.longProbeAction === "restart")) || + (concept.stageIndex !== null && concept.stageIndex > lastStage) || + (concept.scheduleState === "review_ready" && concept.stageIndex !== lastStage) || + (concept.candidate !== undefined) !== (policy.eligibility !== undefined) || + (concept.dueAtMs === null && + (concept.needsSupport || + concept.consecutiveMisses !== 0 || + concept.advisorySuccesses !== 0)) || + (concept.stageIndex !== null && concept.advisorySuccesses === 0) || + (concept.dueAtMs !== null && concept.advisorySuccesses + concept.consecutiveMisses === 0) + ) { + return failure("INVALID_EVENT", "concepts"); + } + } + return review; +} + +export function validateRankingLimit(input: unknown): Result { + if (input === undefined) { + return success(LIMITS.concepts); + } + return integer(input, 0, LIMITS.concepts) + ? success(input + 0) + : failure("INVALID_EVENT", "limit"); +} + +export function validateRelations( + input: unknown, + concepts: ReadonlySet, + budget: StringBudget, +): Result { + if (input === undefined) { + return success([]); + } + const length = arrayLength(input); + if (length !== null && length > LIMITS.relations) { + return failure("RESOURCE_LIMIT_EXCEEDED", "relations", LIMITS.relations); + } + const entries = array(input, LIMITS.relations); + if (!entries) { + return failure("INVALID_RELATION", "relations"); + } + const relations: ConceptRelation[] = []; + for (const entry of entries) { + const fields = record(entry, ["kind", "fromConceptId", "toConceptId"]); + if (!fields) { + return failure("INVALID_RELATION", "relations"); + } + const { kind, fromConceptId, toConceptId } = fields; + if ( + (kind !== "prerequisite" && kind !== "confusable") || + !identifier(fromConceptId) || + !identifier(toConceptId) || + fromConceptId === toConceptId || + !concepts.has(fromConceptId) || + !concepts.has(toConceptId) + ) { + return failure("INVALID_RELATION", "relations"); + } + if (!budget.consume(kind, fromConceptId, toConceptId)) { + return failure("RESOURCE_LIMIT_EXCEEDED", "relations", LIMITS.aggregateStringLength); + } + relations.push({ kind, fromConceptId, toConceptId }); + } + return success(relations); +} diff --git a/src/validation/projections.ts b/src/validation/projections.ts index 6f07f41..ecde413 100644 --- a/src/validation/projections.ts +++ b/src/validation/projections.ts @@ -10,6 +10,7 @@ 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"; +import type { StringBudget } from "./string-budget"; const maxReasons = LIMITS.distinctEvents * 5; // Derived canonical strings are not individual input labels. Allow worst-case JSON escaping, @@ -101,7 +102,11 @@ function reasonBound(code: unknown): number | null | undefined { } } -function readReasons(input: unknown, remaining: number): Result { +function readReasons( + input: unknown, + remaining: number, + budget?: StringBudget, +): Result { const length = arrayLength(input); if (length !== null && length > remaining) { return failure("RESOURCE_LIMIT_EXCEEDED", "reasons", maxReasons); @@ -121,6 +126,9 @@ function readReasons(input: unknown, remaining: number): Result { const length = arrayLength(input); if (length !== null && length > LIMITS.distinctEvents) { @@ -153,6 +162,9 @@ function readIds( if (!identifier(entry) || ids.has(entry)) { return invalid(field); } + if (budget && !budget.consume(entry)) { + return failure("RESOURCE_LIMIT_EXCEEDED", "review", LIMITS.aggregateStringLength); + } ids.add(entry); } return success(Object.freeze([...ids])); @@ -170,6 +182,7 @@ function readCandidate( input: unknown, evaluatedAtMs: number, remaining: number, + budget?: StringBudget, ): Result { const fields = record(input, [ "readiness", @@ -230,7 +243,10 @@ function readCandidate( ) { return invalid("candidate"); } - const reasons = readReasons(fields.reasons, remaining); + if (budget && !budget.consume(readiness)) { + return failure("RESOURCE_LIMIT_EXCEEDED", "review", LIMITS.aggregateStringLength); + } + const reasons = readReasons(fields.reasons, remaining, budget); if (!reasons.ok) { return reasons; } @@ -251,6 +267,7 @@ function readConcept( input: unknown, evaluatedAtMs: number, remaining: number, + budget?: StringBudget, ): Result { const fields = record( input, @@ -335,7 +352,10 @@ function readConcept( ) { return invalid("concepts"); } - const reasons = readReasons(fields.reasons, remaining); + if (budget && !budget.consume(conceptId, scheduleState, recommendationKind, readiness)) { + return failure("RESOURCE_LIMIT_EXCEEDED", "review", LIMITS.aggregateStringLength); + } + const reasons = readReasons(fields.reasons, remaining, budget); if (!reasons.ok) { return reasons; } @@ -359,12 +379,17 @@ function readConcept( fields.candidate, evaluatedAtMs, remaining - reasons.value.length, + budget, ); 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 { +export function validateReviewResult( + input: unknown, + allowUnorderedConcepts = false, + budget?: StringBudget, +): Result { const fields = record(input, [ "identity", "concepts", @@ -379,11 +404,14 @@ export function validateReviewResult(input: unknown): Result { if (!identity.ok) { return identity; } - const applied = readIds(fields.appliedEventIds, "appliedEventIds"); + if (budget && !budget.consume(identity.value.algorithmVersion, identity.value.scopeId)) { + return failure("RESOURCE_LIMIT_EXCEEDED", "review", LIMITS.aggregateStringLength); + } + const applied = readIds(fields.appliedEventIds, "appliedEventIds", budget); if (!applied.ok) { return applied; } - const controls = readIds(fields.controlEventIds, "controlEventIds"); + const controls = readIds(fields.controlEventIds, "controlEventIds", budget); if (!controls.ok) { return controls; } @@ -399,22 +427,27 @@ export function validateReviewResult(input: unknown): Result { if (!entries) { return invalid("concepts"); } - const lifecycle = readReasons(fields.lifecycleReasons, maxReasons); + const lifecycle = readReasons(fields.lifecycleReasons, maxReasons, budget); if (!lifecycle.ok) { return lifecycle; } let remaining = maxReasons - lifecycle.value.length; const concepts: ConceptProjection[] = []; let previousId: string | null = null; + const seen = new Set(); for (const entry of entries) { - const result = readConcept(entry, identity.value.evaluatedAtMs, remaining); + const result = readConcept(entry, identity.value.evaluatedAtMs, remaining, budget); if (!result.ok) { return result; } const concept = result.value; - if (previousId !== null && concept.conceptId <= previousId) { + if ( + seen.has(concept.conceptId) || + (!allowUnorderedConcepts && previousId !== null && concept.conceptId <= previousId) + ) { return invalid("conceptId"); } + seen.add(concept.conceptId); previousId = concept.conceptId; remaining -= concept.reasons.length + (concept.candidate?.reasons.length ?? 0); concepts.push(concept); diff --git a/src/validation/string-budget.ts b/src/validation/string-budget.ts new file mode 100644 index 0000000..d7606d0 --- /dev/null +++ b/src/validation/string-budget.ts @@ -0,0 +1,17 @@ +import { LIMITS } from "./limits"; + +// One counter per invocation. Only validated ordinary string values reach this helper; +// derived canonical identity encodings retain their separate bounds. +export class StringBudget { + private total = 0; + + consume(...values: readonly string[]): boolean { + for (const value of values) { + this.total += value.length; + if (this.total > LIMITS.aggregateStringLength) { + return false; + } + } + return true; + } +} diff --git a/tests/unit/foundation.test.ts b/tests/unit/foundation.test.ts index 78824af..d61bf1e 100644 --- a/tests/unit/foundation.test.ts +++ b/tests/unit/foundation.test.ts @@ -8,6 +8,7 @@ describe("public entry point", () => { "evaluateReadiness", "explainReview", "rebuildReview", + "scheduleDue", "validateEvents", "validatePolicy", ]); diff --git a/tests/unit/priority.test.ts b/tests/unit/priority.test.ts new file mode 100644 index 0000000..582651b --- /dev/null +++ b/tests/unit/priority.test.ts @@ -0,0 +1,386 @@ +import { describe, expect, it } from "vitest"; +import type { + ConceptProjection, + ConceptRelation, + PracticeObservation, + Result, +} from "../../src/index"; +import { rebuildReview, scheduleDue } from "../../src/index"; +import { elapsedPolicy } from "../fixtures/policy"; + +const day = 86_400_000; +const scope = "scope"; +const now = 10 * day; + +function value(result: Result): T { + if (!result.ok) { + throw new Error(JSON.stringify(result.errors)); + } + return result.value; +} + +function practice( + sequence: number, + conceptId: string, + atMs: number, + outcome: PracticeObservation["outcome"] = "pass", +): PracticeObservation { + return { + schemaVersion: 1, + scopeId: scope, + eventId: `event-${sequence}`, + sequence, + atMs, + conceptId, + sessionId: "session", + kind: "practice_observation", + outcome, + }; +} + +function policy() { + return { ...elapsedPolicy(), priority: { overdue: 2, support: 20, relation: 5, stage: 3 } }; +} + +function history() { + return [ + practice(0, "A", 0), + practice(1, "b", 2 * day), + practice(2, "C", 0, "fail"), + practice(3, "C", day, "fail"), + practice(4, "future", now), + practice(5, "unseen", 0, "not_observed"), + ]; +} + +function edge( + kind: ConceptRelation["kind"], + fromConceptId: string, + toConceptId: string, +): ConceptRelation { + return { kind, fromConceptId, toConceptId }; +} + +describe("due ranking", () => { + it("computes independent scores, directional relations, and fixed reasons", () => { + const input = policy(); + const review = value(rebuildReview(input, scope, history(), now)); + const relations = [ + edge("prerequisite", "A", "b"), + edge("confusable", "A", "b"), + edge("confusable", "b", "A"), + edge("confusable", "A", "C"), + edge("prerequisite", "A", "future"), + edge("prerequisite", "A", "b"), + ]; + const result = value(scheduleDue(input, scope, review, now, relations)); + expect( + result.map(({ conceptId, score, features }) => ({ conceptId, score, features })), + ).toEqual([ + { conceptId: "C", score: 41, features: { overdue: 8, support: 1, relation: 1, stage: 0 } }, + { conceptId: "A", score: 27, features: { overdue: 7, support: 0, relation: 2, stage: 1 } }, + { conceptId: "b", score: 18, features: { overdue: 5, support: 0, relation: 1, stage: 1 } }, + ]); + expect(result[1]?.reasons).toEqual([ + { code: "OVERDUE_DAYS", value: 7 }, + { code: "SUPPORT_NEEDED", value: 0 }, + { code: "RELATED_DUE", value: 2 }, + { code: "REVIEW_STAGE", value: 1 }, + ]); + expect(result[0]?.recommendationKind).toBe("support"); + expect(value(scheduleDue(input, scope, review, now, relations, 2))).toEqual(result.slice(0, 2)); + expect(value(scheduleDue(input, scope, review, now, relations, 0))).toEqual([]); + expect( + value( + scheduleDue( + input, + scope, + { ...review, concepts: [...review.concepts].reverse() }, + now, + [...relations].reverse(), + ), + ), + ).toEqual(result); + expect(Object.isFrozen(result)).toBe(true); + expect(Object.isFrozen(result[0]?.features)).toBe(true); + expect(Object.isFrozen(result[0]?.reasons[0])).toBe(true); + }); + + it("defaults to zero weights and sorts ties by date then ASCII ID, including exact due", () => { + const input = elapsedPolicy(); + const events = [ + practice(0, "z", 0), + practice(1, "a", 0), + practice(2, "Z", 0), + practice(3, "first", -day), + practice(4, "later", 1), + ]; + const review = value(rebuildReview(input, scope, events, 3 * day)); + const ranked = value(scheduleDue(input, scope, review, 3 * day)); + expect(ranked.map((item) => item.conceptId)).toEqual(["first", "Z", "a", "z"]); + expect(ranked.every((item) => item.score === 0)).toBe(true); + expect(ranked[3]?.features.overdue).toBe(0); + expect(value(scheduleDue(input, scope, value(rebuildReview(input, scope, [], 0)), 0))).toEqual( + [], + ); + }); + + it("counts only outgoing prerequisite edges and allows confusability cycles", () => { + const input = policy(); + const review = value(rebuildReview(input, scope, history(), now)); + const ranked = value(scheduleDue(input, scope, review, now, [edge("prerequisite", "A", "b")])); + expect(ranked.find((item) => item.conceptId === "A")?.features.relation).toBe(1); + expect(ranked.find((item) => item.conceptId === "b")?.features.relation).toBe(0); + expect( + scheduleDue(input, scope, review, now, [ + edge("confusable", "A", "b"), + edge("confusable", "b", "C"), + edge("confusable", "C", "A"), + ]).ok, + ).toBe(true); + }); + + it("refuses invalid relations and prerequisite cycles even outside the due queue or at zero limit", () => { + const input = policy(); + const review = value(rebuildReview(input, scope, history(), now)); + const invalid = [ + [edge("prerequisite", "A", "A")], + [edge("confusable", "A", "missing")], + [edge("prerequisite", "future", "unseen"), edge("prerequisite", "unseen", "future")], + [{ ...edge("confusable", "A", "b"), extra: true }], + [{ ...edge("confusable", "A", "b"), kind: "unknown" }], + null, + Array(1), + ]; + for (const relations of invalid) { + expect(scheduleDue(input, scope, review, now, relations, 0)).toEqual({ + ok: false, + errors: [{ code: "INVALID_RELATION", field: "relations" }], + }); + } + expect(scheduleDue(input, scope, review, now, Array(10_001))).toEqual({ + ok: false, + errors: [{ code: "RESOURCE_LIMIT_EXCEEDED", field: "relations", limit: 10_000 }], + }); + }); + + it("rejects stale, mismatched, malformed and duplicate projections and bad limits", () => { + const input = policy(); + const review = value(rebuildReview(input, scope, history(), now)); + expect(scheduleDue(input, scope, review, now + 1)).toEqual({ + ok: false, + errors: [{ code: "REBUILD_REQUIRED", field: "evaluatedAtMs" }], + }); + expect(scheduleDue(input, "other", review, now)).toEqual({ + ok: false, + errors: [{ code: "SCOPE_MISMATCH", field: "scopeId" }], + }); + expect(scheduleDue(elapsedPolicy(), scope, review, now)).toEqual({ + ok: false, + errors: [{ code: "POLICY_MISMATCH", field: "policyIdentity" }], + }); + for (const malformed of [ + { ...review, concepts: [...review.concepts, review.concepts[0]] }, + { ...review, concepts: [{ ...review.concepts[0], stageIndex: 63 }] }, + { ...review, identity: { ...review.identity, algorithmVersion: "2" } }, + { ...review, identity: { ...review.identity, schemaVersion: 2 } }, + { ...review, concepts: [{ ...review.concepts[0], needsSupport: "private-canary" }] }, + ]) { + const result = scheduleDue(input, scope, malformed, now); + expect(result.ok).toBe(false); + expect(JSON.stringify(result)).not.toContain("private-canary"); + } + for (const limit of [-1, 1001, 1.5, NaN, null, "1"]) { + expect(scheduleDue(input, scope, review, now, undefined, limit).ok).toBe(false); + } + expect(scheduleDue(input, scope, review, Infinity).ok).toBe(false); + const relation = { + kind: "confusable", + get fromConceptId() { + throw new Error("must not execute"); + }, + toConceptId: "b", + }; + expect(scheduleDue(input, scope, review, now, [relation]).ok).toBe(false); + }); + + it("rejects contradictory support and probe recommendations in actual replay results", () => { + const input = policy(); + const review = value(rebuildReview(input, scope, history(), now)); + const invalid = { ok: false, errors: [{ code: "INVALID_EVENT", field: "concepts" }] }; + function altered(id: string, fields: Partial) { + return { + ...review, + concepts: review.concepts.map((concept) => + concept.conceptId === id ? { ...concept, ...fields } : concept, + ), + }; + } + expect( + scheduleDue( + input, + scope, + altered("C", { needsSupport: false, recommendationKind: "ordinary" }), + now, + ), + ).toEqual(invalid); + expect( + scheduleDue( + input, + scope, + altered("A", { needsSupport: true, recommendationKind: "support" }), + now, + ), + ).toEqual(invalid); + expect( + scheduleDue(input, scope, altered("A", { recommendationKind: "transfer" }), now), + ).toEqual(invalid); + expect( + scheduleDue(input, scope, altered("A", { recommendationKind: "delayed_retrieval" }), now), + ).toEqual(invalid); + }); + + it.each(["support", "keep", "restart"] as const)( + "validates final-stage and maintenance recommendations under %s", + (action) => { + const input = policy(); + input.scheduling.intervalsDays = [1]; + input.scheduling.longProbeAction = action; + input.scheduling.supportAfterMisses = 3; + const clock = 100 * day; + for (const maintained of [false, true]) { + const passes = maintained + ? [practice(0, "A", 0), practice(1, "A", day)] + : [practice(0, "A", 0)]; + const before = value(rebuildReview(input, scope, passes, clock)); + const kind = maintained ? "transfer" : "delayed_retrieval"; + expect(value(scheduleDue(input, scope, before, clock))[0]?.recommendationKind).toBe(kind); + expect( + scheduleDue( + input, + scope, + { + ...before, + concepts: before.concepts.map((concept) => ({ + ...concept, + recommendationKind: "ordinary", + })), + }, + clock, + ).ok, + ).toBe(false); + const failed = value( + rebuildReview(input, scope, [...passes, practice(2, "A", 2 * day, "fail")], clock), + ); + const ranked = value(scheduleDue(input, scope, failed, clock)); + expect(ranked[0]?.features.support).toBe(action === "support" ? 1 : 0); + expect(ranked[0]?.recommendationKind).toBe( + action === "support" ? "support" : action === "restart" ? "ordinary" : kind, + ); + const tampered = { + ...failed, + concepts: failed.concepts.map((concept) => ({ + ...concept, + needsSupport: action !== "support", + recommendationKind: action === "support" ? kind : "support", + })), + }; + expect(scheduleDue(input, scope, tampered, clock).ok).toBe(false); + const reset = value( + rebuildReview( + input, + scope, + [...passes, practice(2, "A", 2 * day, "fail"), practice(3, "A", 3 * day)], + clock, + ), + ); + expect(value(scheduleDue(input, scope, reset, clock))[0]?.features.support).toBe(0); + } + }, + ); + + it("enforces one aggregate string budget across a real review and duplicate raw relations", () => { + const input = policy(); + const ids = Array.from({ length: 1000 }, (_, index) => `c-${index}`.padEnd(128, "x")); + const events = Array.from({ length: 10_000 }, (_, index) => ({ + ...practice(index, ids[index % ids.length] as string, 0), + eventId: `event-${index}`.padEnd(128, "x"), + })); + const review = value(rebuildReview(input, scope, events, now)); + const relation = edge("confusable", ids[0] as string, ids[1] as string); + + // Independent count of ordinary JSON string values; derived identity encodings + // are separately bounded. Each raw relation contributes 266 code units. + function stringUnits(input: unknown): number { + if (typeof input === "string") { + return input.length; + } + if (input !== null && typeof input === "object") { + return Object.values(input).reduce((total: number, item) => total + stringUnits(item), 0); + } + return 0; + } + const ordinaryReview = { + ...review, + identity: { ...review.identity, policyIdentity: "", watermark: "" }, + }; + const remaining = 4_000_000 - stringUnits(input) - scope.length - stringUnits(ordinaryReview); + const maximum = Math.floor(remaining / stringUnits(relation)); + expect(maximum).toBeGreaterThan(0); + expect(maximum).toBeLessThan(10_000); + const within = Array.from({ length: maximum }, () => relation); + expect(value(scheduleDue(input, scope, review, now, within, 0))).toEqual([]); + expect(scheduleDue(input, scope, review, now, [...within, relation], 0)).toEqual({ + ok: false, + errors: [{ code: "RESOURCE_LIMIT_EXCEEDED", field: "relations", limit: 4_000_000 }], + }); + expect( + scheduleDue( + input, + scope, + review, + now, + Array.from({ length: 10_000 }, () => relation), + ).ok, + ).toBe(false); + }); + + it("caps elapsed days safely for opposite-end instants and bounds score", () => { + const input = { + ...elapsedPolicy(), + priority: { overdue: 1000, support: 1000, relation: 1000, stage: 1000 }, + }; + const edgeMs = 8_640_000_000_000_000; + const review = value(rebuildReview(input, scope, [practice(0, "A", -edgeMs)], edgeMs)); + const ranked = value(scheduleDue(input, scope, review, edgeMs)); + expect(ranked[0]?.features.overdue).toBe(3650); + expect(ranked[0]?.score).toBe(3_651_000); + }); + + it("handles the bounded queue and relation graph without recursive traversal", () => { + const input = policy(); + const ids = Array.from({ length: 1000 }, (_, index) => `c-${index}`); + const events = ids.map((id, index) => practice(index, id, 0)); + const review = value(rebuildReview(input, scope, events, now)); + const relations: ConceptRelation[] = []; + for (let from = 0; from < 1000; from += 1) { + for (let offset = 1; offset <= 10; offset += 1) { + relations.push(edge("confusable", `c-${from}`, `c-${(from + offset) % 1000}`)); + } + } + const ranked = value(scheduleDue(input, scope, review, now, relations, 1000)); + expect(ranked).toHaveLength(1000); + expect(ranked.every((item) => item.features.relation === 20)).toBe(true); + const chain = Array.from({ length: 999 }, (_, index) => + edge("prerequisite", `c-${index}`, `c-${index + 1}`), + ); + expect(scheduleDue(input, scope, review, now, chain).ok).toBe(true); + expect( + scheduleDue(input, scope, review, now, [...chain, edge("prerequisite", "c-999", "c-0")]).ok, + ).toBe(false); + expect(scheduleDue(input, scope, { ...review, concepts: Array(1001) }, now)).toEqual({ + ok: false, + errors: [{ code: "RESOURCE_LIMIT_EXCEEDED", field: "concepts", limit: 1000 }], + }); + }); +});