From 44535adeca4c6195af9728a5a54f0874ca454aa0 Mon Sep 17 00:00:00 2001 From: "Christopher S. Aondona" Date: Sun, 29 Nov 2026 20:08:29 +0100 Subject: [PATCH 1/3] fix: align existing skills with released contracts and prepare Retention catalog --- .github/workflows/validate.yml | 4 +++- AGENTS.md | 11 +++++++++-- README.md | 25 ++++++++++++++++++++++++- skills/assay/SKILL.md | 6 +++--- skills/assay/references/api.md | 4 ++-- skills/assay/references/observations.md | 2 +- skills/preceptor/SKILL.md | 6 +++--- skills/preceptor/references/memory.md | 2 +- skills/preceptor/references/sessions.md | 2 +- 9 files changed, 47 insertions(+), 15 deletions(-) diff --git a/.github/workflows/validate.yml b/.github/workflows/validate.yml index b998913..3087dca 100644 --- a/.github/workflows/validate.yml +++ b/.github/workflows/validate.yml @@ -63,13 +63,15 @@ jobs: - name: Test version-bump enforcement run: node --test scripts/check-versions.test.mjs - name: Install released product packages for tests - run: npm install --no-save --no-package-lock --ignore-scripts @0xbuff/throughline@0.0.2 @0xbuff/assay@0.0.1 @0xbuff/preceptor@0.0.2 + run: npm install --no-save --no-package-lock --ignore-scripts @0xbuff/throughline@0.0.2 @0xbuff/assay@0.0.2 @0xbuff/preceptor@0.0.2 @0xbuff/retention@0.0.2 - name: Test example diagrams run: node scripts/smoke-throughline.mjs - name: Test Assay examples and contract boundaries run: node scripts/smoke-assay.mjs - name: Test Preceptor examples and contract boundaries run: node scripts/smoke-preceptor.mjs + - name: Test Retention examples and contract boundaries + run: node scripts/smoke-retention.mjs - name: Check skills CLI run: npx --yes skills add . --list - name: Verify Claude Code and Codex installation for all skills diff --git a/AGENTS.md b/AGENTS.md index cb6a58a..9044a25 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -48,7 +48,7 @@ Do not add empty optional directories, shared runtime dependencies, or cross-ski ## Assay contract -- Assay targets `@0xbuff/assay@0.0.1`, schema 4, evaluator semantics v0.0.5 and composed-required-v1. +- Assay targets `@0xbuff/assay@0.0.2`, schema 4, evaluator semantics v0.0.5 and composed-required-v1. - Keep all runnable examples synthetic and preserve host-owned authorization, execution, evidence authenticity and disclosure. Never equate technical evaluation with formal grading. - Update `evals/assay.json` and `scripts/smoke-assay.mjs` when changing observable guidance. Keep the documented package version independent from the skill version. @@ -58,6 +58,12 @@ Do not add empty optional directories, shared runtime dependencies, or cross-ski - Preserve host-owned authority, assessment locks, bounded dispatch, scoped memory and committed-summary separation. Do not imply advisory output confers credit. - Keep fixtures synthetic, and update `evals/preceptor.json` and `scripts/smoke-preceptor.mjs` when changing observable guidance. +## Retention contract + +- Retention targets `@0xbuff/retention@0.0.2`, schema 1 and algorithm version `"1"`. +- Keep practice scheduling separate from independently admitted credited evidence and candidate readiness. The host owns evidence admission, history, authorization, delivery and physical erasure. +- Keep examples synthetic and update `evals/retention.json` and `scripts/smoke-retention.mjs` when changing observable guidance. + ## Verification Run from the repository root: @@ -66,10 +72,11 @@ Run from the repository root: node scripts/check-skill.mjs node --test scripts/check-skill.test.mjs scripts/check-versions.test.mjs node scripts/check-versions.mjs -npm install --no-save --no-package-lock --ignore-scripts @0xbuff/throughline@0.0.2 @0xbuff/assay@0.0.1 @0xbuff/preceptor@0.0.2 +npm install --no-save --no-package-lock --ignore-scripts @0xbuff/throughline@0.0.2 @0xbuff/assay@0.0.2 @0xbuff/preceptor@0.0.2 @0xbuff/retention@0.0.2 node scripts/smoke-throughline.mjs node scripts/smoke-assay.mjs node scripts/smoke-preceptor.mjs +node scripts/smoke-retention.mjs npx --yes skills add . --list ``` diff --git a/README.md b/README.md index c551708..b7681be 100644 --- a/README.md +++ b/README.md @@ -8,6 +8,7 @@ A collection of self-contained [Agent Skills](https://agentskills.io) for buildi | --- | --- | --- | | [Assay](skills/assay/SKILL.md) | Define, evaluate, validate, and integrate technical assessments. | `npx skills add https://github.com/0xbuffdev/skills --skill assay` | | [Preceptor](skills/preceptor/SKILL.md) | Plan instruction and integrate scoped model assistance, memory and committed summaries. | `npx skills add https://github.com/0xbuffdev/skills --skill preceptor` | +| [Retention](skills/retention/SKILL.md) | Schedule reviews, reconcile learning history and evaluate advisory candidate readiness. | `npx skills add https://github.com/0xbuffdev/skills --skill retention` | | [Throughline](skills/throughline/SKILL.md) | Author, compile, validate, and embed step-by-step Throughline visualizations. | `npx skills add https://github.com/0xbuffdev/skills --skill throughline` | ### Assay @@ -26,7 +27,7 @@ Install the runtime separately in the consuming project: npm install @0xbuff/assay ``` -The skill targets `@0xbuff/assay@0.0.1` (Node.js 24+ ESM, schema 4). Its local references and runnable examples cover evaluation, observation acquisition, protected expectations and public projection. See [the skill](skills/assay/SKILL.md) and [Assay documentation](https://docs.0xbuff.com/docs/assay). +The skill targets `@0xbuff/assay@0.0.2` (Node.js 24+ ESM, schema 4). Its local references and runnable examples cover evaluation, observation acquisition, protected expectations and public projection. See [the skill](skills/assay/SKILL.md) and [Assay documentation](https://docs.0xbuff.com/docs/assay). ### Preceptor @@ -44,6 +45,24 @@ npm install @0xbuff/preceptor The skill targets `@0xbuff/preceptor@0.0.2` (Node.js 24+ ESM). Its references and examples cover model-free planning, scoped ports, narrative memory and committed host feedback. See [the skill](skills/preceptor/SKILL.md) and [Preceptor documentation](https://docs.0xbuff.com/docs/preceptor). +### Retention + +Retention calculates review dates and ranks due concepts from learning observations. It can also evaluate candidate readiness from independently admitted credited evidence. + +Install the skill: + +```sh +npx skills add https://github.com/0xbuffdev/skills --skill retention +``` + +Install the runtime in the consuming project: + +```sh +npm install @0xbuff/retention +``` + +The skill targets `@0xbuff/retention@0.0.2` (Node.js 24+ ESM; compatible ES2022 browser builds). Its references and examples cover policies, event replay, due ranking and advisory readiness. See [the skill](skills/retention/SKILL.md) and [Retention documentation](https://docs.0xbuff.com/docs/retention). + ### Throughline Install the skill for your coding agent: @@ -75,6 +94,10 @@ The skill targets `@0xbuff/throughline@0.0.2`; the interactive player additional │ │ ├── SKILL.md │ │ ├── references/ │ │ └── assets/ +│ ├── retention/ +│ │ ├── SKILL.md +│ │ ├── references/ +│ │ └── assets/ │ └── throughline/ │ ├── SKILL.md # Required skill entry point │ ├── references/ # Detailed usage guides, read as needed diff --git a/skills/assay/SKILL.md b/skills/assay/SKILL.md index b09309a..25b26e4 100644 --- a/skills/assay/SKILL.md +++ b/skills/assay/SKILL.md @@ -1,17 +1,17 @@ --- name: assay description: Build, validate, debug, and integrate technical assessments with @0xbuff/assay. Use when defining versioned criteria, comparing evidence, composing required checks, collecting execution facts, adding human or model advisory reviews, handling protected references, or projecting public assessment results with Assay. -compatibility: Node.js 24+ ESM for @0xbuff/assay@0.0.1. +compatibility: Node.js 24+ ESM for @0xbuff/assay@0.0.2. metadata: author: 0xBUFF - version: "0.1.0" + version: "0.1.1" --- # Assay Assay compares technical evidence against explicit, versioned criteria and returns reproducible findings. Use it to check results in assessment systems, engineering exercises and other tools. -This skill targets package `0.0.1`, schema `4`, evaluator semantics `v0.0.5`, and policy `composed-required-v1`. Check the project's installed package and lockfile before using these contracts. Do not silently upgrade, downgrade or reinterpret another schema. Install with the project's package manager if Assay is absent (for npm, `npm install @0xbuff/assay`). Import from the package root. +This skill targets package `0.0.2`, schema `4`, evaluator semantics `v0.0.5`, and policy `composed-required-v1`. Check the project's installed package and lockfile before using these contracts. Do not silently upgrade, downgrade or reinterpret another schema. If Assay is absent and installation is appropriate for the task, use the project's package manager and the verified version (npm: `npm install @0xbuff/assay@0.0.2`). Import from the package root. ## Workflow diff --git a/skills/assay/references/api.md b/skills/assay/references/api.md index 05b9ac0..7af2643 100644 --- a/skills/assay/references/api.md +++ b/skills/assay/references/api.md @@ -1,6 +1,6 @@ # API and validation -All public imports come from @0xbuff/assay. Schema 4, package 0.0.1, evaluator v0.0.5 and composed-required-v1 are separate identities. +All public imports come from @0xbuff/assay. Schema 4, package 0.0.2, evaluator v0.0.5 and composed-required-v1 are separate identities. | Function or constant | Purpose | | --- | --- | @@ -21,7 +21,7 @@ Creators, verification and structural parsers return ValidationResult: ok true w Evaluate returns a complete result for pass/fail/inconclusive/evaluation_error with schemaVersion, definition, evidenceDigest, optional artifactDigest, outcome, policyVersion, findings, evaluator and warnings. Each finding has criterionId, outcome, reasonCode, evidenceRefs, evaluatorId and evaluatorVersion. -Invalid_definition, invalid_reference and invalid_evidence are separate failures with outcome and diagnostics only, not findings. Definition is verified first, then the supplied reference bundle, then evidence. +invalid_definition, invalid_reference and invalid_evidence are separate failures with outcome and diagnostics only, not findings. Definition is verified first, then the supplied reference bundle, then evidence. | Finding outcome | Reasons | | --- | --- | diff --git a/skills/assay/references/observations.md b/skills/assay/references/observations.md index 1f2c52a..ccd3728 100644 --- a/skills/assay/references/observations.md +++ b/skills/assay/references/observations.md @@ -4,7 +4,7 @@ Call `createEvidenceBundle(definition, { schemaVersion: 4, observations, artifactDigest? })` (omit the optional property when absent). The creator supplies definition lineage and evidenceDigest. Each observation has criterionId, unique evidenceRef, completeness (complete/truncated), kind, and its value fields. Match the criterion's kind. Text, number, boolean and JSON use value; number can have unit; set uses items and itemType. Execution assertions use runRef and assertions with assertionId/state (confirmed/refuted/unknown). Manual observations use artifactRefs. -Missing means omitted, not null or zero. Truncated observations are not passes. An artifact-scoped bundle requires origins on each observation; artifact origins bind the exact digest, independent origins omit the digest. Unscoped observations cannot claim artifact scope. Do not mutate sealed records. Correct and reseal using authorized data. +Omit a missing observation. Do not substitute null or zero for an unavailable value; both can be legitimate observed values. Truncated observations are not passes. An artifact-scoped bundle requires origins on each observation; artifact origins bind the exact digest, independent origins omit the digest. Unscoped observations cannot claim artifact scope. Do not mutate sealed records. Correct and reseal using authorized data. ## Selected execution facts diff --git a/skills/preceptor/SKILL.md b/skills/preceptor/SKILL.md index 92c1fa5..a876754 100644 --- a/skills/preceptor/SKILL.md +++ b/skills/preceptor/SKILL.md @@ -4,14 +4,14 @@ description: Build, validate, debug, and integrate instructional planning and mo compatibility: Node.js 24+ ESM for @0xbuff/preceptor@0.0.2. metadata: author: 0xBUFF - version: "0.1.0" + version: "0.1.1" --- # Preceptor Preceptor selects instructional strategies and coordinates optional model assistance. Its outputs are advisory. The host authenticates the learner, authorizes operations and owns academic decisions. -This skill targets package `0.0.2`, policy `preceptor-policy-v1` and summary schema `preceptor-summary-v1`. Inspect the consuming project's installed version and lockfile first. Do not silently change versions or invent APIs. If absent, install using the project's package manager (npm: `npm install @0xbuff/preceptor`) and verify compatibility. Import from the package root. +This skill targets package `0.0.2`, policy `preceptor-policy-v1` and summary schema `preceptor-summary-v1`. Inspect the consuming project's installed version and lockfile first. Do not silently change versions or invent APIs. If Preceptor is absent and installation is appropriate for the task, use the project's package manager and the verified version (npm: `npm install @0xbuff/preceptor@0.0.2`). Import from the package root. ## Workflow @@ -65,7 +65,7 @@ Copy the complete example assets into the consuming project before running them ## Non-negotiable boundaries -- In `assessment_locked`, return only fixed public process guidance; no model, lesson, memory, practice or summary adapter calls. Defense preparation permits only public assessment criteria and denies memory writes. +- In `assessment_locked`, return only fixed public process guidance; no model, lesson, memory, practice or summary adapter calls. In defense preparation, lesson access is limited to public assessment criteria, and memory mutations are denied. - Model output requests typed operations; it never supplies authority, storage identity, arbitrary RPC, executable callbacks or provider auto-execution. Unknown and denied attempts consume budget. - Never fall back to another lesson revision or reveal protected assessment material. Structural validation is not authentication. - Keep transcripts, narrative facts, official committed decisions and scheduling separate. Do not convert Assay technical findings or model advice into academic credit, admission, grade writes or scheduling commitments. diff --git a/skills/preceptor/references/memory.md b/skills/preceptor/references/memory.md index 77ef923..70792e1 100644 --- a/skills/preceptor/references/memory.md +++ b/skills/preceptor/references/memory.md @@ -6,7 +6,7 @@ Keep narrative facts (struggle, preference, observation) separate from official MemoryPort methods are optional async functions: -- recall(query, signal): query has optional topic, limit and maxFactBytes. Return kind facts, facts array and completeness complete/truncated, or kind unavailable with reason denied, unavailable or transient. +- recall(query, signal): query has optional topic and required limit and maxFactBytes. Distinguish this adapter query from the model's recall arguments, where limit is optional. Return kind facts, facts array and completeness complete/truncated, or kind unavailable with reason denied, unavailable or transient. - remember(proposal, invocation, signal): proposal action create or update, kind and text; update includes factId and expectedRevision. - forget(request, invocation, signal): request contains factId and expectedRevision. diff --git a/skills/preceptor/references/sessions.md b/skills/preceptor/references/sessions.md index 14b8784..902de0d 100644 --- a/skills/preceptor/references/sessions.md +++ b/skills/preceptor/references/sessions.md @@ -4,7 +4,7 @@ Call `await runInstruction(host, request, ports, options)`. SessionRequest contains assistance, text, optional intent, history and limits. SessionOptions contains optional limits, requiredLesson, summary authorization and signal. Supply plain data, not proxies. History is complete alternating learner/assistant pairs. -A ModelPort declares provider and model strings plus async generate(input, signal). The input contains policy (revision, mode, strategy, fixed next actions), context (learner text, history, toolResults, optional committedSummary), tools (descriptors) and remaining limits. Keep trusted policy distinct from all retrieved or generated text. Map provider outputs into the closed ModelResponse contract and keep credentials inside the adapter. +A ModelPort declares provider and model strings plus async generate(input, signal). The input contains policy (revision, mode, strategy, fixed next actions), context (learner text, history, toolResults, optional committedSummary), tools (descriptors) and remaining limits (`remaining`). Keep trusted policy distinct from all retrieved or generated text. Map provider outputs into the closed ModelResponse contract and keep credentials inside the adapter. Every response includes attribution matching the port's provider/model. Optional usage has inputTokens/outputTokens; these are informational. From 4cd3313a7d3b20cf242a1e573493cf46529d5df9 Mon Sep 17 00:00:00 2001 From: "Christopher S. Aondona" Date: Sun, 29 Nov 2026 20:10:31 +0100 Subject: [PATCH 2/3] feat: add self-contained Retention agent skill and validation fixtures --- evals/retention.json | 89 ++++++++++++++++++++++ scripts/smoke-retention.mjs | 69 +++++++++++++++++ skills/retention/SKILL.md | 94 ++++++++++++++++++++++++ skills/retention/assets/priority.mjs | 40 ++++++++++ skills/retention/assets/readiness.mjs | 68 +++++++++++++++++ skills/retention/assets/replay.mjs | 39 ++++++++++ skills/retention/assets/scheduling.mjs | 39 ++++++++++ skills/retention/references/api.md | 57 ++++++++++++++ skills/retention/references/policies.md | 34 +++++++++ skills/retention/references/ranking.md | 18 +++++ skills/retention/references/readiness.md | 29 ++++++++ skills/retention/references/replay.md | 38 ++++++++++ 12 files changed, 614 insertions(+) create mode 100644 evals/retention.json create mode 100644 scripts/smoke-retention.mjs create mode 100644 skills/retention/SKILL.md create mode 100644 skills/retention/assets/priority.mjs create mode 100644 skills/retention/assets/readiness.mjs create mode 100644 skills/retention/assets/replay.mjs create mode 100644 skills/retention/assets/scheduling.mjs create mode 100644 skills/retention/references/api.md create mode 100644 skills/retention/references/policies.md create mode 100644 skills/retention/references/ranking.md create mode 100644 skills/retention/references/readiness.md create mode 100644 skills/retention/references/replay.md diff --git a/evals/retention.json b/evals/retention.json new file mode 100644 index 0000000..daf1b17 --- /dev/null +++ b/evals/retention.json @@ -0,0 +1,89 @@ +{ + "skill_name": "retention", + "evals": [ + { + "id": 1, + "prompt": "Use Retention to calculate the first due review for a binary search concept after a practice pass.", + "expected_output": "Uses root exports, versioned policy, explicit clock and scoped event, checks ok, returns due queue only at or after due time.", + "files": [], + "should_trigger": true + }, + { + "id": 2, + "prompt": "Build spaced review scheduling in my learning app using @0xbuff/retention. An early pass should advance the interval.", + "expected_output": "Preserves early pass stage and due time; due pass advances; tests retry and support rules.", + "files": [], + "should_trigger": true + }, + { + "id": 3, + "prompt": "Implement Retention local calendar reviews across a daylight-saving transition.", + "expected_output": "Uses caller-provided calendarProfile with coverage and sorted transitions; distinguishes elapsed and civil days; tests gap/fold and insufficient coverage.", + "files": [], + "should_trigger": true + }, + { + "id": 4, + "prompt": "I want to pass only the latest Retention event to advanceReview, without the prior history.", + "expected_output": "Requires exact prior identity and complete prior history; explicit rebuild if incompatible; no partial state.", + "files": [], + "should_trigger": true + }, + { + "id": 5, + "prompt": "Use Retention to revoke a credited decision, correct a prior one and delete an event that has not arrived.", + "expected_output": "Preserves durable sequence, exact successor versions, original effective time, tombstone and full replay; no physical erasure claim.", + "files": [], + "should_trigger": true + }, + { + "id": 6, + "prompt": "A practice pass has fresh=true, hints=0 and ladder=3. Count it as a qualifying credited success.", + "expected_output": "Keeps practice scheduling separate; only independently admitted credited evidence qualifies; no automatic credit.", + "files": [], + "should_trigger": true + }, + { + "id": 7, + "prompt": "I have two qualifying Retention passes in the same session. Make candidate_ready by waiting a day.", + "expected_output": "Checks distinct session and actual first/last qualifying span; waiting alone cannot satisfy thresholds; candidate advisory.", + "files": [], + "should_trigger": true + }, + { + "id": 8, + "prompt": "Rank Retention due items by overdue time, support and prerequisite relations. Skip validation when limit is zero.", + "expected_output": "Uses same policy scope clock; validates relations even at zero limit; deterministic score and ties; prerequisites do not block review.", + "files": [], + "should_trigger": true + }, + { + "id": 9, + "prompt": "Can I log the Retention watermark as a harmless hash and trust it as authentication?", + "expected_output": "Explains canonical history JSON contains event data; protect it and authenticate independently.", + "files": [], + "should_trigger": true + }, + { + "id": 10, + "prompt": "My Retention review was computed yesterday, but I want to use it for today's due queue.", + "expected_output": "Rebuilds at explicit current clock; checks failures and stale generation; no fabricated implicit time.", + "files": [], + "should_trigger": true + }, + { + "id": 11, + "prompt": "Write a marketing customer retention campaign for a SaaS product.", + "expected_output": "Does not activate the learning review scheduling skill.", + "files": [], + "should_trigger": false + }, + { + "id": 12, + "prompt": "Use Preceptor to choose a tutoring prompt and retrieve a lesson.", + "expected_output": "Does not activate Retention unless review scheduling is also requested.", + "files": [], + "should_trigger": false + } + ] +} diff --git a/scripts/smoke-retention.mjs b/scripts/smoke-retention.mjs new file mode 100644 index 0000000..f0d9fed --- /dev/null +++ b/scripts/smoke-retention.mjs @@ -0,0 +1,69 @@ +import assert from "node:assert/strict"; +import { execFileSync } from "node:child_process"; +import { readFileSync } from "node:fs"; +import { fileURLToPath } from "node:url"; +import * as retention from "@0xbuff/retention"; + +const root = fileURLToPath(new URL("../", import.meta.url)); +const skill = new URL("../skills/retention/", import.meta.url); +const source = readFileSync(new URL("SKILL.md", skill), "utf8"); +const example = source.match(/^\x60{3}js\n([\s\S]*?)^\x60{3}$/m)?.[1]; +assert.ok(example, "Missing inline minimal example"); +const run = (args, input) => execFileSync(process.execPath, args, { + cwd: root, input, encoding: "utf8", timeout: 10_000, +}).trim(); +assert.equal(run(["--input-type=module"], example), "binary-search 86400000 ordinary"); +for (const [file, output] of [ + ["scheduling.mjs", "86400000 345600000"], + ["replay.mjs", "1 DUE_PASS"], + ["readiness.mjs", "developing 1 candidate_ready 2"], + ["priority.mjs", "binary-search:5 sorting:0"], +]) assert.equal(run([fileURLToPath(new URL("assets/" + file, skill))]), output, file); + +const { validatePolicy, validateEvents, rebuildReview, advanceReview, evaluateReadiness, scheduleDue, explainReview } = retention; +const api = readFileSync(new URL("references/api.md", skill), "utf8"); +for (const name of Object.keys(retention)) assert.match(api, new RegExp("\\b" + name + "\\b")); +const day = 86_400_000; +const policy = { schemaVersion: 1, algorithmVersion: "1", policyId: "deck", policyVersion: "v1", + scheduling: { intervalsDays: [1, 3, 7], retryDays: 1, maintenanceDays: 30, + supportAfterMisses: 2, longProbeAction: "restart", dateArithmetic: "elapsed_milliseconds" } }; +const event = { schemaVersion: 1, kind: "practice_observation", scopeId: "deck", conceptId: "binary-search", + eventId: "review-1", sequence: 0, atMs: 0, sessionId: "session-1", outcome: "pass" }; +function unwrap(result) { assert.equal(result.ok, true, JSON.stringify(result)); return result.value; } +function fails(result) { assert.equal(result.ok, false); assert.ok(result.errors.length); } +unwrap(validatePolicy(policy)); +fails(validatePolicy({ ...policy, scheduling: { ...policy.scheduling, intervalsDays: [0] } })); +assert.equal(unwrap(validateEvents("deck", [event, { ...event }])).length, 1); +fails(validateEvents("deck", [event, { ...event, outcome: "fail" }])); +fails(validateEvents("other", [event])); +const initial = unwrap(rebuildReview(policy, "deck", [event], day - 1)); +assert.equal(unwrap(scheduleDue(policy, "deck", initial, day - 1)).length, 0); +fails(scheduleDue(policy, "deck", initial, day)); +const due = unwrap(rebuildReview(policy, "deck", [event], day)); +assert.equal(unwrap(scheduleDue(policy, "deck", due, day))[0].conceptId, "binary-search"); +assert.equal(unwrap(scheduleDue(policy, "deck", due, day, [], 0)).length, 0); +fails(scheduleDue(policy, "deck", due, day, [{ kind: "prerequisite", fromConceptId: "binary-search", toConceptId: "binary-search" }], 0)); +const appended = [{ ...event, eventId: "review-2", sequence: 1, atMs: day }]; +const next = unwrap(advanceReview(policy, "deck", due.identity, [event], appended, day)); +assert.deepEqual(next, unwrap(rebuildReview(policy, "deck", [event, ...appended], day))); +fails(advanceReview(policy, "deck", due.identity, [], appended, day)); +assert.equal(unwrap(explainReview(next)).concepts[0].practiceReasons.at(-1).code, "DUE_PASS"); +const deletion = { schemaVersion: 1, kind: "review_event_deletion", scopeId: "deck", conceptId: "binary-search", + eventId: "delete-1", sequence: 1, atMs: day, targetEventId: event.eventId }; +const removed = unwrap(rebuildReview(policy, "deck", [event, deletion], day)); +assert.equal(removed.appliedEventIds.length, 0); +assert.equal(removed.concepts[0].scheduleState, "unobserved"); +const eligible = { ...policy, eligibility: { eligibilityPolicyVersion: "v1", minSuccesses: 1, minSessions: 1, + minSpanMs: 0, requireFresh: true, maxHints: 0, minLadder: 3, onFailure: "reset", onNonqualifying: "ignore" } }; +const practice = { ...event, fresh: true, hints: 0, ladder: 3 }; +const candidate = unwrap(evaluateReadiness(eligible, "deck", "binary-search", [practice], day)); +assert.equal(candidate.readiness, "unknown"); +assert.equal(candidate.qualifyingSuccesses, 0); +const credit = { ...practice, kind: "eligible_credited_retrieval", eventId: "credit-1", sequence: 1, + creditDecisionId: "decision-1", decisionVersion: 1, eligibilityPolicyVersion: "v1" }; +assert.equal(unwrap(evaluateReadiness(eligible, "deck", "binary-search", [practice, credit], day)).readiness, "candidate_ready"); +const revoke = { schemaVersion: 1, kind: "credited_decision_revocation", scopeId: "deck", conceptId: "binary-search", + eventId: "revoke-1", sequence: 2, atMs: day, supersedesDecisionId: credit.creditDecisionId, reasonCode: "fixture" }; +assert.equal(unwrap(evaluateReadiness(eligible, "deck", "binary-search", [practice, credit, revoke], day)).readiness, "unknown"); +assert.equal(unwrap(evaluateReadiness(policy, "deck", "binary-search", [practice], day)), null); +console.log("Retention examples, exports, policy, identity, replay, ranking, deletion and eligibility checks passed."); diff --git a/skills/retention/SKILL.md b/skills/retention/SKILL.md new file mode 100644 index 0000000..07ba6a2 --- /dev/null +++ b/skills/retention/SKILL.md @@ -0,0 +1,94 @@ +--- +name: retention +description: Build, validate, debug, and integrate learning review schedules with @0xbuff/retention. Use when implementing spaced retrieval, due review queues, review policies, practice observations, credited evidence, history replay, corrections or deletions, candidate readiness, or deterministic review ranking in learning applications. +compatibility: Node.js 24+ ESM or an ES2022-compatible browser build for @0xbuff/retention@0.0.2. +metadata: + author: 0xBUFF + version: "0.1.0" +--- + +# Retention + +Retention calculates when concepts are due for review, when learners need support and which due reviews to prioritize. It also evaluates advisory candidate readiness from independently admitted credited evidence. Your application owns records, authorization, evidence admission and official decisions. + +This skill targets package `0.0.2`, schema `1` and algorithm version `"1"`. Inspect the installed package and lockfile. Do not silently upgrade, downgrade or assume another version has identical contracts. If absent and installation is appropriate, use the project's package manager (npm: `npm install @0xbuff/retention@0.0.2`). Import from the package root. + +## Workflow + +1. Identify the authenticated scope, concept IDs, complete relevant event history, explicit clock in Unix milliseconds and review policy. Keep ordinary practice separate from credited evidence. +2. Choose the intervals, retry, maintenance and support rules. Validate the policy with `validatePolicy`; read [scheduling and policies](references/policies.md) for calendar arithmetic and transitions. +3. Construct inert events with unique durable IDs and sequences. Use `validateEvents` for structural and identity checks. Read [events and replay](references/replay.md) before implementing corrections, revocations, deletion or incremental updates. +4. Call `rebuildReview(policy, scopeId, events, nowMs)` with complete history. Check `ok` before using the value. Use `advanceReview` only with the exact prior identity and complete prior history; rebuild explicitly when that identity is incompatible. +5. Use `scheduleDue` with the same policy, scope, result and clock. Read [ranking](references/ranking.md) before adding weights or relations. Use `explainReview` for structured reason codes. +6. If advisory readiness is needed, configure eligibility and independently admit credited evidence in the host. Read [readiness](references/readiness.md). Never convert practice results or model advice into credited evidence automatically. +7. Test actual installed exports with synthetic histories. Check first and early reviews, due transitions, invalid events, correction or deletion, stale identities, ranking ties and practice/credit separation as applicable. Report only checks actually run. + +## Minimal example + +Save as `review.mjs` in the consuming project. This fixture uses a practice pass at Unix time zero and an illustrative one-day first interval. + +```js +import { rebuildReview, scheduleDue } from "@0xbuff/retention"; + +const day = 86_400_000; +const policy = { + schemaVersion: 1, + algorithmVersion: "1", + policyId: "deck", + policyVersion: "v1", + scheduling: { + intervalsDays: [1, 3, 7], + retryDays: 1, + maintenanceDays: 30, + supportAfterMisses: 2, + longProbeAction: "restart", + dateArithmetic: "elapsed_milliseconds", + }, +}; + +const event = { + schemaVersion: 1, + kind: "practice_observation", + scopeId: "deck", + conceptId: "binary-search", + eventId: "review-1", + sequence: 0, + atMs: 0, + sessionId: "session-1", + outcome: "pass", +}; + +function value(result) { + if (!result.ok) throw new Error(JSON.stringify(result.errors)); + return result.value; +} + +const review = value(rebuildReview(policy, "deck", [event], day)); +const due = value(scheduleDue(policy, "deck", review, day)); +console.log(due[0].conceptId, due[0].dueAtMs, due[0].recommendationKind); +``` + +Run `node review.mjs`. Expected output: `binary-search 86400000 ordinary`. Before the due instant the queue is empty. The example requires no database, external service or eligibility policy. + +## Choose the integration + +| Task | Read or run | +| --- | --- | +| Configure intervals, support or local calendar rules | [Policies and scheduling](references/policies.md), [early review fixture](assets/scheduling.mjs) | +| Validate events, reconcile corrections or advance a schedule | [Events and replay](references/replay.md), [advance fixture](assets/replay.mjs) | +| Assess candidate readiness | [Readiness](references/readiness.md), [credited evidence fixture](assets/readiness.mjs) | +| Rank due concepts | [Ranking](references/ranking.md), [weighted queue fixture](assets/priority.mjs) | +| Inspect return types, limits or errors | [API and diagnostics](references/api.md) | + +Copy complete assets into the consuming project before running so imports resolve against its package. They contain synthetic data, not evidence of authenticated credit. + +## Boundaries + +- Retention does not authenticate events, own a database, deliver notifications, issue credit or certify mastery. The host authorizes each scope, admits evidence and rejects stale generations. +- A practice pass can affect scheduling but never candidate eligibility. A credited tag alone cannot prove evidence was admitted. Preserve independent host decisions. +- Always pass the explicit clock and complete relevant history. Never substitute a partial history, silently change policy identity or treat a watermark as proof of authenticity. +- A replay watermark contains event data. Do not log or disclose raw histories or watermarks. Deletion controls suppress replay; the host remains responsible for physical erasure and backups. +- Enforce transport size and shape limits before materializing untrusted data. Closed validation is not a sandbox for hostile JavaScript objects. +- A failed result has no partial authoritative projection. Keep host records unchanged and surface safe diagnostics. + +Deliver integration code or a concrete diagnostic, with expected results, verification evidence and remaining host responsibilities. diff --git a/skills/retention/assets/priority.mjs b/skills/retention/assets/priority.mjs new file mode 100644 index 0000000..5af4aad --- /dev/null +++ b/skills/retention/assets/priority.mjs @@ -0,0 +1,40 @@ +import { rebuildReview, scheduleDue } from "@0xbuff/retention"; + +const day = 86_400_000; +const policy = { + schemaVersion: 1, + algorithmVersion: "1", + policyId: "deck", + policyVersion: "v1", + scheduling: { + intervalsDays: [1, 3, 7], + retryDays: 1, + maintenanceDays: 30, + supportAfterMisses: 2, + longProbeAction: "restart", + dateArithmetic: "elapsed_milliseconds", + }, +}; +const event = { + schemaVersion: 1, + kind: "practice_observation", + scopeId: "deck", + conceptId: "binary-search", + eventId: "review-1", + sequence: 0, + atMs: 0, + sessionId: "session-1", + outcome: "pass", +}; +function value(result) { + if (!result.ok) throw new Error(JSON.stringify(result.errors)); + return result.value; +} + +const weighted = { ...policy, priority: { overdue: 2, support: 0, relation: 5, stage: 0 } }; +const other = { ...event, conceptId: "sorting", eventId: "other", sequence: 1 }; +const review = value(rebuildReview(weighted, "deck", [event, other], day)); +const due = value(scheduleDue(weighted, "deck", review, day, [ + { kind: "prerequisite", fromConceptId: "binary-search", toConceptId: "sorting" }, +])); +console.log(due.map(item => item.conceptId + ":" + item.score).join(" ")); diff --git a/skills/retention/assets/readiness.mjs b/skills/retention/assets/readiness.mjs new file mode 100644 index 0000000..82780a1 --- /dev/null +++ b/skills/retention/assets/readiness.mjs @@ -0,0 +1,68 @@ +import { evaluateReadiness } from "@0xbuff/retention"; + +const day = 86_400_000; +const policy = { + schemaVersion: 1, + algorithmVersion: "1", + policyId: "deck", + policyVersion: "v1", + scheduling: { + intervalsDays: [1, 3, 7], + retryDays: 1, + maintenanceDays: 30, + supportAfterMisses: 2, + longProbeAction: "restart", + dateArithmetic: "elapsed_milliseconds", + }, +}; +const event = { + schemaVersion: 1, + kind: "practice_observation", + scopeId: "deck", + conceptId: "binary-search", + eventId: "review-1", + sequence: 0, + atMs: 0, + sessionId: "session-1", + outcome: "pass", +}; +function value(result) { + if (!result.ok) throw new Error(JSON.stringify(result.errors)); + return result.value; +} + +const eligible = { + ...policy, + eligibility: { + eligibilityPolicyVersion: "v1", + minSuccesses: 2, + minSessions: 2, + minSpanMs: day, + requireFresh: true, + maxHints: 0, + minLadder: 3, + onFailure: "reset", + onNonqualifying: "ignore", + }, +}; +function credited(sequence, atMs) { + return { + ...event, + kind: "eligible_credited_retrieval", + sequence, + atMs, + eventId: "credit-" + sequence, + sessionId: "credited-session-" + sequence, + creditDecisionId: "decision-" + sequence, + decisionVersion: 1, + eligibilityPolicyVersion: "v1", + fresh: true, + hints: 0, + ladder: 3, + }; +} +const first = credited(1, day); +const second = credited(2, 2 * day); +const before = value(evaluateReadiness(eligible, "deck", "binary-search", [event, first], 2 * day)); +const after = value(evaluateReadiness(eligible, "deck", "binary-search", [event, first, second], 2 * day)); +console.log(before.readiness, before.qualifyingSuccesses, after.readiness, after.qualifyingSuccesses); diff --git a/skills/retention/assets/replay.mjs b/skills/retention/assets/replay.mjs new file mode 100644 index 0000000..96c8abb --- /dev/null +++ b/skills/retention/assets/replay.mjs @@ -0,0 +1,39 @@ +import { advanceReview, rebuildReview, explainReview } from "@0xbuff/retention"; + +const day = 86_400_000; +const policy = { + schemaVersion: 1, + algorithmVersion: "1", + policyId: "deck", + policyVersion: "v1", + scheduling: { + intervalsDays: [1, 3, 7], + retryDays: 1, + maintenanceDays: 30, + supportAfterMisses: 2, + longProbeAction: "restart", + dateArithmetic: "elapsed_milliseconds", + }, +}; +const event = { + schemaVersion: 1, + kind: "practice_observation", + scopeId: "deck", + conceptId: "binary-search", + eventId: "review-1", + sequence: 0, + atMs: 0, + sessionId: "session-1", + outcome: "pass", +}; +function value(result) { + if (!result.ok) throw new Error(JSON.stringify(result.errors)); + return result.value; +} + +const prior = [event]; +const first = value(rebuildReview(policy, "deck", prior, day)); +const appended = [{ ...event, eventId: "review-2", sequence: 1, atMs: day }]; +const next = value(advanceReview(policy, "deck", first.identity, prior, appended, day)); +const explanation = value(explainReview(next)); +console.log(next.concepts[0].stageIndex, explanation.concepts[0].practiceReasons.at(-1).code); diff --git a/skills/retention/assets/scheduling.mjs b/skills/retention/assets/scheduling.mjs new file mode 100644 index 0000000..6f34427 --- /dev/null +++ b/skills/retention/assets/scheduling.mjs @@ -0,0 +1,39 @@ +import { rebuildReview } from "@0xbuff/retention"; + +const day = 86_400_000; +const policy = { + schemaVersion: 1, + algorithmVersion: "1", + policyId: "deck", + policyVersion: "v1", + scheduling: { + intervalsDays: [1, 3, 7], + retryDays: 1, + maintenanceDays: 30, + supportAfterMisses: 2, + longProbeAction: "restart", + dateArithmetic: "elapsed_milliseconds", + }, +}; +const event = { + schemaVersion: 1, + kind: "practice_observation", + scopeId: "deck", + conceptId: "binary-search", + eventId: "review-1", + sequence: 0, + atMs: 0, + sessionId: "session-1", + outcome: "pass", +}; +function value(result) { + if (!result.ok) throw new Error(JSON.stringify(result.errors)); + return result.value; +} + +const early = { ...event, eventId: "early", sequence: 1, atMs: day / 2 }; +const onDue = { ...event, eventId: "due", sequence: 2, atMs: day }; +const history = [event, early]; +const before = value(rebuildReview(policy, "deck", history, day)); +const after = value(rebuildReview(policy, "deck", [...history, onDue], day)); +console.log(before.concepts[0].dueAtMs, after.concepts[0].dueAtMs); diff --git a/skills/retention/references/api.md b/skills/retention/references/api.md new file mode 100644 index 0000000..bff59fc --- /dev/null +++ b/skills/retention/references/api.md @@ -0,0 +1,57 @@ +# API and diagnostics + +Import from @0xbuff/retention only. All seven public operations are synchronous. Installed type declarations give exact signatures. + +| Operation | Successful value | +| --- | --- | +| validatePolicy(policy) | Policy | +| validateEvents(scopeId, events) | Distinct validated ReviewEvent array | +| rebuildReview(policy, scopeId, events, nowMs) | ReviewResult | +| advanceReview(policy, scopeId, identity, prior, appended, nowMs) | ReviewResult | +| evaluateReadiness(policy, scopeId, conceptId, events, nowMs) | CandidateProjection or null | +| scheduleDue(policy, scopeId, review, nowMs, relations?, limit?) | DueRecommendation array | +| explainReview(review) | ReviewExplanation | + +Each returns Result: { ok: true, value } or { ok: false, errors }. Diagnostics have code and optional safe field/limit. Do not expose raw data or use codes as user-facing prose. + +| Code | Check | +| --- | --- | +| INVALID_EVENT | Closed event shape and fields | +| SCOPE_MISMATCH | Exact authorized scope | +| EVENT_ID_CONFLICT | Different content under one event ID | +| SEQUENCE_CONFLICT | Different IDs with one sequence | +| INVALID_CORRECTION | Lifecycle target, version, chain | +| MISSING_CORRECTION_TARGET | Earlier credit decision absent | +| INVALID_POLICY | Closed policy and ranges | +| POLICY_MISMATCH | Full policy identity compatibility | +| INVALID_RELATION | Relation shape, endpoint, graph | +| INVALID_TIMESTAMP | Clock or checked arithmetic | +| UNSUPPORTED_VERSION | Schema or algorithm version | +| REBUILD_REQUIRED | Prior identity/history or backward clock | +| CALENDAR_PROFILE_MISMATCH | Calendar coverage or resolution | +| RESOURCE_LIMIT_EXCEEDED | Input or derived bound | + +## Bounds + +| Input | Maximum or range | +| --- | --- | +| Raw event entries | 20000 | +| Distinct events | 10000 | +| Distinct concepts | 1000 | +| Raw relations | 10000 | +| Calendar transitions | 4096 | +| Identifier length | 128 ASCII characters | +| Reason code length | 1 to 256 UTF-16 code units | +| Ordinary aggregate string values | 4000000 UTF-16 code units per applicable operation | +| Intervals | 1 to 64 | +| Interval, retry and maintenance days | 1 to 3650 | +| Support threshold and qualifying successes | 1 to 1000 | +| Hints, ladder and weights | 0 to 1000 | +| Calendar offsets | -1440 to 1440 minutes | +| Unix millisecond instants | -8640000000000000 to 8640000000000000 | + +Identifiers start with ASCII alphanumeric, then letters, digits, period, underscore, colon or hyphen. Sequences are nonnegative safe integers. Derived identity encodings have separate bounds. Raw duplicates count toward applicable aggregate budgets. + +Validate inert plain data with own enumerable data properties and dense ordinary arrays. Reflection on hostile objects can allocate key lists before traversal bounds take effect; reject proxies/getters and enforce serialized admission limits before materialization. Never treat validation as authentication. + +For failure, keep authoritative host records unchanged. Rebuild only from complete authorized history when requested. Test against the actual installed version, not a reimplementation. diff --git a/skills/retention/references/policies.md b/skills/retention/references/policies.md new file mode 100644 index 0000000..db5bc21 --- /dev/null +++ b/skills/retention/references/policies.md @@ -0,0 +1,34 @@ +# Policies and practice scheduling + +Use `validatePolicy(input)` and check ok. The normalized value is detached and immutable. A policy includes schemaVersion: 1, algorithmVersion: "1", policyId, policyVersion and scheduling; eligibility and priority are optional. Do not rely on a version label to identify content. + +## Scheduling fields + +| Field | Contract | +| --- | --- | +| intervalsDays | 1 to 64 ordered positive integer day intervals, each at most 3650 | +| retryDays, maintenanceDays | Integers from 1 to 3650 | +| supportAfterMisses | Integer from 1 to 1000 | +| longProbeAction | restart, support or keep | +| dateArithmetic | elapsed_milliseconds or local_calendar_days | + +Elapsed days are exactly 86,400,000 milliseconds. For local_calendar_days supply scheduling.calendarProfile with zoneId, rulesVersion, coverageStartMs, coverageEndMs, initialOffsetMinutes and transitions (atMs, offsetMinutes). Coverage ends exclusively; transitions are strictly ordered, within coverage, at most 4096. Offsets are integer minutes between -1440 and 1440. The caller supplies timezone rules; no system timezone lookup. A skipped local time shifts through the gap; repeated local times choose the earliest valid instant. Cover the entire possible target window, including shifted targets. Insufficient coverage fails rather than guessing. + +## Practice transitions + +Both active practice and credited observations affect practice scheduling. Process effective-time order after replay. + +| Observation | Effect | +| --- | --- | +| First pass | Stage 0; schedule first interval from observation | +| Early pass | Increment advisory successes, clear misses and forced support; keep stage and due time | +| Pass at or after due time | Advance stage, or enter review_ready and maintenance at final stage | +| Miss before final stage or final-stage restart | Clear stage, enter learning, schedule retry | +| Final-stage miss with support or keep | Retain stage and state, schedule retry; support forces support recommendation | +| not_observed | Update lastSeenAtMs; preserve due and counters; unobserved becomes learning | + +A miss increments consecutive misses. Support activates at the threshold or when forced. A later pass clears misses and forced support. Passing time alone does not create a missed observation. + +Recommendation priority: support, transfer (review_ready), delayed_retrieval (last stage), ordinary. Practice readiness is unknown without pass/fail, review_ready in that state, developing otherwise. It is independent of candidate readiness. + +Test elapsed boundaries, early and due passes, misses, maintenance and calendar gaps/folds with explicit synthetic timestamps. Rebuild after any policy content change, even if the version label stayed the same. diff --git a/skills/retention/references/ranking.md b/skills/retention/references/ranking.md new file mode 100644 index 0000000..b0b035b --- /dev/null +++ b/skills/retention/references/ranking.md @@ -0,0 +1,18 @@ +# Due ranking + +Call `scheduleDue(policy, scopeId, review, nowMs, relations?, limit?)` with a successful rebuild/advance value and the exact matching policy, scope and evaluated clock. Rebuild for a new clock or changed policy. Concept IDs must be unique. Ranking does not replay or authenticate history. + +Only concepts due at or before nowMs are selected. Supply all four integer priority weights (0 to 1000) or omit priority for zero weights. + +| Feature | Value | +| --- | --- | +| overdue | Whole elapsed days overdue, capped at 3650 | +| support | 1 if needsSupport, otherwise 0 | +| relation | Distinct related due concepts, capped at 1000 | +| stage | Stage index plus one, or 0 before a stage | + +Score is the sum of features multiplied by weights. Sort descending score, ascending dueAtMs, then ascending ASCII concept ID. Each recommendation contains conceptId, dueAtMs, recommendationKind, score, features and fixed numeric reasons in feature order. Optional limit is 0 to 1000 and applies after ranking; zero still validates inputs. + +Relations have kind prerequisite or confusable, fromConceptId and toConceptId. Prerequisite points from prerequisite to dependent; count outgoing due dependents. Confusable counts in both directions. Duplicate edges, reversed confusable pairs and overlapping relation kinds cannot double-count a neighbor. All endpoints must exist in the review, even non-due concepts. Reject self-relations and directed prerequisite cycles; confusable cycles are valid. At most 10,000 raw relations. + +Relations only affect ranking. They do not block review, change eligibility or change the schedule. Validate compatible recommendation and support states. Any malformed or incompatible input fails without a partial queue. Keep host delivery, authorization and stale-generation checks outside the library. diff --git a/skills/retention/references/readiness.md b/skills/retention/references/readiness.md new file mode 100644 index 0000000..95f6928 --- /dev/null +++ b/skills/retention/references/readiness.md @@ -0,0 +1,29 @@ +# Candidate readiness + +Use candidate readiness only when the host has independently admitted credited evidence. Neither a practice pass, a model verdict, an assessment technical result nor a watermark establishes official credit. + +## Configure eligibility + +Supply all fields on policy.eligibility: + +| Field | Contract | +| --- | --- | +| eligibilityPolicyVersion | Bounded ASCII identifier | +| minSuccesses | 1 to 1000 | +| minSessions | 1 to minSuccesses | +| minSpanMs | Nonnegative safe integer milliseconds | +| requireFresh | Boolean | +| maxHints, minLadder | 0 to 1000 | +| onFailure, onNonqualifying | reset or ignore | + +A surviving credited pass qualifies if its policy version matches and it meets freshness (if required), hint and ladder thresholds. A matching-version fail uses onFailure. A version mismatch or nonqualifying pass uses onNonqualifying. A practice observation never enters this classification. Reset clears successes, distinct sessions and first/last qualifying timestamps. + +## Evaluate + +Call `evaluateReadiness(policy, scopeId, conceptId, events, nowMs)` with complete relevant scope history. Check ok. Without eligibility, the successful value is null after validation and reconciliation; rebuild omits candidate. With eligibility, no active credited observations means unknown, unmet thresholds mean developing, all thresholds met means candidate_ready. + +CandidateProjection includes readiness, qualifyingSuccesses, distinctSessions, firstQualifyingAtMs, lastQualifyingAtMs, qualifyingSpanMs and reasons. Span measures first to last qualifying success, not the current clock. Waiting cannot make a learner eligible. + +Corrections replace evidence at original effective time; revocations/deletions may reduce a previously ready result. Rebuild with all controls. Treat candidate_ready as advisory only; the host owns admission, decisions and authorization. + +Test ordinary practice with identical metadata, different credited sessions, waiting without another success, threshold failures, version mismatch and correction/revocation/deletion. diff --git a/skills/retention/references/replay.md b/skills/retention/references/replay.md new file mode 100644 index 0000000..068a6f3 --- /dev/null +++ b/skills/retention/references/replay.md @@ -0,0 +1,38 @@ +# Events, lifecycle and replay + +## Event contract + +All events have schemaVersion: 1, kind, scopeId, eventId, sequence and atMs. Except scope deletion, each also has conceptId. Use durable nonnegative safe integer sequences, unique IDs and bounded integer Unix milliseconds. + +| kind | Additional fields | +| --- | --- | +| practice_observation | sessionId, outcome (pass/fail/not_observed); optional fresh, hints, ladder | +| eligible_credited_retrieval | sessionId, outcome (pass/fail), fresh, hints, ladder, eligibilityPolicyVersion, creditDecisionId, decisionVersion: 1 | +| credited_decision_correction | supersedesDecisionId, replacementDecisionId, decisionVersion, replacement (credited evidence fields), reasonCode | +| credited_decision_revocation | supersedesDecisionId, reasonCode | +| review_event_deletion | targetEventId | +| review_scope_deletion | throughSequence | + +Correction replacement contains sessionId, outcome, fresh, hints, ladder and eligibilityPolicyVersion; no event envelope. Corrections require exact successor versions (at least 2). Controls have no outer session or outcome. Scope deletion cutoff is inclusive and strictly below its own sequence. + +`validateEvents(scopeId, events)` checks shapes and identity conflicts, normalizes negative zero, collapses identical canonical duplicates, freezes copied data. Different payloads with one event ID or different IDs with one sequence fail. It does not resolve chains, apply deletion or establish chronological ordering. + +## Reconcile and rebuild + +Call `rebuildReview(policy, scopeId, events, nowMs)`. Retention validates all input, sorts by durable sequence, reconciles controls and replays survivors by effective time, root sequence and ASCII event ID. + +- Corrections replace evidence, decision ID and version at the original effective time and sequence. A revocation removes the active observation. Reused decision IDs, forks, missing earlier targets, wrong versions and cross-concept targets fail. +- Deletion of a root, correction or revocation suppresses its whole credited chain. Scope deletion uses the highest cutoff and root sequence. Unknown event targets remain tombstones; known cross-concept targets or deletion controls cannot be deleted by event deletion. Deletion does not bypass chain integrity checks. +- Future observations are validated but excluded until effective time; future credit corrections and revocations are invalid. Deletion controls apply regardless of timestamps. + +Result identity has schemaVersion, algorithmVersion, scopeId, policyIdentity, evaluatedAtMs and watermark. The watermark is canonical JSON of all distinct validated events in sequence order, including suppressed and future events and tombstones. Protect it as raw history. It does not authenticate evidence or prove completeness. + +The result includes appliedEventIds in replay order, controlEventIds in sequence order, lifecycleReasons and concepts sorted by ASCII ID. Each concept has practice fields and optional candidate. A concept named in history with no surviving observations has an unobserved practice projection; empty history has no concepts. + +## Advance and explain + +`advanceReview(policy, scopeId, identity, prior, appended, nowMs)` verifies the prior identity against complete prior events, then validates and replays the combined history from scratch. Late effective observations and exact duplicates are allowed. Changed policy, incomplete prefix, backward clock or incompatible identity requires explicit rebuild. Raw duplicate entries count toward limits, including across both arrays. Never invent a prior identity or discard suppressed/future events. + +`explainReview(review)` validates the result envelope and returns fixed lifecycle and per-concept practice/candidate reasons with bounded numeric values. It does not rerun history, interpret raw correction prose or authenticate a projection. + +Persist complete history outside the library; apply projections only after checking current host generation. Reconcile control events and invalidate stale delivery. Suppression is not physical deletion. From 6cf28fea9e0552879f8a7218675b9f47c50524b2 Mon Sep 17 00:00:00 2001 From: "Christopher S. Aondona" Date: Sun, 29 Nov 2026 20:11:09 +0100 Subject: [PATCH 3/3] test: cover package version alignment and adapter and replay boundaries --- evals/assay.json | 7 +++++++ evals/preceptor.json | 7 +++++++ scripts/smoke-assay.mjs | 2 ++ scripts/smoke-preceptor.mjs | 20 ++++++++++++++++++++ scripts/smoke-retention.mjs | 9 +++++++++ 5 files changed, 45 insertions(+) diff --git a/evals/assay.json b/evals/assay.json index 7ad5f02..2806205 100644 --- a/evals/assay.json +++ b/evals/assay.json @@ -84,6 +84,13 @@ "expected_output": "Does not activate Assay unless technical assessment is also requested; use Throughline skill.", "files": [], "should_trigger": false + }, + { + "id": 13, + "prompt": "My project already pins Assay 0.0.1. Use the skill to add an evaluation without changing dependencies.", + "expected_output": "Checks the installed version and lockfile; verifies the older contract or asks before changing dependencies; does not silently upgrade to 0.0.2.", + "files": [], + "should_trigger": true } ] } diff --git a/evals/preceptor.json b/evals/preceptor.json index e605c74..1fcd84d 100644 --- a/evals/preceptor.json +++ b/evals/preceptor.json @@ -84,6 +84,13 @@ "expected_output": "Does not select the Preceptor software skill.", "files": [], "should_trigger": false + }, + { + "id": 13, + "prompt": "Connect Preceptor memory recall. The model omits limit; can my adapter assume query.limit and query.maxFactBytes are present?", + "expected_output": "Distinguishes optional model request limit from required bounded adapter query limit and maxFactBytes; binds adapter to authorized scope.", + "files": [], + "should_trigger": true } ] } diff --git a/scripts/smoke-assay.mjs b/scripts/smoke-assay.mjs index e357fe9..237e666 100644 --- a/scripts/smoke-assay.mjs +++ b/scripts/smoke-assay.mjs @@ -10,6 +10,8 @@ import { } from "@0xbuff/assay"; const root = fileURLToPath(new URL("../", import.meta.url)); +const manifest = JSON.parse(readFileSync(new URL("../node_modules/@0xbuff/assay/package.json", import.meta.url), "utf8")); +assert.equal(manifest.version, "0.0.2", "Use the package release targeted by this skill"); const skill = new URL("../skills/assay/", import.meta.url); const source = readFileSync(new URL("SKILL.md", skill), "utf8"); const example = source.match(/^\x60{3}js\n([\s\S]*?)^\x60{3}$/m)?.[1]; diff --git a/scripts/smoke-preceptor.mjs b/scripts/smoke-preceptor.mjs index b3744db..16aa43c 100644 --- a/scripts/smoke-preceptor.mjs +++ b/scripts/smoke-preceptor.mjs @@ -7,6 +7,8 @@ import * as preceptor from "@0xbuff/preceptor"; const { planInstruction, runInstruction, projectCommittedSummary, POLICY_REVISION, SUMMARY_SCHEMA_VERSION, SESSION_LIMITS } = preceptor; const root = fileURLToPath(new URL("../", import.meta.url)); +const manifest = JSON.parse(readFileSync(new URL("../node_modules/@0xbuff/preceptor/package.json", import.meta.url), "utf8")); +assert.equal(manifest.version, "0.0.2", "Use the package release targeted by this skill"); const skill = new URL("../skills/preceptor/", import.meta.url); const source = readFileSync(new URL("SKILL.md", skill), "utf8"); const example = source.match(/^\x60{3}js\n([\s\S]*?)^\x60{3}$/m)?.[1]; @@ -83,6 +85,24 @@ const mismatch = await runInstruction(scoped, { assistance: "generate", text: "H assert.equal(mismatch.status, "incomplete_context"); assert.equal(mismatch.toolOutcomes[0].reason, "source_mismatch"); +const recallHost = { ...host, grants: ["memory.recall"], consent: ["memory.recall"], installed: ["memory.recall"] }; +let recallCalls = 0; +const recalled = await runInstruction(recallHost, { assistance: "generate", text: "Help" }, { + model: { ...attribution, async generate(input) { + if (!input.context.toolResults.length) return { kind: "tools", attribution, + requests: [{ callId: "recall-1", operation: "memory.recall", arguments: {} }] }; + return { kind: "final", attribution, text: "Try an example." }; + } }, + memory: { async recall(query) { + recallCalls++; + assert.ok(Number.isSafeInteger(query.limit) && query.limit >= 0); + assert.ok(Number.isSafeInteger(query.maxFactBytes) && query.maxFactBytes >= 0); + return { kind: "facts", facts: [], completeness: "complete" }; + } }, +}); +assert.equal(recalled.status, "completed"); +assert.equal(recallCalls, 1); + const defence = planInstruction({ ...scoped, mode: "defense_preparation" }, { assistance: "plan" }); assert.equal(defence.status, "completed"); assert.equal(defence.capabilities.includes("lesson.read"), false); diff --git a/scripts/smoke-retention.mjs b/scripts/smoke-retention.mjs index f0d9fed..e375abd 100644 --- a/scripts/smoke-retention.mjs +++ b/scripts/smoke-retention.mjs @@ -5,6 +5,8 @@ import { fileURLToPath } from "node:url"; import * as retention from "@0xbuff/retention"; const root = fileURLToPath(new URL("../", import.meta.url)); +const manifest = JSON.parse(readFileSync(new URL("../node_modules/@0xbuff/retention/package.json", import.meta.url), "utf8")); +assert.equal(manifest.version, "0.0.2", "Use the package release targeted by this skill"); const skill = new URL("../skills/retention/", import.meta.url); const source = readFileSync(new URL("SKILL.md", skill), "utf8"); const example = source.match(/^\x60{3}js\n([\s\S]*?)^\x60{3}$/m)?.[1]; @@ -62,6 +64,13 @@ assert.equal(candidate.qualifyingSuccesses, 0); const credit = { ...practice, kind: "eligible_credited_retrieval", eventId: "credit-1", sequence: 1, creditDecisionId: "decision-1", decisionVersion: 1, eligibilityPolicyVersion: "v1" }; assert.equal(unwrap(evaluateReadiness(eligible, "deck", "binary-search", [practice, credit], day)).readiness, "candidate_ready"); +const correction = { schemaVersion: 1, kind: "credited_decision_correction", scopeId: "deck", conceptId: "binary-search", + eventId: "correct-1", sequence: 2, atMs: day, supersedesDecisionId: credit.creditDecisionId, + replacementDecisionId: "decision-2", decisionVersion: 2, reasonCode: "fixture", + replacement: { sessionId: credit.sessionId, outcome: "fail", fresh: true, hints: 0, ladder: 3, eligibilityPolicyVersion: "v1" } }; +const corrected = unwrap(evaluateReadiness(eligible, "deck", "binary-search", [practice, credit, correction], day)); +assert.equal(corrected.readiness, "developing"); +assert.equal(corrected.qualifyingSuccesses, 0); const revoke = { schemaVersion: 1, kind: "credited_decision_revocation", scopeId: "deck", conceptId: "binary-search", eventId: "revoke-1", sequence: 2, atMs: day, supersedesDecisionId: credit.creditDecisionId, reasonCode: "fixture" }; assert.equal(unwrap(evaluateReadiness(eligible, "deck", "binary-search", [practice, credit, revoke], day)).readiness, "unknown");