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 @@ -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.
8 changes: 4 additions & 4 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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

Expand All @@ -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
Expand Down
16 changes: 9 additions & 7 deletions docs/architecture.md
Original file line number Diff line number Diff line change
@@ -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.
2 changes: 1 addition & 1 deletion docs/events.md
Original file line number Diff line number Diff line change
@@ -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";
Expand Down
8 changes: 4 additions & 4 deletions docs/policies.md
Original file line number Diff line number Diff line change
@@ -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";
Expand All @@ -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 = {
Expand All @@ -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.

Expand Down
23 changes: 22 additions & 1 deletion docs/replay.md
Original file line number Diff line number Diff line change
@@ -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.

Expand All @@ -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 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.
35 changes: 34 additions & 1 deletion scripts/verify-dist.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -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"
) {
Expand Down Expand Up @@ -75,4 +80,32 @@ 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.");
Loading