Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -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.
6 changes: 3 additions & 3 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
7 changes: 4 additions & 3 deletions docs/architecture.md
Original file line number Diff line number Diff line change
Expand Up @@ -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.
Expand All @@ -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.
4 changes: 2 additions & 2 deletions docs/policies.md
Original file line number Diff line number Diff line change
Expand Up @@ -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

Expand Down
30 changes: 30 additions & 0 deletions docs/priority.md
Original file line number Diff line number Diff line change
@@ -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.
2 changes: 2 additions & 0 deletions docs/replay.md
Original file line number Diff line number Diff line change
Expand Up @@ -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.
11 changes: 10 additions & 1 deletion scripts/verify-dist.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -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"
) {
Expand Down Expand Up @@ -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.");
28 changes: 28 additions & 0 deletions src/contracts/priority.ts
Original file line number Diff line number Diff line change
@@ -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[];
};
2 changes: 2 additions & 0 deletions src/contracts/results.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,8 @@ export type ErrorCode =
| "INVALID_CORRECTION"
| "MISSING_CORRECTION_TARGET"
| "INVALID_POLICY"
| "POLICY_MISMATCH"
| "INVALID_RELATION"
| "INVALID_TIMESTAMP"
| "UNSUPPORTED_VERSION"
| "REBUILD_REQUIRED"
Expand Down
7 changes: 7 additions & 0 deletions src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,12 @@ export type {
PriorityWeights,
SchedulingPolicy,
} from "./contracts/policies";
export type {
ConceptRelation,
DueRecommendation,
PriorityFeatures,
PriorityReason,
} from "./contracts/priority";
export type {
CandidateProjection,
CandidateReadiness,
Expand All @@ -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";
Expand Down
52 changes: 52 additions & 0 deletions src/priority/features.ts
Original file line number Diff line number Diff line change
@@ -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))),
});
}
74 changes: 74 additions & 0 deletions src/priority/rank.ts
Original file line number Diff line number Diff line change
@@ -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<readonly DueRecommendation[]> {
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)));
}
Loading