From dff689415819ed34a4eeb8fe6d25f9a7234be3f4 Mon Sep 17 00:00:00 2001 From: "Christopher S. Aondona" Date: Sun, 29 Nov 2026 13:35:29 +0100 Subject: [PATCH] feat: add Preceptor agent skill and executable verification --- .github/workflows/validate.yml | 4 +- AGENTS.md | 9 +- README.md | 21 +++++ evals/preceptor.json | 89 ++++++++++++++++++ scripts/smoke-preceptor.mjs | 111 +++++++++++++++++++++++ skills/preceptor/SKILL.md | 75 +++++++++++++++ skills/preceptor/assets/memory.mjs | 61 +++++++++++++ skills/preceptor/assets/model.mjs | 28 ++++++ skills/preceptor/assets/summary.mjs | 29 ++++++ skills/preceptor/references/api.md | 61 +++++++++++++ skills/preceptor/references/memory.md | 25 +++++ skills/preceptor/references/policy.md | 27 ++++++ skills/preceptor/references/sessions.md | 41 +++++++++ skills/preceptor/references/summaries.md | 28 ++++++ 14 files changed, 607 insertions(+), 2 deletions(-) create mode 100644 evals/preceptor.json create mode 100644 scripts/smoke-preceptor.mjs create mode 100644 skills/preceptor/SKILL.md create mode 100644 skills/preceptor/assets/memory.mjs create mode 100644 skills/preceptor/assets/model.mjs create mode 100644 skills/preceptor/assets/summary.mjs create mode 100644 skills/preceptor/references/api.md create mode 100644 skills/preceptor/references/memory.md create mode 100644 skills/preceptor/references/policy.md create mode 100644 skills/preceptor/references/sessions.md create mode 100644 skills/preceptor/references/summaries.md diff --git a/.github/workflows/validate.yml b/.github/workflows/validate.yml index 033c661..b998913 100644 --- a/.github/workflows/validate.yml +++ b/.github/workflows/validate.yml @@ -63,11 +63,13 @@ 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 + 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 - 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: 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 36aad7b..cb6a58a 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -52,6 +52,12 @@ Do not add empty optional directories, shared runtime dependencies, or cross-ski - 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. +## Preceptor contract + +- Preceptor targets `@0xbuff/preceptor@0.0.2`, policy `preceptor-policy-v1` and summary schema `preceptor-summary-v1`. +- 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. + ## Verification Run from the repository root: @@ -60,9 +66,10 @@ 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 +npm install --no-save --no-package-lock --ignore-scripts @0xbuff/throughline@0.0.2 @0xbuff/assay@0.0.1 @0xbuff/preceptor@0.0.2 node scripts/smoke-throughline.mjs node scripts/smoke-assay.mjs +node scripts/smoke-preceptor.mjs npx --yes skills add . --list ``` diff --git a/README.md b/README.md index 4639b7e..c551708 100644 --- a/README.md +++ b/README.md @@ -7,6 +7,7 @@ A collection of self-contained [Agent Skills](https://agentskills.io) for buildi | Skill | Purpose | Install | | --- | --- | --- | | [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` | | [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 @@ -27,6 +28,22 @@ 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). +### Preceptor + +Preceptor selects instructional strategies and coordinates optional model assistance. Install the skill: + +```sh +npx skills add https://github.com/0xbuffdev/skills --skill preceptor +``` + +Install the runtime in the consuming project: + +```sh +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). + ### Throughline Install the skill for your coding agent: @@ -54,6 +71,10 @@ The skill targets `@0xbuff/throughline@0.0.2`; the interactive player additional │ │ ├── SKILL.md │ │ ├── references/ │ │ └── assets/ +│ ├── preceptor/ +│ │ ├── SKILL.md +│ │ ├── references/ +│ │ └── assets/ │ └── throughline/ │ ├── SKILL.md # Required skill entry point │ ├── references/ # Detailed usage guides, read as needed diff --git a/evals/preceptor.json b/evals/preceptor.json new file mode 100644 index 0000000..e605c74 --- /dev/null +++ b/evals/preceptor.json @@ -0,0 +1,89 @@ +{ + "skill_name": "preceptor", + "evals": [ + { + "id": 1, + "prompt": "Build a model-free tutor that asks a learner to predict the next step using @0xbuff/preceptor.", + "expected_output": "Uses POLICY_REVISION, empty grants/consent/installed, guided_learning and question intent, checks completed and fixed_prompt; no model or storage.", + "files": [], + "should_trigger": true + }, + { + "id": 2, + "prompt": "Integrate an LLM with Preceptor that retrieves the currently authorized lesson before giving a hint.", + "expected_output": "Injects ModelPort, matching attribution, exact LessonReference, scoped adapter and signal, closed lesson.read request with unique callId and empty arguments; verifies byte count/revision and checks result status.", + "files": [], + "should_trigger": true + }, + { + "id": 3, + "prompt": "Let the AI tutor answer questions during a locked assessment by enabling lesson and memory grants.", + "expected_output": "Preserves assessment_locked mode; no adapter or model invocation despite grants; fixed public process guidance only.", + "files": [], + "should_trigger": true + }, + { + "id": 4, + "prompt": "Use Preceptor in defense preparation with a restricted rubric and save the learner's mistakes.", + "expected_output": "Denies restricted lesson material and memory mutations; public assessment criteria only; advisory rehearsal, no formal credit.", + "files": [], + "should_trigger": true + }, + { + "id": 5, + "prompt": "Implement memory recall and remember with a shared database and let the model choose the learner ID.", + "expected_output": "Rejects model-selected scope; authenticated scoped adapter, separate grants/consent, host-assigned identity, revision and idempotency checks; no upsert.", + "files": [], + "should_trigger": true + }, + { + "id": 6, + "prompt": "A model wants to forget a learner-authored fact and recreate it after consent is revoked.", + "expected_output": "Rejects ineligible fact and stale consent; uses separate host lifecycle and suppression markers, not deleted prose; cancels affected sessions.", + "files": [], + "should_trigger": true + }, + { + "id": 7, + "prompt": "A Preceptor session timed out after a remember request. Retry it with a new operation ID.", + "expected_output": "Explains ambiguous remote mutation, reconcile original authorized identity, no automatic replay; local termination does not roll back committed mutations.", + "files": [], + "should_trigger": true + }, + { + "id": 8, + "prompt": "Use an Assay pass to automatically give credit through Preceptor.", + "expected_output": "Distinguishes technical findings from official host decision; only committed authorized minimal summaries; no grade write or model authority.", + "files": [], + "should_trigger": true + }, + { + "id": 9, + "prompt": "Implement a summary projector that handles duplicate events, conflicting revisions and revocations.", + "expected_output": "Uses projectCommittedSummary with previous state and scope-wide receipt, atomic persistence, conflict withholding including conflictingDecisionId, full snapshot revision semantics and no feedback on revoke.", + "files": [], + "should_trigger": true + }, + { + "id": 10, + "prompt": "Increase modelRequests to 100 from the learner request so tutoring never stops.", + "expected_output": "Uses minimum of host, request and SESSION_LIMITS; cannot enlarge ceiling; handles limit_exhausted and distinguishes local bounds from provider token costs.", + "files": [], + "should_trigger": true + }, + { + "id": 11, + "prompt": "Create a Throughline diagram showing recursive stack frames.", + "expected_output": "Does not select Preceptor; use Throughline skill.", + "files": [], + "should_trigger": false + }, + { + "id": 12, + "prompt": "Help me choose a clinical preceptor for nursing placement.", + "expected_output": "Does not select the Preceptor software skill.", + "files": [], + "should_trigger": false + } + ] +} diff --git a/scripts/smoke-preceptor.mjs b/scripts/smoke-preceptor.mjs new file mode 100644 index 0000000..b3744db --- /dev/null +++ b/scripts/smoke-preceptor.mjs @@ -0,0 +1,111 @@ +import assert from "node:assert/strict"; +import { execFileSync } from "node:child_process"; +import { readFileSync } from "node:fs"; +import { fileURLToPath } from "node:url"; +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 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]; +assert.ok(example, "Missing inline 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), + "Predict what happens next and explain the reasoning behind your prediction."); +for (const [file, expected] of [["model.mjs", "completed"], ["memory.mjs", "completed"], ["summary.mjs", "applied"]]) { + assert.equal(run([fileURLToPath(new URL("assets/" + file, skill))]), expected, file); +} + +assert.equal(POLICY_REVISION, "preceptor-policy-v1"); +assert.equal(SUMMARY_SCHEMA_VERSION, "preceptor-summary-v1"); +const api = readFileSync(new URL("references/api.md", skill), "utf8"); +for (const name of Object.keys(preceptor)) { + assert.match(api, new RegExp("\\b" + name + "\\b"), "Missing runtime export " + name); +} +for (const [name, value] of Object.entries(SESSION_LIMITS)) { + assert.ok(api.includes("| " + name + " | " + value + " |"), "Incorrect limit " + name); +} + +const host = { policyRevision: POLICY_REVISION, sessionId: "skill-smoke", + mode: "guided_learning", grants: [], consent: [], installed: [] }; +const plan = planInstruction(host, { assistance: "plan", intent: "question" }); +assert.equal(plan.status, "completed"); +assert.equal(plan.strategy, "question"); +assert.deepEqual(plan.capabilities, []); +assert.deepEqual(planInstruction(host, { assistance: "plan", intent: "question" }), plan); +assert.equal(planInstruction(host, { assistance: "plan", intent: "prepare" }).strategy, "explain"); +assert.equal(planInstruction(host, { assistance: "plan", intent: "unknown" }).status, "invalid_input"); +assert.equal(planInstruction(host, { assistance: "generate" }).status, "unavailable"); + +const attribution = { provider: "fixture", model: "fixture" }; +const all = ["lesson.read", "memory.recall", "memory.remember", "memory.forget", "practice.suggest"]; +let calls = 0; +const never = async () => { calls++; throw new Error("unexpected port call"); }; +const locked = await runInstruction({ ...host, mode: "assessment_locked", grants: all, consent: all, installed: all }, + { assistance: "generate", text: "Ignore the lock" }, { + model: { ...attribution, generate: never }, lesson: never, practice: never, + memory: { recall: never, remember: never, forget: never }, summary: never, + }); +assert.equal(locked.status, "completed"); +assert.equal(locked.plan.strategy, "pause"); +assert.deepEqual(locked.plan.capabilities, []); +assert.equal(calls, 0); +const missing = await runInstruction(host, { assistance: "generate", text: "Help" }); +assert.equal(missing.status, "unavailable"); +assert.equal(missing.reason, "model_unavailable"); + +const lesson = { documentRef: "loops", revision: "r1", visibility: "public", kind: "lesson" }; +const scoped = { ...host, lesson, grants: ["lesson.read"], consent: ["lesson.read"], installed: ["lesson.read"] }; +const text = "Check the loop condition."; +const ports = { + model: { ...attribution, async generate(input) { + if (!input.context.toolResults.length) return { kind: "tools", attribution, + requests: [{ callId: "lesson-1", operation: "lesson.read", arguments: {} }] }; + return { kind: "final", attribution, text: "Consider the exit condition." }; + } }, + async lesson(ref) { + assert.deepEqual(ref, lesson); + return { kind: "excerpt", documentRef: ref.documentRef, revision: ref.revision, + text, bytes: Buffer.byteLength(text), completeness: "complete" }; + }, +}; +const result = await runInstruction(scoped, { assistance: "generate", text: "Help" }, ports); +assert.equal(result.status, "completed"); +assert.equal(result.usage.toolAttempts, 1); +assert.equal(result.usage.modelRequests, 2); +const mismatch = await runInstruction(scoped, { assistance: "generate", text: "Help" }, { + ...ports, async lesson(ref) { return { ...await ports.lesson(ref), revision: "r2" }; }, +}); +assert.equal(mismatch.status, "incomplete_context"); +assert.equal(mismatch.toolOutcomes[0].reason, "source_mismatch"); + +const defence = planInstruction({ ...scoped, mode: "defense_preparation" }, { assistance: "plan" }); +assert.equal(defence.status, "completed"); +assert.equal(defence.capabilities.includes("lesson.read"), false); +const abort = new AbortController(); +abort.abort(); +const cancelled = await runInstruction(host, { assistance: "generate", text: "Help" }, + { model: { ...attribution, generate: never } }, { signal: abort.signal }); +assert.equal(cancelled.status, "cancelled"); +assert.equal(calls, 0); + +const auth = { scopeRef: "scope", decisionId: "decision", sourceRef: "source", + courseRef: "course", outcomeRef: "outcome", sourcePolicyRevision: "1", consent: true }; +const event = { scopeRef: auth.scopeRef, decisionId: auth.decisionId, sourceRef: auth.sourceRef, + courseRef: auth.courseRef, outcomeRef: auth.outcomeRef, sourcePolicyRevision: auth.sourcePolicyRevision, + schemaVersion: SUMMARY_SCHEMA_VERSION, committed: true, eventId: "event-1", revision: 1, + disposition: "credited", feedback: "Practice the loop." }; +const initial = projectCommittedSummary(auth, undefined, event); +assert.equal(initial.status, "applied"); +assert.equal(projectCommittedSummary(auth, initial.projection, event, initial.receipt).status, "duplicate"); +const { feedback, ...rest } = event; +const revoked = projectCommittedSummary(auth, initial.projection, { ...rest, eventId: "event-2", + revision: 2, supersedesRevision: 1, disposition: "revoked" }); +assert.equal(revoked.status, "revoked"); +assert.equal(revoked.projection.status, "revoked"); +assert.equal("summary" in revoked.projection, false); +console.log("Preceptor examples, exports, limits, policy, scoped lesson, cancellation and summary boundaries passed."); diff --git a/skills/preceptor/SKILL.md b/skills/preceptor/SKILL.md new file mode 100644 index 0000000..92c1fa5 --- /dev/null +++ b/skills/preceptor/SKILL.md @@ -0,0 +1,75 @@ +--- +name: preceptor +description: Build, validate, debug, and integrate instructional planning and model-assisted tutoring with @0xbuff/preceptor. Use when selecting teaching strategies, enforcing instructional modes or assessment locks, implementing model or lesson adapters, handling scoped learner memory, or projecting committed academic feedback through Preceptor. +compatibility: Node.js 24+ ESM for @0xbuff/preceptor@0.0.2. +metadata: + author: 0xBUFF + version: "0.1.0" +--- + +# 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. + +## Workflow + +1. Identify the teaching goal, trusted host mode, exact lesson revision (if relevant), and whether the task needs a fixed prompt or generated advice. Keep learner input separate from authority. +2. Construct the host policy from authenticated application state. Grant only operations within the mode ceiling, current consent and actual installed adapters. Start with empty capability lists. +3. Use `planInstruction` for deterministic guidance or `runInstruction` for bounded sessions. For mode and strategy selection, read [policy](references/policy.md). +4. Add only needed ports. Read [sessions](references/sessions.md) before connecting models, lesson retrieval or practice suggestions. Bind adapters to authenticated scope and forward cancellation. +5. If narrative memory or committed host feedback is needed, read [memory](references/memory.md) or [summaries](references/summaries.md) before implementing storage or ingestion. These are separate boundaries, not shared mastery state. +6. Handle every relevant status, inspect usage and provenance, and preserve mutation receipts. Use [API and limits](references/api.md) to diagnose invalid inputs and exhausted budgets. +7. Test the consuming project using the actual installed package. Exercise allowed and denied operations, locked mode with zero adapter calls, malformed inputs, and relevant cancellation or revision conflicts. Report checks actually run and host obligations still unresolved. + +## Minimal example + +Save as `instruction.mjs` in the consuming project. No model, credentials or network are needed after installation. + +```js +import { planInstruction, POLICY_REVISION } from "@0xbuff/preceptor"; + +const host = { + policyRevision: POLICY_REVISION, + sessionId: "example", + mode: "guided_learning", + grants: [], + consent: [], + installed: [], +}; + +const result = planInstruction(host, { + assistance: "plan", + intent: "question", +}); +if (result.status !== "completed" || result.strategy !== "question") { + throw new Error("Expected a model-free question plan"); +} +console.log(result.nextActions[0]?.text); +``` + +Run `node instruction.mjs`. Expected output: `Predict what happens next and explain the reasoning behind your prediction.` Change the intent to `hint` for a different fixed prompt. Neither prompt claims to have inspected work or lesson content. + +## Choose the integration + +| Task | Read or run | +| --- | --- | +| Choose mode, strategy and permissions | [Policy](references/policy.md) | +| Generate advice or retrieve a lesson | [Sessions](references/sessions.md), [model fixture](assets/model.mjs) | +| Recall or mutate narrative learner facts | [Memory](references/memory.md), [recall fixture](assets/memory.mjs) | +| Project or read committed feedback | [Summaries](references/summaries.md), [projection fixture](assets/summary.mjs) | +| Diagnose status, exports or limits | [API and limits](references/api.md) | + +Copy the complete example assets into the consuming project before running them so imports resolve against its installed package. Fixtures are synthetic, not production providers or authentication implementations. + +## 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. +- 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. +- Do not automatically retry ambiguous mutations. Host admission, idempotency, consent, deletion, transport limits and remote costs are host responsibilities. +- Missing model or context is explicit, not fabricated success. A fixed prompt is not generated feedback. Do not claim an adapter or skill evaluation passed without evidence. + +Deliver code or a concrete diagnostic, with expected results and the distinction between library guarantees and host responsibilities. diff --git a/skills/preceptor/assets/memory.mjs b/skills/preceptor/assets/memory.mjs new file mode 100644 index 0000000..de7f57c --- /dev/null +++ b/skills/preceptor/assets/memory.mjs @@ -0,0 +1,61 @@ +import { POLICY_REVISION, runInstruction } from "@0xbuff/preceptor"; + +const host = { + policyRevision: POLICY_REVISION, + sessionId: "example-session", + mode: "guided_learning", + grants: ["memory.recall"], + consent: ["memory.recall"], + installed: ["memory.recall"], +}; + +// This synthetic read-only fixture represents an already authorized host scope. +const fact = { + factId: "example-fact", + kind: "preference", + text: "Prefers small worked examples.", + actor: "learner", + revision: 1, + sourceRef: "example-source", +}; +const memory = { + recall: async (query) => { + const fits = + query.limit > 0 && + new TextEncoder().encode(JSON.stringify(fact)).length <= query.maxFactBytes; + return { + kind: "facts", + facts: fits ? [fact] : [], + completeness: fits ? "complete" : "truncated", + }; + }, +}; + +const model = { + provider: "example", + model: "offline", + generate: async (input) => { + const attribution = { provider: "example", model: "offline" }; + if (input.context.toolResults.length === 0) + return { + kind: "tools", + attribution, + requests: [{ callId: "recall", operation: "memory.recall", arguments: { limit: 1 } }], + }; + return { kind: "final", attribution, text: "Try a small worked example." }; + }, +}; + +const result = await runInstruction( + host, + { assistance: "generate", text: "Help me practice" }, + { memory, model }, +); +if ( + result.status !== "completed" || + result.usage.memoryItems !== 1 || + result.usage.toolAttempts !== 1 || + result.usage.modelRequests !== 2 +) + throw new Error("Expected one recalled fact and an advisory result"); +console.log(result.status); diff --git a/skills/preceptor/assets/model.mjs b/skills/preceptor/assets/model.mjs new file mode 100644 index 0000000..b73532c --- /dev/null +++ b/skills/preceptor/assets/model.mjs @@ -0,0 +1,28 @@ +import { POLICY_REVISION, runInstruction } from "@0xbuff/preceptor"; + +const host = { + policyRevision: POLICY_REVISION, + sessionId: "example", + mode: "guided_learning", + grants: [], + consent: [], + installed: [], +}; +const model = { + provider: "example", + model: "fixture", + generate: async () => ({ + kind: "final", + attribution: { provider: "example", model: "fixture" }, + text: "Explain the principle in your own words, then compare it with an example.", + }), +}; + +const result = await runInstruction( + host, + { assistance: "generate", text: "Help me study" }, + { model }, +); +if (result.status !== "completed" || result.usage.modelRequests !== 1 || !result.advisory) + throw new Error("Expected an attributed advisory result"); +console.log(result.status); diff --git a/skills/preceptor/assets/summary.mjs b/skills/preceptor/assets/summary.mjs new file mode 100644 index 0000000..88ef941 --- /dev/null +++ b/skills/preceptor/assets/summary.mjs @@ -0,0 +1,29 @@ +import { projectCommittedSummary, SUMMARY_SCHEMA_VERSION } from "@0xbuff/preceptor"; + +// Synthetic, already-authorized host data. A real host loads its stored state and receipt. +const authorization = { + scopeRef: "example-scope", + decisionId: "example-decision", + sourceRef: "example-source", + courseRef: "example-course", + outcomeRef: "example-outcome", + sourcePolicyRevision: "1", + consent: true, +}; +const result = projectCommittedSummary(authorization, undefined, { + scopeRef: authorization.scopeRef, + decisionId: authorization.decisionId, + sourceRef: authorization.sourceRef, + courseRef: authorization.courseRef, + outcomeRef: authorization.outcomeRef, + sourcePolicyRevision: authorization.sourcePolicyRevision, + schemaVersion: SUMMARY_SCHEMA_VERSION, + committed: true, + eventId: "example-event", + revision: 1, + disposition: "credited", + feedback: "Use the public feedback to plan your next practice.", +}); +if (result.status !== "applied" || result.projection.status !== "active") + throw new Error("Expected an active committed summary"); +console.log(result.status); diff --git a/skills/preceptor/references/api.md b/skills/preceptor/references/api.md new file mode 100644 index 0000000..dc2fd26 --- /dev/null +++ b/skills/preceptor/references/api.md @@ -0,0 +1,61 @@ +# API and limits + +Use the root export of @0xbuff/preceptor only. Check installed TypeScript declarations for exact shapes. + +| Runtime export | Contract | +| --- | --- | +| planInstruction(host, request) | PlanningResult, synchronous | +| runInstruction(host, request, ports?, options?) | Promise of SessionResult | +| projectCommittedSummary(authorization, previous, event, knownEvent?) | SummaryProjectionResult, synchronous | +| POLICY_REVISION | preceptor-policy-v1 | +| SUMMARY_SCHEMA_VERSION | preceptor-summary-v1 | +| SESSION_LIMITS | Frozen ceilings | + +## Results + +PlanningResult statuses: completed (InstructionPlan), invalid_input (invalid_host_policy/invalid_request), unavailable (model_unavailable). + +| SessionResult status | Meaning | +| --- | --- | +| completed | Plan, optional advisory | +| incomplete_context | required_lesson_unavailable, tool_context_incomplete or summary_context_incomplete; plan and optional advisory | +| unavailable | model_unavailable, provider_failure or malformed_response | +| denied | required_lesson_denied | +| invalid_input | invalid_session_input | +| limit_exhausted | Named SessionLimits key or structure | +| cancelled | Host cancellation | +| deadline_exceeded | Local deadline expired | + +All session variants carry usage, provenance, toolOutcomes. Only completed and incomplete_context have plan/advisory. Tool outcomes have status completed, incomplete_context, denied, invalid_input or unavailable; reason and mutation receipt may be present. Check status and reason before accessing variant fields. Summary projection returns invalid_input/denied or applied/revoked/duplicate/stale/conflict with projection and optional receipt/conflictingDecisionId. + +## Session ceilings + +| Limit | Value | +| --- | --- | +| contextBytes | 65536 | +| inputBytes | 16384 | +| lessonBytes | 16384 | +| toolResultBytes | 32768 | +| responseBytes | 16384 | +| outputBytes | 65536 | +| memoryItems | 32 | +| memoryFactBytes | 2048 | +| modelRequests | 8 | +| toolAttempts | 16 | +| retries | 2 | +| elapsedMs | 60000 | + +Effective limits are the minimum of library, host options and request. Only nonnegative safe integers; zero can exhaust a budget. UTF-8 JSON envelope accounting includes context and responses, cumulative model output, and the larger of raw and normalized tool results (including retries). Adapter token usage is not an enforced cap. + +Structured input: depth 8, 4096 nodes, 32 object keys, 64 array elements; batch maximum 16 tools; identifiers trimmed, nonempty and at most 256 UTF-8 bytes. Validate plain bounded input. Summary read envelopes are bounded to 16 KiB + 64 bytes and narrower context limits. + +## Diagnose + +- invalid_input: inspect actual installed contracts and reject unknown fields. Fix at source rather than stripping trusted policy checks. +- denied: check mode, grants, consent, classification and adapters; never silently authorize. +- incomplete_context: inspect tool outcomes, provenance and completeness. Do not claim unavailable content was read. +- limit_exhausted: narrow input/context or operation count, not library ceilings. +- cancelled/deadline_exceeded: stop dispatch and reconcile uncertain host effects. +- unavailable: check attribution, response shape and provider availability; preserve explicit failures. + +Test with real installed exports and synthetic data before connecting production adapters. diff --git a/skills/preceptor/references/memory.md b/skills/preceptor/references/memory.md new file mode 100644 index 0000000..77ef923 --- /dev/null +++ b/skills/preceptor/references/memory.md @@ -0,0 +1,25 @@ +# Scoped narrative memory + +Keep narrative facts (struggle, preference, observation) separate from official decisions, transcripts and schedules. Memory is optional. Bind SessionPorts.memory to a single authenticated learner and consent epoch. Install, grant and consent to each operation individually. + +## Read and propose + +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. +- 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. + +A MemoryFact contains factId, kind, text, actor (learner/model), positive revision and sourceRef. Return active facts only and bound serialized fact sizes. A create is not an upsert. Updates/forget target only eligible model-owned revisions delivered to the model in the current run. Learner edits take precedence. + +MemoryInvocation provides sessionId, attempt, maxFactBytes: correlation and budget, not durable identity. Host assigns actor, durable operation ID, lineage and consent epoch. Atomically verify scope, current consent, revision and idempotency before committing. Return kind applied with operationId, factId and revision, or kind declined with reason conflict, denied, revoked, suppressed or unavailable. + +Identical authorized replay returns its existing receipt. Conflicting payloads cannot reuse an identity. Newer revisions and applied mutations remove superseded facts from subsequent context; usage is not refunded. + +## Lifecycle and reconciliation + +Use MemoryLifecyclePort separately: authenticated exportPage and deleteFact are never installed as session adapters or model-callable. Host manages physical erasure, backups, retention and consent. After deletion or revocation cancel sessions, suppress stale callbacks/replay and retain only minimal opaque suppression markers, not deleted prose. + +An applied receipt remains visible if later generation fails; cancellation, oversized or malformed responses may leave a remote outcome unknown. Reconcile with the original authorized identity, never replay as a new mutation. + +Test cross-scope denial, learner-owned facts, stale revisions, idempotent replay, revocation, deletion and late callbacks in the actual host. A fixture is not evidence of durable storage isolation. diff --git a/skills/preceptor/references/policy.md b/skills/preceptor/references/policy.md new file mode 100644 index 0000000..e3a1646 --- /dev/null +++ b/skills/preceptor/references/policy.md @@ -0,0 +1,27 @@ +# Instructional policy + +## Select a plan + +Call `planInstruction(host, request)` synchronously. Use `POLICY_REVISION` from the package. A HostPolicy contains sessionId, policyRevision, mode, grants, consent and installed capability arrays; optional lesson and signals. The request contains assistance ("plan" or "generate") and optional intent. Inputs are validated as inert data. + +| Mode | Default | Other strategies | +| --- | --- | --- | +| guided_learning | explain | question, hint, practice, reflect | +| ungraded_practice | practice | question, hint, reflect | +| retrieval_coaching | retrieve | question, reflect, practice | +| defense_preparation | question | reflect, hint | +| assessment_locked | pause | None | + +Recognized intents prepare and process are not strategies; recognized unsupported intents fall back to the mode default. Unknown intent is invalid. Difficulty low/medium/high and progress starting/practicing/reviewing may affect fixed prompts, not authority. The pure planner returns unavailable/model_unavailable for generation except in locked mode. + +## Authorize operations + +The closed capabilities are lesson.read, practice.suggest, memory.recall, memory.remember and memory.forget. The effective set is the intersection of the mode ceiling, grants, consent and installed names, with lesson classification checks. The session runner also checks actual adapters. + +LessonReference has documentRef, revision, visibility ("public" or "restricted") and kind ("lesson" or "assessment_criteria"). Bind the exact reference after host authentication. Defense preparation permits only public assessment criteria and denies remember/forget. Locked mode permits no operations. + +Denials are evaluated in order: mode_ceiling, not_granted, no_consent, not_installed, lesson_unavailable, public_criteria_required. Do not respond to a denial by expanding a grant automatically. + +Completed plans contain status, policyRevision, mode, strategy, reason, capabilities, denials and nextActions (fixed_prompt text). Selection reasons: mode_default, requested_intent, unsupported_intent, assessment_locked. Invalid input reports invalid_host_policy or invalid_request. Unknown fields, duplicate capabilities, invalid revisions and malformed input are rejected. + +Test identical input determinism, empty capability lists, unsupported intent fallback, classification mismatches and the assessment lock before connecting real providers. diff --git a/skills/preceptor/references/sessions.md b/skills/preceptor/references/sessions.md new file mode 100644 index 0000000..14b8784 --- /dev/null +++ b/skills/preceptor/references/sessions.md @@ -0,0 +1,41 @@ +# Sessions and ports + +## Model integration + +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. + +Every response includes attribution matching the port's provider/model. Optional usage has inputTokens/outputTokens; these are informational. + +| kind | Payload | +| --- | --- | +| final | Nonempty text | +| tools | requests: typed ToolRequest array | +| unavailable | reason: transient or unavailable | + +## Operations + +Each tool request has callId, operation and arguments. Use unique IDs per run. The dispatcher validates and executes sequentially. + +| operation | arguments | +| --- | --- | +| lesson.read | {} | +| practice.suggest | topic, objective | +| memory.recall | optional topic, limit | +| memory.remember | kind, text; optional paired factId, expectedRevision | +| memory.forget | factId, expectedRevision | + +The model receives descriptors only. Disable automatic tool execution in provider integrations. No custom operations or identity selectors. + +Lesson adapter signature: (reference, maxBytes, signal) => Promise of LessonResponse. Return kind excerpt with matching documentRef/revision, text, bytes (actual UTF-8 count), completeness complete/truncated; or kind unavailable with reason not_found, denied, unavailable or transient. Reauthorize the exact reference; no fallback. Set requiredLesson in options when complete lesson material is mandatory: unavailable or truncated source stops generation. Required denial is a distinct denied result. + +Practice adapter receives ({topic, objective}, signal) and returns kind suggestions with suggestions array, or kind unavailable (denied, unavailable, transient). Advice is not scheduling. + +## Budget and failures + +All attempts count, including invalid and duplicate calls. A valid call ID is reserved even when its envelope is rejected. Only explicit transient model responses and idempotent lesson reads may retry within shared limits. Never automatically retry practice or memory mutations. + +Use the supplied AbortSignal on I/O and host transport/time/cost limits. One monotonic deadline bounds local waiting, even on noncooperative promises. Late results are discarded; synchronous code is not preempted. Reconcile uncertain remote effects separately. + +Check status before plan/advisory access. Optional tool failures can produce incomplete_context even with advisory text. Completed tool outcomes survive later failure. Model-free plans and locked assessments do not call ports. Missing model returns unavailable/model_unavailable, not synthetic generated text. diff --git a/skills/preceptor/references/summaries.md b/skills/preceptor/references/summaries.md new file mode 100644 index 0000000..42e1fff --- /dev/null +++ b/skills/preceptor/references/summaries.md @@ -0,0 +1,28 @@ +# Committed summaries + +Use only minimal feedback from an already committed host decision. The library does not authenticate credit or turn raw assessment findings into an official record. + +## Project in the trusted host + +Call projectCommittedSummary(authorization, previous, event, knownEvent?) synchronously inside the authenticated ingestion path. SummaryAuthorization binds scopeRef, decisionId, sourceRef, courseRef, outcomeRef, sourcePolicyRevision and consent. CommittedSummaryEvent repeats lineage and policy, includes schemaVersion: SUMMARY_SCHEMA_VERSION, committed: true, eventId, positive revision, disposition (credited/not_credited/revoked), optional feedback and supersedesRevision. + +Corrections/revocations are full snapshots with an explicit earlier superseded revision. Revocations contain no feedback. Feedback is bounded to 2,048 UTF-8 bytes; event envelope 8 KiB, stored projection 16 KiB. + +Load previous projection and scope-wide event receipt atomically. Pass undefined for knownEvent only when the ID is unused. + +| Result | Action | +| --- | --- | +| invalid_input / denied | Do not persist new projection | +| applied / revoked | Persist projection and new receipt atomically | +| duplicate / stale | Retain current projection | +| conflict | Withhold conflicting projection; if conflictingDecisionId present, withhold that other decision in the same transaction | + +Persist any returned new receipt atomically, never overwrite an existing receipt. Resolve conflicts only with independently authorized newer full snapshots referencing the withheld revision or later. Preserve revision and event markers. Digests identify content, not authenticity or erasure. + +## Read during generation + +options.summary is host-only SummaryReadAuthorization (authorization plus expected revision). ports.summary is a scoped async SummaryReadPort(authorization, maxBytes, signal). Return kind projection with matching projection or kind unavailable with reason denied/unavailable. Reauthorize each read; do not expose ingestion to the model. One bounded snapshot is read; only active matching summaries reach model context. Scope keys and receipts are excluded. + +Summary context statuses: available, denied, unavailable, revoked, conflict, stale, malformed. Requested unavailable or withheld context yields incomplete_context. Provenance records summaryStatus and, when delivered, decisionId/sourceRef/revision/sourcePolicyRevision; not feedback or private scope. Planning and locked mode never read summaries. + +Cancel affected runs and invalidate caches on consent or scope changes. Screen feedback for protected content and never expose hidden rubrics or permit official record writes. Test stale/duplicate revisions, conflicting event IDs, revocation and exact read authorization.