Skip to content

Local-first 🧠 memory for Hermes Agent that lives in your Obsidian vault and remembers project context. Nightly 😴 dream passes turn repeat corrections into confirmed preferences with measurable confidence. Adapters ship for Claude Code, Codex, and OpenClaw, with an MCP server for anything else.

TypeScript

feat: installed agent rules and a benchmark-gated self-improvement loop (v1.98.0) (#286)

Serg Eroshed21cdb75f277
diff --git a/.claude-plugin/plugin.json b/.claude-plugin/plugin.json
index e333ab43..407aee09 100644
--- a/.claude-plugin/plugin.json
+++ b/.claude-plugin/plugin.json
@@ -1,6 +1,6 @@
{
"name": "open-second-brain",
- "version": "1.97.0",
+ "version": "1.98.0",
"description": "Plugin-first second brain package for AI agents and humans.",
"author": {
"name": "Open Second Brain contributors"
diff --git a/.codex-plugin/plugin.json b/.codex-plugin/plugin.json
index c622f143..713b91f9 100644
--- a/.codex-plugin/plugin.json
+++ b/.codex-plugin/plugin.json
@@ -1,6 +1,6 @@
{
"name": "open-second-brain",
- "version": "1.97.0",
+ "version": "1.98.0",
"description": "Plugin-first second brain package for Codex, Hermes, Claude Code, OpenClaw, and other agent runtimes.",
"author": {
"name": "Open Second Brain contributors",
diff --git a/.gitignore b/.gitignore
index ac720a8f..724a3fdd 100644
--- a/.gitignore
+++ b/.gitignore
@@ -48,3 +48,4 @@ sandbox-vault/
# Operator-handed external review scratch: never tracked (security reproductions stay out of the public repository)
.reviews/
+.grok/
diff --git a/CHANGELOG.md b/CHANGELOG.md
index d863163b..a18389cf 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -5,6 +5,18 @@ All notable changes to this project will be documented in this file.
The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.1.0/),
and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html).
+## [1.98.0] - 2026-11-02
+
+Open Second Brain 1.98.0 is the agent-presence and self-improvement release: the vault states its usage where the agents that read it actually look, and its skills improve only under evidence. The install path closes its own gap - `o2b install --target <host> --apply` now writes the brain-usage block into the agent-instruction file the installed host reads at the vault root, through a shared managed-block writer that preserves every byte outside the block, refuses a hand-edited block by name, and records its ownership so uninstall removes exactly the pair the tool wrote. The dream pass gains an operator-approved exit into those same files: a lesson promotes into a managed lessons block only when the full qualification holds and a fresh approval pins the approved text, every non-member carries one named blocked reason, and the doctor grades every block state it can name. The skill lane gains a benchmark-gated rewrite loop where a skill is rewritten only after a candidate beats the incumbent on scored dev tasks with full coverage and survives the one held-out check - Open Second Brain never calls a model, the calling agent executes the task envelopes, the scorer reads structural predicates and nothing the agent claims about its own work, the accept stays an operator step on the command line, and the incumbent's bytes ride a content-restoring rollback journal until the sequence settles. And ChatGPT desktop is named where its operators look for it: it reads the shared Codex config, and the detect output and install docs say so.
+
+### Added
+
+- **The installer writes the brain-usage block into the agent rules files.** `o2b install --target <host> --apply` for a target whose host reads an agent-instruction file now also writes the canonical write-gate managed block into that file at the vault root - AGENTS.md for codex, cursor, opencode and aider, GEMINI.md for gemini-cli (name-implied only, the open question the precedence table's docblock already carries) - mapped through the one `HOST_INSTRUCTION_PRECEDENCE` table, never a second host-to-file map; copilot-cli, grok, kiro, pi and generic install no instruction step and the plan says so with a named skip. The block body is the canonical gate-and-usage text the write-back contract audits - the same-turn atomic-fact write gate merged with the cross-project-pointer usage content - so the readiness probe grades exactly what install wrote, and a file with no block at all stays `missing-block`, graded skipped, not failed. Every byte goes through the shared rules-block writer, never a direct fs write: operator content outside the block is preserved byte-for-byte, the first write takes an exclusive-create backup, a re-apply is a byte no-op, and a hand-edited block refuses `user-modified-block` with exit 4 unless `--force`. The apply is bound to the approved preview - the apply re-derives the plan from the live disk and refuses `preview-drift` when anything the consent was shown has moved - and the instruction write rides the same consent verdict as the adapter's config writes: one prompt above both, nothing new to consent to twice. Ownership lands in `<vault>/.open-second-brain/instruction-block.lock.json` - per file, the block id, the begin marker and the applied time, the applied time being what makes a hand-edit refusable - and that lock is what `o2b uninstall --target <name> --apply` reads to remove exactly the recorded pair, never a hand-placed one; an absent pair is a named skip and the ownership entry is cleared either way.
+- **Operator-approved lesson promotion into the lessons block.** `o2b brain lessons candidates | approve <pref-id> | deny <pref-id> | refresh-blocks` turns the dream pass's lessons into content the agents that read the rules files actually see, behind the operator's hand. A lesson qualifies only under the full conjunction: preference-derived (dead-end lessons never promote), the preference `confirmed`, the confidence band `high`, the lesson tier `preferred` in the current digest, an explicitly enabled promotion scope (`lessons.promotion.scopes`, env twin `OPEN_SECOND_BRAIN_LESSONS_PROMOTION_SCOPES`; absent or empty disables promotion entirely), and a fresh approval - the ledger pins the content hash of the text the operator approved, so the operator approves text and not an id, and a preference whose text has moved since drops from the block until it is approved again. Every non-member carries exactly one named blocked reason from a closed vocabulary with a pinned precedence, an operator denial dominating. The block body is a deterministic render - no timestamp ever appears, ordering is tier, then scope, then id, and every rendered lesson is provably one line that cannot forge a managed-block marker: a scope or id carrying a line break or a marker-shaped sequence refuses the render by name rather than being silently rewritten. `approve` writes through the same shared rules-block writer on its consent ladder (`--apply`, `--yes`, `--force`) into the named target files (`--target AGENTS.md|CLAUDE.md|GEMINI.md`, repeatable; defaulting to the ones that exist), and `refresh-blocks` re-renders existing blocks dry-run by default and never creates one. The approval ledger is machine state at `<vault>/.open-second-brain/lessons-approvals.json`, deliberately in the derived store and outside `Brain/` so an agent cannot read its own approval state as a note surface - schema-versioned, fail-closed on damage, with the audit history in the `lessons-approved`, `lessons-denied` and `lessons-promoted` log events. The doctor's fail-soft, read-only readiness check grades each managed lessons block against the same derivation a refresh would render - `absent`, `current`, `drifted`, `stale-lessons` - a damaged ledger surfaces as `lessons-approvals-unreadable`, and every finding names the verb that heals it; the brain status snapshot carries the approval counts (approved, denied, stale) report-only, fail-soft with a generalized read error that names the doctor as the surface for the cause, because machine paths stay out of MCP output.
+- **Benchmark-gated skill rewrites: a skill is rewritten only under evidence.** The task set lives vault-side at `Brain/skill-benchmarks/<skill>/tasks.json` with its frozen receipt (`spec.json`), and the loop runs kernel by kernel: `o2b brain skill-proposals rewrite-plan <skill>` verifies the task set against the receipt and prints it with the dev envelopes, the calling agent executes and submits the transcripts, and `rewrite-score <skill> [--rounds-dir <dir>]` grades them. Open Second Brain never calls a model - the envelopes are `needs-llm-step` payloads, dev members only until the single held-out check after a promote - and the scorer validates the submitted shape and grades structural predicates only, refusing a submission that carries a self-reported success field, so nothing the agent claims about its own work can move the metric. Every transcript is bound to the candidate body it was produced against: each envelope carries the candidate's sha-256, and the scorer refuses - by name - a transcript whose binding is missing or stale. Selection is the preregistered three arms, and coverage is part of the preregistration: the dev arms decide only when every dev member has a scored transcript on both arms - a short arm is `not_enough_evidence`, the honest outcome either way - a score for an id outside the receipt's membership is refused as what it is, and the held-out gate runs once, on the full held-out membership only, on the candidate that earned promotion; a miss downgrades it, and a refusal writes nothing, because a hold would record a verdict the one-shot check never earned and would leak which held-out tasks fail. The winning candidate stages as a `scored_rewrite` proposal whose acceptance is the operator's step: MCP never accepts one (a typed refusal points at the command line), the CLI accept requires `--yes` and re-verifies the live receipt and the scored contract at accept time, and the incumbent `SKILL.md` bytes are captured to a vault-side prior-content copy before the overwrite, so the accept journal's rollback restores content and not just existence; the journal parser refuses a marker whose materialized path the accept sequence cannot have produced. Modes: `skill_rewrite.mode` (`gated`, the default - one candidate per gate round; `iterative` - a bounded edit loop over the dev tasks, still gated before any write) and an optional `skill_rewrite_judge_cmd` judge that stays advisory - it never moves the `tasks_passed_rate` metric the gate decides on. A read-only `brain_skill_rewrite_status` MCP tool mirrors one skill's lane - the frozen receipt and whether it still verifies, the completed rounds' verdicts and rates, the staged rewrite's slug - ids and rates only, never task or transcript text, with an unknown skill answering as a named empty status; the `skill_rewrite_eval_grade` telemetry record is written once per completed gate run, and a run that stops before the gates complete writes nothing.
+- **ChatGPT desktop is named as a reader of the shared Codex config.** ChatGPT desktop registers no MCP servers of its own; it reads the `$CODEX_HOME/config.toml` file the codex target writes, so one `o2b install --target codex --apply` serves both hosts and one `o2b uninstall --target codex --apply` undoes it for both. The codex adapter's merge-lane detect note - the CLI-absent lane, where an operator with only the desktop app would otherwise have no surface telling them this target is theirs - names ChatGPT desktop, the README and plugin host tables gain the row, and `install/codex.md` gains the ChatGPT desktop section. There is deliberately no ChatGPT install target id: a second target for one config file would claim bytes the codex target owns and report them as drift.
+- **Docs:** `docs/cli-reference.md` gains the `o2b brain lessons` family and the `rewrite-plan` / `rewrite-score` forms on the skill-proposals row, states the instruction-block step on the install and uninstall rows and the lessons-block doctor checks on the doctor row; `docs/mcp.md` documents the `brain_skill_rewrite_status` tool; `docs/observability.md` names the lessons log events and the rewrite-eval metric; `install/codex.md` gains the ChatGPT desktop section; `docs/cross-project-pointer.md` names the installer as the managed way to keep the block written, with the manual snippet staying for hand-provisioned hosts; the README host tables name ChatGPT desktop.
+
## [1.97.0] - 2026-11-01
Open Second Brain 1.97.0 is the delivery-trust release: the surfaces that hand stored vault text to a remote agent now state whose words they are delivering, and the operator gains a signed way to vouch for the store state its surfaces stamp. Every MCP read that returns stored-record text - the search family, the report-shaped reads, the context and pinned-context tools and the `osb://` preference, topic, active, lessons and backlinks resources - fences agent-origin or unverified text at remote reach inside the same wrapper the intake path uses, fails closed to the fence whenever provenance cannot be derived, and leaves local reads and the stored bytes untouched, with a doctor check naming the pages whose provenance nothing proves. Context receipts gain a verify face that re-hashes what a session was delivered against the vault it was drawn from, and a doctor check reports drift in recent receipts. The opencode lane closes most of its distance to the Claude Code lane: opt-in tool gating that blocks only on an explicit shim deny, and prompt-time recall, navigation and brief injection delivered exactly once per turn through the existing context hook, with a census pinning the surfaces that remain declared divergences. And the store can be signed: `o2b brain attest` measures the log heads and the state-surface stamps into an Ed25519-signed record under an operator-managed key - never auto-generated - with a read-only MCP mirror and a doctor check that reports stale or diverged attestations.
@@ -8804,6 +8816,7 @@ Hermes / Claude Code / Codex / OpenClaw configurations do not change.
- Sandbox vault and plugin manifest fixtures for tests.
- GitHub release workflow for tag-based and manually dispatched releases.
+[1.98.0]: https://github.com/itechmeat/open-second-brain/compare/v1.97.0...v1.98.0
[1.97.0]: https://github.com/itechmeat/open-second-brain/compare/v1.96.0...v1.97.0
[1.96.0]: https://github.com/itechmeat/open-second-brain/compare/v1.95.0...v1.96.0
[1.95.0]: https://github.com/itechmeat/open-second-brain/compare/v1.94.0...v1.95.0
diff --git a/README.md b/README.md
index 56a7c9ed..daafadf1 100644
--- a/README.md
+++ b/README.md
@@ -78,6 +78,7 @@ The full router with readiness criteria is [`install.md`](install.md); native Wi
| ------------------ | ------------------------------------------------------------------------ | -------------------------------------------------- |
| Claude Code | Marketplace plugin: MCP servers and hooks | [`install/claudecode.md`](install/claudecode.md) |
| OpenAI Codex | Marketplace plugin, then `o2b install --target codex --apply` | [`install/codex.md`](install/codex.md) |
+| ChatGPT desktop | Reads the shared Codex config: `o2b install --target codex --apply` | [`install/codex.md`](install/codex.md) |
| Hermes Agent | Plugin and memory provider | [`install/hermes.md`](install/hermes.md) |
| OpenClaw | Native plugin, no MCP | [`install/openclaw.md`](install/openclaw.md) |
| opencode | `o2b install --target opencode --apply`: MCP servers and a native plugin | [`install/opencode.md`](install/opencode.md) |
@@ -123,7 +124,7 @@ The full router with readiness criteria is [`install.md`](install.md); native Wi
## What is new
-Open Second Brain 1.97.0 makes delivery state whose words it hands over. Stored-record text that reaches a remote agent through the MCP read surfaces - search, the report-shaped reads, context and pinned context, and the `osb://` preference, topic, active, lessons, digest and backlinks resources - arrives inside the same untrusted-source fence the intake path uses whenever the record's provenance says agent-authored or cannot be derived, while local reads and the stored bytes stay byte-identical. `o2b brain context-receipts verify` re-hashes what a session was delivered against the live vault it was drawn from, and `o2b brain attest keygen|sign|list|verify` binds the store's log heads and state-surface stamps into Ed25519-signed records under an operator-managed key, with a read-only MCP mirror and doctor checks that name pages whose provenance nothing derives, recent receipt drift and stale attestations. The opencode lane gains opt-in tool gating that blocks only on an explicit shim deny and prompt-time injection delivered once per turn, pinned by a hook-parity census of declared divergences. Every release is described in the [CHANGELOG](CHANGELOG.md).
+Open Second Brain 1.98.0 is the agent-presence and self-improvement release. `o2b install --target <host> --apply` now writes the brain-usage block into the agent-instruction file the installed host reads at the vault root (AGENTS.md for codex, cursor, opencode and aider; GEMINI.md for gemini-cli) under the same consent prompt as the config writes, preserving every byte outside the block and recording its ownership so uninstall removes exactly the pair the tool wrote; the dream pass gains an operator-approved exit into those same files, where a lesson promotes into a managed lessons block only with a fresh approval pinned to the approved text, and the doctor grades every block state it can name. The skill lane gains a benchmark-gated rewrite loop: a skill is rewritten only after a candidate beats the incumbent on scored dev tasks with full coverage and survives the one held-out check - Open Second Brain never calls a model, the scorer reads structural predicates and nothing the agent claims about its own work, and the accept stays an operator step on the command line. And ChatGPT desktop is named where its operators look for it: it reads the shared Codex config, so one codex registration serves both. Every release is described in the [CHANGELOG](CHANGELOG.md).
## Documentation
diff --git a/docs/architecture.md b/docs/architecture.md
index 36563b23..60792469 100644
--- a/docs/architecture.md
+++ b/docs/architecture.md
@@ -433,13 +433,13 @@ not enter through the correction door. The predicate in
surfaces differ in what they serve, never in what the rule says.
The enforcement lives in `tests/mcp/agent-scope-matrix.test.ts`, and its shape
-is the point rather than its size. One hundred and three classified tools carry
-240 call recipes - one per mode, view or operation, because one executed view
+is the point rather than its size. One hundred and eight classified tools carry
+251 call recipes - one per mode, view or operation, because one executed view
is not an executed classification. Every recipe runs TWICE against the same
two-owner fixture, once with the gate closed and once with it open, and the
classification decides what the open run must show: the 32 recipes classified
as reaching owner-taggable content must surface the marker with the gate off,
-which is what stops the closed run from passing vacuously. The other 208 carry
+which is what stops the closed run from passing vacuously. The other 219 carry
a claim of unreachability, and that claim is executed directly - the marker
must be absent even where nothing is hidden. The first version of this probe
asserted only the closed half, and 81 of its entries were driven against
diff --git a/docs/brainstorm/agent-presence-self-improvement/cli-output/consultant.md b/docs/brainstorm/agent-presence-self-improvement/cli-output/consultant.md
new file mode 100644
index 00000000..0670d0a0
--- /dev/null
+++ b/docs/brainstorm/agent-presence-self-improvement/cli-output/consultant.md
@@ -0,0 +1,34 @@
+# Consultant output - agent-presence-self-improvement
+
+The consultant role was performed in-session against the prompt at `cli-output/prompt.md`; the output below is preserved verbatim.
+
+### Variant 1: one installer feature, lessons and rewrites folded into it
+
+- **Approach**: Treat all four cards as one install-surface feature: the instruction block, the lessons block, the ChatGPT naming and even the rewrite lane hang off `o2b install` as steps of one orchestrator, with one manifest recording everything the tool wrote.
+- **Trade-offs**:
+ - Pros: one verb to learn; one consent pass; the lock/manifest story is single.
+ - Cons: the rewrite lane has no install step at all - it is a brain verb family with its own gates, so folding it in is a category error; the lessons approval lifecycle is independent of host detection (a vault with zero installed hosts still promotes lessons); a mega-orchestrator turns every later feature into an `o2b install` regression surface; the card asks for install presence, not install monopoly.
+- **Complexity**: large
+- **Risk**: high
+
+### Variant 2: one shared writer, two producers, separate kernels
+
+- **Approach**: Build one block-id-parametrised rules-block writer over the existing managed-block editor; the installer lane and the lessons lane are its two producers with separate lifecycles and consent surfaces; the rewrite loop is a self-contained kernel lane beside them (task sets, preregistered spec, envelope rollouts, selection and held-out gates, apply through the existing proposal pipeline); ChatGPT desktop is detection-plus-docs on the codex adapter. Lanes own disjoint files; shared registries are append-only.
+- **Trade-offs**:
+ - Pros: exactly one write class for harness-owned files, so one census story and one audit trail; no producer forks the editor; each kernel is testable in isolation; the lanes parallelize behind two early pure commits.
+ - Cons: two consent surfaces for rules files (install's and the lessons verbs'), which the docs must keep distinct; the writer contract must be frozen before the lessons lane starts, adding an ordering constraint the mega-orchestrator would not have.
+- **Complexity**: medium
+- **Risk**: low
+
+### Variant 3: per-feature writers
+
+- **Approach**: Let each lane write its own block logic directly against `insertManagedBlock`: the installer keeps its own compute/apply, the lessons verbs their own.
+- **Trade-offs**:
+ - Pros: no cross-lane contract; each lane ships independently with zero waiting.
+ - Cons: two implementations of the drift refusal, the backup ladder, the idempotence byte-compare and the marker discipline, guaranteed to diverge; two census stories for one write class; the wave's stated spine (one apply-gated rules-file write path) is not built.
+- **Complexity**: small per lane, large in total
+- **Risk**: medium
+
+### Recommended: Variant 2
+
+**Rationale**: The board's scope option names the spine as one apply-gated rules-file write path plus the closed skill loop, and the tree already contains every primitive both halves need - the managed-block editor, the conformance checker, the consent ladder, the proposal pipeline with its journalled accept, the decision-model preregistration discipline. Variant 3 dissolves the spine into two guaranteed-to-diverge writers; Variant 1 miscategories a verb-family feature as an install step and concentrates regression risk in one orchestrator. Variant 2 adds exactly what is missing - one shared writer, one kernel lane - and keeps the lanes disjoint behind two early pure commits.
diff --git a/docs/brainstorm/agent-presence-self-improvement/cli-output/prompt.md b/docs/brainstorm/agent-presence-self-improvement/cli-output/prompt.md
new file mode 100644
index 00000000..56083039
--- /dev/null
+++ b/docs/brainstorm/agent-presence-self-improvement/cli-output/prompt.md
@@ -0,0 +1,23 @@
+You are brainstorming architectural variants for the following task. Do not write code. Do not write a final design. Only produce variants and a recommendation.
+
+# Task
+
+Release wave "agent-presence-self-improvement" (option 1): implement all four kanban cards in one PR on one feature branch.
+
+- t_635e3e72 - Scored skill rewrites gated by task benchmarks: give an existing skill's instructions an improvement lane that is closed-loop over scored tasks. Per-skill benchmark task sets, a candidate rewrite driven through envelopes, a deterministic selection gate the candidate must win on training tasks, one held-out check on the final champion, and an apply path through the existing human-accepted, journalled proposal pipeline.
+- t_ba41a78a - Install writes a brain-usage instruction block into agent rules files: an install step that writes the same-turn atomic-fact write-gate managed block (whose conformance the writeback-contract checker already fully specifies) into the agent-instruction file each installed host actually reads, idempotently, keeping operator content outside the block byte-for-byte.
+- t_1e952e43 - Operator-approved lessons promoted into rules files: an approval-hold tier on lessons plus an apply-gated write that installs a managed block of operator-approved, qualified lessons into the same rules files, reaching agents that never load hooks.
+- t_8b793376 - ChatGPT desktop as an install target: it reads the same ~/.codex/config.toml the codex adapter already writes; the residue is naming it (detect notes, README, guide). The decision left open is separate target vs alias of the codex adapter.
+
+The four cards share one machinery spine: an apply-gated rules-file write path (the installer and the lessons lane are two producers over one writer) plus the closed skill-improvement loop. The task is to argue the SHAPE of the wave - how the four implementations compose into one coherent design.
+
+# Project context
+
+Open Second Brain - local-first agent memory for Claude Code, Codex, opencode and other hosts as an MCP server and CLI (`o2b`), TypeScript on Bun. Kernel invariants that bind every variant: writes to operator surfaces pass explicit apply gates (plan/consent/apply with typed refusals), no model in the kernel (generation is envelope-mediated), no silent fallbacks (errors surface by name), no hardcoded natural-language vocabularies (structural predicates and operator-declared lists), and the tree's census tests fail loudly on unregistered write sites, state surfaces and verdict vocabularies.
+
+Recent commits:
+07125f6d feat: delivery trust, end to end (v1.97.0) (#285)
+285cb9a8 feat: trust and responsiveness hardening - neutralized imports, gitignore guardrails, shadowed-contract detection, parallel MCP reads (v1.96.0) (#281)
+88c118aa feat: verified delivery and honest write surfaces (v1.95.0) (#280)
+
+Answer with three named variants (approach, trade-offs with pros and cons, complexity, risk) and a recommendation with rationale.
diff --git a/docs/brainstorm/agent-presence-self-improvement/design.md b/docs/brainstorm/agent-presence-self-improvement/design.md
new file mode 100644
index 00000000..ae6f4ccd
--- /dev/null
+++ b/docs/brainstorm/agent-presence-self-improvement/design.md
@@ -0,0 +1,115 @@
+# Agent presence and self-improvement - install-time rules-file presence, operator-approved lesson promotion, ChatGPT desktop reach and benchmark-gated skill rewrites
+
+**Status:** draft
+**Audience:** implementation
+
+## Problem statement
+
+Open Second Brain is invisible to most hosts it serves. The only thing telling a host agent the brain exists is the SessionStart/PostCompact hook injection (`hooks/active-inject.ts`); on hosts where no hook is wired, the agent never learns the brain exists, and the same-turn atomic-fact write gate that `src/core/brain/writeback-contract.ts` fully specifies is reported by `o2b doctor --readiness` as a permanently un-actionable `missing-block`, because the checker's own docblock states "NO INSTALLER LIVES HERE". A memory server nobody mentions is almost never called. Two more presence gaps compound this: vetted lessons (the brain's own confirmed, high-confidence, preferred-tier rules) reach only agents that load Open Second Brain hooks, because nothing can install them into the rules files hosts actually read - and no approval tier exists at all, so the one automatic promotion in the tree (`dream-refresh.ts` flips `unconfirmed` to `confirmed` on first applied evidence) is the only lifecycle a lesson has. Reach has a third hole: ChatGPT desktop reads the same `~/.codex/config.toml` the codex adapter already writes, but no surface in the tree names it, so a ChatGPT-desktop-only operator has no way to discover that `o2b install --target codex --apply` is their install command. And on the self-improvement side, the skill lifecycle is open only at the ranking end: invocation evidence flows (`skill_invoked` continuity records, `deriveSkillUsage`, usage-weighted attach ranking), the dream pass plans preference retires only, and nothing ever edits a working skill's SKILL.md against measured outcomes. Skills are static text that can only be replaced by hand.
+
+## Premise verification
+
+Verdicts from targeted reads against this tree at 07125f6d (origin/main, v1.97.0), recorded with the corrections from the recon reports and the inline verification. All four premises held; nothing is dropped and nothing is refused. The corrections below are binding for the plan; the full anchor-by-anchor table lives in variants.md.
+
+- **t_635e3e72 (scored skill rewrites gated by task benchmarks) - premise confirmed, two anchor corrections.** The gap is real: grep for rewrite/benchmark/selection-gate mechanisms across `src/core/brain` and `src/core/surface` returns nothing; the dream pass plans only preference retires (`PlanState.retires`, `src/core/brain/dream-plan.ts:214`) and never touches skill files; the `skill-usage.ts` docblock's "rank, retain, or retire" is aspiration, not implementation. The machinery to reuse is exactly where the recon says: `acceptSkillProposal` at `src/core/brain/skill-proposals.ts:766` with the archive/materialize/commit journal phases, `SkillAcceptLockedError` at :975, materialize writes `overwrite: false` (:868 for the skills root, which passes no `vaultForRelativePath`), the preregistration discipline in `src/core/decision-model/eval-spec.ts` (`hash-order-30-70` at :41, the `promote | hold | not_enough_evidence` three-arm verdict at :56), `parseBenchFixture` at `src/core/bench/fixture.ts:42`, `NEEDS_LLM_STEP`/`buildNeedsLlmStep` in `src/core/brain/llm-step.ts`, config keys at `src/core/config.ts:733/:806/:1887`, and the census rows at `tests/core/architecture/write-site-census.test.ts:744/:1109`. Corrections: `buildNeedsLlmStep` is at `llm-step.ts:85` (recon said :67); and the accept journal records existence flags only (`acceptedExisted`, `materializedExisted`) - no prior-content copy - while `evolveAcceptedProposal` (`skill-proposals.ts:1393`) already overwrites an accepted skill's frontmatter with `overwrite: true`, so an overwrite precedent exists but a body-replacing rewrite still has no rollback path for content. The design's journal extension is required, not optional.
+- **t_ba41a78a (install writes the brain-usage block into agent rules files) - premise confirmed, one scope correction.** The checker exists and is write-only-by-contract (`writeback-contract.ts`: "NO INSTALLER LIVES HERE" docblock, `AGENT_INSTRUCTION_FILES` at :98, `HOST_INSTRUCTION_PRECEDENCE` at :137, `WRITEBACK_CONTRACT_REQUIREMENTS` three clauses, `missingWritebackGateClauses` pure); the managed-block editor exists (`src/core/install/managed-block.ts`, idempotent `insertManagedBlock`, `validateMarkers` refusing multiple/unpaired/reversed markers); the install consent ladder is fail-closed (`src/cli/install/install.ts:415-462`, exit 6 without `--yes` headless); the readiness probe audits the VAULT root (`doctor-readiness.ts`, `workspace = opts.vault`). Correction: the recon's installer table row "claude-code writes CLAUDE.md" is unreachable - `INSTALL_TARGET_ID` (`src/core/runtime/host-facts.ts:61`) has ten members and none is claude-code, as the precedence docblock itself states; the installer maps REGISTERED targets through the precedence table (codex, cursor, opencode, aider to AGENTS.md; gemini-cli to GEMINI.md), so the claude-code row stays audit-side until a claude-code target ever exists.
+- **t_1e952e43 (operator-approved lessons promoted into rules files) - premise confirmed.** No approval-hold tier exists: `BRAIN_PREFERENCE_STATUS` is the closed triple `unconfirmed | confirmed | quarantine` (`src/core/brain/types.ts:89`), promotion is automatic at the dream refresh (the `firstApplied` branch, `dream-refresh.ts:269`), and the operator acts only after the fact (`reject`, `pin`). The lessons digest is derived (`computeLessons`, `LESSON_TIER` at `lessons.ts:73`, idempotent `regenerateLessons` at :470), content-hash pinning exists and is observability-not-enforcement (`content-hash.ts`), the write-approval lane family is inbound-only (`write-gate.ts`, lanes `signals | notes | ingest`), and no rules file is ever written by this tree today. No `o2b brain lessons` verb family exists. Trivial drift: `HOST_INSTRUCTION_PRECEDENCE` is at :137-145 (recon said :136-143).
+- **t_8b793376 (ChatGPT desktop as an install target) - premise confirmed; recon report was absent, verified inline.** Zero references to ChatGPT anywhere in `src/`, `docs/` or `README.md`; the codex adapter (`src/core/install/adapters/codex.ts`) is subprocess-driven with the `$CODEX_HOME/config.toml` TOML-merge fallback, `detect()` keys the note on `Bun.which("codex")` (:121) and reports the target row regardless of binary presence; the target vocabulary is held equal to the registered adapter population in both directions by `tests/core/architecture/host-facts-census.test.ts`; the README supported-clients table names Codex at :80. The external premise (ChatGPT desktop reads the shared codex config) is the upstream card's own finding, already accepted at scope review. The remaining decision is pinned below to alias-of-codex: no new `InstallTargetId`.
+
+## Scope
+
+- Lane B (t_ba41a78a, commits the shared writer FIRST): one shared, block-id-parametrised rules-block writer module (`src/core/install/rules-block.ts`) over the existing managed-block editor, plus the installer lane that uses it - an instruction step in `o2b install` that writes the canonical brain-usage block into the preferred agent-instruction file of targets with a precedence entry, idempotently, consent-gated, backed up, with its own lock file and an uninstall reverse step. The canonical body becomes a named constant beside the checker's contract clauses with a self-test.
+- Lane C (t_1e952e43, depends on the pinned writer): an operator approval tier for lessons and the promotion lane that renders qualifying, approved, fresh (content-hash-matching) lessons into a second, sibling managed block in the same rules files through the same writer - operator verbs `o2b brain lessons candidates|approve|deny|refresh-blocks`, an approval ledger in the derived store, doctor readiness rows, report-only MCP counts. No agent-facing path can approve or write.
+- Lane D (t_8b793376, independent): ChatGPT desktop named as a reader of the codex target - a detect note on the codex adapter when the codex binary is absent, a README supported-clients row and an install/codex.md section. No new install target id; no adapter behavior change.
+- Lane A (t_635e3e72, the L anchor, independent of B/C/D): the benchmark-gated skill rewrite loop - per-skill benchmark task sets (`Brain/skill-benchmarks/<skill>/tasks.json`, structural predicates only), a preregistered spec with a frozen dev/held-out split receipt, envelope-mediated candidate rollouts (one `needs-llm-step` per dev task, the calling agent executes), a deterministic selection gate the candidate must win on dev tasks, one held-out check on the promoted candidate, and an apply path that lands through the existing proposal pipeline with the accept journal extended to restore prior skill bytes on rollback.
+- Integrator: reconciliation of shared append-only registries (command manifest, help text, docs), census coherence across lanes, full local gates.
+
+## Out of scope
+
+- A claude-code install target (none exists; the marketplace plugin is the Claude Code lane) and any `--workspace`-root override for the instruction step: v1 writes at the vault root only, the surface the readiness probe audits. Recorded as follow-ups.
+- A `.cursor/rules` or any out-of-vault rules-file target: it would drag an `OUT_OF_VAULT_STATE` row and egress-registry attribution with it; vault-root files cover the motivating Cursor-with-bare-MCP case today.
+- Any change to the writeback-contract audit semantics (it stays read-only, extracts by the settled default markers, grades exactly as today) and no new finding vocabulary there.
+- Dream-tail or hook-triggered rules-file refreshes: blocks are refreshed only by the operator verb. The consent-once-then-derive middle ground is deliberately not taken this wave.
+- Skill version publishing, version chains or a skill release surface (assigned to another card on the board); single prior-content backup only.
+- Held-out task text in any dev envelope, in any grade record, or in any MCP surface - the envelope builder asserts dev membership and the grade record carries ids and scores, never task or transcript text.
+- Per-adapter rewrites of the aider conf block or any adapter's existing managed block: the instruction step is additive beside them.
+- Version bump, CHANGELOG assembly and the release-wide docs pass: that is the pr-prepare phase, not this plan.
+
+## Chosen approach
+
+One shared writer, two producers, one kernel lane. The wave's center is a single rules-block writer module that both rules-file features import (the installer lane and the lessons lane), so there is exactly one marker-scoped, atomic, idempotent, consent-riding write class for harness-owned files and every new write site lands in one census story. Each of the other two features is a self-contained kernel beside that spine: the skill rewrite loop is three leaf modules plus extensions to the proposal pipeline that already owns gated skill writes, and the ChatGPT lane is detection-plus-docs on the codex adapter. The lanes own disjoint files; the only shared files are append-only registries (command manifest, help text, docs, state surfaces) governed by the protocol in plan.md.
+
+## Kernel invariants honored
+
+- **Apply gates on every new write.** The rules-file write class inherits the install consent ladder verbatim (plan first, `--apply` executes, headless refuses without `--yes`, verdict recorded, `--force` the only override for a drifted block, backups before first writes, typed refusals with exit codes that already exist). Skill-file writes pass the existing human accept through `acceptSkillProposal` with the write-ahead journal, now content-restoring; benchmark directories are written only through the shared atomic writers with the vault-identity write guard at every vault-side entry.
+- **No model in the kernel.** Every generation and every task execution is envelope-mediated (`needs-llm-step`); scoring is deterministic structural predicates; external opinion rides the local command bridge, advisory only, never moving the metric.
+- **No silent fallbacks.** Unknown mode values, malformed task sets, split-receipt mismatches, short dev n, held-out misses, symlinked targets, drifted blocks and hand-edited divergence are all named outcomes (the three-arm verdict, `RulesBlockError` kinds, typed config refusals); a gate failure stages nothing and says so.
+- **No hardcoded natural-language phrases.** The scorer matches structure over closed vocabularies, never prose; lesson qualification uses operator-declared scope lists (no default vocabulary); the one fixed English instruction body is a named, self-tested constant beside the contract clauses, and every other user-visible string follows the tree's existing English constants.
+
+## Design decisions
+
+- **One writer module, two producers, two block ids.** `src/core/install/rules-block.ts` is the only code that moves a rules-file block: `renderRulesBlock`, `writeRulesBlock`, `removeRulesBlock`, `readRulesBlock` and `rulesBlockDrift`, all parametrised by a closed `RULES_BLOCK_ID` pair (`usage | lessons`). The installer and the lessons verbs call it; neither forks the editor. The writer wraps `insertManagedBlock`/`removeManagedBlock` (operator bytes outside the block are preserved by the editor's guarantee), writes atomically, byte-compares before writing so re-application is a no-op, and takes backups before first writes.
+- **The usage block keeps the settled default markers; the lessons block gets its own pair.** The writeback-contract audit extracts the managed block by `DEFAULT_BEGIN_MARKER`/`DEFAULT_END_MARKER` and grades it against the three gate clauses; those spellings are contract, not style. `validateMarkers` refuses two pairs of the SAME spelling, so the lessons block carries a distinct HTML-comment pair (`<!-- >>> open-second-brain lessons >>> -->` / `<!-- >>> open-second-brain lessons <<< -->`), which renders as nothing in markdown and survives in all three instruction files. The audit is untouched by a sibling block: it sees only the default-marker pair, and tests pin that a file with only a lessons block still grades `missing-block`.
+- **The canonical usage body is a named constant beside the contract clauses, self-tested.** `CANONICAL_WRITEBACK_BLOCK_BODY` lives in `src/core/brain/writeback-contract.ts` next to `WRITEBACK_CONTRACT_REQUIREMENTS` (a constant is contract definition; the module stays write-free), merges the gate clauses with the cross-project-pointer usage content (read `Brain/active.md` at session start, `brain_feedback`, `brain_apply_evidence`, the do-not-dream rule), and a checker self-test asserts `missingWritebackGateClauses(CANONICAL_WRITEBACK_BLOCK_BODY)` is empty so the installer can never ship a non-conforming block. The body is fixed English instruction prose assembled as one constant - the posture the recovery prose already established; the checker matches structure (closed clause vocabularies), never prose, and no phrase list enters any matching path. The docblock's "NO INSTALLER LIVES HERE" becomes a pointer to the installer module and its obligations.
+- **The installer step rides the existing consent lane, mapped from the precedence table over registered targets only.** `instructionBlockTargetFor(target)` resolves `HOST_INSTRUCTION_PRECEDENCE[target]` (codex, cursor, opencode, aider to AGENTS.md; gemini-cli to GEMINI.md; targets without an entry, and the generic print-only target, skip the step by name in the plan). In `runTarget` (`src/cli/install/install.ts`) the step is appended to the rendered plan after `adapter.plan` and applied after `adapter.apply` under the SAME consent verdict - the operator consents once to a plan that shows both writes; no second consent vocabulary. `INSTALL_STEP_KINDS` gains nothing (the existing `"managed-block"` kind fits), `INSTALL_TARGET_ID` gains nothing, exit codes are the existing `INSTALL_EXIT` set.
+- **Guarded apply is the protect.ts mould: preview binding, backup, hand-edit refusal.** The apply re-derives exactly the approved before/after bytes and refuses by name on drift (`approved` binding); the first write is preceded by an exclusive-create, collision-laddered backup of the current file recorded in the result and the lock; a block whose extracted body diverges from the canonical one on a file newer than the lock's `applied_at` is a `user-modified-block` refusal (exit 4) unless `--force`, and the forced rewrite replacing a non-conforming body is the documented upgrade path for the docs-snippet manual installs (their one existing marker pair is diverged-from-canonical by construction, since the docs snippet predates the gate clauses). Symlinked instruction files are refused by name - the checker's read posture becomes the writer's posture, because a writer that follows a link has left the workspace.
+- **Ownership is a lock file, never a manifest pseudo-target.** `instruction-block.lock.json` under `<vault>/.open-second-brain/` records schema version, applied_at, the files whose usage block Open Second Brain owns and the begin marker - the `protect.lock.json` shape, declared as a state surface. `ManifestEntry.target` stays typed `InstallTargetId` and the host-facts census stays an equality in both directions. `o2b uninstall --target <host> --apply` removes the pair the lock records; markers absent at uninstall are a named skip.
+- **Vault root, not cwd.** Hosts read instruction files at the project root, but the readiness probe audits the vault root and today the vault is the project for every host this tree installs; a cwd-targeting step would need new `InstallEnv` semantics, an `OUT_OF_VAULT_STATE` row and sweep attribution for no operator in this wave's motivating cases. The gemini-cli reading of GEMINI.md is name-implied (the precedence docblock carries the open question); the plan postNote says so rather than the code pretending certainty.
+- **Lesson promotion is a conjunction, all required, all named.** A lesson enters the block only when it is preference-derived (dead-ends never promote), `confirmed` (the filter `computeLessons` already applies), `high` confidence, `preferred` tier in the current digest, scoped to a member of the operator-declared `lessons.promotion.scopes` config list, and carrying a fresh approval: the approval row pins `approved_content_hash` equal to the preference's existing `_content_hash`, and a mismatch at render time drops the lesson from the block and reports it stale - the operator approved text, not an id. Absent or empty `lessons.promotion.scopes` disables promotion entirely with a named count in the candidates surface; there is no default scope list, because a default would be a hardcoded natural-language vocabulary deciding what counts as agent behavior. The block body is a deterministic render (ordering tier, then scope, then id - the digest's tie-break; no timestamps inside the block, they would defeat byte-idempotence) bounded by the existing `lessons.limit` config.
+- **Approval is operator-only, recorded once, audited in the one log chain.** `o2b brain lessons approve <pref-id>` and `deny` run the install consent ladder shape (plan-first, `--apply` executes, non-interactive refuses without `--yes`, verdict recorded as `yes-flag`/`interactive-yes`); the approve write goes through the shared writer and the ledger row is recorded only after a successful apply. The ledger is `<vault>/.open-second-brain/lessons-approvals.json` - the derived store, not `Brain/`, so an agent can neither read its own approval state nor social-engineer around it. Decisions append `lessons-approved`/`lessons-denied`/`lessons-promoted` log events through `appendLogEvent`, keeping one audit chain. Dream tail, hooks and MCP never write rules files and never approve: `regenerateLessonsQuiet` stays `Brain/`-scoped, and the standing-rules guarantee (no tool rewrites the operator's channel) is preserved by construction. MCP exposure is report-only counts through the existing status plumbing - no new mutating tool, so the visibility-surface registry gains no row.
+- **The readiness probe grades the lessons block honestly.** Beside the existing `writeback_contract` probe rows, a per-file lessons-block row (`absent | current | drifted | stale-lessons`) reports what promotion would and did do, so an operator who never runs `refresh-blocks` sees the staleness as a named finding rather than discovering stale text in the file. The instruction-file ceiling keeps counting both blocks - no exemption, because the ceiling reads the file an agent reads; the canonical usage body stays minimal and the lessons block is bounded by `lessons.limit`.
+- **Benchmark task sets are structural, content-hashed and vault-side.** `Brain/skill-benchmarks/<skill>/tasks.json` is the primary home (operator skills are vault-local and the vault is what syncs; the skills root itself may sit outside the vault); repo fixtures under `tests/fixtures/skill-bench/` exist only for shipped-skill tests, mirroring `tests/fixtures/decision-model/`. A task is `{ id, kind, input, expects }` over a closed kind vocabulary (`invocation_transcript` in this wave) and a closed check vocabulary (`tool_used | artifact_created | step_order | forbidden_step | output_field`) - every predicate names its check, a failure reports the check id, and there is no prose matching anywhere in the scorer. Validation is fail-fast with named errors in the `parseBenchFixture` style; the parsed set is hashed with `sha256Hex(canonicalJson(...))` so a spec can freeze it.
+- **The preregistration is the decision-model eval spec, generalized.** `spec.json` beside the task set freezes the tasks hash, a seed, the `hash-order` split rule over dev/held-out membership (a receipt the runner verifies - `verifyRewriteTake` refuses a task set that no longer matches), the selection metric `tasks_passed_rate`, the required margin and the minimum dev n. The verdict vocabulary is the frozen three-arm `promote | hold | not_enough_evidence` the decision model already pinned: a candidate promotes only by strictly beating the baseline on dev by the margin with n met; a tie holds; a short dev n is its own arm, never a pass.
+- **Rollouts are envelope-mediated; scoring never trusts the agent's self-assessment.** One `needs-llm-step` envelope per dev task (`step: "skill-rewrite-task"`) carries the candidate body and the task input; the calling agent (the CLI loop, exactly the `page-candidates`/`page-draft` flow) executes and submits a structured transcript plus produced artifacts; core validates the returned shape and scores the structural predicates. The agent's own success claim is never a scored input - the same posture that keeps procedural outcomes host-recorded. The held-out gate is a separate one-shot function, the only caller allowed to read held-out ids, run once on the candidate that earned `promote`; a held-out miss downgrades to `hold`; the envelope builder asserts every envelope task id is a dev member, so contamination is refused by construction rather than policed by review.
+- **The mode flag is explicit and unknown values are errors.** `skill_rewrite.mode` resolves `gated` (default, one candidate per round) or `iterative` (a bounded edit loop over dev tasks only, still gated before any write); an absent-key default is the one default the config resolver pattern allows, and an unknown value is a named error, never a silent fallback. The optional external judge rides `runJsonCommandBridge` under `skill_rewrite_judge_cmd`, fail-open and advisory, never moving the metric - the `bench_judge_cmd` contract verbatim.
+- **The apply path is the proposal pipeline, extended in exactly one place.** A promoted candidate stages as a pending proposal with a new `scored_rewrite` pattern kind carrying the scored contract fields (`skill_name`/`skill_description`/`skill_triggers` reuse plus `rewrites_skill`, `spec_hash`, `baseline_score`, `candidate_score`, `heldout_score`); acceptance stays the human step through `acceptSkillProposal` unchanged. Because a rewrite OVERWRITES an existing SKILL.md (today's materialize is `overwrite: false`, and `evolveAcceptedProposal`'s overwrite merges frontmatter only), the accept journal gains `priorContentPath`: the prior bytes are copied under the journal directory before the overwrite, and rollback restores content, not just existence - the one growth the existing machinery needs, pinned in the accept dead-ends suite. The version bumps by the existing `parseVersion + 1` evolve precedent. An operator reject is sticky for the skill name, which also suppresses re-proposing the same rewrite.
+- **Evidence lands as an additive continuity kind, kept never-folded.** `skill_rewrite_eval_grade` records per-round ids, scores and per-check verdicts with the spec hash - never task text, never transcript text - appended only after a completed gate run, added to the union and `CONTINUITY_RECORD_KINDS` in the same edit so an operator can audit why a rewrite landed. Gate failures stage nothing: `hold` and `not_enough_evidence` write only the grade record and leave the incumbent SKILL.md untouched.
+- **ChatGPT desktop is an alias of the codex target, not a target.** A new `InstallTargetId` for a file the codex adapter already owns would fork detect/plan/apply/verify for one config path and break the host-facts census equality for no behavioral difference. The codex adapter's `detect()` note names ChatGPT desktop as a reader of the same file when the codex binary is absent (the shared-config case); the README supported-clients table and `install/codex.md` name ChatGPT desktop with the codex install command. No plan/apply/verify behavior changes: same file, same payload, same drift vocabulary.
+
+## File changes
+
+New:
+
+- `src/core/install/rules-block.ts` - the shared rules-block writer: `RULES_BLOCK_ID` (`usage | lessons`), per-id marker constants, `renderRulesBlock`, `writeRulesBlock`, `removeRulesBlock`, `readRulesBlock`, `rulesBlockDrift`, `RulesBlockError` (lane B).
+- `src/core/install/instruction-block.ts` - the installer lane: `instructionBlockTargetFor`, `planInstructionBlock`, `applyInstructionBlock`, `uninstallInstructionBlock`, instruction-block lock I/O (lane B).
+- `src/core/brain/lessons-promotion.ts` - the promotion kernel: qualification conjunction, deterministic block render, approvals ledger I/O, staleness derivation (lane C).
+- `src/cli/brain/verbs/lessons.ts` - `cmdBrainLessons` dispatching `candidates | approve | deny | refresh-blocks` (lane C).
+- `src/core/brain/skill-rewrite-tasks.ts` - task-set parse/validate/hash; closed kind and check vocabularies; pure leaf (lane A).
+- `src/core/brain/skill-rewrite-spec.ts` - preregistration, split receipt, take verification; pure leaf (lane A).
+- `src/core/brain/skill-rewrite.ts` - envelope builder, transcript validation and scoring, dev selection gate, held-out gate, mode resolution, grade-record assembly (lane A).
+- `src/core/brain/doctor/lessons-block-check.ts` - readiness rows for the lessons block per candidate file (lane C).
+- `tests/fixtures/skill-bench/` - committed example task sets and spec for the suites (lane A).
+
+Modified:
+
+- `src/core/brain/writeback-contract.ts` - `CANONICAL_WRITEBACK_BLOCK_BODY` constant, self-tested; docblock and recovery wording name the installer (lane B).
+- `src/cli/install/install.ts` - plan augmentation and the post-adapter instruction step in `runTarget` under the existing consent gate (lane B).
+- `src/cli/install/uninstall-target.ts` - the reverse step (lane B).
+- `src/core/state/surfaces.ts` - `instruction-block.lock.json` (lane B), `lessons-approvals.json` (lane C), the `Brain/skill-benchmarks/` surface (lane A).
+- `src/core/brain/lessons.ts` consumers only via the new kernel; `src/core/brain/policy/blocks/lessons.ts` - `lessons.promotion.scopes` resolution (lane C).
+- `src/core/brain/types.ts` - `lessons-approved`/`lessons-denied`/`lessons-promoted` log event kinds (lane C).
+- `src/core/brain/status.ts` - approval counts in the snapshot (lane C).
+- `src/core/brain/dream-refresh.ts`, `src/core/brain/dream.ts`, `hooks/` - read for guarantees only, untouched; no lane adds rules-file writes to them.
+- `src/core/brain/skill-proposals.ts` - `scored_rewrite` pattern kind, scored contract fields, journal prior-content capture and content-restoring rollback (lane A).
+- `src/core/brain/skill-accept-journal.ts` - `priorContentPath` field and parse (lane A).
+- `src/core/brain/continuity/types.ts` - additive `skill_rewrite_eval_grade` kind (lane A).
+- `src/core/brain/paths.ts` - benchmark and journal-copy paths (lane A).
+- `src/core/config.ts` - `skill_rewrite.mode`, `skill_rewrite_judge_cmd` (lane A); `lessons.promotion.scopes` (lane C).
+- `src/cli/brain/verbs/skill-proposals.ts` - `rewrite-plan` and `rewrite-score` subcommands (lane A).
+- `src/mcp/brain/procedure-tools.ts` - read-only rewrite status (lane A).
+- `src/core/install/adapters/codex.ts` - detect note naming ChatGPT desktop when the binary is absent (lane D).
+- `README.md` supported-clients row, `install/codex.md` section (lane D).
+- `docs/cli-reference.md` - rows for the new verbs and subcommands (each lane appends its own; the integrator reconciles).
+
+## Risks and open questions
+
+- **Two blocks in one file is a new shape for the audit.** The checker was specified for one default-marker pair; a sibling HTML-comment pair is inert to it by construction, but the interaction tests (lessons-only file, both-blocks file, forced upgrade of a docs-snippet file) are load-bearing and pin the checker's behavior unchanged. If a future contract change ever needs to see the lessons block, that is a new clause vocabulary, not a marker reuse.
+- **Rules files enter the vault's own read surfaces.** A created AGENTS.md becomes visible to the removed-tool sweep, the instruction ceiling and the note indexer; all three already read these files, the step is plan-visible and consent-covered, and the plan postNote names it. The ceiling counts the added lines honestly; an operator with a large own-content file sees the existing warning.
+- **Partial failure between adapter apply and instruction step.** The instruction step is last; a failure exits non-zero with the adapter write committed, and re-running `o2b install --target <host> --apply` converges because every step is idempotent. Stated in the plan render rather than hidden.
+- **Self-reported rollouts can game the metric.** Mitigation is structural: only typed predicates over returned artifacts and validated transcripts score; the agent's own success claim never does; per-check outcomes land in the grade record so a rewrite that wins by dropping checks is visible. Residual risk accepted and named: a determined caller can fabricate transcripts, and the gate is honest about defending against regression, not against a hostile optimizer operator - the human accept is the boundary.
+- **Held-out contamination in iterative mode.** The envelope builder asserts dev membership and the held-out gate is the only held-out reader, but a future contributor could add a second reader; the assertion tests and the grade-record shape (which would show held-out ids in dev envelopes) are the tripwires.
+- **The journal prior-content copy is bounded but new.** One SKILL.md per accept attempt under the journal directory; cleanup rides the existing journal-clear path. A crash between backup and overwrite leaves a recoverable journal - exactly the case the extension exists for, pinned in the dead-ends suite.
+- **Approval freshness couples the ledger to the content hash discipline.** The hash is observability-not-enforcement upstream; promotion makes it enforcement for one narrow decision (block membership). The stale lesson is dropped and reported, never silently kept, and re-approval is one verb - but operators must understand that hand-editing a confirmed preference now silently unpromotes it on the next refresh. Docs say so.
+- **gemini-cli delivery is name-implied.** The precedence table's own docblock carries the open question; both lanes write GEMINI.md per the declared table with the plan postNote, and neither claims more than "file written".
+- **Census overhead.** The wave touches registries that fail loudly on unregistered newcomers (write-site, destructive-site, state-surface, verdict-vocabulary, visibility-surface, claim-attribution, append-shard, continuity reader census, host-facts, import-cycles, layering); every lane lands its registrations with the code that trips them, never retrofitted.
+- **Open: whether install should also offer the lessons block.** The two producers share a writer but keep separate lifecycles and separate consent surfaces this wave; an `o2b install --refresh-blocks` alias that re-renders both is a follow-up decision to make on operator usage, not on taste.
diff --git a/docs/brainstorm/agent-presence-self-improvement/plan.md b/docs/brainstorm/agent-presence-self-improvement/plan.md
new file mode 100644
index 00000000..3b7f126e
--- /dev/null
+++ b/docs/brainstorm/agent-presence-self-improvement/plan.md
@@ -0,0 +1,171 @@
+# Agent presence and self-improvement - implementation plan
+
+Four implementation lanes with strictly disjoint file ownership plus one integrator. Each task is TDD-ready: write the failing test first, run it and see the expected failure, implement until green, refactor green, then run the repo formatter (`./node_modules/.bin/oxfmt`, not `bunx oxfmt`) and the repo lint on the task's own files before every commit, and commit only that task's own files with `git commit --only <paths>` (never a plain `git add` + `git commit`). Each lane runs ONLY its own new or changed test files locally (never the full suite); the integrator runs the full gates. Test runs use a throwaway HOME (`env HOME=$(mktemp -d) bun test <paths>`). Version bump, CHANGELOG assembly and the release-wide docs pass are the pr-prepare phase and are intentionally absent here.
+
+Staged commit order: pure modules commit FIRST so dependent lanes unblock - Lane B's Task B1 (the shared writer) and Lane A's Tasks A1-A2 (the pure scoring leaves) are the earliest commits on the branch; Lane C may not start until B1's commit lands; Lane D is independent of everything.
+
+Dependency-wait rule: a lane whose task depends on another lane's committed file polls `git log -- <file>` for the upstream lane's commit every 30 seconds, for at most 12 minutes. If the commit has not landed when the cap expires, the lane STOPS and reports which pinned-contract file it is waiting on; it never builds against uncommitted code and never re-implements another lane's module locally.
+
+## Cross-lane contracts (frozen before lane work starts)
+
+These are the pinned shapes every lane builds against. A lane that needs to change one stops and renegotiates in this document first; it never narrows an exported shape unilaterally.
+
+- **K1 - the shared rules-block writer (Lane B owns; Lanes B and C consume; committed FIRST).**
+ - `src/core/install/rules-block.ts`: `export const RULES_BLOCK_ID = Object.freeze({ usage: "usage", lessons: "lessons" } as const)`; `export type RulesBlockId = (typeof RULES_BLOCK_ID)[keyof typeof RULES_BLOCK_ID]`; `export const RULES_BLOCK_MARKERS: Readonly<Record<RulesBlockId, { readonly begin: string; readonly end: string }>>` - the `usage` entry is the settled `DEFAULT_BEGIN_MARKER`/`DEFAULT_END_MARKER` from `src/core/install/managed-block.ts` re-exported under the map (the checker's contract spellings); the `lessons` entry is `<!-- >>> open-second-brain lessons >>> -->` / `<!-- >>> open-second-brain lessons <<< -->`.
+ - `export function renderRulesBlock(blockId: RulesBlockId, body: string): { readonly beginMarker: string; readonly endMarker: string; readonly document: string }`.
+ - `export function readRulesBlock(file: string, blockId: RulesBlockId): string | null` - null when no pair of that spelling exists; throws `RulesBlockError` on multiple/unpaired/reversed pairs (wrapping `ManagedBlockError`).
+ - `export const RULES_BLOCK_STATE = Object.freeze({ absent: "absent", current: "current", drifted: "drifted" } as const)`; `export function rulesBlockDrift(file: string, blockId: RulesBlockId, canonicalBody: string): { readonly state: RulesBlockState; readonly extracted: string | null }` - read-only.
+ - `export interface RulesBlockWriteOptions { readonly dryRun?: boolean; readonly force?: boolean; readonly installedAtMs?: number | null }`; `export interface RulesBlockWriteResult { readonly changed: boolean; readonly backupPath: string | null }`; `export function writeRulesBlock(file: string, blockId: RulesBlockId, canonicalBody: string, opts?: RulesBlockWriteOptions): RulesBlockWriteResult` - refuses with `RulesBlockError` (kind `user-modified-block`) when the existing block diverges from `canonicalBody` AND the file mtime is newer than `installedAtMs`, unless `force`; takes an exclusive-create, collision-laddered backup of the current file before the first write and returns its path; writes atomically via `atomicWriteFileSync`; byte-compares so a re-apply is `changed: false`; `dryRun` writes nothing.
+ - `export function removeRulesBlock(file: string, blockId: RulesBlockId, opts?: { readonly dryRun?: boolean }): { readonly removed: boolean }` - a named skip (removed false) when no pair exists; never `unlink`s the file.
+- **K2 - the canonical usage body and the installer mapping (Lane B owns).**
+ - `src/core/brain/writeback-contract.ts` gains exactly one export: `export const CANONICAL_WRITEBACK_BLOCK_BODY: string` - the gate clauses (marker-writeback guardrail token, same-turn rule, atomic-fact rule) merged with the cross-project-pointer usage content (read `Brain/active.md` at session start, `brain_feedback`, `brain_apply_evidence`, the do-not-dream rule); self-tested to satisfy `missingWritebackGateClauses`. No other change to the checker; it stays write-free.
+ - `src/core/install/instruction-block.ts`: `export function instructionBlockTargetFor(target: InstallTargetId): string | null` - `HOST_INSTRUCTION_PRECEDENCE[target][0]` for targets with an entry, null otherwise (named skip); `export interface InstructionBlockPlan { readonly path: string; readonly exists: boolean; readonly changed: boolean; readonly diff: string; readonly note: string | null }`; `export function planInstructionBlock(env: InstallEnv): InstructionBlockPlan` (vault-root path, pure read + diff render); `export function applyInstructionBlock(env: InstallEnv, opts: { readonly dryRun?: boolean; readonly force?: boolean; readonly approved: InstructionBlockPlan }): { readonly backupPath: string | null }` - refuses when the on-disk bytes moved since the approved preview (typed `RulesBlockError`, kind `preview-drift`); instruction-block lock I/O with `export const INSTRUCTION_BLOCK_LOCK_FILE = "instruction-block.lock.json"`.
+- **K3 - the lessons promotion kernel (Lane C owns; the CLI verb, doctor and status consume exactly this).**
+ - `src/core/brain/lessons-promotion.ts`: `export const LESSONS_PROMOTION_SCOPES_CONFIG_KEY = "lessons.promotion.scopes"`; `export interface LessonPromotionCandidate { readonly prefId: string; readonly principle: string; readonly scope: string; readonly tier: LessonTier; readonly confidence: BrainConfidence; readonly contentHash: string }`; `export const LESSON_PROMOTION_BLOCKED = Object.freeze({ scope_not_enabled: "scope_not_enabled", unconfirmed: "unconfirmed", low_confidence: "low_confidence", tier_not_preferred: "tier_not_preferred", not_approved: "not_approved", stale_approval: "stale_approval", denied: "denied" } as const)`; `export function lessonPromotionCandidates(preferences, lessons, approvals, opts: { readonly enabledScopes: ReadonlyArray<string> }): { readonly promotable: ReadonlyArray<LessonPromotionCandidate>; readonly blocked: ReadonlyArray<{ readonly prefId: string; readonly reason: LessonPromotionBlocked }> }` - pure; `export function renderLessonsBlockBody(promotable: ReadonlyArray<LessonPromotionCandidate>): string` - deterministic (tier, then scope, then id ordering; no timestamps; bounded by the `lessons.limit` config); `export const LESSONS_APPROVALS_FILE = "lessons-approvals.json"`; `export interface LessonApprovalRow { readonly prefId: string; readonly decision: "approved" | "denied"; readonly decidedAt: string; readonly decidedBy: "yes-flag" | "interactive-yes"; readonly approvedContentHash: string; readonly targets: ReadonlyArray<string>; readonly blockId: RulesBlockId; readonly lastPromotedAt: string | null }`; `export function readLessonApprovals(vault: string): ReadonlyArray<LessonApprovalRow>`; `export function recordLessonApproval(vault: string, row: LessonApprovalRow): void` (atomic write). Qualification requires preference-derived only, `confirmed`, `high`, `preferred`, scope enabled, approval fresh (hash match) - every non-member carries exactly one named blocked reason.
+- **K4 - the skill rewrite kernels (Lane A owns; the proposal pipeline, CLI and MCP faces consume exactly this).**
+ - `src/core/brain/skill-rewrite-tasks.ts`: `export const SKILL_BENCHMARKS_DIR = "skill-benchmarks"` (under `Brain/`); `export const SKILL_BENCH_TASK_KIND = Object.freeze({ invocation_transcript: "invocation_transcript" } as const)`; `export const SKILL_BENCH_CHECK = Object.freeze({ tool_used: "tool_used", artifact_created: "artifact_created", step_order: "step_order", forbidden_step: "forbidden_step", output_field: "output_field" } as const)`; `export interface SkillBenchmarkTask { readonly id: string; readonly kind: SkillBenchTaskKind; readonly input: string; readonly expects: ReadonlyArray<SkillBenchExpectation> }`; `export interface SkillBenchmarkTaskSet { readonly skillName: string; readonly tasks: ReadonlyArray<SkillBenchmarkTask>; readonly hash: string }`; `export function parseSkillBenchmarkTasks(raw: unknown, source: string): SkillBenchmarkTaskSet` - fail-fast named errors in the `parseBenchFixture` style; hash is `sha256Hex(canonicalJson(tasks))`.
+ - `src/core/brain/skill-rewrite-spec.ts`: `export const SKILL_REWRITE_SPEC_SCHEMA = "o2b.skill-rewrite.v1"`; `export const SKILL_REWRITE_SPLIT_RULE = "hash-order-70-30"`; `export const SKILL_REWRITE_METRIC = "tasks_passed_rate"`; `export const SKILL_REWRITE_VERDICT = Object.freeze({ promote: "promote", hold: "hold", not_enough_evidence: "not_enough_evidence" } as const)`; `export interface SkillRewriteSpec { readonly schemaVersion: string; readonly skillName: string; readonly tasksHash: string; readonly seed: number; readonly splitRule: string; readonly devTaskIds: ReadonlyArray<string>; readonly heldoutTaskIds: ReadonlyArray<string>; readonly requiredMargin: number; readonly minDevTasks: number }`; `export function buildSkillRewriteSpec(skillName: string, tasks: SkillBenchmarkTaskSet, opts?: { readonly seed?: number }): SkillRewriteSpec`; `export function verifyRewriteTake(spec: SkillRewriteSpec, tasks: SkillBenchmarkTaskSet): { readonly ok: boolean; readonly reason: string | null }` - refuses a task set whose hash no longer matches the receipt.
+ - `src/core/brain/skill-rewrite.ts`: `export const SKILL_REWRITE_STEP = "skill-rewrite-task"`; `export function buildRewriteEnvelopes(candidateBody: string, spec: SkillRewriteSpec, tasks: SkillBenchmarkTaskSet): ReadonlyArray<NeedsLlmStep>` - asserts every envelope task id is a `devTaskIds` member (held-out ids are refused by construction); `export interface RewriteTaskScore { readonly taskId: string; readonly passed: boolean; readonly failedChecks: ReadonlyArray<string> }`; `export function scoreRewriteTranscripts(submissions: ReadonlyArray<unknown>, tasks: SkillBenchmarkTaskSet): ReadonlyArray<RewriteTaskScore>` - validates the submitted transcript shape and scores structural predicates only; `export function selectRewriteCandidate(baseline: ReadonlyArray<RewriteTaskScore>, candidate: ReadonlyArray<RewriteTaskScore>, spec: SkillRewriteSpec): { readonly verdict: SkillRewriteVerdict; readonly baselineRate: number; readonly candidateRate: number }`; `export function checkRewriteHeldout(candidate: ReadonlyArray<RewriteTaskScore>, spec: SkillRewriteSpec): SkillRewriteVerdict` - a miss downgrades `promote` to `hold`; `export function resolveSkillRewriteMode(raw: string | undefined): "gated" | "iterative"` - unknown values are named errors.
+ - `src/core/brain/skill-proposals.ts` extension: `export const SCORED_REWRITE_PATTERN_KIND = "scored_rewrite"` added to `SkillProposalPatternKind`; the staged proposal carries `rewrites_skill`, `spec_hash`, `baseline_score`, `candidate_score`, `heldout_score` beside the existing `SKILL_DRAFT_*` contract keys; the accept journal entry gains `priorContentPath` and `compensateSkillAccept` restores prior bytes from it.
+ - `src/core/brain/skill-accept-journal.ts` extension: `priorContentPath?: string` on `SkillAcceptJournalEntry`, parsed and written like the existing fields.
+ - `src/core/brain/continuity/types.ts` extension: `"skill_rewrite_eval_grade"` added to the union and to `CONTINUITY_RECORD_KINDS` in the same edit; the record carries ids, scores and per-check verdicts with the spec hash - never task text, never transcript text.
+ - `src/core/config.ts` extensions: `SKILL_REWRITE_MODE_CONFIG_KEY = "skill_rewrite.mode"` (env twin `OPEN_SECOND_BRAIN_SKILL_REWRITE_MODE`) and `SKILL_REWRITE_JUDGE_CMD_CONFIG_KEY = "skill_rewrite_judge_cmd"` (env twin), resolved with the flat-key + env-twin pattern.
+- **K5 - shared registries are append-only.** Files listed in the shared table below are edited by a lane only in its lane-final task, appends only (never edits, reorders or deletes another lane's entries), and committed in that lane's own final commit via `git commit --only`. The integrator re-freezes ordering and prose.
+
+## File ownership table
+
+Each file is owned by exactly one lane (or nobody). A lane that needs a file outside its ownership stops and renegotiates this contract; it never reaches into another lane's files.
+
+| Files | Owner |
+| ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------- |
+| `src/core/install/rules-block.ts`, `src/core/install/instruction-block.ts` | Lane B |
+| `src/core/brain/writeback-contract.ts`, `src/cli/install/install.ts`, `src/cli/install/uninstall-target.ts` | Lane B |
+| `tests/core/install/rules-block.test.ts`, `tests/core/install/instruction-block.test.ts`, `tests/cli/install-instruction-step.test.ts`, `tests/core/install/uninstall-instruction-step.test.ts` | Lane B |
+| `src/core/brain/lessons-promotion.ts`, `src/cli/brain/verbs/lessons.ts`, `src/core/brain/doctor/lessons-block-check.ts`, `src/core/brain/status.ts`, `src/core/brain/types.ts` (log kinds), `src/core/brain/policy/blocks/lessons.ts` | Lane C |
+| `tests/core/brain/lessons-promotion.test.ts`, `tests/cli/brain-lessons.test.ts`, `tests/core/brain/doctor/lessons-block-check.test.ts`, `tests/mcp/lessons-status-report.test.ts` | Lane C |
+| `src/core/brain/skill-rewrite-tasks.ts`, `src/core/brain/skill-rewrite-spec.ts`, `src/core/brain/skill-rewrite.ts`, `src/core/brain/skill-proposals.ts`, `src/core/brain/skill-accept-journal.ts`, `src/core/brain/continuity/types.ts`, `src/core/brain/paths.ts`, `src/cli/brain/verbs/skill-proposals.ts`, `src/mcp/brain/procedure-tools.ts`, `tests/fixtures/skill-bench/**` | Lane A |
+| `tests/core/brain/skill-rewrite-tasks.test.ts`, `tests/core/brain/skill-rewrite-spec.test.ts`, `tests/core/brain/skill-rewrite.test.ts`, `tests/core/brain/skill-proposals-rewrite.test.ts`, `tests/cli/skill-rewrite-verb.test.ts`, `tests/mcp/skill-rewrite-status.test.ts` | Lane A |
+| `src/core/install/adapters/codex.ts`, `README.md`, `install/codex.md` | Lane D |
+| `tests/core/install/adapters/codex-chatgpt-note.test.ts` | Lane D |
+| `src/core/config.ts` | Renegotiated: Lane A and Lane C each append their own keys in their lane-final commits per K5 (flat-key blocks are additive; no reordering). |
+| `src/core/brain/writeback-contract.ts` consumers (`src/core/doctor-readiness.ts`), `src/core/brain/write-gate.ts`, `src/core/brain/standing-rules.ts`, `src/core/brain/content-hash.ts`, `src/core/install/managed-block.ts`, `src/core/integrity/digest.ts`, `src/core/reliability/command-bridge.ts`, `src/core/decision-model/eval-spec.ts`, `src/core/bench/fixture.ts`, `src/core/brain/llm-step.ts`, `src/core/runtime/host-facts.ts`, `hooks/**`, `src/core/brain/dream*.ts` | Nobody - read-only precedents; no lane modifies them except through the shared protocol rows below |
+
+Shared files (K5 append-only protocol): `src/core/state/surfaces.ts` (Lane B appends the instruction-block lock row, Lane C the lessons-approvals row, Lane A the skill-benchmarks row - each in its lane-final commit); `src/core/config.ts` (Lane A and Lane C, own keys only); `src/cli/command-manifest.ts` and `src/cli/brain/help-text.ts` (Lane A the skill-proposals subcommands, Lane C the lessons verb, each appends its own rows); `tests/cli/manifest-completeness.test.ts`, `tests/cli/help-surface-parity.test.ts`, `tests/cli/completions.test.ts` (Lane A and C, each appends its own entries); `tests/core/architecture/verdict-vocabulary-census.test.ts` (Lane A registers the rewrite verdict/metric kinds, Lane C the lessons-block state vocabulary, each its own entries); `tests/core/architecture/state-surface-census.test.ts` consumers and `tests/core/state/surfaces.test.ts` (each lane extends for its own row); `docs/cli-reference.md` (each lane appends its own rows); `docs/observability.md` (Lane A grade-record row, Lane C lessons-block row).
+
+## Census obligations (exact files; a lane lands its registrations with the code that trips them, never retrofitted)
+
+- **Lane A**: `tests/core/architecture/write-site-census.test.ts` (the benchmark-path and journal-copy writes route through shared atomic writers; any direct `node:fs` content write needs a categorised `DIRECT_WRITE_EXCLUSIONS` row - the existing `skill-proposals.ts` :1109 and `skill-accept-journal.ts` :744 rows are the templates and must be updated for the new call shapes); `tests/core/architecture/destructive-site-census.test.ts` (the rollback's restore/rm sites in the extended journal compensation name their recovery); `tests/core/architecture/append-shard-census.test.ts` (the grade record appends through the continuity store; a raw append for a rewrite round ledger would need an `APPEND_ALLOW_LIST` row - avoid); `tests/core/architecture/import-cycles.test.ts` (`skill-rewrite-tasks.ts` and `skill-rewrite-spec.ts` stay true leaves, `import type` included); `tests/core/architecture/state-surface-census.test.ts` (`Brain/skill-benchmarks/` row with `sources` attribution); `tests/core/brain/continuity/reader-census.test.ts` (the rewrite module reads continuity records on the correct side of the store/read-model split); `tests/core/architecture/claim-attribution-census.test.ts` (the `skill_rewrite_eval_grade` kind); `tests/core/architecture/visibility-surface-census.test.ts` and the `src/mcp/registry-guard.ts` conventions (the read-only rewrite-status surface, beside the `brain_skill_proposals` row at `src/core/search/visibility-surface-registry.ts:773`); `tests/core/architecture/verdict-vocabulary-census.test.ts` (`SKILL_REWRITE_VERDICT`, `SKILL_REWRITE_METRIC`, the check vocabulary); `tests/core/architecture/progress-census.test.ts` (a `Safeguard`-taking options type carries a synchronous progress sink or a written reason); `tests/core/architecture/egress-census.test.ts` (no `dest`-style parameter - the judge rides the command bridge; a `--out` flag would create an obligation). `tests/core/architecture/host-facts-census.test.ts` stays untouched by construction.
+- **Lane B**: `tests/core/architecture/write-site-census.test.ts` (`rules-block.ts`/`instruction-block.ts` write vault-root files through `atomicWriteFileSync` and the exclusive-create backup helper - shared-class rows, no exclusions; a direct `writeFileSync` binding fails the census); `tests/core/architecture/state-surface-census.test.ts` (`instruction-block.lock.json` row, `sources` naming the installer module); `tests/core/install/ownership.test.ts` (vault-rooted joins only - no home/XDG/temp anchors, no `OUT_OF_VAULT_STATE` row; any cwd targeting would create one and is out of scope); `tests/core/architecture/egress-census.test.ts` (the canonical body is static text plus the vault path - never vault memory content, no redactor owed); `tests/core/brain/vault-guard-census.test.ts` (`writeback-contract.ts` stays write-free so it never enters the walked population); `tests/core/architecture/import-cycles.test.ts` and `tests/core/layering.test.ts` (`core/install` -> `core/brain/writeback-contract` -> `core/install/managed-block` acyclic; core never `process.exit` or writes stdout); `tests/core/architecture/host-facts-census.test.ts` (no new target, the step reuses the existing `"managed-block"` kind in `INSTALL_STEP_KINDS` - both censuses satisfied by construction); doctor exit codes unchanged (`INSTALL_EXIT` reuse).
+- **Lane C**: `tests/core/architecture/write-site-census.test.ts` (the lessons verbs write vault-root rules files ONLY through the shared K1 writer - no new direct writer anywhere in the lane); `tests/core/architecture/state-surface-census.test.ts` (`lessons-approvals.json` row with `sources` attributing every module naming the file or its constant); `tests/core/architecture/verdict-vocabulary-census.test.ts` (the lessons-block state findings reuse the K1 `RULES_BLOCK_STATE` family plus the named `stale-lessons` extension, registered); `tests/core/architecture/append-shard-census.test.ts` and the log-chain doctor checks stay green with the three new log event kinds; `tests/core/architecture/destructive-site-census.test.ts` (the lane never unlinks; removal is uninstall's business under Lane B's path); `tests/core/architecture/visibility-surface-census.test.ts` (MCP stays report-only through existing tools - a new tool would require registry rows in both directions and is avoided by design).
+
+## Lane B - the shared rules-block writer and the installer step (t_ba41a78a)
+
+### Task B1: the writer module (commits FIRST on the branch)
+
+- **Files**: new `src/core/install/rules-block.ts` per contract K1; new `tests/core/install/rules-block.test.ts`.
+- **Acceptance**: the failing-first tests prove: `renderRulesBlock` for `usage` emits the settled default marker spellings and for `lessons` the HTML-comment pair; `writeRulesBlock` on a file with operator content preserves every byte outside the block, is idempotent (second apply reports `changed: false` and byte-equal output), detects and preserves CRLF line endings, takes exactly one exclusive-create laddered backup before the first write and none on a no-op, refuses a block that diverged from canonical on a file newer than `installedAtMs` with kind `user-modified-block` unless `force`, refuses through a symlink by name, and refuses multiple/unpaired/reversed pairs of the block's own spelling by wrapping `ManagedBlockError`; `readRulesBlock` returns null when only a DIFFERENT block id's pair exists; `removeRulesBlock` removes only the pair it owns, collapses its own padding, and is a named skip when absent; `dryRun` writes nothing on every path.
+- **Depends on**: none.
+
+### Task B2: canonical body constant and the installer module
+
+- **Files**: modified `src/core/brain/writeback-contract.ts` (`CANONICAL_WRITEBACK_BLOCK_BODY` + docblock/recovery wording per K2); modified `tests/core/brain/writeback-contract.test.ts` (the self-test: `missingWritebackGateClauses(CANONICAL_WRITEBACK_BLOCK_BODY)` empty; the audit still grades a lessons-only file `missing-block` and a both-blocks file by its own pair alone); new `src/core/install/instruction-block.ts` per K2; new `tests/core/install/instruction-block.test.ts`.
+- **Acceptance**: the failing-first tests prove: the constant satisfies the checker (self-test) and its diff preview renders; `instructionBlockTargetFor` returns AGENTS.md for codex/cursor/opencode/aider, GEMINI.md for gemini-cli, null for copilot-cli/grok/kiro/pi/generic (named skips) - derived from `HOST_INSTRUCTION_PRECEDENCE`, asserted to follow the table if it ever grows; `planInstructionBlock` reads with the checker's posture (lstat first, symlink refused), reports exists/changed/diff and a gemini-cli postNote; `applyInstructionBlock` refuses preview drift by name, writes atomically with a backup, records the lock round-trip (schema version, applied_at, owned files, begin marker), and the forced rewrite of a docs-snippet-style non-conforming body upgrades the file to `conforming` (asserted through the real `auditWritebackContractFile`); the gemini-cli note and the absent-file creation case are plan-visible.
+- **Depends on**: B1.
+
+### Task B3: install and uninstall wiring
+
+- **Files**: modified `src/cli/install/install.ts` (plan augmentation + the post-adapter apply step in `runTarget` under the existing consent gate); modified `src/cli/install/uninstall-target.ts` (the reverse step against the lock); new `tests/cli/install-instruction-step.test.ts`; new `tests/core/install/uninstall-instruction-step.test.ts`.
+- **Acceptance**: the failing-first tests prove: the rendered plan includes the instruction step (or its named skip) for every target; one consent verdict covers adapter write and instruction write (the `--yes`/interactive/`headless-refused` matrix from the existing install suite, exit 6 preserved); exit 4 on a `user-modified-block` refusal; a failure after the adapter apply exits non-zero and a re-run converges (idempotent); uninstall removes the lock-recorded pair, is a named skip when markers are absent, and clears the lock; `o2b install --check` behavior is unchanged (the readiness probe remains the block auditor).
+- **Depends on**: B2.
+
+### Task B4: state surface, census registrations and docs (lane final)
+
+- **Files**: modified `src/core/state/surfaces.ts` (`instruction-block.lock.json` row) with `tests/core/architecture/state-surface-census.test.ts` consumers and `tests/core/state/surfaces.test.ts`; `tests/core/architecture/write-site-census.test.ts` and `tests/core/install/ownership.test.ts` verified green with the new module (shared-class rows); docs rows in `docs/cli-reference.md` and a pointer update in `docs/cross-project-pointer.md` (manual installers are pointed at the install command).
+- **Acceptance**: the failing-first tests prove: the surfaces census binds the new row in both directions and `o2b state status` renders it; the write-site census passes with the shared-writer routing and fails if a direct write is introduced; ownership sweep passes with no out-of-vault anchors; the docs rows name the instruction step per target.
+- **Depends on**: B3.
+
+## Lane C - operator-approved lesson promotion (t_1e952e43)
+
+### Task C1: promotion kernel and approvals ledger
+
+- **Files**: new `src/core/brain/lessons-promotion.ts` per contract K3; modified `src/core/brain/policy/blocks/lessons.ts` (`lessons.promotion.scopes` resolution with env twin, absent-or-empty disables with a named count); modified `src/core/brain/types.ts` (log event kinds `lessons-approved`/`lessons-denied`/`lessons-promoted`); new `tests/core/brain/lessons-promotion.test.ts`.
+- **Acceptance**: the failing-first tests prove: qualification is the exact conjunction (preference-derived, `confirmed`, `high`, `preferred`, scope enabled, approval fresh) and every non-member carries exactly one named blocked reason from the closed set; a stale approval (content-hash mismatch against `_content_hash`) drops the lesson from `promotable` and reports `stale_approval`; `renderLessonsBlockBody` is deterministic (same inputs, identical bytes; tier-then-scope-then-id order; no timestamps; bounded by `lessons.limit`); the rendered body satisfies no contract-clause requirement of the usage block and vice versa (the blocks are independent); the ledger round-trips atomically and `readLessonApprovals` never reads `Brain/`; the writer calls go through K1 only (a source-scanning assertion that the module never imports `node:fs` write functions directly).
+- **Depends on**: B1's COMMIT (dependency-wait rule: poll `git log -- src/core/install/rules-block.ts`, 30 s interval, 12 min cap).
+
+### Task C2: operator verbs
+
+- **Files**: new `src/cli/brain/verbs/lessons.ts` (`cmdBrainLessons`: `candidates` read-only; `approve <pref-id>` / `deny <pref-id>` with the install consent ladder shape; `refresh-blocks` re-rendering and writing blocks under management); SHARED appends: `src/cli/command-manifest.ts`, `src/cli/brain/help-text.ts`, `tests/cli/manifest-completeness.test.ts`, `tests/cli/help-surface-parity.test.ts`, `tests/cli/completions.test.ts`; new `tests/cli/brain-lessons.test.ts`.
+- **Acceptance**: the failing-first tests prove: `candidates` lists promotable plus blocked-with-reasons and is read-only; `approve` renders the plan (target files, block diff), refuses headless without `--yes` (exit 6 vocabulary), records the ledger row only after a successful K1 write, and appends the `lessons-approved` event; `deny` records without writing rules files and suppresses future promotion for that id; `refresh-blocks` is a no-op (named) when no block exists under management, never CREATES a block (creation is approve's write), and updates `last_promoted_at`; a stale lesson drops from the block on refresh and is reported by name.
+- **Depends on**: C1.
+
+### Task C3: doctor, status and report-only MCP
+
+- **Files**: new `src/core/brain/doctor/lessons-block-check.ts` (readiness rows per candidate file: `absent | current | drifted | stale-lessons` beside the existing `writeback_contract` probe) with `tests/core/brain/doctor/lessons-block-check.test.ts`; modified `src/core/brain/status.ts` (approved/denied/stale counts in the snapshot); new `tests/mcp/lessons-status-report.test.ts` (counts visible through the existing status plumbing; no new MCP tool name registered anywhere).
+- **Acceptance**: the failing-first tests prove: a vault with a managed block whose lessons went stale yields the named finding with the refresh command; a current block is silent; the counts match the ledger plus derived staleness; MCP output carries the counts without a new tool and the frozen tool-name parity set is untouched; the doctor never mutates and never throws.
+- **Depends on**: C1 (C2 for the next-command wording only).
+
+### Task C4: state surface, census registrations and docs (lane final)
+
+- **Files**: modified `src/core/state/surfaces.ts` (`lessons-approvals.json` row) with the census consumers and `tests/core/state/surfaces.test.ts`; `tests/core/architecture/verdict-vocabulary-census.test.ts` (the lessons-block state vocabulary); docs rows in `docs/cli-reference.md` and `docs/observability.md`.
+- **Acceptance**: the failing-first tests prove: the state-surface census binds the row with `sources` attribution covering every module naming the file; the verdict census accepts the state vocabulary and fails on an unregistered member; the docs name the approval tier, the verb family and the trust boundary (operator-only writes).
+- **Depends on**: C2, C3.
+
+## Lane A - benchmark-gated skill rewrites (t_635e3e72, the L anchor)
+
+### Task A1: task-set kernel (pure leaf, commits early)
+
+- **Files**: new `src/core/brain/skill-rewrite-tasks.ts` per contract K4; new `tests/core/brain/skill-rewrite-tasks.test.ts`; new `tests/fixtures/skill-bench/<example-skill>/tasks.json`.
+- **Acceptance**: the failing-first tests prove: the parser accepts a valid set and rejects every malformed shape with a named error naming the source path (missing id, unknown kind, unknown check, empty expects, duplicate ids, non-string input); the closed vocabularies are frozen and answered by their guards; the hash is `sha256Hex(canonicalJson(tasks))`, stable across parses and sensitive to any task byte; the module imports nothing from the layer above (import-cycles green).
+- **Depends on**: none.
+
+### Task A2: spec kernel (pure leaf, commits early)
+
+- **Files**: new `src/core/brain/skill-rewrite-spec.ts` per contract K4; new `tests/core/brain/skill-rewrite-spec.test.ts`; new `tests/fixtures/skill-bench/<example-skill>/spec.json`.
+- **Acceptance**: the failing-first tests prove: `buildSkillRewriteSpec` derives dev/heldout membership deterministically from the seed and the split rule (same tasks hash plus seed, identical receipt), the receipt covers every task id exactly once across the two arms, `verifyRewriteTake` accepts the matching set and refuses a changed set with the hash in the reason, and the schema constant is refused-by-name on read when unknown.
+- **Depends on**: A1.
+
+### Task A3: gate kernels - envelopes, scoring, selection, held-out, mode
+
+- **Files**: new `src/core/brain/skill-rewrite.ts` per contract K4; new `tests/core/brain/skill-rewrite.test.ts`.
+- **Acceptance**: the failing-first tests prove: `buildRewriteEnvelopes` emits one `needs-llm-step` per DEV task carrying the candidate body and task input, and refuses (named) when any task id is not a dev member - held-out contamination is refused by construction; `scoreRewriteTranscripts` validates the submitted shape (named refusals) and scores only structural predicates, reporting per-check failures by check id, and never scores a self-reported success field; `selectRewriteCandidate` implements the three arms exactly (strict beat by margin with n met promotes, a tie holds, a short dev n is `not_enough_evidence`); `checkRewriteHeldout` downgrades `promote` to `hold` on a held-out miss and passes `promote` through on a full pass; `resolveSkillRewriteMode` accepts `gated`/`iterative` and errors by name on anything else; the grade-record assembly carries ids, scores and check verdicts with the spec hash and NEVER task or transcript text (an assertion over the serialized record).
+- **Depends on**: A2.
+
+### Task A4: apply path - proposal pipeline, journal prior content, continuity kind, config
+
+- **Files**: modified `src/core/brain/skill-proposals.ts` (`SCORED_REWRITE_PATTERN_KIND`, scored contract fields, prior-content capture before the skills-root overwrite, content-restoring rollback in `compensateSkillAccept`); modified `src/core/brain/skill-accept-journal.ts` (`priorContentPath` field + parse); modified `src/core/brain/continuity/types.ts` (`skill_rewrite_eval_grade` in the union AND `CONTINUITY_RECORD_KINDS`, same edit); modified `src/core/brain/paths.ts` (benchmark dir and journal-copy paths); modified `src/core/config.ts` (Lane A's two keys per K5); new `tests/core/brain/skill-proposals-rewrite.test.ts`.
+- **Acceptance**: the failing-first tests prove: a promoted candidate stages a `scored_rewrite` pending proposal carrying `rewrites_skill` and the three scores plus the spec hash; acceptance goes through `acceptSkillProposal` unchanged and bumps the version by the evolve precedent; the journal captures the prior SKILL.md bytes before the overwrite and a simulated crash mid-accept rolls back to the INCUMBENT BODY (content, not just existence) with the journal retained for recovery exactly as the dead-ends suite pins today; the new continuity kind passes the kind guard and the reader census; an unknown `skill_rewrite.mode` value is a named config error; gate failures stage nothing (a `hold` round leaves the proposal tree unchanged and writes only the grade record).
+- **Depends on**: A3.
+
+### Task A5: CLI verbs, MCP status, census registrations and docs (lane final)
+
+- **Files**: modified `src/cli/brain/verbs/skill-proposals.ts` (`rewrite-plan <skill>`: validate task set + spec, print the frozen receipt and the dev envelopes; `rewrite-score <skill> --rounds-dir <dir>`: score submitted transcripts, run selection and held-out gates, print the verdict, stage the pending proposal on promote-only); modified `src/mcp/brain/procedure-tools.ts` (read-only rewrite status: current spec receipt, last grade verdicts; MCP never accepts and never scores); modified `src/core/state/surfaces.ts` (`Brain/skill-benchmarks/` row) with the census consumers; SHARED appends: `src/cli/command-manifest.ts`, `src/cli/brain/help-text.ts`, `tests/cli/manifest-completeness.test.ts`, `tests/cli/help-surface-parity.test.ts`, `tests/cli/completions.test.ts`, `tests/core/architecture/verdict-vocabulary-census.test.ts`, `tests/core/architecture/claim-attribution-census.test.ts`, `tests/core/architecture/visibility-surface-census.test.ts` rows, `tests/core/brain/continuity/reader-census.test.ts`, `docs/cli-reference.md`, `docs/observability.md`; new `tests/cli/skill-rewrite-verb.test.ts`; new `tests/mcp/skill-rewrite-status.test.ts`.
+- **Acceptance**: the failing-first tests prove: `rewrite-plan` refuses a missing or receipt-mismatched task set by name and prints the receipt plus dev envelopes; `rewrite-score` reports per-task check outcomes and the verdict, stages nothing on `hold`/`not_enough_evidence`, stages the proposal on `promote` after the held-out pass, and exits non-zero naming the reason on a refused take; the MCP status surface is read-only and reach-filtered like its neighbors; all census registrations bind (each census fails when the corresponding registration is removed); the manifest, help and completion surfaces match the dispatcher.
+- **Depends on**: A4.
+
+## Lane D - ChatGPT desktop alias of the codex target (t_8b793376)
+
+### Task D1: detect note
+
+- **Files**: modified `src/core/install/adapters/codex.ts` (the `detect()` note names ChatGPT desktop as a reader of the shared config when the codex binary is absent; the note stays a note - no status, plan, apply or verify change); new `tests/core/install/adapters/codex-chatgpt-note.test.ts`.
+- **Acceptance**: the failing-first tests prove: with the binary absent and a config.toml present, the note names ChatGPT desktop and the config merge; with the binary present the note is unchanged; detect status values (`not-installed | drift | installed`) are unchanged for every scenario; the host-facts census and the frozen target vocabulary stay green (no new id).
+- **Depends on**: none.
+
+### Task D2: docs rows (lane final)
+
+- **Files**: modified `README.md` (a supported-clients row naming ChatGPT desktop with the codex install command); modified `install/codex.md` (a ChatGPT desktop section: shared config path, what install writes, uninstall behavior).
+- **Acceptance**: the failing-first check is a docs-content assertion in `tests/core/install/adapters/codex-chatgpt-note.test.ts`: the README row and the codex guide name ChatGPT desktop and the exact install command, so docs drift fails a test.
+- **Depends on**: D1.
+
+## Integrator
+
+### Task I1: reconciliation and full gates
+
+- **Files**: the shared files if any lane overlap needs re-freezing (`src/core/state/surfaces.ts` final row order, `src/core/config.ts` key blocks, `src/cli/command-manifest.ts` and `src/cli/brain/help-text.ts` order, the `tests/cli/*` shared guards, `docs/cli-reference.md` and `docs/observability.md` coherence pass).
+- **Acceptance**: the full local gates pass in CI order - formatter check, `bun run lint`, `bun run typecheck`, and the FULL test suite (the only place the full suite runs); every user-visible surface added by lanes A-D has a docs row; the census registries hold with all four lanes' registrations; no placeholders anywhere; the branch contains only lane commits plus this reconciliation.
+- **Depends on**: B4, C4, A5, D2.
+
+## Commit shape
+
+- Lane commits use conventional messages on this branch, each committing only its own files via `git commit --only <paths>`: `feat(install): shared rules-block writer for agent instruction files` (B1), `feat(install): brain-usage block installer step for agent rules files` (B2-B4), `feat(brain): operator-approved lesson promotion into agent rules files` (C1-C4), `feat(brain): benchmark-gated skill rewrite loop` (A1-A5), `feat(install): name ChatGPT desktop as a codex config reader` (D1-D2). Shared-registry appends ride each lane's final task commit through the same `--only` rule.
+- The brainstorm artifacts commit separately as `chore(brainstorm): agent-presence-self-improvement` before any lane work.
+- Review gates beyond tests: any diff showing a rules-file write outside the K1 writer, a rules-file write reachable from a hook, dream or MCP path, an agent-approvable lesson path, held-out task text in a dev envelope or a grade record, a scored input that reads the agent's own success claim, or a new `InstallTargetId` for the ChatGPT alias is a defect regardless of test outcome.
diff --git a/docs/brainstorm/agent-presence-self-improvement/variants.md b/docs/brainstorm/agent-presence-self-improvement/variants.md
new file mode 100644
index 00000000..6a4c5f24
--- /dev/null
+++ b/docs/brainstorm/agent-presence-self-improvement/variants.md
@@ -0,0 +1,81 @@
+# Variants - agent-presence-self-improvement
+
+Audit trail for the phase-0 brainstorm. The wave-shape variants were generated in-session for this run; the same text lives at `cli-output/consultant.md` with the prompt at `cli-output/prompt.md`. Below them, each feature's rejected alternatives are recorded with the arguments that closed them, and the anchor-by-anchor premise table closes the document.
+
+## Wave shape
+
+### Variant 1: one installer feature, lessons and rewrites folded into it
+
+- **Approach**: Treat all four cards as one install-surface feature: the instruction block, the lessons block, the ChatGPT naming and even the rewrite lane hang off `o2b install` as steps of one orchestrator, with one manifest recording everything the tool wrote.
+- **Trade-offs**:
+ - Pros: one verb to learn; one consent pass; the lock/manifest story is single.
+ - Cons: the rewrite lane has no install step at all - it is a brain verb family with its own gates, so folding it in is a category error; the lessons approval lifecycle is independent of host detection (a vault with zero installed hosts still promotes lessons); a mega-orchestrator turns every later feature into an `o2b install` regression surface; the card asks for install presence, not install monopoly.
+- **Complexity**: large
+- **Risk**: high
+
+### Variant 2: one shared writer, two producers, separate kernels (chosen)
+
+- **Approach**: Build one block-id-parametrised rules-block writer over the existing managed-block editor; the installer lane and the lessons lane are its two producers with separate lifecycles and consent surfaces; the rewrite loop is a self-contained kernel lane beside them (task sets, preregistered spec, envelope rollouts, selection and held-out gates, apply through the existing proposal pipeline); ChatGPT desktop is detection-plus-docs on the codex adapter. Lanes own disjoint files; shared registries are append-only.
+- **Trade-offs**:
+ - Pros: exactly one write class for harness-owned files, so one census story and one audit trail; no producer forks the editor; each kernel is testable in isolation; the lanes parallelize behind two early pure commits.
+ - Cons: two consent surfaces for rules files (install's and the lessons verbs'), which the docs must keep distinct; the writer contract must be frozen before Lane C starts, adding an ordering constraint the mega-orchestrator would not have.
+- **Complexity**: medium
+- **Risk**: low
+
+### Variant 3: per-feature writers
+
+- **Approach**: Let each lane write its own block logic directly against `insertManagedBlock`: the installer keeps its own compute/apply, the lessons verbs their own.
+- **Trade-offs**:
+ - Pros: no cross-lane contract; each lane ships independently with zero waiting.
+ - Cons: two implementations of the drift refusal, the backup ladder, the idempotence byte-compare and the marker discipline, guaranteed to diverge; two census stories for one write class; the wave's stated spine (one apply-gated rules-file write path) is not built.
+- **Complexity**: small per lane, large in total
+- **Risk**: medium
+
+**Recommended: Variant 2.** The board's own scope option names the spine as one write path plus the closed skill loop; Variant 3 dissolves the spine and Variant 1 miscategories the rewrite lane.
+
+## Feature: install writes the brain-usage block (t_ba41a78a)
+
+- **Rejected: a standalone verb (`o2b brain contract install`).** Cleaner ownership, but it fragments the surface the card names, needs its own consent ladder duplicated from the install one, and leaves `o2b install --check` and the detect table blind to the block. Rejected in favor of a step inside `runTarget` riding the existing consent lane.
+- **Rejected: per-adapter installer logic (each adapter gains an instruction step).** The target-to-file map would be re-derived per adapter against the one precedence table the checker already owns, and hosts without adapters (generic) would have no path at all. Rejected in favor of one orchestrator-level step deriving the target from `HOST_INSTRUCTION_PRECEDENCE`.
+- **Rejected: writing the block at the project cwd instead of the vault root.** Hosts read instruction files at the project root, but the readiness probe audits the vault root, `InstallEnv` has no cwd semantics today, and a cwd target drags an `OUT_OF_VAULT_STATE` row and sweep attribution. Vault-root-only is recorded as the v1 boundary with the override as a named follow-up.
+- **Rejected: a second managed block for the write gate beside the docs pointer snippet.** The editor allows exactly one pair per marker spelling; two pairs of the default spellings throw. One canonical body merging pointer usage and gate clauses is the upgrade path for existing manual installs instead.
+- **Rejected: new `InstallTargetId` or new `INSTALL_STEP_KINDS` entries.** `ManifestEntry.target` is typed to the target vocabulary held equal to the adapter registry in both directions; a pseudo-target has no adapter and fails the host-facts census. The existing `"managed-block"` step kind fits.
+
+## Feature: operator-approved lesson promotion (t_1e952e43)
+
+- **Rejected: one block, two body sections (usage gate and lessons in the same marker pair).** It couples two features' lifecycles, makes the contract audit's clause regexes see lessons text, and turns every lessons refresh into a writeback-contract event. Two block ids with distinct marker spellings keep the audit untouched.
+- **Rejected: dream-tail auto-refresh of blocks under management (consent-once-then-derive).** It would make the dream pass a rules-file writer, which `regenerateLessonsQuiet`'s Brain-scoped discipline and the standing-rules guarantee both forbid; the ambient write would also surprise operators reading the dream's write list. Refresh is operator-only this wave; the middle ground is recorded as a follow-up decision.
+- **Rejected: approval state in `Brain/` (a note or frontmatter the agent can read).** An agent that can read its own approval ledger can social-engineer around it; the derived store under `.open-second-brain/` is the existing home of machine-owned state and is already swept by the state-surface census.
+- **Rejected: an MCP approve verb (agent-facing promotion).** Agent-facing verbs never approve their own lessons - the trust boundary the card exists to create. MCP exposure is report-only counts.
+- **Rejected: a default scope vocabulary for qualification.** A hardcoded list of English scope words deciding what counts as agent behavior is exactly the hardcoded natural-language phrase pattern the project forbids; `lessons.promotion.scopes` is operator-declared and absent/empty disables promotion with a named count.
+
+## Feature: benchmark-gated skill rewrites (t_635e3e72)
+
+- **Rejected: a second apply path for rewrites (a dedicated rewrite writer).** The proposal pipeline already owns gated skill writes: staged pending proposals, human accept, write-ahead journal, compensating rollback, sticky reject. A parallel writer would fork the gate and double the census surface. The one extension the pipeline needs is the journal's prior-content copy, because existence-only rollback cannot restore an overwritten body.
+- **Rejected: an in-process model loop for rollouts (the kernel executes tasks itself).** The tree has no agent runtime in core and must not grow one; generation and execution are envelope-mediated through `needs-llm-step`, exactly the page-draft flow the CLI already drives.
+- **Rejected: free-form prose scoring (an LLM judge deciding pass/fail).** An external judge can never be the selection metric: it is fail-open by contract, unverifiable and language-coupled. Structural predicates over returned artifacts score; the optional judge stays advisory through the command bridge, never moving the metric.
+- **Rejected: repository-local task sets as the primary home.** Operator skills are vault-local and the skills root may sit outside the vault; repo fixtures cannot travel with an operator's skill. Vault-side `Brain/skill-benchmarks/` is primary; repo fixtures exist only for shipped-skill tests.
+- **Rejected: a single collapsed quality score.** `bench/types.ts` explicitly separates metric families; collapsing them hides a rewrite that wins by dropping checks. The selection metric stays a rate over tasks, and the grade record carries per-check outcomes so the drop is visible.
+- **Rejected: held-out results fed back between rounds.** The decision-model discipline is explicit: held-out is measured once on the final champion, never looped into optimization. The envelope builder asserts dev membership by construction.
+- **Rejected: versioned skill publishing (a version chain or release surface).** Assigned to another board card; this wave keeps exactly one prior-content backup per accept attempt.
+
+## Feature: ChatGPT desktop reach (t_8b793376)
+
+- **Rejected: a separate `chatgpt-desktop` install target with its own adapter.** ChatGPT desktop reads the same `$CODEX_HOME/config.toml`; a second adapter would fork detect/plan/apply/verify for one config path, break the host-facts census equality between vocabulary and registry, and leave two targets claiming one file. Alias-of-codex is the pinned decision: the codex target's detect note names ChatGPT desktop when the codex binary is absent, and the README and codex guide carry the discovery rows.
+- **Rejected: renaming the codex target's label to cover both products.** The label is quoted in docs, help text and tests; renaming churns every surface for zero behavioral gain, and "Codex CLI" remains the accurate name for the subprocess path. The note and docs carry the alias instead.
+- **Rejected: ChatGPT-specific detection (app-bundle probing, process scanning).** Host detection in this tree keys on files and config, never on manifests or running processes; a bundle probe would be a new detection class with platform-specific failure modes for a target whose file surface is already fully served. The binary-absent-plus-config-present signal is the honest, file-keyed case.
+
+## Orchestrator decision
+
+**Chosen: Variant 2** (the recommended wave shape; every per-feature decision above taken as recorded).
+
+## Premise verification
+
+Spot-checked against the live worktree at 07125f6d (branch feat/agent-presence-self-improvement) on 2026-11-02. No premise was refuted; no card is dropped. Corrections are recorded for the plan.
+
+| Card | Premise | Key anchors checked live | Result |
+| ---------- | ---------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
+| t_635e3e72 | confirmed | `src/core/surface/skills.ts:80` (SKILL_FILE_NAME), `:83` (skillRoots), `:162` (discoverSkills); `src/core/brain/skill-usage.ts:106` (deriveSkillUsage), `:235` (skillUsageRankingWeights); `src/core/brain/skill-proposals.ts:90` (pattern kinds), `:766` (acceptSkillProposal), `:975` (SkillAcceptLockedError), `:868` (skills-root materialize, `overwrite: false`, no `vaultForRelativePath`), `:1393` (evolveAcceptedProposal, `overwrite: true`, frontmatter merge only); `src/core/brain/skill-accept-journal.ts` (existence flags only, no prior-content field); `src/core/decision-model/eval-spec.ts:41` (hash-order-30-70), `:56` (`promote | hold | not_enough_evidence`); `src/core/bench/fixture.ts:42`(parseBenchFixture);`src/core/brain/llm-step.ts:27`(NEEDS_LLM_STEP),`:85`(buildNeedsLlmStep);`src/core/brain/continuity/types.ts:66/:148/:167`(skill_invoked, CONTINUITY_RECORD_KINDS);`src/core/config.ts:733/:806/:1887`(skills_dir, skill_auto_attach, bench_judge_cmd);`tests/core/architecture/write-site-census.test.ts:744/:1109`; `src/core/search/visibility-surface-registry.ts:773`(brain_skill_proposals); grep for rewrite/benchmark/selection-gate across skill modules: zero hits;`PlanState.retires` (dream-plan.ts:214) plans preference retires only | Exact except `buildNeedsLlmStep` at `llm-step.ts:85` (recon said :67) and the journal's existence-only rollback made explicit (the prior-content extension is required). No rewrite lane exists; the preregistration and gate machinery to reuse is exactly where the recon placed it. |
+| t_ba41a78a | confirmed | `src/core/brain/writeback-contract.ts:29-33` (NO INSTALLER LIVES HERE docblock), `:98-102` (AGENT_INSTRUCTION_FILES), `:137-145` (HOST_INSTRUCTION_PRECEDENCE: claude-code/codex/cursor/opencode/aider/gemini-cli), `:173-187` (WRITEBACK_CONTRACT_REQUIREMENTS, three clauses), `missingWritebackGateClauses` pure; `src/core/install/managed-block.ts:21-22` (DEFAULT markers), `insertManagedBlock` idempotent, `validateMarkers` refusing multiple/unpaired/reversed; `src/cli/install/install.ts:415-462` (fail-closed consent, exit 6, `headless-refused`, verdicts `yes-flag`/`interactive-yes`); `src/core/brain/protect.ts:433` (backupHostFile, exclusive create 0600, laddered); `src/core/doctor-readiness.ts` (probe audits `opts.vault`, shadow triples fail); `src/core/runtime/host-facts.ts:61-88` (INSTALL_TARGET_ID, ten members, NO claude-code); `src/core/state/surfaces.ts:297-298/:580/:594` (install/protect lock rows) | Exact except the scope correction: the recon's "claude-code writes CLAUDE.md" installer row is unreachable - there is no claude-code install target (the precedence docblock states it), so the installer maps registered targets only (codex, cursor, opencode, aider to AGENTS.md; gemini-cli to GEMINI.md) and the mapping derives from the table so a future target inherits it. The checker defines conformance and nothing writes today; the installer lane is genuinely absent. |
+| t_1e952e43 | confirmed | `src/core/brain/types.ts:89-103` (BRAIN_PREFERENCE_STATUS = unconfirmed/confirmed/quarantine, no approval state), `:106-111` (BRAIN_CONFIDENCE); `src/core/brain/lessons.ts:73-79` (LESSON_TIER), `:155-253` (computeLessons, confirmed+quarantine filter), `:470-483` (regenerateLessons, idempotent), `:509-515` (regenerateLessonsQuiet); `src/core/brain/dream-refresh.ts:265-280` (automatic firstApplied promotion, quarantine ladder); `src/core/brain/content-hash.ts:1-30` (observability-not-enforcement pinning); `src/core/brain/write-gate.ts:20-56` (inbound lanes signals/notes/ingest); `src/core/brain/standing-rules.ts` (operator channel, never machine-written); no `o2b brain lessons` verb exists; `src/core/install/manifest.ts:37` (derived-store lock home) | Exact except `HOST_INSTRUCTION_PRECEDENCE` at :137-145 (recon said :136-143). No approval-hold tier exists and promotion is automatic today; the write class for harness-owned files does not exist; both halves of the card are real. |
+| t_8b793376 | confirmed (verified inline; the recon report was not present at design time) | grep for ChatGPT across `src/`, `docs/`, `README.md`: zero hits; `src/core/install/adapters/codex.ts:91` (TARGET), `:121` (`Bun.which("codex")`), `:317-334` (detect: status keyed on declared servers, binary-presence note), `$CODEX_HOME`-or-`~/.codex` via `src/core/runtime/host-facts.ts`; `src/core/install/adapters/all.ts` (ten side-effect registrations); `src/core/install/types.ts:167-198` (adapter contract); `tests/core/architecture/host-facts-census.test.ts` (vocabulary equals registry in both directions); `README.md:80` (Codex row in the supported-clients table) | Exact. No ChatGPT surface exists anywhere; the codex adapter serves the shared config file with the TOML-merge fallback already working when the binary is absent; the residue is detection notes plus docs, and the alias-of-codex decision is pinned in design.md. The external premise (ChatGPT desktop reads the codex config) was accepted at scope review per the batch report. |
diff --git a/docs/cli-reference.md b/docs/cli-reference.md
index d513b129..f2fdd97b 100644
--- a/docs/cli-reference.md
+++ b/docs/cli-reference.md
@@ -10,7 +10,7 @@ Most verbs accept `--vault <path>` and `--config <path>`; the values default to
o2b status Show config / vault status
o2b init Bootstrap the vault profile (idempotent)
o2b init --interactive Guided first-time setup wizard
-o2b install Runtime installer: bare form detects, --target <name> plans, --target <name> --apply writes (consent-gated), --check verifies (see "Exit codes" below); --friction reports what each host costs instead of acting on one
+o2b install Runtime installer: bare form detects, --target <name> plans, --target <name> --apply writes (consent-gated), --check verifies (see "Exit codes" below); --friction reports what each host costs instead of acting on one; --apply for a target whose host reads an agent-instruction file also writes the Open Second Brain write-gate managed block into that file at the vault root under the same consent verdict (codex, cursor, opencode and aider read AGENTS.md; gemini-cli reads GEMINI.md, name-implied only; copilot-cli, grok, kiro, pi and generic install no instruction step and the plan says so), preserving every byte outside the block, refusing a hand-edited block with exit 4 unless --force, and recording the ownership entry at <vault>/.open-second-brain/instruction-block.lock.json
o2b install-cli Symlink o2b and vault-log into ~/.local/bin
o2b-mcp Console-script alias for `o2b mcp`, forwards all flags
o2b doctor Run vault + adapter checks
@@ -24,7 +24,7 @@ o2b tool-call Invoke an MCP tool handler from the CLI
o2b version Print the installed Open Second Brain version; --version is a synonym
o2b help --json Print the command/flag manifest as JSON
o2b completions --shell zsh Print completions for bash|zsh|fish|elvish|nushell|powershell
-o2b uninstall Print uninstall plan; --apply-local cleans config; --remove-cli removes symlinks
+o2b uninstall Print uninstall plan; --apply-local cleans config; --remove-cli removes symlinks; --target <name> --apply also removes the instruction block this tool recorded for that host (only a lock-recorded pair is removed, an absent pair is a named skip, and the ownership entry at <vault>/.open-second-brain/instruction-block.lock.json is cleared either way)
o2b update Update Open Second Brain across all detected runtimes; --target <name> / --dry-run / --force / --json
o2b bootstrap One-command harness provisioning for --target <name> (codex, grok, opencode run the adapter's idempotent apply; generic prints the payload plus manual steps; claude-code and zcode are plugin verify-only). --token mints mcp_token_<target> and prints the material exactly once - never on argv, never in a harness config; a second identical run is a byte-identical no-op; --rotate re-mints under the same name (effective on the next request, no restart); --check verifies drift; receipt at <vault>/.open-second-brain/bootstrap.lock.json
o2b mcp token Per-agent MCP token management over the vault's hash-at-rest store: mint (derives mcp_token_<agent> unless --name), rotate, revoke, list; mint and rotate print the material exactly once with a shown-once notice, list shows metadata only
@@ -412,7 +412,7 @@ because it is a report and generates nothing.
## Brain (observing memory)
-```text
+````text
o2b brain init Bootstrap Brain/{inbox,preferences,retired,log,.snapshots}/ + _brain.yaml + _BRAIN.md; --starter drops the bundled example set
o2b brain feedback Record one taste signal (--topic, --signal, --principle, --scope, ...); --scope is optional and falls back to feedback.default_scope from _brain.yaml when set
o2b brain dream Run the deterministic consolidation pass (idempotent; usually cron'd - `o2b brain maintenance run --cron-template` prints a schedule that runs it inside the maintenance lane)
@@ -448,7 +448,7 @@ o2b brain export Read-only dump of active preferences, or (since v1
o2b brain bank-export (CLI-only) One-file backup bundle: preferences, the page graph, page contracts, the sources dashboard. Redacted on the way out; refuses with exit 1 on an unreadable `pref-*.md` (since v1.49.0). Since v1.95.0 a privacy-marker-denied preference row is filtered from the bundle's preferences section before the bundle is composed and named in its `preferences_omitted` report (absent when empty) beside the same stderr notice, so a smaller bundle is never a silent one; unmarked vaults produce byte-identical bundles
o2b brain bank-import (CLI-only) Restore a bank bundle (--mode skip|overwrite|merge) [--trusted-restore]. Preference rows restore UNTRUSTED by default: every row lands `unconfirmed`, unpinned, at low confidence, on a fresh trial window dated from the restore - including a row the bundle already marked unconfirmed - and the run names each row it reset; `--trusted-restore` keeps the carried status, confidence, pin and window verbatim, for a backup you vouch for. A malformed preference already in the DESTINATION does not abort the import: the rows restore and the run prints `topic-key check incomplete: <path>` for each rule the topic-collision scan could not read, because that list is then a partial answer (since v1.49.0)
o2b brain explorer (CLI-only) Force-directed HTML graph of Brain/preferences + retired; live HTTP on 127.0.0.1 or --export <path> single-file. Keyboard-accessible listbox + localStorage layout persistence. Double-click a node to open it in Obsidian (live mode). Since v1.49.0 BOTH modes refuse a Brain file they cannot parse - `--export` writes nothing and exits 1, and live mode does not start, because a browser showing a silently smaller graph is the same lie as a written file - and `--export` runs the shared redactor over the graph, so its output differs from a pre-v1.49.0 export on any vault holding a credential-shaped value. Since v1.86.0 live mode serves two read-only console routes beside the graph, `/counts.json` (recall-telemetry summary, most-recalled artifacts, a written-per-day histogram over the trailing 30 days, per-surface report-snapshot dates that read as disabled while the feature is off) and `/status.json` (the operator snapshot), both re-reading the vault on every GET, and the page renders Counts and Vault status sections from them; a static export states that the live routes are unreachable instead of firing fetches that can only fail
-o2b brain doctor Check Brain-specific invariants (status-vs-folder, broken wikilinks, ...). --remediate [--dry-run] plans a dependency-ordered repair and applies auto-safe content-hash re-stamps. Since v1.81.0 the report also prints a count-only archive section over Brain/.archives/ (entries, combined bytes, stamped pages whose entry is missing or mismatched, entries no page cites; silent on a vault that never archived a source) and runs the fail-soft `blank-session-identity` check, counting continuity records still carrying the legacy blank session id; both are informational and neither repairs. Since v1.96.0 the pass runs the fail-soft `git-tracked-derived-state` check - derived runtime state under `.open-second-brain/` that git already tracks (measured by `git ls-files`, never inferred from status) is an ERROR naming one location-independent untrack command (`git -C '<vault>' rm -r --cached -- .open-second-brain`, single-quoted, runnable from any directory) plus the missing `/.open-second-brain/` ignore line, with the tracked paths listed as capped evidence and the remainder counted, a present-but-unignored untracked store is a warning, and the check is silent outside a git worktree, when the store directory is absent, and when git cannot answer; the ignore half is remediated by `o2b brain init`'s idempotent guard block, the untracking is git's own, and the check never edits anything. Since v1.96.0 the pass also runs the fail-soft `planted-structure-rows` audit - one warning counting live structure rows (wikilinks, `@osb` markers, ```osb fence lines, ATX headings). The population splits by family: the marker and osb-fence families are scanned on every readable page under `Brain/` - no Brain writer emits a live marker line or an osb fence, so one anywhere in the derived layer is planted - while the wikilink and heading families are scanned only on the third-party provenance lanes (brain-capture captures, brain-source summaries, untrusted-stamped pages, quarantined entities), where caller text lands; on both populations the sections the Brain writers themselves render are excluded, not reported - a capture's marker-authorized `## Guidance` section and a source summary's `## Sources`, `## Premises`, `## Entities` and `## Connections to existing notes` citation sections, plus its `## Parts` and `## Table` derivation headings, are this vault's own output. The finding names up to five paths and counts the rest, names lane pages first, deduplicates `Brain/pending/` staged copies against their publish targets, skips pages the caller may not read, and is silent on a vault with none; under `markdown_neutralize_mode: shadow` the finding appends the preview naming what enforce would escape on the next capture or untrusted ingest of the same text. The audit is read-only by contract: the rows leave only by re-capturing the text with the gate in `enforce` or by a later repair pass, so the finding carries no `o2b` command
+o2b brain doctor Check Brain-specific invariants (status-vs-folder, broken wikilinks, ...). --remediate [--dry-run] plans a dependency-ordered repair and applies auto-safe content-hash re-stamps. Since v1.81.0 the report also prints a count-only archive section over Brain/.archives/ (entries, combined bytes, stamped pages whose entry is missing or mismatched, entries no page cites; silent on a vault that never archived a source) and runs the fail-soft `blank-session-identity` check, counting continuity records still carrying the legacy blank session id; both are informational and neither repairs. Since v1.96.0 the pass runs the fail-soft `git-tracked-derived-state` check - derived runtime state under `.open-second-brain/` that git already tracks (measured by `git ls-files`, never inferred from status) is an ERROR naming one location-independent untrack command (`git -C '<vault>' rm -r --cached -- .open-second-brain`, single-quoted, runnable from any directory) plus the missing `/.open-second-brain/` ignore line, with the tracked paths listed as capped evidence and the remainder counted, a present-but-unignored untracked store is a warning, and the check is silent outside a git worktree, when the store directory is absent, and when git cannot answer; the ignore half is remediated by `o2b brain init`'s idempotent guard block, the untracking is git's own, and the check never edits anything. Since v1.96.0 the pass also runs the fail-soft `planted-structure-rows` audit - one warning counting live structure rows (wikilinks, `@osb` markers, ```osb fence lines, ATX headings). The population splits by family: the marker and osb-fence families are scanned on every readable page under `Brain/` - no Brain writer emits a live marker line or an osb fence, so one anywhere in the derived layer is planted - while the wikilink and heading families are scanned only on the third-party provenance lanes (brain-capture captures, brain-source summaries, untrusted-stamped pages, quarantined entities), where caller text lands; on both populations the sections the Brain writers themselves render are excluded, not reported - a capture's marker-authorized `## Guidance` section and a source summary's `## Sources`, `## Premises`, `## Entities` and `## Connections to existing notes` citation sections, plus its `## Parts` and `## Table` derivation headings, are this vault's own output. The finding names up to five paths and counts the rest, names lane pages first, deduplicates `Brain/pending/` staged copies against their publish targets, skips pages the caller may not read, and is silent on a vault with none; under `markdown_neutralize_mode: shadow` the finding appends the preview naming what enforce would escape on the next capture or untrusted ingest of the same text. The audit is read-only by contract: the rows leave only by re-capturing the text with the gate in `enforce` or by a later repair pass, so the finding carries no `o2b` command. Since v1.98.0 the pass also runs the fail-soft, read-only `lessons-block` readiness check over the managed agent-rules blocks (the brain-usage block `o2b install` writes and the operator-approved lessons block beside it): each lessons block is graded against the same derivation a refresh would render - `lessons-block-absent` when an approval names a rules file that carries no block, `lessons-block-drifted` when a block is behind the canonical body, `lessons-block-stale-lessons` when it still carries a lesson whose approval went stale - every finding names the verb that heals it (`o2b brain lessons approve` / `refresh-blocks`, including the `--force` wording for a hand-edited block) and a current block is silent; a damaged approvals ledger surfaces as `lessons-approvals-unreadable`, lifted only by the operator moving or deleting the file
o2b brain health Semantic-health report (since v0.14.0): contradictory confirmed preferences, recurring concepts with no dedicated preference, stale claims, plus a clean | watch | investigate verdict
o2b brain history Render a preference's edit-history timeline (since v0.14.0): one entry per content mutation (principle / scope / status before -> after)
o2b brain audit Render a preference's full mutation audit trail (since v0.21.0): create / promote / update / retire / merge with agent, reason, revision + content-hash before/after. ret- or bare-slug arg resolves to the same trail
@@ -488,7 +488,7 @@ o2b brain validate --paths <path> [--paths <path>...] [--strict] | --
o2b brain scaffold-stub list [--limit N] [--json] | write <target> [--path <p>] [--source <s>...] [--if-exists refuse|skip] [--apply] [--json] - unresolved wikilink targets. list reads them from the search index and refuses with a state and a next_command when that index is missing or only partially resolved, never printing an empty list for an index nobody finished resolving; write materialises a stub whose title is the target and whose body links back to its sources. A target that already resolves, or names several notes, is refused
o2b brain note-history Decompose a note's git history into episodic phases split on a commit-time gap (since v1.11.0)
o2b brain import-claude-memory (CLI-only) Import metadata.type=feedback entries from a Claude Code memory directory into Brain/preferences/. --dry-run / --apply, sidecar manifest for idempotency, UPDATE preserves accumulated evidence; --approval-digest <hex> seals the plan - non-interactive --apply must carry the digest a prior --dry-run printed and then lands exactly the approved plan or nothing (a stale digest refuses with a re-run remedy), an entry whose name cannot land a parseable tag skips as a named row instead of aborting, and a digest paired with --dry-run refuses
-```
+````
### Time axis (since v0.10.18)
@@ -695,6 +695,7 @@ Wikilinks to frontmatter `aliases:` resolve at index materialization (schema v7)
```text
o2b brain pending list [--lane signals|notes|ingest|all] | apply <id> [--dry-run] | reject <id> --reason <text> [--dry-run] - review the write-approval queues (`write_approval.enabled` plus the per-lane keys); signals stage flat in Brain/pending/ (sig- ids), note creates under Brain/pending/notes/ (note- ids carrying the encoded publish target), ingest summary pages under Brain/pending/ingest/ (ing- ids); list shows every lane sorted and names unreadable entries with a reason, apply moves the unchanged document to its decoded publish target (--dry-run previews and writes nothing), reject renders it into Brain/retired/ with the reason; everything staged under Brain/pending/ stays out of the search index (admission reason `review-pending`), so recall cannot surface an unreviewed document
+o2b brain lessons candidates | approve <pref-id> [--target AGENTS.md|CLAUDE.md|GEMINI.md] [--apply] [--yes] [--force] | deny <pref-id> [--apply] [--yes] | refresh-blocks [--apply] [--yes] [--force] - operator-approved lesson promotion into the managed lessons block of the agent rules files (t_1e952e43). candidates is read-only: the promotable set, every blocked lesson with its single named reason, and the resolved promotion scopes (`lessons.promotion.scopes`; absent-or-empty disables promotion). approve rides the install consent ladder (plan-only default, headless `--apply` without `--yes` refuses with exit 6), records the approval only after the rules-file writes landed, and pins the approved text by content hash; deny records without writing rules files; refresh-blocks re-renders blocks under management (dry run by default; never creates one), drops a lesson whose approval went stale by name, and stamps last_promoted_at. Operator-only writes: no MCP tool exposes this verb family, so an agent can never approve its own lessons. The decisions in force live in the approval ledger `<vault>/.open-second-brain/lessons-approvals.json`; deleting it lifts every approval and refusal at once, which blocks rather than promotes
o2b brain signal retire <id> --reason <text> [--superseded-by <id>] - move an inbox signal to Brain/retired/ with retire frontmatter (_status, retired_at, retired_reason, optional superseded_by, old-id alias); retired signals leave dream intake but stay queryable
o2b brain entity prune [--confirm] [--json] - list entity nodes whose labels fail the structural quality gate (dry-run default); --confirm removes nodes and their edges behind the snapshot gate and reports the recovery point
o2b brain entity lexicon rebuild [--apply] [--json] - rebuild the store-learned label lexicon from the vault's own pages (dry-run default; --apply writes only the derived Brain/entities/lexicon.json)
@@ -905,6 +906,8 @@ o2b brain orphan-repair [--apply --confirm "apply orphan repair"] - detach
o2b brain design-note <topic> [--payload <json> | --payload-file <path>] [--agent <name>] [--json] - the one-shot sibling of `o2b brain panel`. Without a payload it is read-only: it grounds the topic in the vault's tension records, decision records and truth projections and prints the single needs-llm-step envelope the calling agent answers, naming any store the vault holds nothing in (which is not the same as a store that matched nothing). With a payload it validates the written note and commits it as Brain/decisions/design-<date>-<topic>.md. The note must weigh named alternatives and mark EXACTLY ONE recommended: zero and two-plus are both refused, and the refusal states the count. A second note for the same topic on the same day is refused, never overwritten
o2b brain skill-proposals page-candidates [--json] - read-only: gate the vault's user pages on the page-meta trio (core tier, non-stale lifecycle, high confidence) and an observed-reuse floor, skip any page an installed skill already covers, and return one needs-llm-step envelope per admitted page plus every skip with its reason
o2b brain skill-proposals page-draft <page> (--payload <json> | --payload-file <path>) [--json] - validate a returned SKILL.md draft and stage it as a pending mature_page proposal INSIDE the vault; accept is what materializes the SKILL.md under the configured skills root, through the write-ahead journal
+o2b brain skill-proposals rewrite-plan <skill> --candidate-file <path> [--skills-root <path>] [--json] - verify the skill's benchmark task set (Brain/skill-benchmarks/<skill>/tasks.json) against its frozen receipt (spec.json) and print the receipt plus the dev-round envelopes: one baseline round over the incumbent body and one candidate round over the candidate file, each with its transcript drop site under Brain/skill-benchmarks/<skill>/rounds/. Held-out members are never printed here - their single check is handed out by rewrite-score, only after a promote. Refuses by name on a missing task set, a receipt the task set no longer matches (naming the hash in the reason), an unknown skill_rewrite.mode, or a missing incumbent
+o2b brain skill-proposals rewrite-score <skill> [--rounds-dir <dir>] [--candidate-file <path>] [--skills-root <path>] [--json] - grade the submitted round transcripts with structural predicates only (never a self-reported success field), run the preregistered selection gate (a candidate promotes only by strictly beating the baseline by more than the pinned margin with the dev n met; a tie holds; a short dev arm is its own not_enough_evidence arm), hand out the ONE held-out round on a promote, and stage a scored_rewrite pending proposal ONLY on a final promote after the held-out pass. A hold and a short dev arm write only the grade record (skill_rewrite_eval_grade in the continuity ledger) and stage nothing. The optional judge (skill_rewrite_judge_cmd) rides the command bridge, is advisory, and never moves the metric. Re-runnable: the transcripts stay in the rounds tree and the gates are deterministic
o2b brain extract-signals <session-ref> [--payload <json> | --payload-file <path>] [--surveyed-turns-hash <sha256>] [--force] [--agent <name>] [--json] - mine durable taste signals from an already-imported session's user turns. Without a payload it is read-only: it prints the turns it would mine and the single needs-llm-step envelope the calling agent answers. With a payload it validates the answer and writes the accepted items into Brain/inbox/ as speculative source_type: auto_extract signals, subject to the durability denylist and to Brain/pending/ staging when write approval is on. A payload over the per-session cap, an item below the confidence floor, or two items sharing a topic refuses the whole payload by name and writes nothing; a session with no imported turns is refused, never reported as empty
With the optional decision-model turn pre-filter (use extract_prefilter, docs/decision-models/extract-prefilter.md) the --json plan may add turns_dropped, skipped { reason: decision_model_prefilter, turns_dropped } with llm_step: null (nothing to mine), and decision_model { degraded }; none appears with the use off. Payload items accept an optional string source_turn
Since v1.86.0 a commit that ends with nothing written and nothing staged records a zero-yield tombstone for the session in the session mining ledger (<vault>/.open-second-brain/session-mining-ledger.json, beside the session import ledger, keyed on a SHA-256 of the mined turn material), and a plan over that session at unchanged content returns no envelope: --json carries skipped { reason: mining_tombstone, mining_outcome { written, staged, deduped, durability_rejected } } with llm_step: null and empty turns_mined, and text mode names the breakdown. --force bypasses the tombstone for exactly the one plan call it is given to - the remedy when a downstream preference was removed and the session should be re-proposed; a re-import that changes the session's turns re-opens it with no clearing step, and a corrupt mining ledger is refused by name rather than read as empty. The commit keys the record on the session's turns as they stand at commit time. A plan that hands out an envelope records the hash of the turns it offered as a pending survey (<vault>/.open-second-brain/session-mining-surveys.json), so plan, then a plain commit of its answer (an empty items list included) is all it takes; the barren commit writes its tombstone only while the session still holds exactly the surveyed turns, and a turn imported after the plan, two pending plans over different turns, or no plan since the last commit withholds the tombstone and names why in mining_ledger_failure (a yield is recorded either way). A plan whose survey could not be recorded carries survey_record_failure in --json and names it in text. --surveyed-turns-hash optionally passes the plan's surveyed_turns_hash back as a check - a value that is not a 64-character lowercase hex digest refuses the commit, and a value the session no longer matches writes the signals but no mining record and names why. A commit that succeeds but cannot record its tombstone still exits 0, naming the failure as mining_ledger_failure in --json and in text
@@ -2323,32 +2326,32 @@ narrowed them - so an existing consumer's payload is unchanged.
identifier safe to branch on, and each names its own lane in its own name,
so there is no separate lane field that could drift from it:
-| Code | The narrowing it reports |
-| ------------------------------------ | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
+| Code | The narrowing it reports |
+| ------------------------------------ | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ |
| `index-stale` | the index was last updated more than ten minutes ago (`detail.ageSeconds`), so notes changed since then may be missing; `detail.behindCount` is the measured number of documents the next incremental run would add, update or delete, counted live under the same gate that fires the code by a stat-only walk diffed against the index - an upper bound (a touch-only file counts as changed), a measured zero rides too, and absent means not measured, never zero. The code still does not say a refresh is running: freshen on read starts a background run when it can, and starts none when it is off, a failed run is backing off, another run or writer holds the index, the index is read-only for this reader, or the run cannot be spawned |
-| `keyword-fts-match-empty` | the query tokenised to an empty FTS match, so the keyword lane never ran |
-| `keyword-trigram-lane-fault` | the trigram candidate lane could not be read; `detail.fault` carries that lane's own classification |
-| `semantic-embeddings-absent` | the index holds no compatible embedding |
-| `semantic-vec-extension-unavailable` | sqlite-vec is not loaded on this machine |
-| `semantic-capability-blocked` | the configured semantic capability blocks the vector lane; `detail.tier` names the rung |
-| `semantic-cost-unpriced` | the embedding model has no known price and `embedding_cost_gate_usd` is positive, so the query embed of a caller that is not local was refused before any provider call and the semantic lane did not run |
-| `semantic-query-truncated` | the query was longer than the effective embedding input window, so the semantic lane searched a cut prefix of it; `detail.windowTokens` is the window |
-| `semantic-query-empty-fit` | the instruction prefix alone fills the effective embedding input window, so no part of the query was left to embed and the semantic lane did not run; `detail.windowTokens` is the window |
-| `semantic-provider-unavailable` | the embedding provider could not answer; `detail.category` carries the error category |
-| `semantic-empty-query-vector` | the provider answered with an empty query vector |
-| `semantic-structured-lanes-skipped` | a structured semantic lane was requested while semantic search is off |
-| `semantic-embedding-abi-drift` | the index carries embeddings written by another build; `detail.fields` counts the contradicted ABI fields |
-| `hybrid-degraded` | hybrid recall was asked for and the semantic lane did not run, so this answer is keyword-only |
-| `hybrid-deadline-exceeded` | the composite hybrid path (embed, semantic top-k, rerank, second pass) outlived `search_hybrid_deadline_ms`, so the phases past the budget were cut; `detail.budgetMs` is the deadline, `detail.elapsedMs` the moment it fired |
-| `person-derived-ambiguity` | a person form in the query reached several people only through derivation (an initial, a word order or an operator nickname), so nothing was expanded for it rather than guess one person; `detail` maps that form to the competing person ids, dot-joined |
-| `rank-cap-truncated-pool` | the rank cap truncated the candidate pool; `detail.cap` is the cap that bit |
-| `rerank-provider-unavailable` | the configured cross-encoder reranker (remote endpoint or local model) could not answer, so the answer keeps the heuristic order; `detail.category` is one of `auth`, `quota`, `gone`, `rejected`, `transient`, `timeout`, `network`, `malformed`, `unclassified` |
-| `rerank-model-sunset` | the configured rerank model's announced decommission date has passed, so no rerank request was sent and the answer keeps the heuristic order |
-| `relevance-floor-dropped-rows` | the relevance floor dropped ranked rows; `detail.dropped` counts them |
-| `source-session-capped-rows` | the per-source-session pool cap (`search_pool_max_per_session`, since v1.83.0) dropped ranked rows whose source import session already held its share of the pool; when that left the window under-filled, the pool was re-widened once before this answer was cut; `detail.dropped` counts them against `detail.cap` |
-| `scope-filters-dropped-rows` | visibility, ownership, or session / project scope dropped ranked rows; `detail.dropped` against `detail.before` |
-| `cross-vault-origin-failed` | a cross-vault origin could not be searched; `detail.origin` is the origin label |
-| `cross-vault-chain-stopped` | an origin answered confidently and the remaining origins were deliberately not searched; `detail.skipped` counts them |
+| `keyword-fts-match-empty` | the query tokenised to an empty FTS match, so the keyword lane never ran |
+| `keyword-trigram-lane-fault` | the trigram candidate lane could not be read; `detail.fault` carries that lane's own classification |
+| `semantic-embeddings-absent` | the index holds no compatible embedding |
+| `semantic-vec-extension-unavailable` | sqlite-vec is not loaded on this machine |
+| `semantic-capability-blocked` | the configured semantic capability blocks the vector lane; `detail.tier` names the rung |
+| `semantic-cost-unpriced` | the embedding model has no known price and `embedding_cost_gate_usd` is positive, so the query embed of a caller that is not local was refused before any provider call and the semantic lane did not run |
+| `semantic-query-truncated` | the query was longer than the effective embedding input window, so the semantic lane searched a cut prefix of it; `detail.windowTokens` is the window |
+| `semantic-query-empty-fit` | the instruction prefix alone fills the effective embedding input window, so no part of the query was left to embed and the semantic lane did not run; `detail.windowTokens` is the window |
+| `semantic-provider-unavailable` | the embedding provider could not answer; `detail.category` carries the error category |
+| `semantic-empty-query-vector` | the provider answered with an empty query vector |
+| `semantic-structured-lanes-skipped` | a structured semantic lane was requested while semantic search is off |
+| `semantic-embedding-abi-drift` | the index carries embeddings written by another build; `detail.fields` counts the contradicted ABI fields |
+| `hybrid-degraded` | hybrid recall was asked for and the semantic lane did not run, so this answer is keyword-only |
+| `hybrid-deadline-exceeded` | the composite hybrid path (embed, semantic top-k, rerank, second pass) outlived `search_hybrid_deadline_ms`, so the phases past the budget were cut; `detail.budgetMs` is the deadline, `detail.elapsedMs` the moment it fired |
+| `person-derived-ambiguity` | a person form in the query reached several people only through derivation (an initial, a word order or an operator nickname), so nothing was expanded for it rather than guess one person; `detail` maps that form to the competing person ids, dot-joined |
+| `rank-cap-truncated-pool` | the rank cap truncated the candidate pool; `detail.cap` is the cap that bit |
+| `rerank-provider-unavailable` | the configured cross-encoder reranker (remote endpoint or local model) could not answer, so the answer keeps the heuristic order; `detail.category` is one of `auth`, `quota`, `gone`, `rejected`, `transient`, `timeout`, `network`, `malformed`, `unclassified` |
+| `rerank-model-sunset` | the configured rerank model's announced decommission date has passed, so no rerank request was sent and the answer keeps the heuristic order |
+| `relevance-floor-dropped-rows` | the relevance floor dropped ranked rows; `detail.dropped` counts them |
+| `source-session-capped-rows` | the per-source-session pool cap (`search_pool_max_per_session`, since v1.83.0) dropped ranked rows whose source import session already held its share of the pool; when that left the window under-filled, the pool was re-widened once before this answer was cut; `detail.dropped` counts them against `detail.cap` |
+| `scope-filters-dropped-rows` | visibility, ownership, or session / project scope dropped ranked rows; `detail.dropped` against `detail.before` |
+| `cross-vault-origin-failed` | a cross-vault origin could not be searched; `detail.origin` is the origin label |
+| `cross-vault-chain-stopped` | an origin answered confidently and the remaining origins were deliberately not searched; `detail.skipped` counts them |
Members are not invented for conditions nothing reports, so every code
above has a producer on the search path today. `hybrid-degraded` is the
diff --git a/docs/cross-project-pointer.md b/docs/cross-project-pointer.md
index e22f8f8a..e74e6600 100644
--- a/docs/cross-project-pointer.md
+++ b/docs/cross-project-pointer.md
@@ -16,9 +16,19 @@ reads on startup. Common targets:
- `AGENTS.md` — Codex, Cursor, Aider, and other tools that follow the
`agents.md` convention.
-Pick one location per project. The managed-block fences let a future
-`o2b brain bootstrap` command rewrite the snippet idempotently; manual
-edits inside the fences are preserved on subsequent runs.
+Pick one location per project. You can have Open Second Brain write
+and maintain this block for you instead of pasting it by hand:
+`o2b install --target <host> --apply` writes the managed block into the
+agent-instruction file your host reads at the vault root (AGENTS.md for
+codex, cursor, opencode and aider; GEMINI.md for gemini-cli), under an
+explicit consent prompt, keeping every byte outside the block intact on
+every re-run. The installed block merges the usage content below with
+the memory write gate, and a later uninstall removes exactly the pair
+the tool wrote. The manual snippet stays for hosts you provision by
+hand. Install only writes the vault-root instruction file of the target
+host; there, a pasted snippet or any hand edit inside the managed
+fences makes the run refuse with `user-modified-block` unless `--force`
+replaces it (a backup of the previous file is taken first).
Replace `<absolute-vault-path>` with the absolute path of your
Obsidian-compatible vault before pasting.
diff --git a/docs/mcp.md b/docs/mcp.md
index 1c8dd1a1..5f1cd1f2 100644
--- a/docs/mcp.md
+++ b/docs/mcp.md
@@ -399,6 +399,7 @@ flags for a narrower per-process full server.
| `brain_writes` | Read-only listing of recorded note writes (create / update / append / revert), newest first, with the agent, the device the log shard names, the target path and the content digest on each side. Filters by agent, device, path, op and time window. `action: plan_revert` returns the sealed plan for undoing a selection of those writes - one entry per target with its action, refusal reason and both digests - and never applies it; applying is CLI-only. | — |
| `brain_audit` | Read-only per-preference mutation trail (create / promote / update / retire / merge) with agent, reason, revision + content-hash before/after. | `pref_id` |
| `brain_attestations` | Read-only attestation evidence (since v1.97.0) — the `brain_secrets` split applied to signatures: `list` returns the vault's Ed25519-signed store attestations newest first (id, created-at, signing device, store digest, record path) and `verify` re-measures the store against the newest one (per-shard intact/appended/diverged/missing, the signature, the store-digest comparison). Report-only evidence about store state; it carries no note content, so it answers identically at every reach. Key generation and signing are operator CLI verbs (`o2b brain attest keygen \| sign`) with no tool surface — an agent that could mint a signing key would attest nothing an operator vouches for. | `operation` |
+| `brain_skill_rewrite_status` | Read-only rewrite-lane status (agent-presence, t_635e3e72): one skill's frozen benchmark receipt and whether its task set still verifies, the completed gate rounds' verdicts and rates, and the slug of any staged rewrite awaiting a human accept. Ids and rates only — no task text, no transcript text — and MCP never accepts or scores regardless: staging and grading stay CLI-only (`o2b brain skill-proposals rewrite-plan \| rewrite-score`). An unknown skill answers as a named empty status, not an error. | `skill_name` |
| `brain_brief` | Brain summary for any window: `view: morning \| daily \| weekly \| monthly \| operator \| digest \| today`. `view=today` embeds the operator dashboard: obligations sorted due-today and overdue first, one-off pledges, open loops, merged recent activity, totals. `view=digest` also snapshots its report under `Brain/reports/` for the run-over-run delta when report snapshots are enabled (skipped below local reach and under an enforced owner scope). | `view` |
| `brain_analytics` | Brain analytics for any lens: `view: timeline \| attention_flows \| belief_evolution \| concept_synthesis \| dedup`. `view=attention_flows` seeds its default flow recipe when the vault lacks one; `view=dedup` summarises the persisted exact-hash ingest dedup records into a trend plus a per-source re-ingest ranking; every count is an exact sha-256 drop, never a semantic figure (the semantic detectors nominate merge candidates and never drop). | `view` |
| `brain_search` | Vault search with optional structured query lanes, explicit focus hints, time ranges, evidence-pack diagnostics, a selectable recall `profile` (`fast \| balanced \| thorough`), an FTS `match_mode` (`all` \| `any`), a pushed `kind` filter (`page` \| `section`) plus SQL pushdown for the promoted `properties` keys (since v1.80.0), and since v1.82.0 an opt-in iterative recall loop (`iterative`, `iterative_token`, `iterative_payload`) whose surviving coverage gaps pause with a plan the caller answers. Write-classified: it persists activation access events by default and the opt-in reinforce, recall-telemetry and query-demand ledgers under `Brain/search/` - ranking state later searches read back. | `query` |
diff --git a/docs/observability.md b/docs/observability.md
index 46aeba8e..b2e321da 100644
--- a/docs/observability.md
+++ b/docs/observability.md
@@ -4,22 +4,22 @@ Open Second Brain records what it did - learning events, recall decisions, serve
## Surfaces at a glance
-| Surface | Location | Writer | Format |
-|---|---|---|---|
-| Brain log | `Brain/log/<date>[.<device-id>].md` + JSONL sidecar | `appendLogEvent()` in `src/core/brain/log.ts` | Markdown line + JSONL row per event |
-| Continuity store | `Brain/log/continuity/<month>[.<device-id>].jsonl` | `appendContinuityRecord()` in `src/core/brain/continuity/store.ts` | one JSON record per line |
-| Idempotency ledger | `Brain/logs/idempotency/<month>[.<device-id>].jsonl` | `rememberKey()` in `src/core/brain/idempotency-ledger.ts` | one `key -> content hash` record per line |
-| Decision ledger | `Brain/logs/decisions/<month>[.<device-id>].jsonl` | `appendDecisionLedger()` in `src/core/brain/permissions/ledger.ts`; read back by `o2b brain permissions ledger` | one JSON decision row per line (see "The decision ledger" below) |
-| Preference mutation audit | `Brain/log/pref-audit/<pref-id>/device[.<device-id>].jsonl` (legacy flat `Brain/log/pref-audit/<pref-id>[.<device-id>].jsonl` still read) | `appendPrefAudit()` in `src/core/brain/pref-audit.ts` | one JSON record per line |
-| Session lineage ledger | `Brain/.state/session-lineage[.<device-id>].jsonl` (+ `session-lineage-gaps[.<device-id>].jsonl`) | `recordLineageObservation()` in `src/core/brain/lineage/ledger.ts` | one JSON record per line, sequence-numbered and hash-chained per file |
-| Session lifecycle audit | `Brain/log/session-lifecycle/<ISO-week>[.<device-id>].jsonl` | `captureSessionLifecycleEvent()` in `src/core/brain/session-lifecycle.ts` | JSONL audit rows |
-| Other audit weeks | `<ISO-week>[.<device-id>].jsonl` under `Brain/log/hygiene/`, `Brain/log/secret-custody/`, `Brain/log/schema-mutations/`, `Brain/log/watchdog/` (fallback `.open-second-brain/watchdog-audit/`) and `.open-second-brain/hook-audit/` | `appendAuditRecord()` in `src/core/reliability/audit.ts`, the one writer every audit site calls | JSONL audit rows |
-| Fixed-name ledgers | `Brain/log/query-demand`, `Brain/log/recurrence-support`, `Brain/log/capture-decisions`, `Brain/skill-proposals/verifier-rejections`, `Brain/preferences/pref-<slug>.history`, `Brain/projects/git/<repo>/commits` and `.open-second-brain/maintenance-runs`, each `<stem>[.<device-id>].jsonl` | the owning module's path helper through `shardedFileName()` in `src/core/brain/ledger-shards.ts` | one JSON record per line |
-| Bench runs | `<runs-dir>/<run-id>/` (default `.open-second-brain/bench-runs/`; excluded from git by the guard block `o2b brain init` seeds into the vault `.gitignore`) | `runMemoryBench()` in `src/core/bench/phases.ts` | `checkpoint.json`, per-question results, `report.json` |
-| Failed automatic upgrade | `.open-second-brain/self-heal-upgrade.json` (per device, not synced with `Brain/`) | `recordSelfHealUpgradeFailure()` in `src/core/maintenance/self-heal-upgrade-state.ts` | one JSON object: `failed_at`, `error`, `consecutive_failures`, `pending`, `retry_after`; read by `o2b doctor` (`self_heal_upgrade`), `o2b brain status` and `o2b brain upgrade --dry-run` |
-| Metrics | `Brain/metrics/<surface>[.<device-id>].jsonl` | `appendMetric()` in `src/core/brain/metrics.ts` | one run-level JSON record per line (see `docs/metrics.md`) |
-| Signal archive | `Brain/inbox/archived/sig-*.md` | the dream pass (`archiveStaleSignals()` in `src/core/brain/dream-apply.ts`, policy in `src/core/brain/signal-archive.ts`) | the inbox signal file, moved byte for byte; the moving run's `dream` log event lists every id under `archived_signals` |
-| Dedup index cache | `$OPEN_SECOND_BRAIN_DEDUP_CACHE_DIR`, else the user cache dir `open-second-brain/dedup-index/<vault-digest>.json` (outside the vault; `OPEN_SECOND_BRAIN_DEDUP_CACHE=0` disables) | `writeDedupIndexCache()` in `src/core/brain/dedup-index-cache.ts` | one JSON file per vault: per directory its listing digest, count and mtime, per signal file its size, mtime, id and `dedup_hash`; derived, safe to delete |
+| Surface | Location | Writer | Format |
+| ------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
+| Brain log | `Brain/log/<date>[.<device-id>].md` + JSONL sidecar | `appendLogEvent()` in `src/core/brain/log.ts` | Markdown line + JSONL row per event |
+| Continuity store | `Brain/log/continuity/<month>[.<device-id>].jsonl` | `appendContinuityRecord()` in `src/core/brain/continuity/store.ts` | one JSON record per line |
+| Idempotency ledger | `Brain/logs/idempotency/<month>[.<device-id>].jsonl` | `rememberKey()` in `src/core/brain/idempotency-ledger.ts` | one `key -> content hash` record per line |
+| Decision ledger | `Brain/logs/decisions/<month>[.<device-id>].jsonl` | `appendDecisionLedger()` in `src/core/brain/permissions/ledger.ts`; read back by `o2b brain permissions ledger` | one JSON decision row per line (see "The decision ledger" below) |
+| Preference mutation audit | `Brain/log/pref-audit/<pref-id>/device[.<device-id>].jsonl` (legacy flat `Brain/log/pref-audit/<pref-id>[.<device-id>].jsonl` still read) | `appendPrefAudit()` in `src/core/brain/pref-audit.ts` | one JSON record per line |
+| Session lineage ledger | `Brain/.state/session-lineage[.<device-id>].jsonl` (+ `session-lineage-gaps[.<device-id>].jsonl`) | `recordLineageObservation()` in `src/core/brain/lineage/ledger.ts` | one JSON record per line, sequence-numbered and hash-chained per file |
+| Session lifecycle audit | `Brain/log/session-lifecycle/<ISO-week>[.<device-id>].jsonl` | `captureSessionLifecycleEvent()` in `src/core/brain/session-lifecycle.ts` | JSONL audit rows |
+| Other audit weeks | `<ISO-week>[.<device-id>].jsonl` under `Brain/log/hygiene/`, `Brain/log/secret-custody/`, `Brain/log/schema-mutations/`, `Brain/log/watchdog/` (fallback `.open-second-brain/watchdog-audit/`) and `.open-second-brain/hook-audit/` | `appendAuditRecord()` in `src/core/reliability/audit.ts`, the one writer every audit site calls | JSONL audit rows |
+| Fixed-name ledgers | `Brain/log/query-demand`, `Brain/log/recurrence-support`, `Brain/log/capture-decisions`, `Brain/skill-proposals/verifier-rejections`, `Brain/preferences/pref-<slug>.history`, `Brain/projects/git/<repo>/commits` and `.open-second-brain/maintenance-runs`, each `<stem>[.<device-id>].jsonl` | the owning module's path helper through `shardedFileName()` in `src/core/brain/ledger-shards.ts` | one JSON record per line |
+| Bench runs | `<runs-dir>/<run-id>/` (default `.open-second-brain/bench-runs/`; excluded from git by the guard block `o2b brain init` seeds into the vault `.gitignore`) | `runMemoryBench()` in `src/core/bench/phases.ts` | `checkpoint.json`, per-question results, `report.json` |
+| Failed automatic upgrade | `.open-second-brain/self-heal-upgrade.json` (per device, not synced with `Brain/`) | `recordSelfHealUpgradeFailure()` in `src/core/maintenance/self-heal-upgrade-state.ts` | one JSON object: `failed_at`, `error`, `consecutive_failures`, `pending`, `retry_after`; read by `o2b doctor` (`self_heal_upgrade`), `o2b brain status` and `o2b brain upgrade --dry-run` |
+| Metrics | `Brain/metrics/<surface>[.<device-id>].jsonl` | `appendMetric()` in `src/core/brain/metrics.ts` | one run-level JSON record per line (see `docs/metrics.md`) |
+| Signal archive | `Brain/inbox/archived/sig-*.md` | the dream pass (`archiveStaleSignals()` in `src/core/brain/dream-apply.ts`, policy in `src/core/brain/signal-archive.ts`) | the inbox signal file, moved byte for byte; the moving run's `dream` log event lists every id under `archived_signals` |
+| Dedup index cache | `$OPEN_SECOND_BRAIN_DEDUP_CACHE_DIR`, else the user cache dir `open-second-brain/dedup-index/<vault-digest>.json` (outside the vault; `OPEN_SECOND_BRAIN_DEDUP_CACHE=0` disables) | `writeDedupIndexCache()` in `src/core/brain/dedup-index-cache.ts` | one JSON file per vault: per directory its listing digest, count and mtime, per signal file its size, mtime, id and `dedup_hash`; derived, safe to delete |
### The per-device shard rule
@@ -41,35 +41,36 @@ The `prompt_prefix` metric surface measures STRUCTURAL prompt-prefix stability (
`appendLogEvent()` writes one human-readable line to the daily Markdown log plus a structured JSONL sidecar row. These events are always-on: each one is the audit trail of the operation that produced it, never optional telemetry. Kinds (from `BRAIN_LOG_EVENT_KIND` in `src/core/brain/types.ts`):
-| Kind | Fires when |
-|---|---|
-| `dream`, `promote`, `retire`, `noted-redundant`, `signal-suppressed`, `skip-corrupted-frontmatter`, `reconcile` | the deterministic learning pass runs. The `dream` event lists signals moved to `inbox/processed/` under `moved_to_processed` and signals moved to `inbox/archived/` (older than `dream.contradiction_window_days`, never consumed) under `archived_signals` |
-| `feedback`, `apply-evidence`, `force-confirmed`, `reject` | a taste signal or evidence event is recorded |
-| `pin`, `unpin`, `rollback`, `merge`, `upgrade` | operator-facing vault maintenance |
-| `freeze`, `unfreeze` | an operator stopped or reopened the content lane for every device that syncs the vault (`o2b brain freeze` / `o2b brain unfreeze`). One event per real transition only - a second freeze, or an unfreeze on an open vault, writes nothing. `freeze` carries the `reason` and the `device_id` it was set from; `unfreeze` carries the `frozen_at`, `by` and `reason` read off the marker before it was removed, which is the only place they survive the file |
-| `write-refused` | a write was refused because the vault is frozen. Appended at the MCP tool boundary - the guard that refuses sits below the log module and cannot append without closing an import cycle - one per refused call, carrying the `tool`, the `agent` and the marker's `reason`. The Brain log itself keeps writing while frozen (the audit write lane, `WRITE_LANE.audit` in `src/core/brain/freeze-marker.ts`), because a freeze that silenced the log would erase the record of itself |
-| `scan-inline`, `import-session`, `import-claude-memory` | capture and import operations |
-| `note` | a narrative milestone is recorded (`brain_note`); since v1.81.0 also the answer-quote-check Stop hook's enforce trail - exactly one event per turn that found unverified quoted spans, carrying `hook: answer-quote-check`, the phases that ran, the checked and unverified counts, and the findings as capped one-line previews |
-| `note-write` | a vault note is created, updated, appended to, or reverted |
-| `session-lifecycle` | a captured lifecycle event also produced Brain writes |
-| `decision-open` | a question was parked with enumerated options at `Brain/decisions/open-<slug>.md`, ahead of the decision it may become. Payload carries the `open` wikilink, the `title`, the option `count` and the `agent`. Distinct from `decision-record` because nothing has been decided yet |
-| `decision-resolved` | an open decision was closed by choosing one of its options, minting a real `type: decision` page. Payload carries the `open` wikilink, the minted `decision` wikilink, the `choice` and the `agent`. The minted page itself carries the usual `decision-record` event; this event records the transition |
-| `decision-discarded` | an open decision was closed WITHOUT a decision. Payload carries the `open` wikilink, the `reason` and the `agent`. Separated from `decision-resolved` so "never decided" is machine-filterable against "decided as X" |
-| `ambient-withheld` | an ambient extraction capture was suppressed by operator consent (`guardrails.ambient_writeback: false`). One event per suppressed capture, carrying the count of signals the capture would have written - never their content. Keys absent log nothing, because the lane ran as today |
+| Kind | Fires when |
+| --------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ |
+| `dream`, `promote`, `retire`, `noted-redundant`, `signal-suppressed`, `skip-corrupted-frontmatter`, `reconcile` | the deterministic learning pass runs. The `dream` event lists signals moved to `inbox/processed/` under `moved_to_processed` and signals moved to `inbox/archived/` (older than `dream.contradiction_window_days`, never consumed) under `archived_signals` |
+| `feedback`, `apply-evidence`, `force-confirmed`, `reject` | a taste signal or evidence event is recorded |
+| `pin`, `unpin`, `rollback`, `merge`, `upgrade` | operator-facing vault maintenance |
+| `freeze`, `unfreeze` | an operator stopped or reopened the content lane for every device that syncs the vault (`o2b brain freeze` / `o2b brain unfreeze`). One event per real transition only - a second freeze, or an unfreeze on an open vault, writes nothing. `freeze` carries the `reason` and the `device_id` it was set from; `unfreeze` carries the `frozen_at`, `by` and `reason` read off the marker before it was removed, which is the only place they survive the file |
+| `write-refused` | a write was refused because the vault is frozen. Appended at the MCP tool boundary - the guard that refuses sits below the log module and cannot append without closing an import cycle - one per refused call, carrying the `tool`, the `agent` and the marker's `reason`. The Brain log itself keeps writing while frozen (the audit write lane, `WRITE_LANE.audit` in `src/core/brain/freeze-marker.ts`), because a freeze that silenced the log would erase the record of itself |
+| `scan-inline`, `import-session`, `import-claude-memory` | capture and import operations |
+| `note` | a narrative milestone is recorded (`brain_note`); since v1.81.0 also the answer-quote-check Stop hook's enforce trail - exactly one event per turn that found unverified quoted spans, carrying `hook: answer-quote-check`, the phases that ran, the checked and unverified counts, and the findings as capped one-line previews |
+| `note-write` | a vault note is created, updated, appended to, or reverted |
+| `session-lifecycle` | a captured lifecycle event also produced Brain writes |
+| `decision-open` | a question was parked with enumerated options at `Brain/decisions/open-<slug>.md`, ahead of the decision it may become. Payload carries the `open` wikilink, the `title`, the option `count` and the `agent`. Distinct from `decision-record` because nothing has been decided yet |
+| `decision-resolved` | an open decision was closed by choosing one of its options, minting a real `type: decision` page. Payload carries the `open` wikilink, the minted `decision` wikilink, the `choice` and the `agent`. The minted page itself carries the usual `decision-record` event; this event records the transition |
+| `decision-discarded` | an open decision was closed WITHOUT a decision. Payload carries the `open` wikilink, the `reason` and the `agent`. Separated from `decision-resolved` so "never decided" is machine-filterable against "decided as X" |
+| `ambient-withheld` | an ambient extraction capture was suppressed by operator consent (`guardrails.ambient_writeback: false`). One event per suppressed capture, carrying the count of signals the capture would have written - never their content. Keys absent log nothing, because the lane ran as today |
+| `lessons-approved`, `lessons-denied`, `lessons-promoted` (agent-presence, t_1e952e43) | the operator records a lesson-promotion decision or a managed block receives lesson content. Operator CLI only - `o2b brain lessons approve` / `deny` / `refresh-blocks`; no agent-facing surface can mint these events, so the audit trail of what entered an agent rules file is operator-authored by construction. `lessons-approved` carries the `pref` wikilink, the `targets`, the pinned `approved_content_hash` and the consent verdict; `lessons-denied` carries the `pref` and the verdict; `lessons-promoted` carries the `targets` that changed and the `prefs` delivered, one event per write that landed (a no-op refresh emits nothing). The doctor grades managed blocks in the four-state vocabulary `absent \| current \| drifted \| stale-lessons` (registered in the verdict-vocabulary census), where stale-lessons is an approval whose pinned hash no longer matches the live text; the counts ride the brain status snapshot (`lessons.approved/denied/stale`) without a new surface |
### Note writes
Every note mutation funnels through two seams - `createNote` and the write-batch kernel - and each one appends exactly ONE `note-write` event. The payload is all strings, because the log payload contract admits `string | string[]` and nothing else:
-| Field | What it holds |
-|---|---|
-| `write_id` | `nw_<14 timestamp digits>_<16 hex>`, derived from the event body, so two devices that record the same write agree on its id |
-| `op` | `create`, `update`, `append`, or `revert` (`NOTE_WRITE_OP`) |
-| `target` | vault-relative POSIX path of the note |
-| `hash_before` | sha-256 of the bytes replaced, or the literal `absent` when the target did not exist - deliberately not the sha-256 of zero bytes, which an empty FILE would also produce |
-| `hash_after` | sha-256 of the bytes now on disk, or the same literal `absent` when the write left no file - which only a `revert` that removes a note the selected writes created produces, paired with `bytes_after: 0` |
-| `bytes_before` / `bytes_after` | byte sizes, rendered as decimal strings |
-| `agent` | `resolveAgentName()` against the config the writing surface runs under; caller-asserted by construction, as `src/core/write-binding/index.ts` states |
+| Field | What it holds |
+| ------------------------------ | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
+| `write_id` | `nw_<14 timestamp digits>_<16 hex>`, derived from the event body, so two devices that record the same write agree on its id |
+| `op` | `create`, `update`, `append`, or `revert` (`NOTE_WRITE_OP`) |
+| `target` | vault-relative POSIX path of the note |
+| `hash_before` | sha-256 of the bytes replaced, or the literal `absent` when the target did not exist - deliberately not the sha-256 of zero bytes, which an empty FILE would also produce |
+| `hash_after` | sha-256 of the bytes now on disk, or the same literal `absent` when the write left no file - which only a `revert` that removes a note the selected writes created produces, paired with `bytes_after: 0` |
+| `bytes_before` / `bytes_after` | byte sizes, rendered as decimal strings |
+| `agent` | `resolveAgentName()` against the config the writing surface runs under; caller-asserted by construction, as `src/core/write-binding/index.ts` states |
The device is NOT a payload field: it rides on the log shard name exactly as it does for every other event, and `origin_channel` is stamped by the appender. `listNoteWrites` (`src/core/brain/notes/write-log.ts`) reads the record back and reports the shard as the `device`, the empty string being the legacy un-sharded log rather than an unknown machine. `o2b brain writes` and the `brain_writes` MCP tool are the two surfaces over it, and `brain_agent_query --kind note` answers "which notes did this agent touch" off the same events.
@@ -79,15 +80,15 @@ The device is NOT a payload field: it rides on the log shard name exactly as it
**Revert.** `o2b brain writes revert (--agent A | --device D | --path P) [--since --until]` reads the same events back and plans what undoing them would do; `brain_writes` action `plan_revert` returns the same plan and never applies it. A selector naming none of agent, device or path is refused by name (`unbounded_selector`): a time window alone selects every write by every agent on every machine, which is a vault rollback and has its own verb. Per target, over the selected writes S (oldest..newest) and every recorded write A on that target:
-| Verdict | When |
-|---|---|
-| `refuse` / `unrecorded` | the current bytes cannot be read at all, so no drift verdict is possible |
-| `refuse` / `drift` | sha-256 of the bytes on disk is not the `hash_after` of the newest write in S - including the target being gone when it should be there |
-| `refuse` / `interleaved` | a write in `A \ S` sits between the oldest and newest write in S **in the merged total order** - `(timestamp, shard id, line)`, the order `readLogDay` already yields. Timestamps are second-precision, so "between" is a position and not a clock comparison: line order inside one shard IS append order, and three writes in one second on one device are perfectly ordered. The one tie that is not evidence is a same-second tie ACROSS shards, where the merge falls back to the shard id - a name, not a clock - and two devices could have written in either order. So a non-selected write sharing a second with a selected write is trusted only when it shares that write's shard; a cross-shard tie is `interleaved` on doubt |
-| `refuse` / `already-reverted` | the target already holds exactly what the revert would produce |
-| `refuse` / `image-missing` | a restore's before-image is not in the store, or no longer hashes to its own name |
-| `delete` | the oldest write in S has `hash_before: absent` AND no write in A precedes it - the selection brought the note into existence |
-| `restore` | otherwise: put back the before-image of the oldest write in S |
+| Verdict | When |
+| ----------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
+| `refuse` / `unrecorded` | the current bytes cannot be read at all, so no drift verdict is possible |
+| `refuse` / `drift` | sha-256 of the bytes on disk is not the `hash_after` of the newest write in S - including the target being gone when it should be there |
+| `refuse` / `interleaved` | a write in `A \ S` sits between the oldest and newest write in S **in the merged total order** - `(timestamp, shard id, line)`, the order `readLogDay` already yields. Timestamps are second-precision, so "between" is a position and not a clock comparison: line order inside one shard IS append order, and three writes in one second on one device are perfectly ordered. The one tie that is not evidence is a same-second tie ACROSS shards, where the merge falls back to the shard id - a name, not a clock - and two devices could have written in either order. So a non-selected write sharing a second with a selected write is trusted only when it shares that write's shard; a cross-shard tie is `interleaved` on doubt |
+| `refuse` / `already-reverted` | the target already holds exactly what the revert would produce |
+| `refuse` / `image-missing` | a restore's before-image is not in the store, or no longer hashes to its own name |
+| `delete` | the oldest write in S has `hash_before: absent` AND no write in A precedes it - the selection brought the note into existence |
+| `restore` | otherwise: put back the before-image of the oldest write in S |
A refused target is reported, never skipped, and the plan's digest - `sha256(canonical JSON of { selector, entries })`, deliberately NOT covering `planned_at` - covers refusals too, so an operator who applies a digest applies the plan they read. `--apply <digest>` re-plans from scratch and refuses `digest_mismatch` before any byte moves when the vault changed in between; a plan with no actionable entry is refused `nothing_to_apply`; a frozen vault refuses the whole apply by name before anything is read. Everything that does run goes inside ONE `withDestructiveSnapshot` under the `note-revert` reason, so a revert that half-succeeds still has one recovery point covering the state before all of it. Each restored or deleted target keeps a before-image of the bytes it replaced and is recorded through `recordNoteWrite` with `op: revert` - a delete as `hash_after: absent`, `bytes_after: 0` - which is what makes a revert attributable and itself revertible: reverting the reverting agent puts the bytes back.
@@ -106,7 +107,7 @@ Once the log is the attribution record for every write, a line someone deleted o
`o2b brain log verify [--json]` walks every shard and reports the first break in each, by path and line: `hash-mismatch` (the line was edited after it was written), `prev-mismatch` (a line between it and its predecessor was removed or reordered), `malformed` (the line carries no usable chain link where the chain had already started). It exits 1 when any shard does not link up. `o2b brain doctor` emits one `log-chain-broken` warning per broken shard with the same next command. Neither repairs anything: the only way to make a broken chain verify is to rewrite the history it records, which is the act the chain exists to detect.
-Rows written before the chain shipped carry no `h`. They are counted as **legacy** and are clean while they precede the chain — the first chained line after them anchors the shard with `prev: null`. The same shape *after* a chained line is not history but a line whose links were stripped, and it is reported. The head of a shard is not exempt either: the Brain log never compacts, so a first chained line naming a predecessor means the head of the file was cut off. Sync-conflict copies are excluded from verification — they are the doctor's separate `sync-conflict-log` finding, and their chain never held by construction.
+Rows written before the chain shipped carry no `h`. They are counted as **legacy** and are clean while they precede the chain — the first chained line after them anchors the shard with `prev: null`. The same shape _after_ a chained line is not history but a line whose links were stripped, and it is reported. The head of a shard is not exempt either: the Brain log never compacts, so a first chained line naming a predecessor means the head of the file was cut off. Sync-conflict copies are excluded from verification — they are the doctor's separate `sync-conflict-log` finding, and their chain never held by construction.
## The decision ledger
@@ -116,12 +117,12 @@ The row shape is closed: `ts`, `actor` (the resolved principal), `via` (`token`,
When rows land is deliberately quiet:
-| Trigger | Rows |
-|---|---|
-| No permissions document, every gate key off | none - default-silent like every ledger |
-| A permissions document resolves `ask` or `deny` for a staged-lane write | one row naming the entry, role or default that decided |
-| A permissions document resolves `allow` | one row ONLY when the document sets `ledger.record_allows: true` |
-| `integrity.owner_scope_writes: warn` allows a caller-named foreign owner on the preference lane | one row carrying the gate key as `source` |
+| Trigger | Rows |
+| ----------------------------------------------------------------------------------------------- | ---------------------------------------------------------------- |
+| No permissions document, every gate key off | none - default-silent like every ledger |
+| A permissions document resolves `ask` or `deny` for a staged-lane write | one row naming the entry, role or default that decided |
+| A permissions document resolves `allow` | one row ONLY when the document sets `ledger.record_allows: true` |
+| `integrity.owner_scope_writes: warn` allows a caller-named foreign owner on the preference lane | one row carrying the gate key as `source` |
The append contract is absolute: a failed append NEVER throws and never blocks the verdict it records. The ledger rides behind gates that must refuse or stage a write even when accountability cannot be written, so every failure - an unwritable directory, a lock another writer holds - comes back as `{ logged: false, audit_reason }` that the caller surfaces; the receipt carries the reason rather than claiming a record that does not exist.
@@ -131,24 +132,25 @@ The append contract is absolute: a failed append NEVER throws and never blocks t
Every continuity record shares one envelope, and exactly these eight fields in this order: `schema`, `id`, `kind`, `createdAt`, `sourceRefs`, `payload`, `private`, `redacted`. The table marks how each kind is gated - this is the always-on vs opt-in matrix, verified against the call sites named in the right column.
-| Kind | Gate | Emitted by |
-|---|---|---|
-| `recall_telemetry` | opt-in per call (`telemetry` option/param); the prompt-time hook emitter is gated by `recall_inject_enabled` instead | `packContext` (`mode: context_pack`), `buildPreCompressPack` (`mode: pre_compress`), `brain_search` MCP handler (`mode: search`), `brain_query` MCP handler (`mode: query`, since v0.40.0 - payload carries the query kind only, never the supplied preference id / topic / timestamp), and since v1.46.0 the `UserPromptSubmit` recall-inject hook (`mode: search`, `channel: hook`, mapping its inject / abstain / error decision onto `ok` / `empty` / `error`; with the optional `recall_inject` decision-model use in `shadow` or `enforce`, `metadata` gains a `decision_model` object - `mode`, `outcome` (`ok`, `not_sent` or `degraded`), `latency_ms`, `notes_dropped`, `abstained` - and the abstain reason `decision_model_abstain`, never prompt or note text; see `docs/decision-models/recall-inject.md`) |
-| `context_receipt` | opt-in per call (`receipt` option/param) | `packContext`, `buildPreCompressPack` |
-| `gate_telemetry` | config key `recall_gate_telemetry` (default off) | `brain_recall_gate` MCP handler; a call carrying `decision_answerable` while that decision-model use is on adds `adequacy_level` and `decision_answerable` (`probability`, `disagrees`); since v1.69.0 a call carrying `turn_id` records it under `turn_id`, which the read-model lifts like every other turn id; since v1.82.0 a call that carried a measured quality also records the graded surfacing key - `key` (null exactly where nothing was measurable), `tier` and the `channel` the decision arrived over - and the summary counts the measured records by tier (`by_tier`) |
-| `negative_recall` | config key `recall_gate_telemetry` (default off - the SAME gate as `gate_telemetry` above, so one config decision governs both observations the recall gate makes) | `brain_recall_gate` MCP handler on the zero-usable-result path only (`emitNegativeRecallTelemetry` in `src/core/brain/gate-telemetry.ts`) - one record per gate call whose caller reported no usable result, carrying the typed corpus verdict (`state`, `complete`, the named `unknown_reason` when the verdict is `unknown`, `reason`) plus the reduced coverage receipt when one could be built (`coverage_digest`, `documents`, `chunks`, `schema_version`, `embedding_signature`, `last_indexed_at`, `scope`, `unindexed_roots`). Two receipt fields are not copied into the payload: `index_path` is deliberately dropped - a host filesystem path is not vault content and these records sync between devices, and the digest already binds it; the `embeddings` census the receipt carries is likewise absent from the payload and likewise bound by `coverage_digest`, so a reader comparing two records still sees a keyword-only index differ from a fully embedded one. Same prompt invariant as `gate_telemetry`: a SHA-256 prefix (`prompt_hash`) and the length (`prompt_chars`), never the prompt. A call with usable results writes NO record, so a corpus statement is never invented for an attempt that had one |
-| `generation_report` | opt-in per call (`enable`) or config key `generation_trace_enabled` (default off) | inbound agent report after a generation handoff (`brain_generation_reports` action `record`, `o2b brain generation-reports record`) |
-| `mcp_route_latency` | config key `mcp_route_metrics_enabled` (default off) | the MCP server's tool-call seam (`MCPServer.invokeToolHandler` in `src/mcp/server.ts`) - one record per `tools/call` and per CLI-bridge `callTool`; payload carries the tool name, scope, status, duration, and argument KEY NAMES only, never argument values, plus the optional `decision_ms` and allowlisted `stages` timings |
-| `decision_model_call` | the optional decision model is active (`decision_model_enabled: "true"` AND the named key variable set, which a self-hosted `laya` or `openjev` server on loopback does not need, and no vault opt-out); an install without the feature writes none | `runDecision` in `src/core/decision-model/run.ts` - one record per attempted decision request: `use`, `mode`, `provider`, `model` (the answering version), `calibrated`, `question_count`, `candidate_count`, `input_tokens`, `output_tokens`, `cost_usd`, `cost_source` (`reported`, `estimated` or `unknown`), `latency_ms`, `outcome` (`ok` or a degrade reason), `state_hash` (sha-256 of the redacted state), `origin` (`eval` or `ping`) when not an ordinary use call, plus per-use identifiers (a rerank adds `head_size`, `withheld_count`, `budget_dropped_count`, `frontmatter_only_count` when a frontmatter-only chunk was not sent, `injection_suspected` in `enforce`, `answerable_probability`, and in `shadow` `heuristic_order` and `decision_order` as paths, in `enforce` `decision_permutation` as head positions; every other use adds its own identifiers and counts, described on its page under `docs/decision-models/`). Never the state, a passage, a prompt or a question text. Fail-open: a failed write never fails the search. The daily cost gate and `o2b decision-model report` read these records |
-| `decision_model_extract_commit` | the optional decision model is active and the `extract_prefilter` use is not `off` | commit phase of `brain_extract_signals` / `o2b brain extract-signals` (`src/core/brain/extract-signals-prefilter.ts`) - one record per commit that wrote items: `session_id`, `mode`, `written_count`, `source_turns` (the cited turn ids that name a real turn of the session) and `without_source_turn_count`; turn ids and counts only, never text. Read by `o2b decision-model report --use extract_prefilter` for its regret metric |
-| `token_impact` | config key `token_impact_ledger_enabled` (default off) | `brain_token_impact` action `record` (`emitTokenImpact` in `src/core/brain/token-impact.ts`) - one sample per context pack; payload carries the tokenizer-exact prompt-token counts (`baseline_tokens`, `packed_tokens`, signed `delta_tokens`), the `method` label (`exact`/`fallback`), an optional opaque `pack_id`, an optional `source` attribution (`decision_model:<use>` for savings of a decision-model use), and the optional modeled inference-avoidance estimate - never raw prompts or recalled text |
-| `token_impact_outcome` | config key `token_impact_ledger_enabled` (default off) | `brain_token_impact` action `outcome` (`recordTokenImpactOutcome`) - one first-pass/repair/retry post used only to calibrate the modeled ledger |
-| `context_pack_outcome` | config key `context_pack_outcome_enabled` (default off) | `brain_context_pack_outcome` action `post` (`postContextPackOutcome` in `src/core/brain/context-pack-outcome.ts`) - one compact per-sample outcome row for a carried context-pack quality-sample id: first-pass/repair/retry counters plus three STRICTLY SEPARATE token signals (`exact_prompt_token_savings`, `modeled_inference_avoidance`, `observed_provider_tokens`), never merged; payload carries counters + an opaque `sample_id` only, never raw prompts or recalled text, and a caller-omitted field is not invented. One `post` writes THREE records, all joined on the same `sample_id`: this row, a `token_impact_outcome` calibration post, and a `context_pack_evidence` row (both listed separately below and in this table). The thin wrapper `emitContextPackOutcome` returns only this row; the two composed records are written either way |
-| `context_pack_evidence` | config key `context_pack_outcome_enabled` (default off - the same gate as the outcome row it accompanies) | composed by every `brain_context_pack_outcome` action `post` (`recordContextPackEvidence` in `src/core/brain/context-pack-evidence.ts`) - one row per outcome row, joined on the same `sample_id`, carrying the evidence the kernel reads back off disk (the `context_receipt` that id names: `final_text_hash`, `item_count`, `final_text_chars`) and a closed `verdict` over the acting agent's optional claim: `match`, `mismatch`, `unclaimed` (evidence obtained, nothing asserted), or `unresolved`. A `mismatch` lists the drifted fields and is RECORDED, never resolved - the outcome row is neither rejected nor silently corrected by it. An `unresolved` verdict names why through a separate token, `sample_absent` (the log was read and holds no such receipt) or `evidence_unreadable` (the log could not be read at all), so absence is never reported as inability. Payload carries those tokens + the opaque `sample_id` only, never raw prompts or recalled text. NOT an independent attestation: the agent id on the row is self-asserted and this same process wrote the receipt it now reads. The `post` response echoes the payload under `evidence`, so a contradicted claim is visible to the poster and not only to a later reader |
-| `ingest_dedup` | always-on, fail-open; written ONLY by a run that actually dropped something | the three ingest runs that drop an item on an exact sha-256 `dedup_hash` collision: `captureSessionLifecycleEvent`, `scanInline`, `importSession` (`emitIngestDedupReport` in `src/core/brain/dedup-telemetry.ts`) - one record per run, payload carries the `surface`, the run's `exact_deduped` total, and a `by_source` map keyed by the session id or vault-relative note path being re-ingested. A run that deduped nothing writes NO record, so a real zero stays distinguishable from an absent measurement. Every count is an EXACT-hash drop; the semantic detectors nominate merge candidates and never drop, so no semantic figure appears here |
-| `session_turn`, `session_summary_node` | always-on within its operation | session-recall import (`src/core/brain/session-recall.ts`) - the write IS the operation |
-| `pre_compact_extract` | always-on within its operation | explicit pre-compact extraction (`src/core/brain/pre-compact-extract.ts`) |
-| `source_invalidation` | always-on within its operation | source drift detection (`appendContinuitySourceInvalidation`) |
+| Kind | Gate | Emitted by |
+| -------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
+| `recall_telemetry` | opt-in per call (`telemetry` option/param); the prompt-time hook emitter is gated by `recall_inject_enabled` instead | `packContext` (`mode: context_pack`), `buildPreCompressPack` (`mode: pre_compress`), `brain_search` MCP handler (`mode: search`), `brain_query` MCP handler (`mode: query`, since v0.40.0 - payload carries the query kind only, never the supplied preference id / topic / timestamp), and since v1.46.0 the `UserPromptSubmit` recall-inject hook (`mode: search`, `channel: hook`, mapping its inject / abstain / error decision onto `ok` / `empty` / `error`; with the optional `recall_inject` decision-model use in `shadow` or `enforce`, `metadata` gains a `decision_model` object - `mode`, `outcome` (`ok`, `not_sent` or `degraded`), `latency_ms`, `notes_dropped`, `abstained` - and the abstain reason `decision_model_abstain`, never prompt or note text; see `docs/decision-models/recall-inject.md`) |
+| `context_receipt` | opt-in per call (`receipt` option/param) | `packContext`, `buildPreCompressPack` |
+| `gate_telemetry` | config key `recall_gate_telemetry` (default off) | `brain_recall_gate` MCP handler; a call carrying `decision_answerable` while that decision-model use is on adds `adequacy_level` and `decision_answerable` (`probability`, `disagrees`); since v1.69.0 a call carrying `turn_id` records it under `turn_id`, which the read-model lifts like every other turn id; since v1.82.0 a call that carried a measured quality also records the graded surfacing key - `key` (null exactly where nothing was measurable), `tier` and the `channel` the decision arrived over - and the summary counts the measured records by tier (`by_tier`) |
+| `negative_recall` | config key `recall_gate_telemetry` (default off - the SAME gate as `gate_telemetry` above, so one config decision governs both observations the recall gate makes) | `brain_recall_gate` MCP handler on the zero-usable-result path only (`emitNegativeRecallTelemetry` in `src/core/brain/gate-telemetry.ts`) - one record per gate call whose caller reported no usable result, carrying the typed corpus verdict (`state`, `complete`, the named `unknown_reason` when the verdict is `unknown`, `reason`) plus the reduced coverage receipt when one could be built (`coverage_digest`, `documents`, `chunks`, `schema_version`, `embedding_signature`, `last_indexed_at`, `scope`, `unindexed_roots`). Two receipt fields are not copied into the payload: `index_path` is deliberately dropped - a host filesystem path is not vault content and these records sync between devices, and the digest already binds it; the `embeddings` census the receipt carries is likewise absent from the payload and likewise bound by `coverage_digest`, so a reader comparing two records still sees a keyword-only index differ from a fully embedded one. Same prompt invariant as `gate_telemetry`: a SHA-256 prefix (`prompt_hash`) and the length (`prompt_chars`), never the prompt. A call with usable results writes NO record, so a corpus statement is never invented for an attempt that had one |
+| `generation_report` | opt-in per call (`enable`) or config key `generation_trace_enabled` (default off) | inbound agent report after a generation handoff (`brain_generation_reports` action `record`, `o2b brain generation-reports record`) |
+| `mcp_route_latency` | config key `mcp_route_metrics_enabled` (default off) | the MCP server's tool-call seam (`MCPServer.invokeToolHandler` in `src/mcp/server.ts`) - one record per `tools/call` and per CLI-bridge `callTool`; payload carries the tool name, scope, status, duration, and argument KEY NAMES only, never argument values, plus the optional `decision_ms` and allowlisted `stages` timings |
+| `decision_model_call` | the optional decision model is active (`decision_model_enabled: "true"` AND the named key variable set, which a self-hosted `laya` or `openjev` server on loopback does not need, and no vault opt-out); an install without the feature writes none | `runDecision` in `src/core/decision-model/run.ts` - one record per attempted decision request: `use`, `mode`, `provider`, `model` (the answering version), `calibrated`, `question_count`, `candidate_count`, `input_tokens`, `output_tokens`, `cost_usd`, `cost_source` (`reported`, `estimated` or `unknown`), `latency_ms`, `outcome` (`ok` or a degrade reason), `state_hash` (sha-256 of the redacted state), `origin` (`eval` or `ping`) when not an ordinary use call, plus per-use identifiers (a rerank adds `head_size`, `withheld_count`, `budget_dropped_count`, `frontmatter_only_count` when a frontmatter-only chunk was not sent, `injection_suspected` in `enforce`, `answerable_probability`, and in `shadow` `heuristic_order` and `decision_order` as paths, in `enforce` `decision_permutation` as head positions; every other use adds its own identifiers and counts, described on its page under `docs/decision-models/`). Never the state, a passage, a prompt or a question text. Fail-open: a failed write never fails the search. The daily cost gate and `o2b decision-model report` read these records |
+| `decision_model_extract_commit` | the optional decision model is active and the `extract_prefilter` use is not `off` | commit phase of `brain_extract_signals` / `o2b brain extract-signals` (`src/core/brain/extract-signals-prefilter.ts`) - one record per commit that wrote items: `session_id`, `mode`, `written_count`, `source_turns` (the cited turn ids that name a real turn of the session) and `without_source_turn_count`; turn ids and counts only, never text. Read by `o2b decision-model report --use extract_prefilter` for its regret metric |
+| `token_impact` | config key `token_impact_ledger_enabled` (default off) | `brain_token_impact` action `record` (`emitTokenImpact` in `src/core/brain/token-impact.ts`) - one sample per context pack; payload carries the tokenizer-exact prompt-token counts (`baseline_tokens`, `packed_tokens`, signed `delta_tokens`), the `method` label (`exact`/`fallback`), an optional opaque `pack_id`, an optional `source` attribution (`decision_model:<use>` for savings of a decision-model use), and the optional modeled inference-avoidance estimate - never raw prompts or recalled text |
+| `token_impact_outcome` | config key `token_impact_ledger_enabled` (default off) | `brain_token_impact` action `outcome` (`recordTokenImpactOutcome`) - one first-pass/repair/retry post used only to calibrate the modeled ledger |
+| `context_pack_outcome` | config key `context_pack_outcome_enabled` (default off) | `brain_context_pack_outcome` action `post` (`postContextPackOutcome` in `src/core/brain/context-pack-outcome.ts`) - one compact per-sample outcome row for a carried context-pack quality-sample id: first-pass/repair/retry counters plus three STRICTLY SEPARATE token signals (`exact_prompt_token_savings`, `modeled_inference_avoidance`, `observed_provider_tokens`), never merged; payload carries counters + an opaque `sample_id` only, never raw prompts or recalled text, and a caller-omitted field is not invented. One `post` writes THREE records, all joined on the same `sample_id`: this row, a `token_impact_outcome` calibration post, and a `context_pack_evidence` row (both listed separately below and in this table). The thin wrapper `emitContextPackOutcome` returns only this row; the two composed records are written either way |
+| `context_pack_evidence` | config key `context_pack_outcome_enabled` (default off - the same gate as the outcome row it accompanies) | composed by every `brain_context_pack_outcome` action `post` (`recordContextPackEvidence` in `src/core/brain/context-pack-evidence.ts`) - one row per outcome row, joined on the same `sample_id`, carrying the evidence the kernel reads back off disk (the `context_receipt` that id names: `final_text_hash`, `item_count`, `final_text_chars`) and a closed `verdict` over the acting agent's optional claim: `match`, `mismatch`, `unclaimed` (evidence obtained, nothing asserted), or `unresolved`. A `mismatch` lists the drifted fields and is RECORDED, never resolved - the outcome row is neither rejected nor silently corrected by it. An `unresolved` verdict names why through a separate token, `sample_absent` (the log was read and holds no such receipt) or `evidence_unreadable` (the log could not be read at all), so absence is never reported as inability. Payload carries those tokens + the opaque `sample_id` only, never raw prompts or recalled text. NOT an independent attestation: the agent id on the row is self-asserted and this same process wrote the receipt it now reads. The `post` response echoes the payload under `evidence`, so a contradicted claim is visible to the poster and not only to a later reader |
+| `ingest_dedup` | always-on, fail-open; written ONLY by a run that actually dropped something | the three ingest runs that drop an item on an exact sha-256 `dedup_hash` collision: `captureSessionLifecycleEvent`, `scanInline`, `importSession` (`emitIngestDedupReport` in `src/core/brain/dedup-telemetry.ts`) - one record per run, payload carries the `surface`, the run's `exact_deduped` total, and a `by_source` map keyed by the session id or vault-relative note path being re-ingested. A run that deduped nothing writes NO record, so a real zero stays distinguishable from an absent measurement. Every count is an EXACT-hash drop; the semantic detectors nominate merge candidates and never drop, so no semantic figure appears here |
+| `session_turn`, `session_summary_node` | always-on within its operation | session-recall import (`src/core/brain/session-recall.ts`) - the write IS the operation |
+| `pre_compact_extract` | always-on within its operation | explicit pre-compact extraction (`src/core/brain/pre-compact-extract.ts`) |
+| `source_invalidation` | always-on within its operation | source drift detection (`appendContinuitySourceInvalidation`) |
+| `skill_rewrite_eval_grade` | always-on, one record per COMPLETED benchmark-gated skill rewrite gate run (agent-presence, t_635e3e72); a run that ends before the gates complete - a promote still awaiting its single held-out check - writes nothing | `recordSkillRewriteGrade` in `src/core/brain/skill-proposals.ts`, called from `o2b brain skill-proposals rewrite-score`: payload carries the skill name, the spec hash and tasks hash the run verified against, the metric (`tasks_passed_rate`), the seed and split rule, the final verdict (`promote` / `hold` / `not_enough_evidence`, where a hold is also what a missed held-out check downgrades a promote to), the baseline and candidate rates, and per-task rows (`task_id`, `passed`, `failed_checks`) for the dev and held-out arms. Identifiers, numbers, booleans and check ids only - never task text and never transcript text; the payload is rebuilt field by field at the boundary so nothing else in the caller's object survives. Kept never-folded so an operator can audit why a rewrite landed or held; the MCP status surface reads the same rows read-only |
Session lifecycle capture (`captureSessionLifecycleEvent`) writes audit rows and Brain log events, and no continuity record at all unless the event actually dropped a repeat - in which case it writes exactly one `ingest_dedup` record. Both halves of that boundary are pinned by regression tests (`tests/core/brain/continuity-emit.test.ts` for the silent path, `tests/core/brain/dedup-telemetry.test.ts` for the dedup path).
@@ -163,15 +165,15 @@ Since v0.39.0 every new continuity record is stamped `schema: "o2b.continuity.v1
## Correlation IDs
-| Field | Where | Stable join? |
-|---|---|---|
-| `id` (`ctn_<stamp>_<sha16>`) | every continuity record | yes - content-hash dedup id |
-| `createdAt` | every continuity record | ordering key (store sorts by `createdAt`, then `id`) |
-| `sourceRefs[].id` / `.path` | continuity records | joins records to vault artifacts |
-| `session_id`, `turn_id` | payloads of session-scoped kinds; lifted by the read-model | yes - the cross-surface session join |
-| `handoffKind`, `handoffRef` | `generation_report` payload `handoff`; lifted by the read-model | yes - joins a generation report to the write-session / context-receipt / dream run it traced |
-| `timestamp` + `agent` | Brain log events | per-event attribution |
-| `agentId`, `isSidechain` | `SessionTurn`, from a transcript that records delegation | yes - the only thing separating a delegated sub-agent's turns from its parent's, because a sub-agent transcript reuses the PARENT's session id |
+| Field | Where | Stable join? |
+| ---------------------------- | --------------------------------------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------- |
+| `id` (`ctn_<stamp>_<sha16>`) | every continuity record | yes - content-hash dedup id |
+| `createdAt` | every continuity record | ordering key (store sorts by `createdAt`, then `id`) |
+| `sourceRefs[].id` / `.path` | continuity records | joins records to vault artifacts |
+| `session_id`, `turn_id` | payloads of session-scoped kinds; lifted by the read-model | yes - the cross-surface session join |
+| `handoffKind`, `handoffRef` | `generation_report` payload `handoff`; lifted by the read-model | yes - joins a generation report to the write-session / context-receipt / dream run it traced |
+| `timestamp` + `agent` | Brain log events | per-event attribution |
+| `agentId`, `isSidechain` | `SessionTurn`, from a transcript that records delegation | yes - the only thing separating a delegated sub-agent's turns from its parent's, because a sub-agent transcript reuses the PARENT's session id |
Multi-agent vaults attribute writers via per-agent identity (`brain_agent_query`). Delegated sub-agents are correlated as of v1.49.0, and by the additive route this sentence used to promise: `SessionTurn` carries an optional `agentId` and an optional `isSidechain: true`, both emitted only where the transcript records them, so a flat transcript keeps its pre-delegation shape byte for byte. A sub-agent transcript reuses its PARENT's session id, so those two fields are the only thing separating the two agents' turns. The `SubagentStop` hook records the close under `<delegator>-sub-<agent-id>`; the `agent_transcript_path` the event also carries is deliberately not persisted, being a machine-local host path.
diff --git a/install/codex.md b/install/codex.md
index c4e80031..3fa3b44e 100644
--- a/install/codex.md
+++ b/install/codex.md
@@ -82,6 +82,40 @@ makes Codex's Brain writes distinguishable per runtime, and in a shared
multi-device vault also per device - the same derivation the `grok` and
`opencode` adapters apply.
+## ChatGPT desktop
+
+ChatGPT desktop has no MCP registration of its own: it reads the shared
+Codex configuration at `$CODEX_HOME/config.toml` (default
+`~/.codex/config.toml`), the same file the `codex` target writes. One
+registration serves both, so the install command is the codex one from
+step 4 (add `--vault`, `--apply` and `--yes` as there):
+
+```bash
+o2b install --target codex --apply
+```
+
+Steps 1 and 2 need the `codex` binary - they drive the marketplace
+clone it creates. A desktop-only machine without the Codex CLI skips
+both and installs the `o2b` CLI by hand instead, exactly as
+`install/prerequisites.md` describes (`scripts/o2b install-cli` links
+`o2b` into `~/.local/bin`); with `o2b` on PATH, the install command
+above is all that remains of this page.
+
+Install writes the two `[mcp_servers.*]` tables into that shared file -
+through `codex mcp add` when the `codex` binary is on PATH, otherwise
+through the direct TOML merge. In the merge case the detect output of
+`o2b install` names ChatGPT desktop as a reader of the file. ChatGPT
+desktop picks the servers up on its next session start, and `$CODEX_HOME`
+relocates the file for both hosts exactly as documented above.
+
+`o2b uninstall --target codex --apply` removes the shared registration,
+which undoes it for ChatGPT desktop at the same time. Uninstall resolves
+the vault through the same chain install does, so aim it at the vault
+the install wrote: pass the same `--vault` (or set `VAULT_DIR` the same
+way), because the install manifest it reads lives there. Only the two
+Open Second Brain tables are removed; every other table in the file
+stays.
+
## 5. Verify
```bash
diff --git a/openclaw.plugin.json b/openclaw.plugin.json
index 6c867c7d..0edf394d 100644
--- a/openclaw.plugin.json
+++ b/openclaw.plugin.json
@@ -2,7 +2,7 @@
"id": "open-second-brain",
"name": "Open Second Brain",
"description": "Second brain for AI agents using Obsidian-compatible Markdown vaults.",
- "version": "1.97.0",
+ "version": "1.98.0",
"activation": { "onStartup": true },
"skills": ["./skills"],
"contracts": {
diff --git a/openclaw/index.js b/openclaw/index.js
index b520bd13..83a75e43 100644
--- a/openclaw/index.js
+++ b/openclaw/index.js
@@ -2207,6 +2207,120 @@ var init_path_constants = __esm(() => {
]);
});
+// src/core/integrity/digest.ts
+var init_digest = () => {};
+
+// src/core/reliability/command-bridge.ts
+var init_command_bridge = () => {};
+
+// src/core/brain/llm-step.ts
+var NEEDS_LLM_STEP_KEYS;
+var init_llm_step = __esm(() => {
+ NEEDS_LLM_STEP_KEYS = Object.freeze([
+ "status",
+ "step",
+ "prompt",
+ "schema_hints",
+ "target_path"
+ ]);
+});
+
+// src/core/brain/skill-rewrite-tasks.ts
+import { posix as posix2 } from "node:path";
+var SKILL_BENCHMARKS_DIR = "skill-benchmarks", SKILL_BENCHMARKS_ROOT_REL, SKILL_BENCH_TASK_KIND, SKILL_BENCH_TASK_KINDS, SKILL_BENCH_CHECK, SKILL_BENCH_CHECKS, SKILL_BENCH_VALUE_CLASS, SKILL_BENCH_VALUE_CLASSES;
+var init_skill_rewrite_tasks = __esm(() => {
+ init_digest();
+ init_path_constants();
+ SKILL_BENCHMARKS_ROOT_REL = posix2.join(BRAIN_ROOT_REL, SKILL_BENCHMARKS_DIR);
+ SKILL_BENCH_TASK_KIND = Object.freeze({
+ invocation_transcript: "invocation_transcript"
+ });
+ SKILL_BENCH_TASK_KINDS = Object.freeze(Object.values(SKILL_BENCH_TASK_KIND));
+ SKILL_BENCH_CHECK = Object.freeze({
+ tool_used: "tool_used",
+ artifact_created: "artifact_created",
+ step_order: "step_order",
+ forbidden_step: "forbidden_step",
+ output_field: "output_field"
+ });
+ SKILL_BENCH_CHECKS = Object.freeze(Object.values(SKILL_BENCH_CHECK));
+ SKILL_BENCH_VALUE_CLASS = Object.freeze({
+ non_empty_string: "non_empty_string",
+ number: "number",
+ boolean: "boolean",
+ non_empty_array: "non_empty_array"
+ });
+ SKILL_BENCH_VALUE_CLASSES = Object.freeze(Object.values(SKILL_BENCH_VALUE_CLASS));
+});
+
+// src/core/brain/skill-rewrite-spec.ts
+var SKILL_REWRITE_VERDICT, SKILL_REWRITE_VERDICTS, HASH_HEX_LENGTH = 64, HASH_HEX_RE;
+var init_skill_rewrite_spec = __esm(() => {
+ init_digest();
+ init_skill_rewrite_tasks();
+ SKILL_REWRITE_VERDICT = Object.freeze({
+ promote: "promote",
+ hold: "hold",
+ not_enough_evidence: "not_enough_evidence"
+ });
+ SKILL_REWRITE_VERDICTS = Object.freeze(Object.values(SKILL_REWRITE_VERDICT));
+ HASH_HEX_RE = new RegExp(`^[0-9a-f]{${HASH_HEX_LENGTH}}$`);
+});
+
+// src/core/brain/skill-rewrite.ts
+function isSkillRewriteMode(value) {
+ return typeof value === "string" && SKILL_REWRITE_MODES.includes(value);
+}
+function resolveSkillRewriteMode(raw) {
+ const value = raw?.trim() ?? "";
+ if (value === "")
+ return SKILL_REWRITE_MODE.gated;
+ if (isSkillRewriteMode(value))
+ return value;
+ throw new SkillRewriteError(`skill rewrite mode '${value}' is unknown (expected one of ${SKILL_REWRITE_MODES.join(", ")})`);
+}
+var SKILL_REWRITE_ROUND_ARM, SKILL_REWRITE_ROUND_ARMS, SKILL_REWRITE_MODE, SKILL_REWRITE_MODES, SkillRewriteError, SELF_REPORTED_KEYS, KNOWN_SUBMISSION_KEYS, SUBMISSION_SHAPE_HINT;
+var init_skill_rewrite = __esm(() => {
+ init_digest();
+ init_command_bridge();
+ init_llm_step();
+ init_skill_rewrite_tasks();
+ init_skill_rewrite_spec();
+ init_skill_rewrite_spec();
+ SKILL_REWRITE_ROUND_ARM = Object.freeze({
+ baseline: "baseline",
+ candidate: "candidate",
+ heldout: "heldout"
+ });
+ SKILL_REWRITE_ROUND_ARMS = Object.freeze(Object.values(SKILL_REWRITE_ROUND_ARM));
+ SKILL_REWRITE_MODE = Object.freeze({
+ gated: "gated",
+ iterative: "iterative"
+ });
+ SKILL_REWRITE_MODES = Object.freeze(Object.values(SKILL_REWRITE_MODE));
+ SkillRewriteError = class SkillRewriteError extends Error {
+ constructor(message) {
+ super(message);
+ this.name = "SkillRewriteError";
+ }
+ };
+ SELF_REPORTED_KEYS = Object.freeze([
+ "success",
+ "passed",
+ "succeeded",
+ "ok"
+ ]);
+ KNOWN_SUBMISSION_KEYS = Object.freeze([
+ "task_id",
+ "steps",
+ "tools_used",
+ "artifacts",
+ "output",
+ "candidate_sha256"
+ ]);
+ SUBMISSION_SHAPE_HINT = "Return one JSON object per task with keys: task_id (string), steps (string array), " + "tools_used (string array), artifacts (string array), output (object), " + "candidate_sha256 (string, the sha-256 hex digest of the candidate skill body the " + "task was performed against). " + "No other top-level keys.";
+});
+
// src/core/brain/wikilink.ts
var init_wikilink = () => {};
@@ -2239,6 +2353,7 @@ __export(exports_config, {
INSTALLATION_SECRET_CONFIG_KEY: () => INSTALLATION_SECRET_CONFIG_KEY,
INSTALLATION_SECRET_ENV_KEY: () => INSTALLATION_SECRET_ENV_KEY,
INSTALLATION_SECRET_RE: () => INSTALLATION_SECRET_RE,
+ LESSONS_PROMOTION_SCOPES_ENV_KEY: () => LESSONS_PROMOTION_SCOPES_ENV_KEY,
MAINTENANCE_CUSTOM_TASKS_CONFIG_KEY: () => MAINTENANCE_CUSTOM_TASKS_CONFIG_KEY,
MAINTENANCE_CUSTOM_TASKS_ENV: () => MAINTENANCE_CUSTOM_TASKS_ENV,
MAINTENANCE_EMBEDDINGS_CONFIG_KEY: () => MAINTENANCE_EMBEDDINGS_CONFIG_KEY,
@@ -2248,6 +2363,10 @@ __export(exports_config, {
PARTNER_CODEGRAPH_DISABLED_ENV: () => PARTNER_CODEGRAPH_DISABLED_ENV,
REGROUND_PART_CHARS_DEFAULT: () => REGROUND_PART_CHARS_DEFAULT,
SESSION_CAPTURE_ROLES: () => SESSION_CAPTURE_ROLES,
+ SKILL_REWRITE_JUDGE_CMD_CONFIG_KEY: () => SKILL_REWRITE_JUDGE_CMD_CONFIG_KEY,
+ SKILL_REWRITE_JUDGE_CMD_ENV_KEY: () => SKILL_REWRITE_JUDGE_CMD_ENV_KEY,
+ SKILL_REWRITE_MODE_CONFIG_KEY: () => SKILL_REWRITE_MODE_CONFIG_KEY,
+ SKILL_REWRITE_MODE_ENV_KEY: () => SKILL_REWRITE_MODE_ENV_KEY,
UNCONFIGURED_AGENT_NAME: () => UNCONFIGURED_AGENT_NAME,
UnsupportedPlatformError: () => UnsupportedPlatformError,
VAULT_STORE_REF_PREFIX: () => VAULT_STORE_REF_PREFIX,
@@ -2308,6 +2427,8 @@ __export(exports_config, {
resolveSessionHandoff: () => resolveSessionHandoff,
resolveSharedNamespace: () => resolveSharedNamespace,
resolveSkillAutoAttach: () => resolveSkillAutoAttach,
+ resolveSkillRewriteJudgeCmd: () => resolveSkillRewriteJudgeCmd,
+ resolveSkillRewriteModeConfig: () => resolveSkillRewriteModeConfig,
resolveSkillsAttachTriggers: () => resolveSkillsAttachTriggers,
resolveSkillsAttachUsageOrdering: () => resolveSkillsAttachUsageOrdering,
resolveSkillsDir: () => resolveSkillsDir,
@@ -2986,6 +3107,16 @@ function resolveTelegramCaptureAllowlist(configPath) {
}
return ids;
}
+function resolveSkillRewriteModeConfig(configPath) {
+ const env = process.env[SKILL_REWRITE_MODE_ENV_KEY]?.trim();
+ const raw = env || discoverConfig(configPath).data[SKILL_REWRITE_MODE_CONFIG_KEY]?.trim();
+ return resolveSkillRewriteMode(raw);
+}
+function resolveSkillRewriteJudgeCmd(configPath) {
+ const env = process.env[SKILL_REWRITE_JUDGE_CMD_ENV_KEY]?.trim();
+ const raw = env || discoverConfig(configPath).data[SKILL_REWRITE_JUDGE_CMD_CONFIG_KEY]?.trim();
+ return raw !== undefined && raw !== "" ? raw : undefined;
+}
function expandTilde(p, platform = process.platform, home = homedir2()) {
if (p === "~")
return home;
@@ -2995,7 +3126,7 @@ function expandTilde(p, platform = process.platform, home = homedir2()) {
return join5(home, p.slice(2));
return p;
}
-var import_proper_lockfile2, namedSecretResolver, CONFIG_VALUE_REJECTED_CHARS, UNSUPPORTED_CONFIG_PLATFORMS, UnsupportedPlatformError, ConfigReadError, UNCONFIGURED_AGENT_NAME = "agent", SHARED_NAMESPACE_KEY = "shared_namespace", DEVICE_ID_RE, INSTALLATION_SECRET_CONFIG_KEY = "installation_secret", INSTALLATION_SECRET_ENV_KEY = "O2B_INSTALLATION_SECRET", INSTALLATION_SECRET_RE, VAULT_STORE_REF_PREFIX = "vault://", VAULT_STORE_REF_HEX_LEN = 32, DECISION_RECALL_MAX_PER_SESSION_CONFIG_KEY = "decision_recall.max_per_session", DECISION_RECALL_MAX_PER_SESSION_ENV_KEY = "OPEN_SECOND_BRAIN_DECISION_RECALL_MAX_PER_SESSION", DECISION_RECALL_MIN_SPACING_TURNS_CONFIG_KEY = "decision_recall.min_spacing_turns", DECISION_RECALL_MIN_SPACING_TURNS_ENV_KEY = "OPEN_SECOND_BRAIN_DECISION_RECALL_MIN_SPACING_TURNS", MODEL_CONTEXT_WINDOW_ENV_KEY = "OPEN_SECOND_BRAIN_MODEL_CONTEXT_WINDOW", ANSWER_QUOTE_CHECK_MODES, QUOTE_CHECK_BLOCK = "quote_check", ANSWER_QUOTE_CHECK_PHASES, QUOTE_CHECK_DEFAULT = "shadow", quoteCheckWarnedUnknownKeys, RECALL_INJECT_CAP_SPECS, REGROUND_PART_CHARS_DEFAULT = 9000, MAINTENANCE_EMBEDDINGS_ENV = "OPEN_SECOND_BRAIN_MAINTENANCE_EMBEDDINGS", MAINTENANCE_EMBEDDINGS_CONFIG_KEY = "maintenance_embeddings", MAINTENANCE_CUSTOM_TASKS_ENV = "OPEN_SECOND_BRAIN_MAINTENANCE_CUSTOM_TASKS", MAINTENANCE_CUSTOM_TASKS_CONFIG_KEY = "maintenance_custom_tasks", PARTNER_CODEGRAPH_DISABLED_ENV = "OPEN_SECOND_BRAIN_PARTNER_CODEGRAPH_DISABLED", PARTNER_CODEGRAPH_DISABLED_CONFIG_KEY = "partner_codegraph_disabled", SESSION_CAPTURE_ROLES;
+var import_proper_lockfile2, namedSecretResolver, CONFIG_VALUE_REJECTED_CHARS, UNSUPPORTED_CONFIG_PLATFORMS, UnsupportedPlatformError, ConfigReadError, UNCONFIGURED_AGENT_NAME = "agent", SHARED_NAMESPACE_KEY = "shared_namespace", DEVICE_ID_RE, INSTALLATION_SECRET_CONFIG_KEY = "installation_secret", INSTALLATION_SECRET_ENV_KEY = "O2B_INSTALLATION_SECRET", INSTALLATION_SECRET_RE, VAULT_STORE_REF_PREFIX = "vault://", VAULT_STORE_REF_HEX_LEN = 32, DECISION_RECALL_MAX_PER_SESSION_CONFIG_KEY = "decision_recall.max_per_session", DECISION_RECALL_MAX_PER_SESSION_ENV_KEY = "OPEN_SECOND_BRAIN_DECISION_RECALL_MAX_PER_SESSION", DECISION_RECALL_MIN_SPACING_TURNS_CONFIG_KEY = "decision_recall.min_spacing_turns", DECISION_RECALL_MIN_SPACING_TURNS_ENV_KEY = "OPEN_SECOND_BRAIN_DECISION_RECALL_MIN_SPACING_TURNS", LESSONS_PROMOTION_SCOPES_ENV_KEY = "OPEN_SECOND_BRAIN_LESSONS_PROMOTION_SCOPES", MODEL_CONTEXT_WINDOW_ENV_KEY = "OPEN_SECOND_BRAIN_MODEL_CONTEXT_WINDOW", ANSWER_QUOTE_CHECK_MODES, QUOTE_CHECK_BLOCK = "quote_check", ANSWER_QUOTE_CHECK_PHASES, QUOTE_CHECK_DEFAULT = "shadow", quoteCheckWarnedUnknownKeys, RECALL_INJECT_CAP_SPECS, REGROUND_PART_CHARS_DEFAULT = 9000, MAINTENANCE_EMBEDDINGS_ENV = "OPEN_SECOND_BRAIN_MAINTENANCE_EMBEDDINGS", MAINTENANCE_EMBEDDINGS_CONFIG_KEY = "maintenance_embeddings", MAINTENANCE_CUSTOM_TASKS_ENV = "OPEN_SECOND_BRAIN_MAINTENANCE_CUSTOM_TASKS", MAINTENANCE_CUSTOM_TASKS_CONFIG_KEY = "maintenance_custom_tasks", PARTNER_CODEGRAPH_DISABLED_ENV = "OPEN_SECOND_BRAIN_PARTNER_CODEGRAPH_DISABLED", PARTNER_CODEGRAPH_DISABLED_CONFIG_KEY = "partner_codegraph_disabled", SESSION_CAPTURE_ROLES, SKILL_REWRITE_MODE_CONFIG_KEY = "skill_rewrite.mode", SKILL_REWRITE_MODE_ENV_KEY = "OPEN_SECOND_BRAIN_SKILL_REWRITE_MODE", SKILL_REWRITE_JUDGE_CMD_CONFIG_KEY = "skill_rewrite_judge_cmd", SKILL_REWRITE_JUDGE_CMD_ENV_KEY = "OPEN_SECOND_BRAIN_SKILL_REWRITE_JUDGE_CMD";
var init_config = __esm(() => {
init_fs_atomic();
init_secret_ref();
@@ -3004,6 +3135,7 @@ var init_config = __esm(() => {
init_pointer();
init_errors();
init_path_constants();
+ init_skill_rewrite();
init_format_wikilink();
import_proper_lockfile2 = __toESM(require_proper_lockfile(), 1);
CONFIG_VALUE_REJECTED_CHARS = ['"', "\\", `
@@ -3944,6 +4076,8 @@ var init_paths = __esm(() => {
init_ledger_shards();
init_path_constants();
init_vault_identity();
+ init_skill_rewrite_tasks();
+ init_skill_rewrite();
init_path_safety();
init_freeze_marker();
init_path_constants();
diff --git a/package.json b/package.json
index 03f8b021..ddcb46c4 100644
--- a/package.json
+++ b/package.json
@@ -1,6 +1,6 @@
{
"name": "open-second-brain",
- "version": "1.97.0",
+ "version": "1.98.0",
"private": false,
"description": "Second brain for AI agents using Obsidian-compatible Markdown vaults. Works with Hermes, Claude Code, Codex, and OpenClaw.",
"keywords": [
diff --git a/plugin.yaml b/plugin.yaml
index d5c5c051..8fb22f34 100644
--- a/plugin.yaml
+++ b/plugin.yaml
@@ -1,5 +1,5 @@
name: open-second-brain
-version: "1.97.0"
+version: "1.98.0"
description: "Open Second Brain - native Hermes memory provider backed by an Obsidian-compatible Markdown vault."
author: "Open Second Brain contributors"
memory_provider: true
diff --git a/plugins/codex/.codex-plugin/plugin.json b/plugins/codex/.codex-plugin/plugin.json
index e283d904..ee5a820e 100644
--- a/plugins/codex/.codex-plugin/plugin.json
+++ b/plugins/codex/.codex-plugin/plugin.json
@@ -1,6 +1,6 @@
{
"name": "open-second-brain",
- "version": "1.97.0",
+ "version": "1.98.0",
"description": "Plugin-first second brain package for Codex, Hermes, Claude Code, OpenClaw, and other agent runtimes.",
"author": {
"name": "Open Second Brain contributors",
diff --git a/plugins/codex/README.md b/plugins/codex/README.md
index 9e9540b4..bedda8d1 100644
--- a/plugins/codex/README.md
+++ b/plugins/codex/README.md
@@ -78,6 +78,7 @@ The full router with readiness criteria is [`install.md`](https://github.com/ite
| ------------------ | ------------------------------------------------------------------------ | -------------------------------------------------- |
| Claude Code | Marketplace plugin: MCP servers and hooks | [`install/claudecode.md`](https://github.com/itechmeat/open-second-brain/blob/main/install/claudecode.md) |
| OpenAI Codex | Marketplace plugin, then `o2b install --target codex --apply` | [`install/codex.md`](https://github.com/itechmeat/open-second-brain/blob/main/install/codex.md) |
+| ChatGPT desktop | Reads the shared Codex config: `o2b install --target codex --apply` | [`install/codex.md`](https://github.com/itechmeat/open-second-brain/blob/main/install/codex.md) |
| Hermes Agent | Plugin and memory provider | [`install/hermes.md`](https://github.com/itechmeat/open-second-brain/blob/main/install/hermes.md) |
| OpenClaw | Native plugin, no MCP | [`install/openclaw.md`](https://github.com/itechmeat/open-second-brain/blob/main/install/openclaw.md) |
| opencode | `o2b install --target opencode --apply`: MCP servers and a native plugin | [`install/opencode.md`](https://github.com/itechmeat/open-second-brain/blob/main/install/opencode.md) |
@@ -123,7 +124,7 @@ The full router with readiness criteria is [`install.md`](https://github.com/ite
## What is new
-Open Second Brain 1.97.0 makes delivery state whose words it hands over. Stored-record text that reaches a remote agent through the MCP read surfaces - search, the report-shaped reads, context and pinned context, and the `osb://` preference, topic, active, lessons, digest and backlinks resources - arrives inside the same untrusted-source fence the intake path uses whenever the record's provenance says agent-authored or cannot be derived, while local reads and the stored bytes stay byte-identical. `o2b brain context-receipts verify` re-hashes what a session was delivered against the live vault it was drawn from, and `o2b brain attest keygen|sign|list|verify` binds the store's log heads and state-surface stamps into Ed25519-signed records under an operator-managed key, with a read-only MCP mirror and doctor checks that name pages whose provenance nothing derives, recent receipt drift and stale attestations. The opencode lane gains opt-in tool gating that blocks only on an explicit shim deny and prompt-time injection delivered once per turn, pinned by a hook-parity census of declared divergences. Every release is described in the [CHANGELOG](https://github.com/itechmeat/open-second-brain/blob/main/CHANGELOG.md).
+Open Second Brain 1.98.0 is the agent-presence and self-improvement release. `o2b install --target <host> --apply` now writes the brain-usage block into the agent-instruction file the installed host reads at the vault root (AGENTS.md for codex, cursor, opencode and aider; GEMINI.md for gemini-cli) under the same consent prompt as the config writes, preserving every byte outside the block and recording its ownership so uninstall removes exactly the pair the tool wrote; the dream pass gains an operator-approved exit into those same files, where a lesson promotes into a managed lessons block only with a fresh approval pinned to the approved text, and the doctor grades every block state it can name. The skill lane gains a benchmark-gated rewrite loop: a skill is rewritten only after a candidate beats the incumbent on scored dev tasks with full coverage and survives the one held-out check - Open Second Brain never calls a model, the scorer reads structural predicates and nothing the agent claims about its own work, and the accept stays an operator step on the command line. And ChatGPT desktop is named where its operators look for it: it reads the shared Codex config, so one codex registration serves both. Every release is described in the [CHANGELOG](https://github.com/itechmeat/open-second-brain/blob/main/CHANGELOG.md).
## Documentation
diff --git a/plugins/hermes/plugin.yaml b/plugins/hermes/plugin.yaml
index d5c5c051..8fb22f34 100644
--- a/plugins/hermes/plugin.yaml
+++ b/plugins/hermes/plugin.yaml
@@ -1,5 +1,5 @@
name: open-second-brain
-version: "1.97.0"
+version: "1.98.0"
description: "Open Second Brain - native Hermes memory provider backed by an Obsidian-compatible Markdown vault."
author: "Open Second Brain contributors"
memory_provider: true
diff --git a/pyproject.toml b/pyproject.toml
index d4532a52..106a769c 100644
--- a/pyproject.toml
+++ b/pyproject.toml
@@ -12,7 +12,7 @@ build-backend = "setuptools.build_meta"
# `hermes_agent.memory_providers` group, not a CLI script.
[project]
name = "open-second-brain"
-version = "1.97.0"
+version = "1.98.0"
description = "Hermes Python shim for Open Second Brain. Most of the project (CLI, MCP server, OpenClaw plugin) is TypeScript on Bun; see package.json."
readme = "README.md"
requires-python = ">=3.11"
diff --git a/src/cli/brain.ts b/src/cli/brain.ts
index ee2f83ee..c0dab015 100644
--- a/src/cli/brain.ts
+++ b/src/cli/brain.ts
@@ -20,6 +20,7 @@ import {
cmdBrainTension,
cmdBrainDream,
cmdBrainApplyEvidence,
+ cmdBrainLessons,
cmdBrainDigest,
cmdBrainIntentReview,
cmdBrainRetention,
@@ -283,6 +284,8 @@ export async function handleBrainSubcommand(argv: ReadonlyArray<string>): Promis
return await cmdBrainPin(rest);
case "unpin":
return await cmdBrainUnpin(rest);
+ case "lessons":
+ return await cmdBrainLessons(rest);
case "state":
return await cmdBrainState(rest);
case "set-primary":
diff --git a/src/cli/brain/help-text.ts b/src/cli/brain/help-text.ts
index 39ea0533..c6230db7 100644
--- a/src/cli/brain/help-text.ts
+++ b/src/cli/brain/help-text.ts
@@ -154,6 +154,7 @@ Brain verbs (observing memory):
today Today dashboard: due obligations, open loops, recent activity, totals
apply-markers Apply @osb set frontmatter write-backs (report by default; --apply writes)
pending Review the write-approval queues (signals/notes/ingest): list | apply <id> | reject <id>
+ lessons Operator-approved lesson promotion: candidates | approve <id> | deny <id> | refresh-blocks
signal Fact signal lifecycle: retire <id> --reason <text>
capture Stage one capture from the terminal: body, source, sender, guidance
telegram-capture Inbound Telegram capture bot: run (long-poll) | catchup
@@ -1176,8 +1177,8 @@ export const VERB_HELP: Record<string, string> = {
" o2b brain generation-reports show <report-id> [--vault <path>] [--json]\n" +
"Inbound, opt-in LLM generation tracing. record is gated (default off) by --enable or generation_trace_enabled; only prompt_hash + counts are stored, never the prompt.\n",
"skill-proposals":
- "usage: o2b brain skill-proposals <learn|list|accept|reject|recover|usage|page-candidates|page-draft> [args]\n" +
- "Proposal queue lifecycle, from continuity telemetry and from mature vault pages.\n" +
+ "usage: o2b brain skill-proposals <learn|list|accept|reject|recover|usage|page-candidates|page-draft|rewrite-plan|rewrite-score> [args]\n" +
+ "Proposal queue lifecycle, from continuity telemetry, from mature vault pages, and from benchmark-gated rewrite rounds.\n" +
" learn [--min-support <n>] [--vault <path>] [--json]\n" +
" list [--vault <path>] [--json]\n" +
" accept <slug> [--note <text>] [--vault <path>] [--json]\n" +
@@ -1186,8 +1187,11 @@ export const VERB_HELP: Record<string, string> = {
" usage [--vault <path>] [--json]\n" +
" page-candidates [--vault <path>] [--json]\n" +
" page-draft <page> (--payload <json> | --payload-file <path>) [--vault <path>] [--json]\n" +
+ " rewrite-plan <skill> --candidate-file <path> [--skills-root <path>] [--vault <path>] [--json]\n" +
+ " rewrite-score <skill> [--rounds-dir <dir>] [--candidate-file <path>] [--skills-root <path>] [--vault <path>] [--json]\n" +
"page-candidates is read-only: it gates the vault's user pages on the page-meta trio (core tier, non-stale lifecycle, high confidence) and an observed-reuse floor, skips any page an installed skill already covers, and returns one needs-llm-step envelope per admitted page plus every skip with its reason. page-draft validates the returned draft and STAGES it as a pending mature_page proposal inside the vault; accept is what materializes the SKILL.md under the configured skills root.\n" +
- "recover resolves accept sequences a crash abandoned. It refuses, naming the file, on a held accept lock and on an unreadable journal marker; --discard-unreadable removes those markers.\n",
+ "recover resolves accept sequences a crash abandoned. It refuses, naming the file, on a held accept lock and on an unreadable journal marker; --discard-unreadable removes those markers.\n" +
+ "rewrite-plan verifies the skill's benchmark task set against its frozen receipt and prints the receipt plus the dev-round envelopes: a baseline round over the incumbent body and a candidate round over --candidate-file, each with its transcript drop site under Brain/skill-benchmarks/<skill>/rounds/. Held-out members are never printed here. rewrite-score grades the submitted transcripts with structural predicates only, runs the preregistered selection gate (a candidate promotes only by strictly beating the baseline by the pinned margin with the dev n met), hands out the single held-out round on a promote, and stages a scored_rewrite pending proposal ONLY on a final promote after the held-out pass; a hold and a short dev arm write only the grade record. The optional judge (skill_rewrite_judge_cmd) is advisory and never moves the metric. An unknown skill_rewrite.mode refuses by name; MCP reads the same status read-only and never accepts or scores.\n",
"procedural-memory":
"usage: o2b brain procedural-memory <reconcile|list|mark-used> [args]\n" +
"Procedural index reconciliation and usage tracking sidecar.\n" +
@@ -1259,6 +1263,23 @@ export const VERB_HELP: Record<string, string> = {
"renders it into Brain/retired/ with retire-shaped frontmatter (the\n" +
"same --dry-run honesty). Applying or rejecting a missing id exits 2\n" +
"(never a silent no-op).\n",
+ lessons:
+ "usage: o2b brain lessons candidates [--vault <path>] [--json]\n" +
+ " o2b brain lessons approve <pref-id> [--target <file>...] [--apply] [--yes] [--force]\n" +
+ " o2b brain lessons deny <pref-id> [--apply] [--yes] [--vault <path>] [--json]\n" +
+ " o2b brain lessons refresh-blocks [--apply] [--yes] [--force] [--vault <path>] [--json]\n" +
+ "Operator-approved lesson promotion into the managed lessons block of the\n" +
+ "agent rules files (AGENTS.md, CLAUDE.md, GEMINI.md). candidates is\n" +
+ "read-only: the promotable set plus every blocked lesson with its single\n" +
+ "named reason, and the resolved promotion scopes. approve follows the\n" +
+ "install consent ladder: plan-only by default, --apply executes, headless\n" +
+ "--apply without --yes refuses with exit 6; the ledger row is recorded\n" +
+ "only after the rules-file writes landed, and every byte goes through the\n" +
+ "shared rules-block writer. deny records without writing rules files.\n" +
+ "refresh-blocks re-renders blocks under management (dry run by default;\n" +
+ "never creates a block), drops a lesson whose approval went stale by\n" +
+ "name, and stamps lastPromotedAt on what it wrote. Operator-only: no MCP\n" +
+ "tool exposes these subcommands.\n",
signal:
"usage: o2b brain signal retire <id> --reason <text> [--superseded-by <id>] [--vault <path>] [--json]\n" +
"Retire an extracted fact signal: move Brain/inbox/sig-*.md into\n" +
diff --git a/src/cli/brain/verbs/index.ts b/src/cli/brain/verbs/index.ts
index f6256da2..0e36d706 100644
--- a/src/cli/brain/verbs/index.ts
+++ b/src/cli/brain/verbs/index.ts
@@ -158,3 +158,4 @@ export { cmdBrainHygiene } from "./hygiene.ts";
export { cmdBrainRefresh } from "./refresh.ts";
export { cmdBrainAnticipate } from "./anticipate.ts";
export { cmdBrainPermissions } from "./permissions.ts";
+export { cmdBrainLessons } from "./lessons.ts";
diff --git a/src/cli/brain/verbs/lessons.ts b/src/cli/brain/verbs/lessons.ts
new file mode 100644
index 00000000..a138f3d5
--- /dev/null
+++ b/src/cli/brain/verbs/lessons.ts
@@ -0,0 +1,1060 @@
+/**
+ * `o2b brain lessons` - operator-approved lesson promotion (t_1e952e43,
+ * task C2). Thin CLI wrapper over the promotion kernel
+ * (`src/core/brain/lessons-promotion.ts`); qualification, rendering and
+ * the approval ledger all live there. This verb adds only the operator
+ * surfaces: listing, the consent ladder, and managed-block maintenance.
+ *
+ * Subcommands:
+ *
+ * - `candidates` is READ-ONLY: the promotable set, every blocked lesson
+ * with its single named reason, and the resolved promotion scopes.
+ * It writes nothing - no rules file, no ledger, no log event.
+ * - `approve <pref-id>` follows the install consent ladder: plan-only
+ * by default (target files and the block diff), `--apply` executes,
+ * a headless `--apply` without `--yes` refuses with exit 6, an
+ * interactive `--apply` without `--yes` asks once. Before any write,
+ * the plan for EVERY affected target is computed and every writer
+ * refusal is fired (the same dry pre-pass refresh-blocks runs), so a
+ * refusal on one target refuses the whole verb and no target is left
+ * written and unmanaged. The ledger row is recorded only AFTER the
+ * rules-block writes landed, so a refused approve lifts nothing -
+ * not even a prior denial. Every rules-file byte goes through the
+ * shared writer (`src/core/install/rules-block.ts`); this verb never
+ * writes a rules file itself.
+ * - `deny <pref-id>` records the decision and appends the log event,
+ * gated by the same ladder because a denial is a state change too;
+ * it never writes a rules file.
+ * - `refresh-blocks` re-renders the managed lessons blocks from the
+ * currently qualified set. It is a dry preview by default, is a
+ * named no-op when no block exists under management (it never
+ * CREATES a block - creation is approve's write), drops a lesson
+ * whose approval went stale by name, and stamps `lastPromotedAt`
+ * on the rows whose content a write delivered.
+ *
+ * Trust boundary: these verbs are operator-only. No MCP tool and no hook
+ * or dream path reaches them; an agent-facing surface that could approve
+ * its own lessons is a design defect regardless of what tests say.
+ */
+
+import { existsSync, statSync } from "node:fs";
+import { join } from "node:path";
+
+import { computeContentHash } from "../../../core/brain/content-hash.ts";
+import {
+ LESSON_PROMOTION_BLOCKED,
+ currentApprovalFor,
+ gatherLessonsPromotionInputs,
+ lessonPromotionCandidates,
+ lessonsBlockLimit,
+ markLessonPromoted,
+ readLessonApprovals,
+ recordLessonApproval,
+ renderLessonsBlockWithDrops,
+ type LessonApprovalRow,
+ type LessonPromotionCandidate,
+ type RenderedLessonsBlock,
+} from "../../../core/brain/lessons-promotion.ts";
+import { appendLogEvent } from "../../../core/brain/log.ts";
+import { isoSecond } from "../../../core/brain/time.ts";
+import { BRAIN_LOG_EVENT_KIND, type BrainLogEventKind } from "../../../core/brain/types.ts";
+import { AGENT_INSTRUCTION_FILES } from "../../../core/brain/writeback-contract.ts";
+import { renderPrefLink } from "../../../core/brain/wikilink.ts";
+import {
+ FUTURE_ANCHOR_ALLOWANCE_MS,
+ RULES_BLOCK_ERROR_KIND,
+ RULES_BLOCK_ID,
+ RulesBlockError,
+ readRulesBlock,
+ removeRulesBlock,
+ writeRulesBlock,
+} from "../../../core/install/rules-block.ts";
+import {
+ brainVerbContext,
+ fail,
+ ok,
+ okJson,
+ parse,
+ readSingleLine,
+ renderUnifiedDiff,
+ resolveBrainAgent,
+ usageError,
+ writeJson,
+} from "../helpers.ts";
+
+/**
+ * Every code this verb family returns, named once so the docblock, the
+ * returns and the tests read one table. `consentRefused` is 6, the
+ * install ladder's reserved verdict (`INSTALL_EXIT.consentRefused`), so
+ * every consent-bearing surface in the tool answers with the same number.
+ */
+export const LESSONS_EXIT = Object.freeze({
+ ok: 0,
+ runtimeError: 1,
+ usage: 2,
+ consentRefused: 6,
+} as const);
+
+/**
+ * Clock slack between the ledger's promotion stamp and a file mtime,
+ * mirroring the rules-block writer's own slack: a write landing within a
+ * second of its record must not read as a later hand edit. The writer
+ * enforces this on its write path; the same slack guards the removal
+ * path here, where the writer deliberately carries no divergence gate.
+ */
+const REMOVAL_MTIME_SLACK_MS = 1000;
+
+/** One planned change to one managed rules file, before consent. */
+interface RefreshAction {
+ readonly target: string;
+ readonly kind: "write" | "remove";
+ /** The canonical body, for `write` actions. */
+ readonly body: string;
+ /** The ownership stamp the writer's hand-edit gate compares against. */
+ readonly installedAtMs: number | null;
+ /** Qualified lessons the `lessons.limit` cut dropped from this render. */
+ readonly droppedIds: ReadonlyArray<string>;
+}
+
+/** A target that carries no block refresh may touch, reported by name. */
+interface RefreshSkip {
+ readonly target: string;
+ readonly reason: string;
+}
+
+export async function cmdBrainLessons(argv: string[]): Promise<number> {
+ const sub = argv[0];
+ const rest = argv.slice(1);
+ switch (sub) {
+ case "candidates":
+ return lessonsCandidates(rest);
+ case "approve":
+ return await lessonsApprove(rest);
+ case "deny":
+ return await lessonsDeny(rest);
+ case "refresh-blocks":
+ return await lessonsRefreshBlocks(rest);
+ default:
+ return usageError(
+ "brain lessons requires a subcommand: candidates | approve <pref-id> | deny <pref-id> | " +
+ "refresh-blocks",
+ );
+ }
+}
+
+// ----- Shared helpers ---------------------------------------------------------
+
+/** The qualification split plus the vault inputs it derived from. */
+interface Qualification {
+ readonly inputs: ReturnType<typeof gatherLessonsPromotionInputs>;
+ readonly promotable: ReadonlyArray<LessonPromotionCandidate>;
+ readonly blocked: ReadonlyArray<{ readonly prefId: string; readonly reason: string }>;
+}
+
+/** Gather the vault inputs and split qualification against `approvals`. */
+function qualify(
+ vault: string,
+ configPath: string,
+ approvals: ReadonlyArray<LessonApprovalRow>,
+): Qualification {
+ const inputs = gatherLessonsPromotionInputs(vault, { configPath });
+ const { promotable, blocked } = lessonPromotionCandidates(
+ inputs.preferences,
+ inputs.lessons,
+ approvals,
+ { enabledScopes: inputs.scopes.scopes },
+ );
+ return { inputs, promotable, blocked };
+}
+
+/**
+ * The agent rules files a promotion may touch, in the fixed
+ * `AGENT_INSTRUCTION_FILES` order. An explicit `--target` must name one
+ * of them - an arbitrary path would put a rules-file write outside the
+ * audited file set. The default is the files that exist at the vault
+ * root (discovery by existence, never glob), so a plain `approve` plans
+ * against the files the operator actually has.
+ */
+function resolveTargets(
+ vault: string,
+ explicit: ReadonlyArray<string>,
+): { readonly targets: ReadonlyArray<string> } | { readonly error: string } {
+ for (const name of explicit) {
+ if (!(AGENT_INSTRUCTION_FILES as ReadonlyArray<string>).includes(name)) {
+ return {
+ error: `--target must be one of ${AGENT_INSTRUCTION_FILES.join(", ")}, got ${name}`,
+ };
+ }
+ }
+ if (explicit.length > 0) return { targets: explicit };
+ return { targets: AGENT_INSTRUCTION_FILES.filter((name) => existsSync(join(vault, name))) };
+}
+
+/**
+ * The qualified lessons whose approval covers `file`: promotion honours
+ * the per-file targets an approval named, so a lesson approved for one
+ * rules file never rides into another.
+ */
+function qualifiedForFile(
+ promotable: ReadonlyArray<LessonPromotionCandidate>,
+ approvals: ReadonlyArray<LessonApprovalRow>,
+ file: string,
+): ReadonlyArray<LessonPromotionCandidate> {
+ return promotable.filter((candidate) => {
+ const row = currentApprovalFor(approvals, candidate.prefId);
+ return row !== null && row.decision === "approved" && row.targets.includes(file);
+ });
+}
+
+/**
+ * Canonical block render for one target file, or null when nothing
+ * qualifies. The full render (body plus the cap's named drops) so every
+ * verb can report a lesson the `lessons.limit` cut instead of letting it
+ * leave the block silently.
+ */
+function canonicalRenderFor(
+ promotable: ReadonlyArray<LessonPromotionCandidate>,
+ approvals: ReadonlyArray<LessonApprovalRow>,
+ file: string,
+ vault: string,
+): RenderedLessonsBlock | null {
+ const qualified = qualifiedForFile(promotable, approvals, file);
+ if (qualified.length === 0) return null;
+ return renderLessonsBlockWithDrops(qualified, { limit: lessonsBlockLimit(vault) });
+}
+
+/** Canonical block body for one target file, or null when nothing qualifies. */
+function canonicalBodyFor(
+ promotable: ReadonlyArray<LessonPromotionCandidate>,
+ approvals: ReadonlyArray<LessonApprovalRow>,
+ file: string,
+ vault: string,
+): string | null {
+ return canonicalRenderFor(promotable, approvals, file, vault)?.body ?? null;
+}
+
+/** The consent verdict this invocation will record, in the shared vocabulary. */
+function consentVerdict(yes: boolean): LessonApprovalRow["decidedBy"] {
+ return yes ? "yes-flag" : "interactive-yes";
+}
+
+/**
+ * The install ladder's headless gate: an `--apply` without `--yes` on a
+ * `--json` or non-TTY run refuses before anything is written, with the
+ * reserved `headless-refused` verdict on the stream a headless consumer
+ * parses (stdout under `--json`, stderr otherwise) and exit 6.
+ */
+function refuseHeadless(json: boolean, context: string): number {
+ const refusal =
+ `this command requires --yes in non-interactive mode (--json or non-TTY stdin); ` +
+ `nothing was written (${context})`;
+ if (json) {
+ writeJson({ consent: "headless-refused", written: false, error: refusal });
+ } else {
+ process.stderr.write(`error: ${refusal}\n`);
+ }
+ return LESSONS_EXIT.consentRefused;
+}
+
+/**
+ * One rules-block writer refusal, named by kind so failures stay legible
+ * ("user-modified-block: ..."). Duck-typed on the `kind` property rather
+ * than only `instanceof`, so the name survives even when the error object
+ * crossed a module-registry boundary.
+ */
+function rulesBlockErrorLine(err: unknown): string {
+ if (err instanceof RulesBlockError) return `${err.kind}: ${err.message}`;
+ if (
+ typeof err === "object" &&
+ err !== null &&
+ typeof (err as { kind?: unknown }).kind === "string" &&
+ err instanceof Error
+ ) {
+ return `${(err as unknown as { kind: string }).kind}: ${err.message}`;
+ }
+ return err instanceof Error ? err.message : String(err);
+}
+
+/**
+ * The latest promotion stamp among the approval rows covering `file`, as
+ * epoch ms - the ownership record the writer's hand-edit gate compares
+ * the file mtime against. No stamped row returns null, which makes the
+ * writer refuse to overwrite a diverged block nobody recorded. A stamp
+ * further than the shared clock-skew allowance into the future is
+ * ignored as if unparsable: the ledger is agent-writable state, and a
+ * future-stamped record would make every operator hand-edit read as a
+ * canonical move under an untouched file - the fail-closed direction is
+ * "no trustworthy record".
+ */
+function installedAtMsFor(
+ approvals: ReadonlyArray<LessonApprovalRow>,
+ file: string,
+): number | null {
+ let latest: number | null = null;
+ for (const row of approvals) {
+ if (row.decision !== "approved" || !row.targets.includes(file)) continue;
+ if (row.lastPromotedAt === null) continue;
+ const ms = Date.parse(row.lastPromotedAt);
+ if (!Number.isFinite(ms)) continue;
+ if (ms > Date.now() + FUTURE_ANCHOR_ALLOWANCE_MS) continue;
+ if (latest === null || ms > latest) latest = ms;
+ }
+ return latest;
+}
+
+/**
+ * Whether a managed file looks hand-edited since its last recorded
+ * promotion, with the same slack the writer grants its own writes. A
+ * null stamp means no recorded promotion, so the block cannot be proven
+ * ours and counts as touched - the fail-closed direction.
+ */
+function touchedSincePromotion(installedAtMs: number | null, file: string): boolean {
+ if (installedAtMs === null) return true;
+ try {
+ const mtimeMs = statSync(file, { throwIfNoEntry: false })?.mtimeMs;
+ if (mtimeMs === undefined) return true;
+ return mtimeMs > installedAtMs + REMOVAL_MTIME_SLACK_MS;
+ } catch {
+ return true;
+ }
+}
+
+/** Append a lessons log event; a failed append warns, it never fails the verb. */
+function appendLessonsEvent(
+ vault: string,
+ eventType: BrainLogEventKind,
+ body: Record<string, string>,
+): void {
+ try {
+ appendLogEvent(vault, { timestamp: isoSecond(new Date()), eventType, body });
+ } catch (err) {
+ process.stderr.write(`warning: append ${eventType} log failed: ${(err as Error).message}\n`);
+ }
+}
+
+/** The per-target block diff lines an approve plan (or prompt) shows. */
+function approvePlanLines(
+ vault: string,
+ prefId: string,
+ promotable: ReadonlyArray<LessonPromotionCandidate>,
+ approvals: ReadonlyArray<LessonApprovalRow>,
+ targets: ReadonlyArray<string>,
+): string[] {
+ const lines: string[] = [
+ `approve plan for ${prefId} (nothing written until --apply):`,
+ ` targets: ${targets.join(", ")}`,
+ ];
+ for (const target of targets) {
+ const file = join(vault, target);
+ const body = canonicalBodyFor(promotable, approvals, target, vault);
+ const current = readRulesBlock(file, RULES_BLOCK_ID.lessons);
+ if (body === null) {
+ lines.push(` ${target}: no qualified lesson covers this file (no change)`);
+ continue;
+ }
+ if (current === null) {
+ lines.push(` ${target}: creates the managed lessons block:`);
+ lines.push(indentDiff(renderUnifiedDiff("", body, `${target} lessons block`)));
+ continue;
+ }
+ if (current.replace(/\s+$/, "") === body.replace(/\s+$/, "")) {
+ lines.push(` ${target}: block already current (no change)`);
+ continue;
+ }
+ lines.push(` ${target}: updates the managed lessons block:`);
+ lines.push(indentDiff(renderUnifiedDiff(current, body, `${target} lessons block`)));
+ }
+ return lines;
+}
+
+/** Indent a unified diff one level, so plan output nests under its file line. */
+function indentDiff(diff: string): string {
+ return diff
+ .split("\n")
+ .map((line) => ` ${line}`)
+ .join("\n");
+}
+
+/** The provisional row a qualification simulation runs against. */
+function provisionalRow(
+ prefId: string,
+ targets: ReadonlyArray<string>,
+ liveHash: string,
+): LessonApprovalRow {
+ return {
+ prefId,
+ decision: "approved",
+ decidedAt: isoSecond(new Date()),
+ decidedBy: "yes-flag",
+ approvedContentHash: liveHash,
+ targets,
+ blockId: RULES_BLOCK_ID.lessons,
+ lastPromotedAt: null,
+ };
+}
+
+/** One rules-file write through the K1 writer, with the ownership stamp. */
+function writeBlock(
+ file: string,
+ body: string,
+ opts: {
+ readonly dryRun: boolean;
+ readonly force: boolean;
+ readonly installedAtMs: number | null;
+ },
+): { readonly changed: boolean } {
+ const result = writeRulesBlock(file, RULES_BLOCK_ID.lessons, body, {
+ dryRun: opts.dryRun,
+ force: opts.force,
+ ...(opts.installedAtMs !== null ? { installedAtMs: opts.installedAtMs } : {}),
+ });
+ return { changed: result.changed };
+}
+
+// ----- candidates -------------------------------------------------------------
+
+function lessonsCandidates(argv: string[]): number {
+ const { flags } = parse(argv, {
+ vault: { type: "string" },
+ json: { type: "boolean" },
+ });
+ const { config, vault } = brainVerbContext(flags);
+ const json = flags["json"] === true;
+ const ledger = readLessonApprovals(vault);
+ // A malformed promotion scopes value is a named refusal, never a
+ // silent "disabled": the operator must tell configured-wrong from
+ // never-configured.
+ let split: Qualification;
+ try {
+ split = qualify(vault, config, ledger);
+ } catch (err) {
+ return fail(rulesBlockErrorLine(err));
+ }
+ const { inputs, promotable, blocked } = split;
+ if (json) {
+ okJson({
+ command: "brain lessons candidates",
+ promotable: promotable.map((candidate) => ({
+ prefId: candidate.prefId,
+ principle: candidate.principle,
+ scope: candidate.scope,
+ tier: candidate.tier,
+ confidence: candidate.confidence,
+ })),
+ blocked: blocked.map((entry) => ({ prefId: entry.prefId, reason: entry.reason })),
+ scopes: { count: inputs.scopes.count, origin: inputs.scopes.origin },
+ });
+ } else {
+ const lines = [
+ `promotion scopes: ${inputs.scopes.count === 0 ? "(none - promotion disabled)" : inputs.scopes.scopes.join(", ")}` +
+ ` (origin: ${inputs.scopes.origin})`,
+ `promotable: ${promotable.length}; blocked: ${blocked.length}`,
+ ];
+ for (const candidate of promotable) {
+ lines.push(
+ ` promotable ${candidate.prefId} (scope: ${candidate.scope}, tier: ${candidate.tier}, ` +
+ `confidence: ${candidate.confidence})`,
+ );
+ }
+ for (const entry of blocked) {
+ lines.push(` blocked ${entry.prefId} (${entry.reason})`);
+ }
+ ok(lines.join("\n"));
+ }
+ return LESSONS_EXIT.ok;
+}
+
+// ----- approve ----------------------------------------------------------------
+
+async function lessonsApprove(argv: string[]): Promise<number> {
+ const { flags, positional } = parse(argv, {
+ vault: { type: "string" },
+ target: { type: "string-array" },
+ apply: { type: "boolean" },
+ yes: { type: "boolean" },
+ force: { type: "boolean" },
+ json: { type: "boolean" },
+ });
+ const apply = flags["apply"] === true;
+ const yes = flags["yes"] === true;
+ const force = flags["force"] === true;
+ const json = flags["json"] === true;
+ const rawId = positional[0]?.trim() ?? "";
+ if (rawId === "") {
+ return usageError("brain lessons approve requires a preference id: approve <pref-id>");
+ }
+ const { config, vault } = brainVerbContext(flags);
+ const agent = resolveBrainAgent(flags, config);
+ const prefId = rawId.startsWith("pref-") ? rawId : `pref-${rawId}`;
+
+ const targets = resolveTargets(vault, (flags["target"] as ReadonlyArray<string>) ?? []);
+ if ("error" in targets) return usageError(targets.error);
+
+ const ledger = readLessonApprovals(vault);
+ const previous = currentApprovalFor(ledger, prefId);
+ // A malformed promotion scopes value refuses the verb by name, before
+ // any simulation, write or ledger row (see resolvePromotionScopesStrict).
+ let inputs: ReturnType<typeof gatherLessonsPromotionInputs>;
+ try {
+ inputs = gatherLessonsPromotionInputs(vault, { configPath: config });
+ } catch (err) {
+ return fail(rulesBlockErrorLine(err));
+ }
+ const pref = inputs.preferences.find((entry) => entry.id === prefId);
+ if (pref === undefined) {
+ process.stderr.write(
+ `error: no readable preference named ${prefId} under ${join(vault, "Brain", "preferences")}\n`,
+ );
+ return LESSONS_EXIT.usage;
+ }
+ if (targets.targets.length === 0) {
+ return fail(
+ `no agent rules file found at the vault root (${AGENT_INSTRUCTION_FILES.join(", ")}); ` +
+ "pass --target to name one",
+ );
+ }
+ const liveHash = computeContentHash(pref.principle, pref.scope);
+
+ // The decision is simulated first - a provisional approved row pinning
+ // the live hash replaces any prior row (the state table's latest
+ // decision wins, so a re-approve lifts a denial) - so the verb names
+ // the gate that still refuses BEFORE any ledger row or log event is
+ // recorded. An approval never rescues an unqualified lesson.
+ const simulated = [
+ ...ledger.filter((row) => row.prefId !== prefId),
+ provisionalRow(prefId, targets.targets, liveHash),
+ ];
+ const sim = lessonPromotionCandidates(inputs.preferences, inputs.lessons, simulated, {
+ enabledScopes: inputs.scopes.scopes,
+ });
+ const verdict = sim.blocked.find((entry) => entry.prefId === prefId);
+ if (verdict !== undefined) {
+ return fail(
+ `${prefId} is not promotable: ${verdict.reason} - approve records an approval only for a ` +
+ "lesson that qualifies now (confirmed, high confidence, preferred tier, enabled scope)",
+ );
+ }
+
+ // The plan render is a refusal surface too (a target with malformed
+ // markers, or a lesson whose scope cannot render as one block line):
+ // it refuses BEFORE consent, never with a crash past it.
+ let planLines: string[];
+ try {
+ planLines = approvePlanLines(vault, prefId, sim.promotable, simulated, targets.targets);
+ } catch (err) {
+ return fail(rulesBlockErrorLine(err));
+ }
+ if (!apply) {
+ if (json) {
+ writeJson({
+ command: "brain lessons approve",
+ prefId,
+ apply: false,
+ targets: targets.targets,
+ plan: planLines,
+ });
+ } else {
+ ok(planLines.join("\n"));
+ }
+ return LESSONS_EXIT.ok;
+ }
+
+ // Consent above the write lane, the install ladder verbatim.
+ if (!yes) {
+ if (json || !process.stdin.isTTY) {
+ return refuseHeadless(json, `approving ${prefId} into agent rules files`);
+ }
+ process.stderr.write(planLines.join("\n") + "\n");
+ process.stderr.write("Proceed? [y/N] ");
+ const ans = await readSingleLine();
+ if (ans.trim().toLowerCase() !== "y" && ans.trim().toLowerCase() !== "yes") {
+ ok("approval cancelled; nothing was written");
+ return LESSONS_EXIT.ok;
+ }
+ }
+
+ // The dry pre-pass, the same pure-plan discipline the installer and
+ // refresh-blocks hold: the plan for EVERY affected target is computed
+ // and every writer refusal is fired BEFORE any write lands. A refusal
+ // on any target refuses the whole verb, so a multi-target approve can
+ // never leave an earlier target written, approved-shaped, and managed
+ // by nothing (the ledger row lands only after every write succeeds).
+ const prePassRefusals: string[] = [];
+ for (const target of targets.targets) {
+ let body: string | null;
+ try {
+ body = canonicalBodyFor(sim.promotable, simulated, target, vault);
+ } catch (err) {
+ prePassRefusals.push(`${target}: ${rulesBlockErrorLine(err)}`);
+ continue;
+ }
+ if (body === null) continue; // unreachable: the approved lesson qualifies
+ try {
+ writeBlock(join(vault, target), body, {
+ dryRun: true,
+ force,
+ installedAtMs: installedAtMsFor(ledger, target),
+ });
+ } catch (err) {
+ prePassRefusals.push(`${target}: ${rulesBlockErrorLine(err)}`);
+ }
+ }
+ if (prePassRefusals.length > 0) {
+ return fail(
+ `approve refused before any write:\n` +
+ prePassRefusals.map((line) => ` ${line}`).join("\n") +
+ "\nnothing was written and no approval was recorded",
+ );
+ }
+
+ const written: string[] = [];
+ try {
+ for (const target of targets.targets) {
+ const body = canonicalBodyFor(sim.promotable, simulated, target, vault);
+ if (body === null) continue; // unreachable: the approved lesson qualifies
+ const result = writeBlock(join(vault, target), body, {
+ dryRun: false,
+ force,
+ installedAtMs: installedAtMsFor(ledger, target),
+ });
+ if (result.changed) written.push(target);
+ }
+ } catch (err) {
+ return fail(rulesBlockErrorLine(err));
+ }
+
+ // The row lands only after every write succeeded: a refused approve
+ // lifts nothing, and a denial that was on disk stays on disk.
+ const now = new Date();
+ const consent = consentVerdict(yes);
+ recordLessonApproval(vault, {
+ prefId,
+ decision: "approved",
+ decidedAt: isoSecond(now),
+ decidedBy: consent,
+ approvedContentHash: liveHash,
+ targets: targets.targets,
+ blockId: RULES_BLOCK_ID.lessons,
+ lastPromotedAt: written.length > 0 ? isoSecond(now) : (previous?.lastPromotedAt ?? null),
+ });
+ appendLessonsEvent(vault, BRAIN_LOG_EVENT_KIND.lessonsApproved, {
+ pref: renderPrefLink({ id: prefId }),
+ targets: targets.targets.join(", "),
+ approved_content_hash: liveHash,
+ consent,
+ agent,
+ });
+ if (written.length > 0) {
+ appendLessonsEvent(vault, BRAIN_LOG_EVENT_KIND.lessonsPromoted, {
+ targets: written.join(", "),
+ prefs: renderPrefLink({ id: prefId }),
+ agent,
+ });
+ }
+
+ // Name the cap's shortfall: a just-approved lesson that sorts past the
+ // `lessons.limit` cut stays approved and recorded, and the result says
+ // so by name instead of going quiet while the block omits it.
+ const limit = lessonsBlockLimit(vault);
+ const dropped: string[] = [];
+ for (const target of targets.targets) {
+ for (const id of canonicalRenderFor(sim.promotable, simulated, target, vault)?.droppedIds ??
+ []) {
+ if (!dropped.includes(id)) dropped.push(id);
+ }
+ }
+ const droppedLines = dropped.map(
+ (id) =>
+ `capped: ${id} did not fit the lessons block (lessons.limit ${limit}); it stays ` +
+ "approved and rides the block when the limit widens or an earlier lesson drops",
+ );
+
+ if (json) {
+ okJson({
+ command: "brain lessons approve",
+ prefId,
+ consent,
+ recorded: true,
+ written: written.length > 0,
+ targets: targets.targets,
+ changed: written,
+ dropped,
+ });
+ } else {
+ ok(
+ `approved: ${prefId} (targets: ${targets.targets.join(", ")}; ` +
+ `${written.length > 0 ? `wrote ${written.join(", ")}` : "block already current"})` +
+ (droppedLines.length > 0 ? `\n${droppedLines.join("\n")}` : ""),
+ );
+ }
+ return LESSONS_EXIT.ok;
+}
+
+// ----- deny -------------------------------------------------------------------
+
+async function lessonsDeny(argv: string[]): Promise<number> {
+ const { flags, positional } = parse(argv, {
+ vault: { type: "string" },
+ apply: { type: "boolean" },
+ yes: { type: "boolean" },
+ json: { type: "boolean" },
+ });
+ const apply = flags["apply"] === true;
+ const yes = flags["yes"] === true;
+ const json = flags["json"] === true;
+ const rawId = positional[0]?.trim() ?? "";
+ if (rawId === "") {
+ return usageError("brain lessons deny requires a preference id: deny <pref-id>");
+ }
+ const { config, vault } = brainVerbContext(flags);
+ const agent = resolveBrainAgent(flags, config);
+ const prefId = rawId.startsWith("pref-") ? rawId : `pref-${rawId}`;
+
+ // A malformed promotion scopes value refuses the verb by name, before
+ // anything is recorded (see resolvePromotionScopesStrict).
+ let inputs: ReturnType<typeof gatherLessonsPromotionInputs>;
+ try {
+ inputs = gatherLessonsPromotionInputs(vault, { configPath: config });
+ } catch (err) {
+ return fail(rulesBlockErrorLine(err));
+ }
+ const pref = inputs.preferences.find((entry) => entry.id === prefId);
+ if (pref === undefined) {
+ process.stderr.write(
+ `error: no readable preference named ${prefId} under ${join(vault, "Brain", "preferences")}\n`,
+ );
+ return LESSONS_EXIT.usage;
+ }
+ const liveHash = computeContentHash(pref.principle, pref.scope);
+
+ if (!apply) {
+ const line =
+ `would record a denial for ${prefId} (no rules file is written; ` + "pass --apply to record)";
+ if (json) {
+ writeJson({
+ command: "brain lessons deny",
+ prefId,
+ apply: false,
+ written: false,
+ plan: line,
+ });
+ } else {
+ ok(line);
+ }
+ return LESSONS_EXIT.ok;
+ }
+
+ // Consent gates the ledger write: a denial is a state change the
+ // operator owns, so the same ladder sits above it.
+ if (!yes) {
+ if (json || !process.stdin.isTTY) {
+ return refuseHeadless(json, `denying ${prefId}`);
+ }
+ process.stderr.write(`Record the denial of ${prefId}? No rules file is written. [y/N] `);
+ const ans = await readSingleLine();
+ if (ans.trim().toLowerCase() !== "y" && ans.trim().toLowerCase() !== "yes") {
+ ok("denial cancelled; nothing was recorded");
+ return LESSONS_EXIT.ok;
+ }
+ }
+
+ const now = new Date();
+ const consent = consentVerdict(yes);
+ recordLessonApproval(vault, {
+ prefId,
+ decision: "denied",
+ decidedAt: isoSecond(now),
+ decidedBy: consent,
+ approvedContentHash: liveHash,
+ targets: [],
+ blockId: RULES_BLOCK_ID.lessons,
+ lastPromotedAt: null,
+ });
+ appendLessonsEvent(vault, BRAIN_LOG_EVENT_KIND.lessonsDenied, {
+ pref: renderPrefLink({ id: prefId }),
+ consent,
+ agent,
+ });
+
+ if (json) {
+ okJson({ command: "brain lessons deny", prefId, consent, recorded: true, targets: [] });
+ } else {
+ ok(`denied: ${prefId} (recorded; a managed block drops it on the next refresh-blocks run)`);
+ }
+ return LESSONS_EXIT.ok;
+}
+
+// ----- refresh-blocks -----------------------------------------------------------
+
+async function lessonsRefreshBlocks(argv: string[]): Promise<number> {
+ const { flags } = parse(argv, {
+ vault: { type: "string" },
+ apply: { type: "boolean" },
+ yes: { type: "boolean" },
+ force: { type: "boolean" },
+ json: { type: "boolean" },
+ });
+ const apply = flags["apply"] === true;
+ const yes = flags["yes"] === true;
+ const force = flags["force"] === true;
+ const json = flags["json"] === true;
+ const { config, vault } = brainVerbContext(flags);
+ const agent = resolveBrainAgent(flags, config);
+
+ const ledger = readLessonApprovals(vault);
+ // A malformed promotion scopes value refuses the verb by name, before
+ // any plan or write (see resolvePromotionScopesStrict).
+ let split: Qualification;
+ try {
+ split = qualify(vault, config, ledger);
+ } catch (err) {
+ return fail(rulesBlockErrorLine(err));
+ }
+ const { promotable, blocked } = split;
+ const stale = blocked
+ .filter((entry) => entry.reason === LESSON_PROMOTION_BLOCKED.staleApproval)
+ .map((entry) => entry.prefId);
+
+ // Under management = an approved decision named the file AND the file
+ // carries the lessons pair. Discovery by existence over the fixed list,
+ // never glob; refresh never creates a block.
+ const universe = (AGENT_INSTRUCTION_FILES as ReadonlyArray<string>).filter((name) =>
+ ledger.some((row) => row.decision === "approved" && row.targets.includes(name)),
+ );
+ const skips: RefreshSkip[] = [];
+ const errors: string[] = [];
+ const actions: RefreshAction[] = [];
+ for (const target of universe) {
+ const file = join(vault, target);
+ if (!existsSync(file)) {
+ skips.push({ target, reason: "no such file at the vault root (refresh never creates it)" });
+ continue;
+ }
+ let extracted: string | null;
+ try {
+ extracted = readRulesBlock(file, RULES_BLOCK_ID.lessons);
+ } catch (err) {
+ errors.push(`${target}: ${rulesBlockErrorLine(err)}`);
+ continue;
+ }
+ if (extracted === null) {
+ skips.push({ target, reason: "no managed lessons block (refresh never creates one)" });
+ continue;
+ }
+ let render: RenderedLessonsBlock | null;
+ try {
+ render = canonicalRenderFor(promotable, ledger, target, vault);
+ } catch (err) {
+ // A canonical body that cannot render (a lesson whose scope could
+ // forge a marker line) is a named per-target error, not a crash.
+ errors.push(`${target}: ${rulesBlockErrorLine(err)}`);
+ continue;
+ }
+ const body = render === null ? null : render.body;
+ const installedAtMs = installedAtMsFor(ledger, target);
+ if (body === null) {
+ // Removal is the empty qualified set's only honest render. The
+ // writer carries no divergence gate on removal, so the same
+ // hand-edit slack guards it here: refuse unless --force.
+ if (touchedSincePromotion(installedAtMs, file) && !force) {
+ errors.push(
+ `${target}: ${RULES_BLOCK_ERROR_KIND.userModifiedBlock}: appears hand-edited since the ` +
+ "last promotion; refusing to remove the block. Re-run with --force to remove it anyway",
+ );
+ continue;
+ }
+ actions.push({ target, kind: "remove", body: "", installedAtMs, droppedIds: [] });
+ continue;
+ }
+ actions.push({
+ target,
+ kind: "write",
+ body,
+ installedAtMs,
+ droppedIds: render === null ? [] : render.droppedIds,
+ });
+ }
+ if (errors.length > 0) {
+ process.stderr.write(errors.map((line) => `error: ${line}`).join("\n") + "\n");
+ return LESSONS_EXIT.runtimeError;
+ }
+
+ const staleLines = stale.map(
+ (id) => `stale approval: ${id} - the approved text moved; approve again to re-pin it`,
+ );
+
+ // The cap's shortfall, named per target: a qualified lesson past the
+ // `lessons.limit` cut is reported, never silently truncated.
+ const droppedByTarget = actions
+ .filter((action) => action.kind === "write" && action.droppedIds.length > 0)
+ .map((action) => ({ target: action.target, ids: action.droppedIds }));
+ const dropLines = droppedByTarget.flatMap((entry) =>
+ entry.ids.map((id) => `capped: ${id} past the lessons.limit cut on ${entry.target}`),
+ );
+
+ if (actions.length === 0) {
+ const lines = [
+ "no lessons block under management - refresh never creates a block; approve a lesson first",
+ ...skips.map((skip) => ` ${skip.target}: ${skip.reason}`),
+ ...staleLines,
+ ];
+ if (json) {
+ writeJson({
+ command: "brain lessons refresh-blocks",
+ apply,
+ changed: [],
+ removed: [],
+ skips,
+ stale,
+ dropped: [],
+ });
+ } else {
+ ok(lines.join("\n"));
+ }
+ return LESSONS_EXIT.ok;
+ }
+
+ // Dry pass first: it computes (and refuses) exactly like the real pass,
+ // so the operator sees the true plan and a refusal lands before any
+ // consent is asked. A writer refusal here is the verdict for the whole
+ // run - named by kind on stderr, nothing written, exit 1.
+ let dry: RefreshPassResult;
+ try {
+ dry = runRefreshPass(vault, actions, { dryRun: true, force });
+ } catch (err) {
+ process.stderr.write(`error: ${rulesBlockErrorLine(err)}\n`);
+ return LESSONS_EXIT.runtimeError;
+ }
+ const planLines = [
+ `refresh plan for ${actions.length} managed block(s)${apply ? "" : " (dry run; pass --apply to write)"}:`,
+ ...dry.changed.map((target) => ` ${target}: would write the managed lessons block`),
+ ...dry.unchanged.map((target) => ` ${target}: block already current (no change)`),
+ ...dry.removed.map(
+ (target) => ` ${target}: would remove the block (no qualified lessons remain)`,
+ ),
+ ...dropLines.map((line) => ` ${line}`),
+ ...skips.map((skip) => ` ${skip.target}: ${skip.reason}`),
+ ...staleLines,
+ ];
+
+ if (!apply) {
+ if (json) {
+ writeJson({
+ command: "brain lessons refresh-blocks",
+ apply: false,
+ wouldChange: dry.changed,
+ wouldRemove: dry.removed,
+ skips,
+ stale,
+ dropped: droppedByTarget,
+ });
+ } else {
+ ok(planLines.join("\n"));
+ }
+ return LESSONS_EXIT.ok;
+ }
+
+ // Consent above the write lane, the install ladder verbatim.
+ if (!yes) {
+ if (json || !process.stdin.isTTY) {
+ return refuseHeadless(json, "refreshing the managed lessons blocks");
+ }
+ process.stderr.write(planLines.join("\n") + "\n");
+ process.stderr.write("Proceed? [y/N] ");
+ const ans = await readSingleLine();
+ if (ans.trim().toLowerCase() !== "y" && ans.trim().toLowerCase() !== "yes") {
+ ok("refresh cancelled; nothing was written");
+ return LESSONS_EXIT.ok;
+ }
+ }
+
+ let real: RefreshPassResult;
+ try {
+ real = runRefreshPass(vault, actions, { dryRun: false, force });
+ } catch (err) {
+ process.stderr.write(`error: ${rulesBlockErrorLine(err)}\n`);
+ return LESSONS_EXIT.runtimeError;
+ }
+
+ // Stamp the rows whose content a write actually delivered, then append
+ // the promotion event. A removal stamps nothing: dropping a lesson is
+ // derived-state maintenance, not a delivery.
+ const now = new Date();
+ const stamped = new Set<string>();
+ for (const target of real.changed) {
+ for (const candidate of qualifiedForFile(promotable, ledger, target)) {
+ stamped.add(candidate.prefId);
+ }
+ }
+ for (const prefId of stamped) {
+ markLessonPromoted(vault, prefId, now);
+ }
+ if (real.changed.length > 0) {
+ appendLessonsEvent(vault, BRAIN_LOG_EVENT_KIND.lessonsPromoted, {
+ targets: real.changed.join(", "),
+ prefs: [...stamped].map((id) => renderPrefLink({ id })).join("\n"),
+ agent,
+ });
+ }
+
+ if (json) {
+ okJson({
+ command: "brain lessons refresh-blocks",
+ consent: consentVerdict(yes),
+ changed: real.changed,
+ removed: real.removed,
+ current: real.unchanged,
+ skips,
+ stale,
+ dropped: droppedByTarget,
+ stamped: [...stamped],
+ });
+ } else {
+ const lines = [
+ ...real.changed.map((target) => `wrote: ${target}`),
+ ...real.removed.map((target) => `removed the lessons block from: ${target}`),
+ ...real.unchanged.map((target) => `already current: ${target}`),
+ ...dropLines,
+ ...skips.map((skip) => `skipped: ${skip.target} (${skip.reason})`),
+ ...staleLines,
+ ...(stamped.size > 0 ? [`stamped lastPromotedAt: ${[...stamped].join(", ")}`] : []),
+ ];
+ ok(lines.join("\n"));
+ }
+ return LESSONS_EXIT.ok;
+}
+
+/** The outcome of one refresh pass, targets grouped by what happened. */
+interface RefreshPassResult {
+ readonly changed: string[];
+ readonly unchanged: string[];
+ readonly removed: string[];
+}
+
+/** One pass over the planned actions, dry or real; refusals propagate. */
+function runRefreshPass(
+ vault: string,
+ actions: ReadonlyArray<RefreshAction>,
+ opts: { readonly dryRun: boolean; readonly force: boolean },
+): RefreshPassResult {
+ const changed: string[] = [];
+ const unchanged: string[] = [];
+ const removed: string[] = [];
+ for (const action of actions) {
+ const file = join(vault, action.target);
+ if (action.kind === "write") {
+ const result = writeBlock(file, action.body, {
+ dryRun: opts.dryRun,
+ force: opts.force,
+ installedAtMs: action.installedAtMs,
+ });
+ if (result.changed) changed.push(action.target);
+ else unchanged.push(action.target);
+ } else {
+ const result = removeRulesBlock(file, RULES_BLOCK_ID.lessons, { dryRun: opts.dryRun });
+ if (result.removed) removed.push(action.target);
+ else unchanged.push(action.target);
+ }
+ }
+ return { changed, unchanged, removed };
+}
diff --git a/src/cli/brain/verbs/skill-proposals.ts b/src/cli/brain/verbs/skill-proposals.ts
index a1153cc3..8c083b55 100644
--- a/src/cli/brain/verbs/skill-proposals.ts
+++ b/src/cli/brain/verbs/skill-proposals.ts
@@ -1,7 +1,11 @@
-import { readFileSync } from "node:fs";
-import { relative } from "node:path";
+import { existsSync, readFileSync, readdirSync } from "node:fs";
+import { join, relative } from "node:path";
-import { resolveSkillsDir } from "../../../core/config.ts";
+import {
+ resolveSkillsDir,
+ resolveSkillRewriteJudgeCmd,
+ resolveSkillRewriteModeConfig,
+} from "../../../core/config.ts";
import {
SkillPageDraftError,
commitSkillPageDraft,
@@ -12,9 +16,44 @@ import {
discardUnreadableSkillAcceptJournals,
learnSkillProposals,
listPendingSkillProposals,
+ pendingSkillProposalPatternKind,
recoverSkillProposalAccepts,
rejectSkillProposal,
+ readRewriteIncumbent,
+ recordSkillRewriteGrade,
+ SCORED_REWRITE_PATTERN_KIND,
+ stageScoredRewriteProposal,
+ DeclaredSkillProposalError,
+ type RewriteIncumbent,
} from "../../../core/brain/skill-proposals.ts";
+import {
+ buildRewriteEnvelopes,
+ buildRewriteGradeRecord,
+ buildRewriteHeldoutEnvelopes,
+ checkRewriteHeldout,
+ runRewriteJudge,
+ scoreRewriteTranscripts,
+ selectRewriteCandidate,
+ type RewriteTaskScore,
+ type SkillRewriteMode,
+} from "../../../core/brain/skill-rewrite.ts";
+import {
+ parseSkillRewriteSpec,
+ skillRewriteSpecHash,
+ verifyRewriteTake,
+ SKILL_REWRITE_VERDICT,
+ type SkillRewriteSpec,
+} from "../../../core/brain/skill-rewrite-spec.ts";
+import { sha256Hex } from "../../../core/integrity/digest.ts";
+import {
+ parseSkillBenchmarkTasks,
+ SKILL_BENCHMARK_TASKS_FILE,
+} from "../../../core/brain/skill-rewrite-tasks.ts";
+import {
+ skillBenchmarkRoundsDir,
+ skillBenchmarkSpecPath,
+ skillBenchmarkTasksPath,
+} from "../../../core/brain/paths.ts";
import { deriveSkillUsage } from "../../../core/brain/skill-usage.ts";
import { ResponseShapeError } from "../../../core/brain/response-shape.ts";
import { ResponseCheckError } from "../../../core/brain/response-checks.ts";
@@ -25,7 +64,15 @@ import {
type PayloadStrip,
} from "../../../core/brain/payload-json.ts";
import { canonicalNotePath } from "../../../core/path-safety.ts";
-import { CliError, brainVerbContext, failWith, parse } from "../helpers.ts";
+import { CliError, brainVerbContext, failWith, parse, writeJson } from "../helpers.ts";
+
+/**
+ * The consent verdict this verb answers with when a `scored_rewrite`
+ * accept is refused for want of the explicit flag: 6, the install
+ * consent ladder's reserved `consentRefused` number, so every
+ * consent-bearing surface in the tool exits the same way.
+ */
+const SKILL_PROPOSALS_EXIT = { consentRefused: 6 } as const;
export async function cmdBrainSkillProposals(argv: string[]): Promise<number> {
const sub = argv[0];
@@ -38,9 +85,11 @@ export async function cmdBrainSkillProposals(argv: string[]): Promise<number> {
if (sub === "usage") return usage(rest);
if (sub === "page-candidates") return pageCandidates(rest);
if (sub === "page-draft") return pageDraft(rest);
+ if (sub === "rewrite-plan") return rewritePlan(rest);
+ if (sub === "rewrite-score") return rewriteScore(rest);
throw new CliError(
"brain skill-proposals: expected learn, list, accept, reject, recover, usage, " +
- "page-candidates, or page-draft",
+ "page-candidates, page-draft, rewrite-plan, or rewrite-score",
);
}
@@ -310,11 +359,44 @@ function accept(argv: string[]): number {
vault: { type: "string" },
json: { type: "boolean" },
note: { type: "string" },
+ yes: { type: "boolean" },
});
const slug = trim(positional[0]);
if (!slug) throw new CliError("brain skill-proposals accept: slug is required");
const { config, vault } = brainVerbContext(flags);
const note = trim(flags["note"]);
+ // The human accept is the consent boundary (review security M1, round-2
+ // residual R2): a `scored_rewrite` accept OVERWRITES an incumbent
+ // SKILL.md, and the agent that staged the proposal runs shell commands,
+ // so the MCP accept refusal alone does not keep the overwrite out of
+ // its reach. The explicit flag is the same consent every other
+ // irreversible verb in the tree gates on (`install --apply`,
+ // `brain lessons approve --apply`), and without it the accept is a
+ // named refusal BEFORE anything is written - the exact command to
+ // re-run is printed, the incumbent keeps its bytes, and the draft stays
+ // pending. Ordinary proposals create or fill vault pages and never
+ // overwrite; they accept exactly as before.
+ if (
+ pendingSkillProposalPatternKind(vault, slug) === SCORED_REWRITE_PATTERN_KIND &&
+ flags["yes"] !== true
+ ) {
+ const refusal =
+ `'${slug}' is a ${SCORED_REWRITE_PATTERN_KIND} proposal whose accept OVERWRITES an ` +
+ "incumbent skill, so the human accept requires explicit consent: re-run with --yes. " +
+ "Nothing was written. The exact command: " +
+ `o2b brain skill-proposals accept ${slug} --yes`;
+ if (flags["json"]) {
+ // The registered refusal verdict (CONSENT_VERDICTS in trust.ts), the
+ // same string every sibling lane's --json refusal envelope carries -
+ // a headless consumer branches on the verdict, so the field stays in
+ // the one machine vocabulary even though the exit code already says
+ // consentRefused.
+ writeJson({ consent: "headless-refused", written: false, error: refusal });
+ } else {
+ process.stderr.write(`error: ${refusal}\n`);
+ }
+ return SKILL_PROPOSALS_EXIT.consentRefused;
+ }
// Resolved HERE rather than inside the core: the surface knows which
// config chain this invocation is running against, and a `mature_page`
// accept materializes into whichever skills root that chain names.
@@ -367,3 +449,427 @@ function parsePositiveInteger(value: string, label: string): number {
if (parsed < 1) throw new CliError(`${label} must be a positive integer`);
return parsed;
}
+
+// ----- the rewrite gate rounds (agent-presence, Lane A) -------------------------
+
+/** The task set + spec pair a rewrite round is gated against, once verified. */
+interface VerifiedBenchmark {
+ readonly spec: SkillRewriteSpec;
+ readonly specHash: string;
+}
+
+/**
+ * Load and verify the benchmark: parse the task set and the spec, then run
+ * `verifyRewriteTake`. Every refusal names the file or the receipt reason -
+ * a stale benchmark silently gating nothing is worse than a loud stop.
+ */
+function loadVerifiedBenchmark(vault: string, skill: string): VerifiedBenchmark {
+ const tasksPath = skillBenchmarkTasksPath(vault, skill);
+ if (!existsSync(tasksPath)) {
+ throw new CliError(
+ `brain skill-proposals rewrite: no benchmark task set for '${skill}' at ${tasksPath} ` +
+ `(${SKILL_BENCHMARK_TASKS_FILE} must exist before a rewrite round can be planned)`,
+ );
+ }
+ const specPath = skillBenchmarkSpecPath(vault, skill);
+ if (!existsSync(specPath)) {
+ throw new CliError(
+ `brain skill-proposals rewrite: no frozen spec for '${skill}' at ${specPath} ` +
+ "(run the receipt step before planning a rewrite round)",
+ );
+ }
+ let rawTasks: unknown;
+ let rawSpec: unknown;
+ try {
+ rawTasks = JSON.parse(readFileSync(tasksPath, "utf8"));
+ rawSpec = JSON.parse(readFileSync(specPath, "utf8"));
+ } catch (error) {
+ throw new CliError(
+ `brain skill-proposals rewrite: the benchmark files for '${skill}' are not valid JSON: ` +
+ (error instanceof Error ? error.message : String(error)),
+ );
+ }
+ const tasks = parseSkillBenchmarkTasks(rawTasks, tasksPath);
+ const spec = parseSkillRewriteSpec(rawSpec, specPath);
+ const take = verifyRewriteTake(spec, tasks);
+ if (!take.ok) {
+ throw new CliError(
+ `brain skill-proposals rewrite: refused take for '${skill}': ${take.reason ?? "receipt mismatch"}`,
+ );
+ }
+ return { spec, specHash: skillRewriteSpecHash(spec) };
+}
+
+/**
+ * The incumbent body and version, read from the skills root this
+ * invocation's config names. A rewrite gates the CANDIDATE against the
+ * INCUMBENT, so the incumbent's bytes are the baseline round's body and
+ * its `version` is what the staged proposal bumps; a skill with no
+ * incumbent is not a rewrite target and is refused by name.
+ */
+/**
+ * The incumbent, resolved through the core's own skills-root resolution so
+ * a plan or score refusal names the same file the accept would write.
+ * The core refuses by name; this wrapper keeps the CLI error prefix.
+ */
+function loadIncumbent(
+ vault: string,
+ configPath: string,
+ skill: string,
+ override: string | undefined,
+): RewriteIncumbent {
+ const skillsRoot = override?.trim() || resolveSkillsDir(configPath) || undefined;
+ try {
+ return readRewriteIncumbent(vault, skill, skillsRoot ? { skillsRoot } : {});
+ } catch (error) {
+ if (error instanceof DeclaredSkillProposalError) {
+ throw new CliError(`brain skill-proposals rewrite: ${error.message}`);
+ }
+ throw error;
+ }
+}
+
+/**
+ * `rewrite-plan <skill> --candidate-file <path>`: validate the task set and
+ * the frozen spec, print the receipt, and hand out the dev-round envelopes
+ * - one baseline round over the incumbent body, one candidate round over
+ * the candidate body. Held-out members are never printed here: their
+ * single check is handed out by rewrite-score, only after a promote.
+ */
+function rewritePlan(argv: string[]): number {
+ const { flags, positional } = parse(argv, {
+ vault: { type: "string" },
+ json: { type: "boolean" },
+ "skills-root": { type: "string" },
+ "candidate-file": { type: "string", required: true },
+ });
+ const skill = trim(positional[0]);
+ if (!skill) throw new CliError("brain skill-proposals rewrite-plan: skill name is required");
+ const { config, vault } = brainVerbContext(flags);
+ const mode = resolveSkillRewriteModeConfig(config);
+ const { spec, specHash } = loadVerifiedBenchmark(vault, skill);
+ const tasks = loadTasks(vault, skill);
+ const candidatePath = trim(flags["candidate-file"]);
+ if (!candidatePath) {
+ throw new CliError("brain skill-proposals rewrite-plan: --candidate-file is required");
+ }
+ const candidateBody = readCandidateBody(candidatePath);
+ const incumbent = loadIncumbent(vault, config, skill, flags["skills-root"] as string | undefined);
+
+ const baseline = buildRewriteEnvelopes(incumbent.body, spec, tasks, { round: "baseline" });
+ const candidate = buildRewriteEnvelopes(candidateBody, spec, tasks, { round: "candidate" });
+
+ if (flags["json"]) {
+ process.stdout.write(
+ JSON.stringify(
+ {
+ skill,
+ mode,
+ receipt: {
+ schema_version: spec.schemaVersion,
+ tasks_hash: spec.tasksHash,
+ seed: spec.seed,
+ split_rule: spec.splitRule,
+ dev_task_ids: spec.devTaskIds,
+ // The count, never the ids: held-out members do not leave the
+ // kernel through this surface, and their single check is handed
+ // out by rewrite-score only after a promote.
+ heldout_task_count: spec.heldoutTaskIds.length,
+ required_margin: spec.requiredMargin,
+ min_dev_tasks: spec.minDevTasks,
+ spec_hash: specHash,
+ },
+ incumbent_version: incumbent.version,
+ rounds: { baseline, candidate },
+ },
+ null,
+ 2,
+ ) + "\n",
+ );
+ return 0;
+ }
+
+ process.stdout.write(
+ `rewrite-plan ${skill}: mode=${mode} schema=${spec.schemaVersion} spec=${specHash} ` +
+ `tasks=${spec.tasksHash} split=${spec.splitRule} seed=${spec.seed} margin=${spec.requiredMargin} ` +
+ `dev=${spec.devTaskIds.length} heldout=${spec.heldoutTaskIds.length} ` +
+ `incumbent_version=${incumbent.version}\n`,
+ );
+ for (const envelope of [...baseline, ...candidate]) {
+ process.stdout.write(
+ ` ${envelope.round} ${envelope["task_id"]} -> ${envelope.target_path}\n` +
+ `${envelope.prompt
+ .split("\n")
+ .map((line) => ` ${line}`)
+ .join("\n")}\n`,
+ );
+ }
+ return 0;
+}
+
+function loadTasks(vault: string, skill: string): ReturnType<typeof parseSkillBenchmarkTasks> {
+ return parseSkillBenchmarkTasks(
+ JSON.parse(readFileSync(skillBenchmarkTasksPath(vault, skill), "utf8")),
+ skillBenchmarkTasksPath(vault, skill),
+ );
+}
+
+/**
+ * `rewrite-score <skill> --candidate-file <path> [--rounds-dir <dir>]`:
+ * score the submitted transcripts, run the selection gate, and either
+ * hand out the single held-out round (promote, held-out not yet scored) or
+ * apply the held-out gate and stage the pending proposal on a final
+ * promote. A hold and a short dev arm write ONLY the grade record.
+ *
+ * The candidate body is required on every run, not just a staging one:
+ * the scorer binds each candidate-arm submission to the CURRENT candidate
+ * body through the `candidate_sha256` its envelope carried, so a
+ * transcript left over from a previous candidate can never gate this one.
+ *
+ * The command is re-runnable: the transcripts stay in the rounds tree, the
+ * gates are deterministic, and the second run sees the held-out arm the
+ * first run asked for.
+ */
+function rewriteScore(argv: string[]): number {
+ const { flags, positional } = parse(argv, {
+ vault: { type: "string" },
+ json: { type: "boolean" },
+ "rounds-dir": { type: "string" },
+ "candidate-file": { type: "string" },
+ "skills-root": { type: "string" },
+ });
+ const skill = trim(positional[0]);
+ if (!skill) throw new CliError("brain skill-proposals rewrite-score: skill name is required");
+ const { config, vault } = brainVerbContext(flags);
+ const mode: SkillRewriteMode = resolveSkillRewriteModeConfig(config);
+ const { spec, specHash } = loadVerifiedBenchmark(vault, skill);
+ const tasks = loadTasks(vault, skill);
+
+ const candidatePath = trim(flags["candidate-file"]);
+ if (!candidatePath) {
+ throw new CliError(
+ "brain skill-proposals rewrite-score: --candidate-file is required so the scorer binds " +
+ "transcripts to the candidate body they were produced against (candidate_sha256)",
+ );
+ }
+ const candidateBody = readCandidateBody(candidatePath);
+ const candidateHash = sha256Hex(candidateBody);
+
+ const roundsDir = trim(flags["rounds-dir"]) ?? skillBenchmarkRoundsDir(vault, skill);
+ const baseline = scoreArm(vault, roundsDir, "baseline", tasks, spec);
+ const candidate = scoreArm(vault, roundsDir, "candidate", tasks, spec, candidateHash);
+ const selection = selectRewriteCandidate(baseline, candidate, spec);
+
+ // The advisory judge rides the command bridge, fail-open, and never
+ // moves the metric: its verdicts are reported beside the deterministic
+ // ones and reach nothing downstream.
+ const judge = runRewriteJudge(resolveSkillRewriteJudgeCmd(config), {
+ skill,
+ spec_hash: specHash,
+ metric: "tasks_passed_rate",
+ baseline_rate: selection.baselineRate,
+ candidate_rate: selection.candidateRate,
+ verdict: selection.verdict,
+ });
+
+ let heldoutScores: ReadonlyArray<RewriteTaskScore> = [];
+ let heldoutVerdict: string | null = null;
+ let heldoutEnvelopes: ReturnType<typeof buildRewriteHeldoutEnvelopes> | null = null;
+ let staged: { id: string; slug: string; documentSha256: string } | null = null;
+
+ if (selection.verdict === SKILL_REWRITE_VERDICT.promote) {
+ const heldoutDir = join(roundsDir, "heldout");
+ if (existsSync(heldoutDir) && readDirNames(heldoutDir).length > 0) {
+ heldoutScores = scoreArm(vault, roundsDir, "heldout", tasks, spec, candidateHash);
+ heldoutVerdict = checkRewriteHeldout(heldoutScores, spec);
+ const finalVerdict = heldoutVerdict;
+ if (finalVerdict === SKILL_REWRITE_VERDICT.promote) {
+ const incumbent = loadIncumbent(
+ vault,
+ config,
+ skill,
+ flags["skills-root"] as string | undefined,
+ );
+ const result = stageScoredRewriteProposal(vault, {
+ skill: {
+ name: skill,
+ description: incumbent.description ?? "Rewritten by a benchmark-gated gate round.",
+ triggers: incumbent.triggers ?? [],
+ body: candidateBody,
+ },
+ spec,
+ specHash,
+ baselineScore: selection.baselineRate,
+ candidateScore: selection.candidateRate,
+ heldoutScore: heldoutScores.length > 0 ? passedRateOf(heldoutScores) : 1,
+ incumbentVersion: incumbent.version,
+ });
+ if (result.outcome !== "created") {
+ throw new CliError(
+ `brain skill-proposals rewrite-score: staging declined (${result.outcome}${
+ "reason" in result ? `: ${result.reason}` : ""
+ })`,
+ );
+ }
+ staged = { id: result.id, slug: result.slug, documentSha256: result.documentSha256 };
+ }
+ } else {
+ // The one moment held-out text may enter an envelope: the selection
+ // just promoted the candidate, and the single check has not run yet.
+ heldoutEnvelopes = buildRewriteHeldoutEnvelopes(candidateBody, spec, tasks);
+ }
+ }
+
+ const finalVerdict =
+ heldoutVerdict ??
+ (selection.verdict === SKILL_REWRITE_VERDICT.promote ? null : selection.verdict);
+ const gradeRecorded =
+ finalVerdict !== null
+ ? recordSkillRewriteGrade(vault, {
+ payload: buildRewriteGradeRecord({
+ skill,
+ spec,
+ specHash,
+ selection,
+ heldoutVerdict:
+ heldoutVerdict === SKILL_REWRITE_VERDICT.promote
+ ? SKILL_REWRITE_VERDICT.promote
+ : SKILL_REWRITE_VERDICT.hold,
+ devScores: candidate,
+ heldoutScores,
+ // The candidate binding (review round-2, M1 residual R1):
+ // the promote record carries the sha-256 staging stamped on
+ // the pending proposal, so the accept-time match can refuse
+ // a promote earned over a different candidate. A hold round
+ // stages nothing and binds nothing.
+ candidateSha256: staged?.documentSha256,
+ }),
+ }).id
+ : null;
+
+ if (flags["json"]) {
+ process.stdout.write(
+ JSON.stringify(
+ {
+ skill,
+ mode,
+ spec_hash: specHash,
+ tasks_hash: spec.tasksHash,
+ verdict: finalVerdict ?? "heldout_pending",
+ baseline_rate: selection.baselineRate,
+ candidate_rate: selection.candidateRate,
+ dev: candidate,
+ held_out: heldoutScores,
+ heldout_verdict: heldoutVerdict,
+ heldout_envelopes: heldoutEnvelopes,
+ judge,
+ staged,
+ grade_record_id: gradeRecorded,
+ },
+ null,
+ 2,
+ ) + "\n",
+ );
+ return 0;
+ }
+
+ process.stdout.write(
+ `rewrite-score ${skill}: verdict=${finalVerdict ?? "heldout_pending"} ` +
+ `baseline=${selection.baselineRate.toFixed(3)} candidate=${selection.candidateRate.toFixed(3)} ` +
+ `mode=${mode}\n`,
+ );
+ for (const score of candidate) {
+ process.stdout.write(
+ ` dev ${score.taskId} ${score.passed ? "pass" : `fail(${score.failedChecks.join(",")})`}\n`,
+ );
+ }
+ for (const score of heldoutScores) {
+ process.stdout.write(
+ ` held-out ${score.taskId} ${score.passed ? "pass" : `fail(${score.failedChecks.join(",")})`}\n`,
+ );
+ }
+ if (judge.status !== "skipped") {
+ process.stdout.write(` judge ${judge.status}${judge.detail ? `: ${judge.detail}` : ""}\n`);
+ }
+ if (heldoutEnvelopes !== null) {
+ process.stdout.write(" held-out round pending; the single check's envelopes:\n");
+ for (const envelope of heldoutEnvelopes) {
+ process.stdout.write(
+ ` ${envelope.round} ${envelope["task_id"]} -> ${envelope.target_path}\n` +
+ `${envelope.prompt
+ .split("\n")
+ .map((line) => ` ${line}`)
+ .join("\n")}\n`,
+ );
+ }
+ }
+ if (staged !== null) process.stdout.write(` staged ${staged.id}\n`);
+ return 0;
+}
+
+/**
+ * Read the candidate body, refusing by name when the file is not there.
+ * The raw ENOENT would put a machine stack where a refusal belongs.
+ */
+function readCandidateBody(path: string): string {
+ try {
+ return readFileSync(path, "utf8").trim();
+ } catch (error) {
+ throw new CliError(
+ `brain skill-proposals rewrite: --candidate-file is not readable at ${path}: ` +
+ (error instanceof Error ? error.message : String(error)),
+ );
+ }
+}
+
+/**
+ * Read one arm's transcript files from the rounds tree and score them.
+ * `candidateHash` binds the arm's submissions to the CURRENT candidate
+ * body (kernel review, Fixer A1's transcript-candidate binding): a
+ * submission whose `candidate_sha256` is missing or stale is refused by
+ * name. The baseline arm is left unbound - its transcripts answer the
+ * incumbent's envelopes, and the incumbent does not change mid-round.
+ */
+function scoreArm(
+ vault: string,
+ roundsDir: string,
+ arm: "baseline" | "candidate" | "heldout",
+ tasks: ReturnType<typeof parseSkillBenchmarkTasks>,
+ spec: SkillRewriteSpec,
+ candidateHash?: string,
+): ReadonlyArray<RewriteTaskScore> {
+ const binding = candidateHash !== undefined ? { candidateHash } : {};
+ if (arm === "heldout") {
+ // The caller decides when the held-out arm is allowed to exist.
+ const dir = join(roundsDir, arm);
+ if (!existsSync(dir)) return [];
+ return scoreRewriteTranscripts(readSubmissions(dir), tasks, {
+ arm: "heldout",
+ spec,
+ ...binding,
+ });
+ }
+ const dir = join(roundsDir, arm);
+ if (!existsSync(dir)) {
+ throw new CliError(
+ `brain skill-proposals rewrite-score: no ${arm} round transcripts under ${dir}; ` +
+ "run rewrite-plan and execute the envelopes first - an absent arm is not a passing arm",
+ );
+ }
+ return scoreRewriteTranscripts(readSubmissions(dir), tasks, { arm: "dev", spec, ...binding });
+}
+
+function readSubmissions(dir: string): ReadonlyArray<unknown> {
+ return readDirNames(dir)
+ .toSorted()
+ .map((name) => JSON.parse(readFileSync(join(dir, name), "utf8")));
+}
+
+function readDirNames(dir: string): ReadonlyArray<string> {
+ return readdirSync(dir).filter((name) => name.endsWith(".json"));
+}
+
+function passedRateOf(scores: ReadonlyArray<RewriteTaskScore>): number {
+ if (scores.length === 0) return 0;
+ return scores.filter((score) => score.passed).length / scores.length;
+}
diff --git a/src/cli/command-manifest.ts b/src/cli/command-manifest.ts
index 2755b01f..485a06ad 100644
--- a/src/cli/command-manifest.ts
+++ b/src/cli/command-manifest.ts
@@ -825,8 +825,23 @@ export const CLI_COMMAND_MANIFEST: CliRootManifest = Object.freeze({
command("knowledge-gaps", "Rank recurring queries the vault answers poorly"),
command(
"skill-proposals",
- "Learn, list, review, and recover skill proposals, including drafts from mature pages",
+ "Learn, list, review, and recover skill proposals, including drafts from mature pages and benchmark-gated rewrites",
[flag("vault", "string"), flag("payload", "string"), flag("payload-file", "string")],
+ [
+ command("rewrite-plan", "Print a rewrite round's frozen receipt and dev envelopes", [
+ flag("vault", "string"),
+ flag("candidate-file", "string"),
+ flag("skills-root", "string"),
+ flag("json", "boolean"),
+ ]),
+ command("rewrite-score", "Score submitted rewrite rounds and gate the verdict", [
+ flag("vault", "string"),
+ flag("rounds-dir", "string"),
+ flag("candidate-file", "string"),
+ flag("skills-root", "string"),
+ flag("json", "boolean"),
+ ]),
+ ],
),
command("procedural-memory", "Reconcile or list the procedural memory index and its usage"),
command("procedural-graph", "Rebuild or show the procedural graph and hint projections"),
@@ -940,6 +955,40 @@ export const CLI_COMMAND_MANIFEST: CliRootManifest = Object.freeze({
command("stale", "Stale preferences, signals, and log files against configured thresholds"),
command("daily", "Daily brief: events by kind, status transitions, vault delta"),
command("weekly", "Seven-day synthesis: transitions, retired, contradictions, vault delta"),
+ // t_1e952e43: operator-approved lesson promotion into agent rules
+ // files. Operator-only; no MCP tool exposes these subcommands.
+ command(
+ "lessons",
+ "Operator-approved lesson promotion: candidates | approve <pref-id> | deny <pref-id> | refresh-blocks",
+ [flag("vault", "string"), flag("target", "string-array")],
+ [
+ command("candidates", "List promotable lessons and blocked ones with reasons", [
+ flag("vault", "string"),
+ ]),
+ command("approve", "Approve a lesson and write it into the named agent rules files", [
+ flag("target", "string-array"),
+ flag("apply", "boolean"),
+ flag("yes", "boolean"),
+ flag("force", "boolean"),
+ flag("vault", "string"),
+ ]),
+ command("deny", "Record a denial; the lesson is suppressed from promotion", [
+ flag("apply", "boolean"),
+ flag("yes", "boolean"),
+ flag("vault", "string"),
+ ]),
+ command(
+ "refresh-blocks",
+ "Re-render managed lessons blocks (dry run by default; never creates a block)",
+ [
+ flag("apply", "boolean"),
+ flag("yes", "boolean"),
+ flag("force", "boolean"),
+ flag("vault", "string"),
+ ],
+ ),
+ ],
+ ),
],
),
command(
diff --git a/src/cli/install/install.ts b/src/cli/install/install.ts
index 6469deea..2cdb65fd 100644
--- a/src/cli/install/install.ts
+++ b/src/cli/install/install.ts
@@ -52,10 +52,19 @@ import { isInstallTargetId, type InstallTargetId } from "../../core/runtime/host
import { renderDataOwnership } from "../../core/install/ownership.ts";
import type { DataOwnership } from "../../core/install/ownership.ts";
import { measureDataOwnership } from "../../core/install/ownership-measure.ts";
-import { InstallError } from "../../core/install/types.ts";
+import { InstallError, type InstallPlan, type InstallStep } from "../../core/install/types.ts";
import type { ApplyOpts, InstallEnv, VerifyResult } from "../../core/install/types.ts";
+import {
+ applyInstructionBlock,
+ instructionBlockTargetFor,
+ instructionStepNoPrecedenceReason,
+ planInstructionBlock,
+} from "../../core/install/instruction-block.ts";
+import type { InstructionBlockPlan } from "../../core/install/instruction-block.ts";
+import { RULES_BLOCK_ERROR_KIND, RulesBlockError } from "../../core/install/rules-block.ts";
import {
renderApplyJson,
+ type ApplyInstructionBlockOutcome,
renderApplyResult,
renderDetectJson,
renderDetectTable,
@@ -375,6 +384,58 @@ function runFriction(args: ParsedInstallArgs): number {
return INSTALL_EXIT.ok;
}
+/**
+ * The instruction step a target's plan gains, or null when the target
+ * installs no agent-instruction file (a named skip renders as a
+ * postNote instead, see {@link augmentPlanWithInstructionStep}).
+ *
+ * The step rides the same `runTarget` lane the adapter writes do - one
+ * plan render, ONE consent verdict above both writes, one apply - so
+ * there is nothing new to consent to twice (t_ba41a78a B3). The kind is
+ * the existing `managed-block` member; no new step vocabulary.
+ */
+function instructionStepFor(
+ env: InstallEnv,
+ target: InstallTargetId,
+): { step: InstallStep; plan: InstructionBlockPlan } | null {
+ if (instructionBlockTargetFor(target) === null) return null;
+ const plan = planInstructionBlock(env, target);
+ const preview =
+ plan.changed === true
+ ? `install the Open Second Brain write-gate managed block in ${plan.path}` +
+ (plan.note === null ? "" : ` (${plan.note})`)
+ : `${plan.path} already carries the current write-gate managed block (no change)`;
+ const step: InstallStep = {
+ kind: "managed-block",
+ path: plan.path,
+ preview,
+ ...(plan.diff !== "" ? { diff: plan.diff } : {}),
+ };
+ return { step, plan };
+}
+
+/**
+ * Append the instruction step (or its named skip) to a rendered plan.
+ * Pure over the given plan: the original plan still goes to the adapter,
+ * and the augmented copy is what the operator consents to.
+ */
+function augmentPlanWithInstructionStep(
+ plan: InstallPlan,
+ target: InstallTargetId,
+ step: InstallStep | null,
+): InstallPlan {
+ if (step === null) {
+ return {
+ ...plan,
+ postNotes: [
+ ...plan.postNotes,
+ `instruction block: skipped for ${target} - the host reads no agent-instruction file in HOST_INSTRUCTION_PRECEDENCE`,
+ ],
+ };
+ }
+ return { ...plan, steps: [...plan.steps, step] };
+}
+
async function runTarget(args: ParsedInstallArgs): Promise<number> {
const adapter = defaultRegistry.get(args.target!);
if (!adapter) return refuseUnknownTarget("--target", args.target!);
@@ -402,12 +463,35 @@ async function runTarget(args: ParsedInstallArgs): Promise<number> {
const plan = adapter.plan(payload, env);
+ // t_ba41a78a B3: the instruction step rides this lane. The pure plan
+ // computes now (reads only); the apply below re-derives it from the
+ // live disk and refuses if the bytes moved since this render, so what
+ // the operator consents to is exactly what gets written. A refusal at
+ // plan time (a symbolic link, malformed markers, an unreadable file)
+ // must be the named error, never an unhandled rejection: nothing has
+ // been consented to or written yet, so the run ends here with the
+ // named message and the runtime exit.
+ let instruction: ReturnType<typeof instructionStepFor>;
+ try {
+ instruction = instructionStepFor(env, args.target as InstallTargetId);
+ } catch (e) {
+ if (e instanceof RulesBlockError) {
+ process.stderr.write(`error: ${e.message}\n`);
+ return INSTALL_EXIT.runtimeError;
+ }
+ throw e;
+ }
+ const renderedPlan =
+ instruction === null
+ ? augmentPlanWithInstructionStep(plan, args.target as InstallTargetId, null)
+ : augmentPlanWithInstructionStep(plan, args.target as InstallTargetId, instruction.step);
+
// Plan-only (no --apply, no --check) — print and return.
if (!args.apply) {
if (args.json) {
- process.stdout.write(renderPlanJson(plan));
+ process.stdout.write(renderPlanJson(renderedPlan));
} else {
- process.stdout.write(renderPlan(plan));
+ process.stdout.write(renderPlan(renderedPlan));
}
return INSTALL_EXIT.ok;
}
@@ -447,7 +531,7 @@ async function runTarget(args: ParsedInstallArgs): Promise<number> {
// asking for apply consent, not previewing a dry run. The plain
// print-only plan (no --apply) keeps its stdout dry-run render
// below.
- process.stderr.write(renderPlan(plan, { consent: true }));
+ process.stderr.write(renderPlan(renderedPlan, { consent: true }));
process.stderr.write("Proceed? [y/N] ");
const ans = await readSingleLine();
if (ans.toLowerCase() !== "y" && ans.toLowerCase() !== "yes") {
@@ -461,16 +545,68 @@ async function runTarget(args: ParsedInstallArgs): Promise<number> {
// same vocabulary protect/unprotect/doctor record.
const consent: LaneConsentVerdict = args.yes ? "yes-flag" : "interactive-yes";
+ let instructionApply: ReturnType<typeof applyInstructionBlock> | null = null;
try {
const result = adapter.apply(plan, payload, env, opts);
+ // t_ba41a78a B3: the instruction write runs after the adapter apply,
+ // under the SAME consent verdict - the prompt above covered both
+ // writes. A refusal here (hand-edited block, preview drift, symlink)
+ // leaves the adapter write in place and exits non-zero; a re-run
+ // converges because the step is idempotent and bound to a fresh
+ // plan. The approved binding is the plan this run rendered.
+ if (instruction !== null) {
+ instructionApply = applyInstructionBlock(env, {
+ dryRun: opts.dryRun,
+ force: opts.force,
+ approved: instruction.plan,
+ });
+ }
// An apply that returned changed the machine, so the close fires
// unconditionally here - unlike verify, where exit 0 also covers a
// runtime nobody installed.
const ownership = ownershipFor(env, args.config);
if (args.json) {
- process.stdout.write(renderApplyJson(result, ownership, consent));
+ // The instruction-block outcome rides the apply payload (the
+ // uninstall payload has carried the same-named field since its step
+ // shipped): a headless consumer that consented to a plan whose JSON
+ // showed the managed-block step reads what that step did from the
+ // receipt on the stream it parses, not only from the human line.
+ const instructionBlock: ApplyInstructionBlockOutcome =
+ instruction === null
+ ? {
+ file: null,
+ created: false,
+ changed: false,
+ backup_path: null,
+ skipped_reason: instructionStepNoPrecedenceReason(args.target as InstallTargetId),
+ }
+ : {
+ file: instruction.plan.path,
+ created: instructionApply?.created ?? false,
+ changed: instructionApply?.changed ?? false,
+ backup_path: instructionApply?.backupPath ?? null,
+ skipped_reason: null,
+ };
+ process.stdout.write(renderApplyJson(result, ownership, consent, instructionBlock));
} else {
process.stdout.write(renderApplyResult(result, consent));
+ // The instruction write is invisible in the adapter's own summary
+ // (its step count is the adapter's), so one line says what this
+ // lane did with the operator's consent. The line is derived from
+ // what the apply actually did - a first install CREATES the file
+ // and takes no backup, so `backupPath` alone cannot tell created
+ // from already-current, and claiming "already carries" right after
+ // creating would be false.
+ if (instructionApply !== null && !opts.dryRun) {
+ const path = instruction?.plan.path ?? "";
+ process.stdout.write(
+ instructionApply.created
+ ? `instruction block: ${path} created with the write-gate block\n`
+ : instructionApply.changed
+ ? `instruction block: ${path} now carries the write-gate block\n`
+ : `instruction block: ${path} already carries the current write-gate block\n`,
+ );
+ }
process.stdout.write(renderDataOwnership(ownership));
}
return INSTALL_EXIT.ok;
@@ -485,6 +621,15 @@ async function runTarget(args: ParsedInstallArgs): Promise<number> {
if (e.hint) process.stderr.write(`hint: ${e.hint}\n`);
return INSTALL_EXIT.runtimeError;
}
+ // The instruction step's refusals ride the same exit vocabulary: a
+ // hand-edited block IS a user-modified-block (exit 4, --force is the
+ // documented override); every other kind is a named runtime error.
+ if (e instanceof RulesBlockError) {
+ process.stderr.write(`error: ${e.message}\n`);
+ return e.kind === RULES_BLOCK_ERROR_KIND.userModifiedBlock
+ ? INSTALL_EXIT.userModifiedBlock
+ : INSTALL_EXIT.runtimeError;
+ }
process.stderr.write(`error: ${(e as Error).message}\n`);
return INSTALL_EXIT.runtimeError;
}
diff --git a/src/cli/install/render.ts b/src/cli/install/render.ts
index 909753c5..39835865 100644
--- a/src/cli/install/render.ts
+++ b/src/cli/install/render.ts
@@ -201,12 +201,42 @@ export function renderApplyResult(result: ApplyResult, consent: LaneConsentVerdi
* schema'd document with `applied_at` semantics; the receipt for consent
* is this CLI payload.
*/
+/**
+ * What the consented managed-block step did on an apply, as the apply
+ * payload's `instruction_block` field. The uninstall payload has carried
+ * the same-named field since its step shipped; the apply receipt carries
+ * it too so a headless consumer that consented to a plan showing the
+ * step can read the outcome of that step from the payload it parses,
+ * instead of the write being reported only on the human path. The shape
+ * mirrors the uninstall field: snake_case keys, a null `file` and a
+ * `skipped_reason` sentence when the target maps no instruction file in
+ * `HOST_INSTRUCTION_PRECEDENCE`.
+ */
+export interface ApplyInstructionBlockOutcome {
+ /** The vault-root file the step wrote, or null on a named skip. */
+ readonly file: string | null;
+ /** True when the apply created the file (a first install takes no backup). */
+ readonly created: boolean;
+ /** True when the apply changed the file's bytes (or would, under dry-run). */
+ readonly changed: boolean;
+ /** The exclusive-create backup of the prior bytes; null when none was taken. */
+ readonly backup_path: string | null;
+ /** Why nothing was written, or null when the step ran. */
+ readonly skipped_reason: string | null;
+}
+
export function renderApplyJson(
result: ApplyResult,
ownership: DataOwnership,
consent: LaneConsentVerdict,
+ instructionBlock: ApplyInstructionBlockOutcome,
): string {
- return installJson({ consent, ...result, [DATA_OWNERSHIP_KEY]: ownership });
+ return installJson({
+ consent,
+ ...result,
+ instruction_block: instructionBlock,
+ [DATA_OWNERSHIP_KEY]: ownership,
+ });
}
export function renderVerifyTable(rows: ReadonlyArray<VerifyResult>): string {
diff --git a/src/cli/install/uninstall-target.ts b/src/cli/install/uninstall-target.ts
index 055e5393..08aad355 100644
--- a/src/cli/install/uninstall-target.ts
+++ b/src/cli/install/uninstall-target.ts
@@ -11,7 +11,8 @@
import { homedir } from "node:os";
import { parseFlags } from "../argparse.ts";
-import { defaultConfigPath, discoverConfig } from "../../core/config.ts";
+import { defaultConfigPath } from "../../core/config.ts";
+import { resolveInstallVault } from "./install.ts";
import { defaultRegistry } from "../../core/install/registry.ts";
import "../../core/install/adapters/aider.ts";
import "../../core/install/adapters/codex.ts";
@@ -24,6 +25,52 @@ import "../../core/install/adapters/kiro.ts";
import "../../core/install/adapters/opencode.ts";
import "../../core/install/adapters/pi.ts";
import { InstallError, type InstallEnv } from "../../core/install/types.ts";
+import { isInstallTargetId, type InstallTargetId } from "../../core/runtime/host-facts.ts";
+import {
+ instructionBlockTargetFor,
+ instructionStepNoPrecedenceReason,
+ readInstructionBlockLock,
+ uninstallInstructionBlock,
+} from "../../core/install/instruction-block.ts";
+
+/**
+ * The reverse instruction step, against the ownership lock (t_ba41a78a
+ * B3): remove the usage block pair from the instruction file this
+ * target's host reads, but ONLY when the lock recorded it - a pair
+ * nobody recorded is not proven ours, and uninstall never removes
+ * operator content on a guess. Every non-removal outcome is a named
+ * skip rendered beside the adapter's own.
+ */
+function uninstallInstructionStep(
+ env: InstallEnv,
+ target: string,
+ dryRun: boolean,
+): { file: string | null; removed: boolean; skipped_reason: string | null } {
+ const mapped = isInstallTargetId(target) ? instructionBlockTargetFor(target) : null;
+ if (mapped === null) {
+ return {
+ file: null,
+ removed: false,
+ skipped_reason: instructionStepNoPrecedenceReason(target as InstallTargetId),
+ };
+ }
+ const recorded = readInstructionBlockLock(env.vault).files[mapped] !== undefined;
+ if (!recorded) {
+ return {
+ file: mapped,
+ removed: false,
+ skipped_reason: `no lock-recorded instruction block in ${mapped}`,
+ };
+ }
+ const result = uninstallInstructionBlock(env, mapped, { dryRun });
+ return result.removed
+ ? { file: mapped, removed: true, skipped_reason: null }
+ : {
+ file: mapped,
+ removed: false,
+ skipped_reason: `${mapped} carries no usage block pair`,
+ };
+}
export async function cmdUninstallTarget(argv: string[]): Promise<number> {
const { flags } = parseFlags(argv, {
@@ -46,10 +93,15 @@ export async function cmdUninstallTarget(argv: string[]): Promise<number> {
}
const dryRun = !flags["apply"];
+ // The vault resolves through the SAME chain the install verb uses
+ // (`resolveInstallVault`: --vault, then VAULT_DIR, the project pointer,
+ // the active profile, the config vault key). The old local chain here
+ // read the config key BEFORE VAULT_DIR - the exact split install.ts
+ // documents as fixed - so an install that resolved VAULT_DIR was
+ // uninstalled from the configured vault, where the install manifest is
+ // absent and the removal refuses while the real install state stays.
const cfgPath = (flags["config"] as string | undefined) ?? defaultConfigPath();
- const cfg = discoverConfig(cfgPath).data;
- const vault =
- (flags["vault"] as string | undefined) ?? cfg["vault"] ?? process.env["VAULT_DIR"] ?? "";
+ const vault = resolveInstallVault((flags["vault"] as string | null) ?? null, cfgPath);
if (!vault) {
process.stderr.write(
"error: vault not configured. Pass --vault <path>, set VAULT_DIR, or run `o2b init`.\n",
@@ -74,12 +126,20 @@ export async function cmdUninstallTarget(argv: string[]): Promise<number> {
try {
const result = adapter.uninstall(env, opts);
+ const instruction = uninstallInstructionStep(env, target, dryRun);
if (flags["json"]) {
- process.stdout.write(JSON.stringify(result, null, 2) + "\n");
+ process.stdout.write(
+ JSON.stringify({ ...result, instruction_block: instruction }, null, 2) + "\n",
+ );
return 0;
}
const lines: string[] = [];
lines.push(`o2b uninstall --target ${target}` + (dryRun ? " (dry-run)" : " --apply"));
+ if (instruction.removed) {
+ lines.push(` removed instruction block: ${instruction.file}`);
+ } else if (instruction.skipped_reason !== null) {
+ lines.push(` skipped: instruction block (${instruction.skipped_reason})`);
+ }
if (result.removed_keys.length > 0) {
lines.push(" removed keys:");
for (const k of result.removed_keys) lines.push(` - ${k}`);
diff --git a/src/cli/stdin.ts b/src/cli/stdin.ts
index 1a6c49ba..4c8287ba 100644
--- a/src/cli/stdin.ts
+++ b/src/cli/stdin.ts
@@ -8,9 +8,22 @@
* the read resolves. `echo body | o2b brain capture` then "succeeded"
* without capturing anything, and `o2b brain secret set` stored nothing -
* a silent data loss, not a crash. Draining `Bun.stdin.stream()` through a
- * `Response` holds a live stream reader, which keeps the loop alive on
- * every platform, and returns the same text.
+ * held stream reader keeps the loop alive on every platform, and returns
+ * the same text.
+ *
+ * The read runs to completion through the stream's own async iterator,
+ * which releases the stream when it ends: the CLI reads stdin once per
+ * process, but a long-lived embedder (the test runner among them) shares
+ * one stdin across callers, and a reader left holding the drained body
+ * locks it forever - the next event-listener reader in the same process,
+ * the y/N prompt, then fails with `ReadableStream is locked` instead of
+ * seeing the empty pipe the drained stdin is. A second call still refuses
+ * (`Bun.stdin`'s body is single-consumption), exactly as before.
*/
export async function readStdinText(): Promise<string> {
- return await new Response(Bun.stdin.stream()).text();
+ let text = "";
+ for await (const chunk of Bun.stdin.stream()) {
+ text += typeof chunk === "string" ? chunk : Buffer.from(chunk as Uint8Array).toString("utf8");
+ }
+ return text;
}
diff --git a/src/core/brain/continuity/types.ts b/src/core/brain/continuity/types.ts
index 5665a20e..d07e0363 100644
--- a/src/core/brain/continuity/types.ts
+++ b/src/core/brain/continuity/types.ts
@@ -133,7 +133,17 @@ export type ContinuityRecordKind =
* name, and a receipt_compaction record never describes a context
* operation.
*/
- | "receipt_compaction";
+ | "receipt_compaction"
+ /**
+ * One completed benchmark-gated skill rewrite gate run
+ * (agent-presence, Lane A). The per-task verdicts of the dev and
+ * held-out arms, the rates they decided on, and the spec hash the run
+ * verified against - identifiers, numbers, booleans and check ids
+ * only, never task text and never transcript text. Written once per
+ * completed gate run, kept never-folded so an operator can audit why
+ * a rewrite landed or held.
+ */
+ | "skill_rewrite_eval_grade";
/**
* Every {@link ContinuityRecordKind} member as a runtime list, in union
@@ -173,6 +183,7 @@ export const CONTINUITY_RECORD_KINDS: ReadonlyArray<ContinuityRecordKind> = Obje
"reply_presence",
"session_entity_mention",
"receipt_compaction",
+ "skill_rewrite_eval_grade",
]);
/** Narrow an unvalidated record's `kind` to a {@link ContinuityRecordKind}. */
diff --git a/src/core/brain/destructive-sites.ts b/src/core/brain/destructive-sites.ts
index b112978d..b9c0f15a 100644
--- a/src/core/brain/destructive-sites.ts
+++ b/src/core/brain/destructive-sites.ts
@@ -273,9 +273,13 @@ export const DESTRUCTIVE_SITES: Readonly<Record<string, DestructiveSiteDeclarati
calls: ["rmSync"],
recovery: UNARCHIVED_BRAIN,
reason:
- "removes the accept-journal marker once the accept committed. The journal is a " +
- "crash-recovery record for the accept it describes, so keeping it past the " +
- "commit would make the NEXT run try to roll back finished work.",
+ "removes the accept-journal marker once the accept committed, and the " +
+ "prior-content copy beside it when a scored rewrite captured one - both " +
+ "forced, so clearing a journal that never captured anything is not an " +
+ "error. The journal is a crash-recovery record for the accept it " +
+ "describes, so keeping it past the commit would make the NEXT run try " +
+ "to roll back finished work; the same holds for the copy, whose only " +
+ "reader is the rollback the completed accept has just made moot.",
},
"src/core/brain/lineage/identity.ts": {
calls: ["unlinkSync"],
@@ -434,7 +438,14 @@ export const DESTRUCTIVE_SITES: Readonly<Record<string, DestructiveSiteDeclarati
"artifact the accept materialised only when the journal recorded that neither " +
"existed beforehand. The `rmdirSync` finishes that rollback for a `mature_page` " +
"accept, which creates a directory to hold its SKILL.md: `rmdirSync` refuses a " +
- "non-empty directory, so only the empty shell this sequence made is removed.",
+ "non-empty directory, so only the empty shell this sequence made is removed. " +
+ "A `scored_rewrite` accept OVERWRITES an incumbent, so when the journal " +
+ "recorded that the artifact DID exist and carries a prior-content copy, the " +
+ "same rollback restores the incumbent bytes through `atomicWriteFileSync` " +
+ "instead of removing anything; a missing copy is a named refusal that keeps " +
+ "the journal on disk, because silently leaving the candidate body on an " +
+ "incumbent's path is the one outcome worse than the crash being recovered " +
+ "from.",
},
// --- Repair under an explicit apply ----------------------------------
diff --git a/src/core/brain/doctor-exits.ts b/src/core/brain/doctor-exits.ts
index 4947cd28..e25470e5 100644
--- a/src/core/brain/doctor-exits.ts
+++ b/src/core/brain/doctor-exits.ts
@@ -461,6 +461,39 @@ const EXCLUSIONS: ReadonlyArray<DoctorExitExclusion> = [
"meant to say exists only in the source it was captured from - reconstructing it here " +
"would be inventing the observation",
},
+ {
+ // The lessons-block readiness family (t_1e952e43, task C3). All four
+ // are operator advisories over derived state the refresh verb heals;
+ // each finding already names the exact verb (approve for a missing
+ // block, refresh for a stale or diverged one), so a registry command
+ // would repeat what the finding carries.
+ code: "lessons-block-absent",
+ reason:
+ "an approval names a rules file that carries no lessons block; creation sits behind the " +
+ "approve verb's consent ladder, which the finding itself names, so nothing here is healable " +
+ "without the operator's explicit consent and no single command belongs in the registry",
+ },
+ {
+ code: "lessons-block-drifted",
+ reason:
+ "a managed lessons block is behind the canonical body; the refresh verb converges it and " +
+ "the finding names that verb including the force wording for a hand-edited block, so a " +
+ "registry row would only duplicate what the finding already says",
+ },
+ {
+ code: "lessons-block-stale-lessons",
+ reason:
+ "a managed block still carries a lesson whose approval went stale; the refresh drops it " +
+ "until the operator approves the moved text again, which the finding names - the decision " +
+ "is the operator's own re-approval, not a command the doctor can carry",
+ },
+ {
+ code: "lessons-approvals-unreadable",
+ reason:
+ "the approvals ledger is damaged; every approval is lifted only by the operator moving or " +
+ "deleting the file, which the finding spells out with the fail-closed direction - there is " +
+ "no mechanical repair a registry row could offer",
+ },
];
/** Two entries claimed one code - the table would silently lose one. */
diff --git a/src/core/brain/doctor.ts b/src/core/brain/doctor.ts
index 68d4d085..6ad73748 100644
--- a/src/core/brain/doctor.ts
+++ b/src/core/brain/doctor.ts
@@ -98,6 +98,7 @@ import { frozenVaultCheck } from "./doctor/frozen-check.ts";
import { gitTrackedStateCheck } from "./doctor/git-tracked-state-check.ts";
import { secretsSyncExposureCheck } from "./doctor/secrets-sync-check.ts";
import { logChainCheck } from "./doctor/log-chain-check.ts";
+import { lessonsBlockCheck } from "./doctor/lessons-block-check.ts";
import { attestationCheck } from "./doctor/attestation-check.ts";
import { checkSemanticHealth } from "./doctor/semantic-health-check.ts";
import {
@@ -231,6 +232,13 @@ const DOCTOR_CHECKS: ReadonlyArray<DoctorCheck> = Object.freeze([
// grammar the neutralizer escapes with.
plantedRowsCheck,
logChainCheck,
+ // The lessons-block readiness check (t_1e952e43): the managed lessons
+ // blocks of the agent rules files graded against the same derivation
+ // a refresh would render. Fail-soft, read-only, operator-scope only.
+ lessonsBlockCheck,
+ // The lessons-block readiness check (t_1e952e43): the managed lessons
+ // blocks of the agent rules files graded against the same derivation
+ // a refresh would render. Fail-soft, read-only, operator-scope only.
// The attestation liveness check (delivery trust, t_3bdb82b0): a stale,
// unkeyed or diverged newest attestation, one warning under one code.
attestationCheck,
diff --git a/src/core/brain/doctor/lessons-block-check.ts b/src/core/brain/doctor/lessons-block-check.ts
new file mode 100644
index 00000000..616e8fc9
--- /dev/null
+++ b/src/core/brain/doctor/lessons-block-check.ts
@@ -0,0 +1,341 @@
+/**
+ * The lessons-block doctor check (t_1e952e43, task C3).
+ *
+ * A failSoft, read-only check over the MANAGED lessons blocks of the
+ * agent rules files - managed meaning an approval row names the file,
+ * because consent lives in the ledger and the doctor does not invent it.
+ * One finding per candidate file, graded against the same derivation a
+ * refresh would render now (`planLessonsBlock`), so what the doctor
+ * says and what the next write would do cannot disagree:
+ *
+ * - `lessons-block-stale-lessons` - the block still carries a lesson
+ * whose approval went stale (the approved text moved); the refresh
+ * drops it until the operator approves again;
+ * - `lessons-block-drifted` - the block is behind the canonical body
+ * (a new lesson qualified, or it holds content nothing qualifies
+ * for any more);
+ * - `lessons-block-absent` - approvals name the file but no block
+ * exists; creation is approve's write, so the remedy names approve,
+ * never refresh;
+ * - a current block is silent.
+ *
+ * The per-file grade is a four-state vocabulary shared with the writer's
+ * own drift states plus the named `stale-lessons` extension - registered
+ * in the verdict-vocabulary census with the code that introduced it.
+ *
+ * The check never mutates a byte and never throws: a damaged approvals
+ * ledger folds into one warning naming the file and the recovery, and a
+ * per-file surprise folds into that file's warning.
+ */
+
+import { existsSync } from "node:fs";
+import { join } from "node:path";
+
+import type { DoctorCheck, DoctorCheckContext, DoctorFindings } from "./check.ts";
+import {
+ LESSONS_APPROVALS_FILE,
+ lessonIdsInBlockBody,
+ planLessonsBlock,
+ readLessonApprovals,
+ type LessonApprovalRow,
+ type LessonsBlockPlan,
+} from "../lessons-promotion.ts";
+import { RULES_BLOCK_ID, RulesBlockError, readRulesBlock } from "../../install/rules-block.ts";
+
+/** How a managed lessons block grades, in the census-registered vocabulary. */
+export const LESSONS_BLOCK_STATE = Object.freeze({
+ /** Approvals name the file but no file, or no block pair, exists. */
+ absent: "absent",
+ /** The pair exists and carries exactly what a refresh would render. */
+ current: "current",
+ /** The pair exists but diverges from the canonical body. */
+ drifted: "drifted",
+ /** The pair still carries a lesson whose approval went stale. */
+ staleLessons: "stale-lessons",
+} as const);
+
+export type LessonsBlockState = (typeof LESSONS_BLOCK_STATE)[keyof typeof LESSONS_BLOCK_STATE];
+export const LESSONS_BLOCK_STATES: ReadonlyArray<LessonsBlockState> = Object.freeze(
+ Object.values(LESSONS_BLOCK_STATE),
+);
+
+/** True when `value` (read back off disk or wire) is a block state. */
+export function isLessonsBlockState(value: unknown): value is LessonsBlockState {
+ return (
+ typeof value === "string" && (LESSONS_BLOCK_STATES as ReadonlyArray<string>).includes(value)
+ );
+}
+
+/**
+ * The finding codes this check emits, one constant each so every `code:`
+ * site stays a bare named code readable by the doctor-exit census.
+ */
+export const LESSONS_BLOCK_ABSENT_CODE = "lessons-block-absent";
+export const LESSONS_BLOCK_DRIFTED_CODE = "lessons-block-drifted";
+export const LESSONS_BLOCK_STALE_LESSONS_CODE = "lessons-block-stale-lessons";
+export const LESSONS_LEDGER_UNREADABLE_CODE = "lessons-approvals-unreadable";
+
+/** The refresh command the drifted and stale findings both name. */
+export const LESSONS_REFRESH_COMMAND = "o2b brain lessons refresh-blocks --apply --yes";
+
+/**
+ * The agent-instruction files a lessons block may be managed in: the
+ * fixed-list guard for the target strings the approvals ledger carries.
+ * Ledger rows are machine state in the derived store, so a target string
+ * is validated against this list BEFORE any path is derived from it - an
+ * off-list target (a traversal, a planted path) never reaches
+ * `join(vault, target)` and is skipped, not graded. The list is restated
+ * here because a static import of `AGENT_INSTRUCTION_FILES` from the
+ * write-back contract would close the doctor import cycle (see the
+ * candidate-universe comment in {@link lessonsBlockStates});
+ * `tests/core/brain/doctor/lessons-block-check.test.ts` pins this copy
+ * to the contract list, so the two cannot drift silently.
+ */
+export const LESSONS_BLOCK_MANAGED_FILES: ReadonlyArray<string> = Object.freeze([
+ "AGENTS.md",
+ "CLAUDE.md",
+ "GEMINI.md",
+]);
+
+export interface LessonsBlockStateRow {
+ /** The rules file graded (a basename from the fixed list). */
+ readonly file: string;
+ readonly state: LessonsBlockState;
+ /** Lessons the block still carries whose approvals went stale. */
+ readonly staleIds: ReadonlyArray<string>;
+ /** Lessons a refresh would render into this file now. */
+ readonly qualifiedIds: ReadonlyArray<string>;
+}
+
+interface Grade {
+ readonly state: LessonsBlockState;
+ readonly staleIds: ReadonlyArray<string>;
+ readonly qualifiedIds: ReadonlyArray<string>;
+ readonly detail: string | null;
+}
+
+/** True when two block bodies are the same text modulo fence padding. */
+function sameBody(a: string, b: string | null): boolean {
+ if (b === null) return false;
+ const strip = (text: string): string => text.replace(/\s+$/, "");
+ return strip(a) === strip(b);
+}
+
+/**
+ * Grade one candidate file against its approvals and the live vault.
+ * Throws only what readRulesBlock throws (symlink, unreadable, broken
+ * marker pair) - callers fold that into a per-file warning.
+ */
+
+/** The consent-derived candidate files, first-seen over the sorted ledger. */
+function candidateFiles(ledger: ReadonlyArray<LessonApprovalRow>): ReadonlyArray<string> {
+ const files: string[] = [];
+ for (const row of ledger) {
+ if (row.decision !== "approved") continue;
+ for (const target of row.targets) {
+ // The fixed-list guard: a ledger-supplied target off the known
+ // instruction-file list is never turned into a path.
+ if (!LESSONS_BLOCK_MANAGED_FILES.includes(target)) continue;
+ if (!files.includes(target)) files.push(target);
+ }
+ }
+ return files;
+}
+
+function gradeFile(
+ vault: string,
+ file: string,
+ ledger: ReadonlyArray<LessonApprovalRow>,
+ now: Date,
+ configPath?: string,
+): Grade | null {
+ // Defense in depth beside candidateFiles: any caller handing this
+ // grader a ledger-supplied string gets the same fixed-list guard
+ // before the join below.
+ if (!LESSONS_BLOCK_MANAGED_FILES.includes(file)) return null;
+ const covered = ledger.some((row) => row.decision === "approved" && row.targets.includes(file));
+ if (!covered) return null;
+ const path = join(vault, file);
+ if (!existsSync(path)) {
+ return { state: LESSONS_BLOCK_STATE.absent, staleIds: [], qualifiedIds: [], detail: null };
+ }
+ let extracted: string | null;
+ try {
+ extracted = readRulesBlock(path, RULES_BLOCK_ID.lessons);
+ } catch (err) {
+ if (err instanceof RulesBlockError) {
+ return {
+ state: LESSONS_BLOCK_STATE.drifted,
+ staleIds: [],
+ qualifiedIds: [],
+ detail: err.message,
+ };
+ }
+ throw err;
+ }
+ if (extracted === null) {
+ return { state: LESSONS_BLOCK_STATE.absent, staleIds: [], qualifiedIds: [], detail: null };
+ }
+ // The plan resolves against the config the CALLER selected - the
+ // doctor run's `configPath` - not against whatever file discovery
+ // would find: two configs with different `lessons.promotion.scopes`
+ // qualify different lessons, and grading the block against the wrong
+ // list reported drifted or stale for a block the selected config
+ // renders current. No path given, the planner keeps its own default.
+ const plan: LessonsBlockPlan = planLessonsBlock(vault, file, {
+ now,
+ ...(configPath !== undefined ? { configPath } : {}),
+ });
+ const staleIds = lessonIdsInBlockBody(extracted).filter((id) => plan.staleIds.includes(id));
+ if (staleIds.length > 0) {
+ return {
+ state: LESSONS_BLOCK_STATE.staleLessons,
+ staleIds,
+ qualifiedIds: plan.qualifiedIds,
+ detail: null,
+ };
+ }
+ if (!sameBody(extracted, plan.body)) {
+ return {
+ state: LESSONS_BLOCK_STATE.drifted,
+ staleIds: [],
+ qualifiedIds: plan.qualifiedIds,
+ detail: null,
+ };
+ }
+ return {
+ state: LESSONS_BLOCK_STATE.current,
+ staleIds: [],
+ qualifiedIds: plan.qualifiedIds,
+ detail: null,
+ };
+}
+
+/**
+ * The per-file readiness rows for the managed lessons blocks: one row
+ * per file an approved decision names, in the fixed file order. A
+ * damaged ledger answers with no rows - the check is the surface that
+ * names the damage.
+ */
+export function lessonsBlockStates(
+ vault: string,
+ opts: { readonly now?: Date; readonly configPath?: string } = {},
+): ReadonlyArray<LessonsBlockStateRow> {
+ let ledger: ReadonlyArray<LessonApprovalRow>;
+ try {
+ ledger = readLessonApprovals(vault);
+ } catch {
+ return [];
+ }
+ const now = opts.now ?? new Date();
+ const rows: LessonsBlockStateRow[] = [];
+ // The candidate universe is CONSENT-DERIVED: the files the approved
+ // decisions name, first-seen over the pref-id-sorted ledger, so the row
+ // order is deterministic without importing the write-back contract's
+ // audited list - doctor.ts already sits inside that module's import
+ // cycle (write-binding -> attributes -> diagnostics -> doctor), and a
+ // static import from this check would close a loop the import-cycle
+ // census forbids. A rules file carrying a lessons pair with NO
+ // recorded decision is not managed state and stays out of scope here;
+ // the writer's own consent records are the source of truth.
+ const candidates: string[] = [];
+ for (const row of ledger) {
+ if (row.decision !== "approved") continue;
+ for (const target of row.targets) {
+ if (!candidates.includes(target)) candidates.push(target);
+ }
+ }
+ for (const file of candidates) {
+ try {
+ const grade = gradeFile(vault, file, ledger, now, opts.configPath);
+ if (grade !== null) {
+ rows.push({
+ file,
+ state: grade.state,
+ staleIds: grade.staleIds,
+ qualifiedIds: grade.qualifiedIds,
+ });
+ }
+ } catch {
+ // A per-file surprise stays out of the readiness rows; the check
+ // below is the surface that names it as a warning.
+ }
+ }
+ return rows;
+}
+
+export const lessonsBlockCheck: DoctorCheck = {
+ failSoft: true,
+ run(ctx: DoctorCheckContext, out: DoctorFindings): void {
+ let ledger: ReadonlyArray<LessonApprovalRow>;
+ try {
+ ledger = readLessonApprovals(ctx.vault);
+ } catch (err) {
+ out.issues.push({
+ severity: "warning",
+ code: LESSONS_LEDGER_UNREADABLE_CODE,
+ path: join(ctx.vault, ".open-second-brain", LESSONS_APPROVALS_FILE),
+ message:
+ `the lessons approvals ledger ${LESSONS_APPROVALS_FILE} could not be read: ` +
+ `${(err as Error).message} - no lesson can be approved, denied or refreshed while the ` +
+ "ledger is unreadable; move the file aside or delete it to start clean, which lifts " +
+ "every approval (the fail-closed direction)",
+ });
+ return;
+ }
+ for (const file of candidateFiles(ledger)) {
+ let grade: Grade | null;
+ try {
+ grade = gradeFile(ctx.vault, file, ledger, ctx.now, ctx.configPath);
+ } catch (err) {
+ out.issues.push({
+ severity: "warning",
+ code: LESSONS_BLOCK_DRIFTED_CODE,
+ path: file,
+ message: `the managed lessons block of ${file} could not be graded: ${(err as Error).message}`,
+ });
+ continue;
+ }
+ if (grade === null || grade.state === LESSONS_BLOCK_STATE.current) continue;
+ if (grade.state === LESSONS_BLOCK_STATE.absent) {
+ const qualified =
+ grade.qualifiedIds.length > 0 ? ` (qualified now: ${grade.qualifiedIds.join(", ")})` : "";
+ out.issues.push({
+ severity: "warning",
+ code: LESSONS_BLOCK_ABSENT_CODE,
+ path: file,
+ message:
+ `${file} is named by an approved lesson but carries no managed lessons block` +
+ `${qualified} - creation is approve's write: ` +
+ `o2b brain lessons approve <pref-id> --apply --yes --target ${file}`,
+ });
+ continue;
+ }
+ if (grade.state === LESSONS_BLOCK_STATE.staleLessons) {
+ out.issues.push({
+ severity: "warning",
+ code: LESSONS_BLOCK_STALE_LESSONS_CODE,
+ path: file,
+ message:
+ `the lessons block of ${file} still carries stale lesson(s) ${grade.staleIds.join(", ")} ` +
+ " - the approved text moved, so a refresh drops them until the operator approves " +
+ `again: ${LESSONS_REFRESH_COMMAND}`,
+ });
+ continue;
+ }
+ out.issues.push({
+ severity: "warning",
+ code: LESSONS_BLOCK_DRIFTED_CODE,
+ path: file,
+ message:
+ `the lessons block of ${file} diverges from what a refresh would render` +
+ (grade.detail !== null ? ` (${grade.detail})` : "") +
+ (grade.qualifiedIds.length > 0
+ ? `; qualified now: ${grade.qualifiedIds.join(", ")}`
+ : "") +
+ `: ${LESSONS_REFRESH_COMMAND}` +
+ " (pass --force if the block was hand-edited)",
+ });
+ }
+ },
+};
diff --git a/src/core/brain/lessons-promotion.ts b/src/core/brain/lessons-promotion.ts
new file mode 100644
index 00000000..16e2052e
--- /dev/null
+++ b/src/core/brain/lessons-promotion.ts
@@ -0,0 +1,968 @@
+/**
+ * Operator-approved lesson promotion (t_1e952e43).
+ *
+ * The promotion kernel the CLI verbs, the doctor check and the status
+ * snapshot all consume. A lesson leaves the brain and enters the managed
+ * lessons block of an agent rules file ONLY when the full qualification
+ * conjunction holds:
+ *
+ * - preference-derived (dead-end lessons never promote);
+ * - the preference is `confirmed` (not unconfirmed, not quarantine);
+ * - the confidence band is `high`;
+ * - the lesson tier is `preferred` in the current digest;
+ * - the preference's scope is an explicitly enabled promotion scope
+ * (`lessons.promotion.scopes`; absent-or-empty disables promotion);
+ * - an approval row is on record, decision `approved`, and FRESH: the
+ * approved content hash still matches the live preference text. The
+ * operator approves text, not an id - a drifted preference drops from
+ * the block until it is approved again.
+ *
+ * Every non-member carries exactly ONE named blocked reason from the
+ * closed {@link LESSON_PROMOTION_BLOCKED} vocabulary, with a pinned
+ * precedence (an operator denial dominates the report; intrinsic gates
+ * are reported before the approval gates that sit downstream of them).
+ *
+ * The block body is a pure, deterministic render of the qualified set:
+ * identical inputs produce identical bytes, no timestamp ever appears,
+ * ordering is tier, then scope, then id. Every rendered lesson is
+ * provably one line that cannot forge a managed-block marker: the
+ * principle is whitespace-collapsed, and a scope or id carrying a line
+ * break or a marker-shaped sequence REFUSES the render by name
+ * ({@link LessonRenderError}) rather than being silently rewritten.
+ * Idempotence lives in the shared
+ * rules-block writer (`src/core/install/rules-block.ts`), which is the
+ * ONLY writer for these files: this module never touches a rules file,
+ * it only renders bodies and keeps the approval ledger.
+ *
+ * The approval ledger is machine state in the derived store
+ * (`<vault>/.open-second-brain/lessons-approvals.json`), deliberately
+ * outside `Brain/`: an agent must not read its own approval state as a
+ * note surface. It is a state TABLE keyed by preference id (the latest
+ * decision per id wins), not a history - the audit history is the
+ * `lessons-approved` / `lessons-denied` / `lessons-promoted` log events.
+ * It follows the house ledger discipline (`session-mining-ledger.ts`):
+ * schema-versioned, fail-closed on any damage, written under the file
+ * lock through the shared atomic writer, sorted-key serialization.
+ */
+
+import { existsSync, readFileSync, readdirSync } from "node:fs";
+import { join } from "node:path";
+
+import { discoverConfig, LESSONS_PROMOTION_SCOPES_ENV_KEY } from "../config.ts";
+import { atomicWriteFileSync } from "../fs-atomic.ts";
+import { RULES_BLOCK_ID, RULES_BLOCK_MARKERS, type RulesBlockId } from "../install/rules-block.ts";
+import { computeContentHash } from "./content-hash.ts";
+import { listDeadEnds } from "./dead-ends.ts";
+import { LESSON_TIER, computeLessons, type LessonEntry, type LessonTier } from "./lessons.ts";
+import { DERIVED_STORE_DIR } from "./path-constants.ts";
+import { brainDirs, preferencePath } from "./paths.ts";
+import { parsePreference } from "./preference.ts";
+import {
+ LESSONS_CORROBORATION_MIN_DEFAULT,
+ LESSONS_HALF_LIFE_DAYS_DEFAULT,
+ LESSONS_LIMIT_DEFAULT,
+ LESSONS_PROMOTION_SCOPES_CONFIG_KEY,
+ resolveLessonsPromotionScopes,
+ type LessonsPromotionScopesResolution,
+} from "./policy/blocks/lessons.ts";
+import { loadBrainConfig } from "./policy.ts";
+import { acquireLockSyncWithRetry, ingestLockRemedy } from "./sync-lockfile.ts";
+import { isoSecond } from "./time.ts";
+import { BRAIN_PREFERENCE_STATUS, type BrainConfidence, type BrainPreference } from "./types.ts";
+import { assertVaultIdentityForWrite } from "./vault-identity.ts";
+
+export { LESSONS_PROMOTION_SCOPES_CONFIG_KEY };
+export {
+ LESSONS_PROMOTION_SCOPES_ORIGIN,
+ resolveLessonsPromotionScopes,
+ type LessonsPromotionScopesOrigin,
+ type LessonsPromotionScopesResolution,
+} from "./policy/blocks/lessons.ts";
+
+// ----- Promotion scope resolution (malformed values refuse by name) ---------
+
+/**
+ * A promotion scopes value that is PRESENT but malformed (the
+ * bracket-shaped list syntax the flat config key cannot represent). The
+ * policy block's resolver keeps its documented fallback (such a value
+ * resolves disabled with origin `absent`); this kernel boundary refuses
+ * instead, because an operator must be able to tell "configured wrong"
+ * from "never configured" - promotion is consent-bearing, and a mistyped
+ * key must not silently read as a decision to disable it.
+ */
+export class LessonsPromotionScopesMalformedError extends Error {
+ constructor(
+ message: string,
+ public readonly source: "env" | "config",
+ public readonly rawValue: string,
+ ) {
+ super(message);
+ this.name = "LessonsPromotionScopesMalformedError";
+ }
+}
+
+/**
+ * Same shape test as the policy resolver's private `isBracketShapedList`;
+ * the two must stay in step, and the pin is
+ * `tests/core/brain/lessons-promotion.test.ts` (the strict refusal test
+ * exercises both layers over one value).
+ */
+function isBracketShapedListValue(raw: string): boolean {
+ return raw.startsWith("[") && raw.endsWith("]");
+}
+
+/**
+ * Resolve the promotion scopes for promotion: the policy resolver's
+ * answer, unless a present value is malformed - then a named refusal.
+ * The environment twin is checked first (it wins precedence, so its
+ * malformed value must not hide behind a valid config value either).
+ */
+export function resolvePromotionScopesStrict(
+ configPath?: string,
+): LessonsPromotionScopesResolution {
+ const remedy =
+ 'set a comma-separated list (for example "backend, testing") or remove the key; ' +
+ "promotion stays disabled until then";
+ const env = process.env[LESSONS_PROMOTION_SCOPES_ENV_KEY]?.trim();
+ if (env !== undefined && env !== "" && isBracketShapedListValue(env)) {
+ throw new LessonsPromotionScopesMalformedError(
+ `lessons.promotion.scopes is malformed: ${LESSONS_PROMOTION_SCOPES_ENV_KEY} is set to ` +
+ `"${env}", a bracket-shaped list the flat config key cannot represent; ${remedy}`,
+ "env",
+ env,
+ );
+ }
+ const raw = discoverConfig(configPath).data[LESSONS_PROMOTION_SCOPES_CONFIG_KEY]?.trim();
+ if (raw !== undefined && raw !== "" && isBracketShapedListValue(raw)) {
+ throw new LessonsPromotionScopesMalformedError(
+ `lessons.promotion.scopes is malformed: the config value is "${raw}", a bracket-shaped ` +
+ `list the flat config key cannot represent; ${remedy}`,
+ "config",
+ raw,
+ );
+ }
+ return resolveLessonsPromotionScopes(configPath);
+}
+
+// ----- Promotion qualification ----------------------------------------------
+
+/**
+ * Why a lesson is NOT promotable. Closed vocabulary; every non-member of
+ * the qualified set carries exactly one member as its reason.
+ */
+export const LESSON_PROMOTION_BLOCKED = Object.freeze({
+ /** An operator deny row is on record for this id. */
+ denied: "denied",
+ /** The preference is unconfirmed or quarantined. */
+ unconfirmed: "unconfirmed",
+ /** No scope, or a scope outside the enabled promotion scopes. */
+ scopeNotEnabled: "scope_not_enabled",
+ /** The confidence band is below `high`. */
+ lowConfidence: "low_confidence",
+ /** No lesson entry yet, or its tier is below `preferred`. */
+ tierNotPreferred: "tier_not_preferred",
+ /** An approval is on record but its pinned content hash no longer matches. */
+ staleApproval: "stale_approval",
+ /** No approval row is on record for this id. */
+ notApproved: "not_approved",
+} as const);
+
+/** Closed union over {@link LESSON_PROMOTION_BLOCKED}. */
+export type LessonPromotionBlocked =
+ (typeof LESSON_PROMOTION_BLOCKED)[keyof typeof LESSON_PROMOTION_BLOCKED];
+
+/** The blocked reasons, in pinned precedence order (see below). */
+export const LESSON_PROMOTION_BLOCKED_MEMBERS: ReadonlyArray<LessonPromotionBlocked> =
+ Object.freeze(Object.values(LESSON_PROMOTION_BLOCKED));
+
+/** True when `value` (read back off disk or wire) is a blocked reason. */
+export function isLessonPromotionBlocked(value: unknown): value is LessonPromotionBlocked {
+ return (
+ typeof value === "string" &&
+ (LESSON_PROMOTION_BLOCKED_MEMBERS as ReadonlyArray<string>).includes(value)
+ );
+}
+
+/** One lesson qualified for promotion into the rules-file block. */
+export interface LessonPromotionCandidate {
+ readonly prefId: string;
+ readonly principle: string;
+ readonly scope: string;
+ readonly tier: LessonTier;
+ readonly confidence: BrainConfidence;
+ /**
+ * Hash of the LIVE preference text in the shared `content-hash.ts`
+ * vocabulary - the value an approval row must pin to stay fresh.
+ */
+ readonly contentHash: string;
+}
+
+/** One non-member of the qualified set, with its single named reason. */
+export interface BlockedLessonPromotion {
+ readonly prefId: string;
+ readonly reason: LessonPromotionBlocked;
+}
+
+export interface LessonPromotionCandidatesOptions {
+ /** The enabled promotion scope names (resolved `lessons.promotion.scopes`). */
+ readonly enabledScopes: ReadonlyArray<string>;
+}
+
+/**
+ * The approval decision currently in force for one preference id: the
+ * LAST row for that id in array order (the ledger is a state table; its
+ * reader returns rows in id order, so a caller passing `undefined` for a
+ * missing id resolves to `undefined` here).
+ */
+export function currentApprovalFor(
+ approvals: ReadonlyArray<LessonApprovalRow>,
+ prefId: string,
+): LessonApprovalRow | null {
+ let found: LessonApprovalRow | null = null;
+ for (const row of approvals) {
+ if (row.prefId === prefId) found = row;
+ }
+ return found;
+}
+
+/**
+ * Classify every input preference into promotable lessons and
+ * blocked-with-one-reason rows. Pure: reads nothing, writes nothing; the
+ * caller resolves the enabled scopes (with the vault) and reads the
+ * ledger. Blocked reasons follow the pinned precedence:
+ *
+ * 1. `denied` - the operator's explicit will dominates the report;
+ * 2. `unconfirmed` - intrinsic gate, cheapest and first in the ladder;
+ * 3. `scope_not_enabled` - promotion must stay inside enabled scopes;
+ * 4. `low_confidence` - band below `high`;
+ * 5. `tier_not_preferred` - the digest has not earned the tier;
+ * 6. `stale_approval` - approved once, but the text moved;
+ * 7. `not_approved` - no operator decision yet.
+ */
+export function lessonPromotionCandidates(
+ preferences: ReadonlyArray<BrainPreference>,
+ lessons: ReadonlyArray<LessonEntry>,
+ approvals: ReadonlyArray<LessonApprovalRow>,
+ opts: LessonPromotionCandidatesOptions,
+): {
+ readonly promotable: ReadonlyArray<LessonPromotionCandidate>;
+ readonly blocked: ReadonlyArray<BlockedLessonPromotion>;
+} {
+ const lessonByPrefId = new Map<string, LessonEntry>();
+ for (const entry of lessons) {
+ if (entry.kind !== "preference") continue;
+ lessonByPrefId.set(entry.id, entry);
+ }
+
+ const promotable: LessonPromotionCandidate[] = [];
+ const blocked: BlockedLessonPromotion[] = [];
+
+ for (const pref of preferences) {
+ const reason = blockedReasonFor(
+ pref,
+ lessonByPrefId.get(pref.id),
+ approvals,
+ opts.enabledScopes,
+ );
+ if (reason === null) {
+ promotable.push({
+ prefId: pref.id,
+ principle: pref.principle,
+ scope: (pref.scope ?? "").trim(),
+ tier: lessonByPrefId.get(pref.id)?.tier ?? LESSON_TIER.preferred,
+ confidence: pref.confidence,
+ contentHash: computeContentHash(pref.principle, pref.scope),
+ });
+ } else {
+ blocked.push({ prefId: pref.id, reason });
+ }
+ }
+
+ return { promotable, blocked };
+}
+
+/** The single pinned blocked reason for `pref`, or null when qualified. */
+function blockedReasonFor(
+ pref: BrainPreference,
+ lesson: LessonEntry | undefined,
+ approvals: ReadonlyArray<LessonApprovalRow>,
+ enabledScopes: ReadonlyArray<string>,
+): LessonPromotionBlocked | null {
+ const approval = currentApprovalFor(approvals, pref.id);
+ if (approval !== null && approval.decision === "denied") {
+ return LESSON_PROMOTION_BLOCKED.denied;
+ }
+ if (pref.status !== BRAIN_PREFERENCE_STATUS.confirmed) {
+ return LESSON_PROMOTION_BLOCKED.unconfirmed;
+ }
+ const scope = (pref.scope ?? "").trim();
+ if (scope === "" || !enabledScopes.includes(scope)) {
+ return LESSON_PROMOTION_BLOCKED.scopeNotEnabled;
+ }
+ if (pref.confidence !== "high") {
+ return LESSON_PROMOTION_BLOCKED.lowConfidence;
+ }
+ if (lesson === undefined || lesson.tier !== LESSON_TIER.preferred) {
+ return LESSON_PROMOTION_BLOCKED.tierNotPreferred;
+ }
+ if (approval === null) {
+ return LESSON_PROMOTION_BLOCKED.notApproved;
+ }
+ const liveHash = computeContentHash(pref.principle, pref.scope);
+ if (approval.blockId !== RULES_BLOCK_ID.lessons || approval.approvedContentHash !== liveHash) {
+ return LESSON_PROMOTION_BLOCKED.staleApproval;
+ }
+ return null;
+}
+
+// ----- Block body render -----------------------------------------------------
+
+/**
+ * The render order's tier rank: `preferred` first, then the tiers a
+ * future producer could contribute, then the negative classes. Every
+ * promotable lesson is `preferred` today, so this is stability for the
+ * day the qualification changes, not a live ordering.
+ */
+function lessonTierRank(tier: LessonTier): number {
+ return tier === LESSON_TIER.preferred ? 0 : tier === LESSON_TIER.tentative ? 1 : 2;
+}
+
+export interface RenderLessonsBlockBodyOptions {
+ /**
+ * Maximum lessons rendered. The caller resolves the bound from the
+ * `lessons.limit` config (the digest bound promotion inherits); the
+ * render enforces it here so a caller that resolves it cannot forget
+ * to apply it. A positive integer is required - any other value is a
+ * named refusal, never a silent clamp.
+ */
+ readonly limit?: number;
+}
+
+/** Which rendered field a {@link LessonRenderError} refused. */
+export type LessonRenderField = "prefId" | "scope";
+
+/**
+ * One lesson cannot be rendered as one managed-block line: its scope or
+ * id carries a line break or a marker-shaped sequence that could forge a
+ * lessons or usage marker inside the fence. The render refuses the
+ * lesson by name instead of silently rewriting the text - the operator
+ * fixes the preference and approves again.
+ */
+export class LessonRenderError extends Error {
+ constructor(
+ message: string,
+ public readonly prefId: string,
+ public readonly field: LessonRenderField,
+ ) {
+ super(message);
+ this.name = "LessonRenderError";
+ }
+}
+
+/** Every marker string a rendered lesson line must never carry. */
+const LESSON_LINE_FORBIDDEN_MARKERS: ReadonlyArray<string> = Object.freeze(
+ Object.values(RULES_BLOCK_MARKERS).flatMap((pair) => [pair.begin, pair.end]),
+);
+
+/**
+ * Refuse a candidate whose scope or id could break the one-line-per-
+ * lesson invariant: a line break can forge a whole-line marker, and a
+ * marker-shaped sequence anywhere in the scope is refused on sight (the
+ * discipline is "provably cannot be a marker line", not "happens not to
+ * be one"). The principle is NOT validated here - it is whitespace-
+ * collapsed below, which cannot form a marker line.
+ */
+function assertRenderableLine(candidate: LessonPromotionCandidate): void {
+ const scopeProblem = /\r|\n/.test(candidate.scope)
+ ? "it carries a line break"
+ : LESSON_LINE_FORBIDDEN_MARKERS.some((marker) => candidate.scope.includes(marker))
+ ? "it carries a managed-block marker string"
+ : null;
+ if (scopeProblem !== null) {
+ throw new LessonRenderError(
+ `renderLessonsBlockBody refuses ${candidate.prefId}: the scope is not one renderable ` +
+ "managed-block line - a scope that could forge a lessons or usage marker must never " +
+ `enter the fence (${scopeProblem}); fix the preference's scope to a single-line value ` +
+ "and approve again",
+ candidate.prefId,
+ "scope",
+ );
+ }
+ const idProblem = /\s/.test(candidate.prefId)
+ ? "it carries whitespace"
+ : candidate.prefId.includes("`")
+ ? "it carries a backtick"
+ : null;
+ if (idProblem !== null) {
+ throw new LessonRenderError(
+ `renderLessonsBlockBody refuses ${candidate.prefId}: the id is not one renderable ` +
+ `managed-block line (${idProblem}, which would break the one-line-per-lesson shape ` +
+ "and the id parser); fix the preference id and approve again",
+ candidate.prefId,
+ "prefId",
+ );
+ }
+}
+
+/** What a render produced: the body and the lessons its limit cut. */
+export interface RenderedLessonsBlock {
+ readonly body: string;
+ /**
+ * The qualified lessons that fell past the limit cut, in render order.
+ * A cap that truncates silently would park a just-approved lesson
+ * outside the block with no named report anywhere; callers surface
+ * this list by name in their results.
+ */
+ readonly droppedIds: ReadonlyArray<string>;
+}
+
+/**
+ * Render the body WITH its cap drops named: the same bytes
+ * {@link renderLessonsBlockBody} produces, plus the ids the limit cut.
+ */
+export function renderLessonsBlockWithDrops(
+ promotable: ReadonlyArray<LessonPromotionCandidate>,
+ opts: RenderLessonsBlockBodyOptions = {},
+): RenderedLessonsBlock {
+ if (promotable.length === 0) {
+ throw new Error(
+ "renderLessonsBlockBody: nothing to render - an empty qualified set must REMOVE the " +
+ "block through removeRulesBlock, not write an empty fence",
+ );
+ }
+ if (opts.limit !== undefined && (!Number.isInteger(opts.limit) || opts.limit <= 0)) {
+ throw new RangeError(
+ `renderLessonsBlockBody: limit must be a positive integer, got ${String(opts.limit)}`,
+ );
+ }
+ const limit = opts.limit ?? Number.POSITIVE_INFINITY;
+
+ const ordered = promotable.toSorted((a, b) => {
+ const tierDelta = lessonTierRank(a.tier) - lessonTierRank(b.tier);
+ if (tierDelta !== 0) return tierDelta;
+ const scopeDelta = a.scope.localeCompare(b.scope);
+ if (scopeDelta !== 0) return scopeDelta;
+ return a.prefId.localeCompare(b.prefId);
+ });
+
+ const head = ordered.slice(0, limit);
+ for (const candidate of head) assertRenderableLine(candidate);
+
+ const out: string[] = [
+ "Operator-approved lessons, promoted from the vault's confirmed preferences",
+ "(scope-gated, hash-pinned approvals). Managed by Open Second Brain:",
+ "do not hand-edit - refresh with `o2b brain lessons refresh-blocks`.",
+ "",
+ ];
+ for (const candidate of head) {
+ const principle = candidate.principle.replace(/\s+/g, " ").trim();
+ out.push(`- \`${candidate.prefId}\` (scope: ${candidate.scope}) — ${principle}`);
+ }
+ return {
+ body: out.join("\n") + "\n",
+ droppedIds: ordered.slice(limit).map((candidate) => candidate.prefId),
+ };
+}
+
+/**
+ * Render the body that goes between the lessons markers in a rules file.
+ * Deterministic: identical inputs produce identical bytes; ordering is
+ * tier, then scope, then id; no timestamp ever appears (a stamped body
+ * would defeat the byte-idempotent write). One line per lesson; principle
+ * text is whitespace-collapsed so the one-line-per-lesson invariant holds,
+ * and a scope or id that could forge a marker line is a named refusal
+ * ({@link LessonRenderError}), never a silent rewrite.
+ *
+ * An EMPTY qualified set is a named refusal, not an empty fence: removal
+ * of a whole block - markers included - is the shared writer's
+ * `removeRulesBlock`, and a caller holding no promotable lessons must
+ * call that instead.
+ */
+export function renderLessonsBlockBody(
+ promotable: ReadonlyArray<LessonPromotionCandidate>,
+ opts: RenderLessonsBlockBodyOptions = {},
+): string {
+ return renderLessonsBlockWithDrops(promotable, opts).body;
+}
+
+/**
+ * The block bound a caller renders under: the `lessons.limit` config, the
+ * same knob that bounds the digest the promotable set derives from.
+ * A config that cannot be read resolves the shared default - config
+ * errors are doctor's surface, and this is a bound, not a veto.
+ */
+export function lessonsBlockLimit(vault: string): number {
+ try {
+ const cfg = loadBrainConfig(vault);
+ return cfg.lessons?.limit ?? LESSONS_LIMIT_DEFAULT;
+ } catch {
+ return LESSONS_LIMIT_DEFAULT;
+ }
+}
+
+// ----- Approvals ledger --------------------------------------------------------
+
+/** Only ledger schema this build understands. Anything else is refused. */
+export const LESSONS_APPROVALS_SCHEMA_VERSION = 1 as const;
+
+/** Basename of the approvals ledger inside the derived store. */
+export const LESSONS_APPROVALS_FILE = "lessons-approvals.json";
+
+/** Absolute path of the approvals ledger for a vault. */
+export function lessonsApprovalsPath(vault: string): string {
+ return join(vault, DERIVED_STORE_DIR, LESSONS_APPROVALS_FILE);
+}
+
+/**
+ * How the operator consented, in the shared consent vocabulary the
+ * install ladder and the protect lane record. The lessons verbs are
+ * operator-only, so a ledger row always carries one of these two.
+ */
+export const LESSON_DECISION_BY = Object.freeze({
+ yesFlag: "yes-flag",
+ interactiveYes: "interactive-yes",
+} as const);
+export type LessonDecisionBy = (typeof LESSON_DECISION_BY)[keyof typeof LESSON_DECISION_BY];
+
+/** One approval state row: the decision currently in force for one id. */
+export interface LessonApprovalRow {
+ readonly prefId: string;
+ readonly decision: "approved" | "denied";
+ /** When the operator decided, ISO-8601. */
+ readonly decidedAt: string;
+ /** How the operator consented, from {@link LESSON_DECISION_BY}. */
+ readonly decidedBy: LessonDecisionBy;
+ /**
+ * Hash the decision pinned, in the shared `content-hash.ts` vocabulary.
+ * For an approval this is the text the operator saw; freshness is the
+ * match of this hash against the live preference text.
+ */
+ readonly approvedContentHash: string;
+ /** The rules files the decision covers (basenames). Empty on a denial. */
+ readonly targets: ReadonlyArray<string>;
+ /** The rules block the approval is for; always the lessons block today. */
+ readonly blockId: RulesBlockId;
+ /** When the block last received this lesson's content, or null. */
+ readonly lastPromotedAt: string | null;
+}
+
+/** Shape of the ledger on disk: one row per decided preference id. */
+interface LessonsApprovalsFileShape {
+ readonly schema_version: typeof LESSONS_APPROVALS_SCHEMA_VERSION;
+ readonly rows: ReadonlyArray<LessonApprovalRow>;
+}
+
+/** The remedy every file-level refusal names, in the mining-ledger style. */
+const CORRUPT_LEDGER_REMEDY =
+ "; to recover, move the file aside or delete it - every approval is then lifted " +
+ "and every lesson needs approving again, which is the fail-closed direction";
+
+/**
+ * Read the approval ledger. A missing file is an empty ledger (nothing is
+ * approved, nothing is denied). ANY damage - corrupt JSON, an unknown
+ * schema version, a container that is not an object, a damaged row - is a
+ * hard named refusal: a silently dropped approval would block a lesson
+ * the operator approved, and a silently dropped denial would re-open one
+ * they refused, so no partial read is honest here. Never reads `Brain/`:
+ * the ledger lives in the derived store and stays there.
+ */
+export function readLessonApprovals(vault: string): ReadonlyArray<LessonApprovalRow> {
+ const path = lessonsApprovalsPath(vault);
+ if (!existsSync(path)) return [];
+ let parsed: unknown;
+ try {
+ parsed = JSON.parse(readFileSync(path, "utf8"));
+ } catch (err) {
+ throw new Error(`lessons approvals ledger is corrupted JSON: ${path}${CORRUPT_LEDGER_REMEDY}`, {
+ cause: err,
+ });
+ }
+ if (parsed === null || typeof parsed !== "object" || Array.isArray(parsed)) {
+ throw new Error(`lessons approvals ledger is not an object: ${path}${CORRUPT_LEDGER_REMEDY}`);
+ }
+ const obj = parsed as Record<string, unknown>;
+ if (obj["schema_version"] !== LESSONS_APPROVALS_SCHEMA_VERSION) {
+ throw new Error(
+ `lessons approvals ledger schema_version ${String(obj["schema_version"])} not supported ` +
+ `(expected ${LESSONS_APPROVALS_SCHEMA_VERSION}): ${path}${CORRUPT_LEDGER_REMEDY}`,
+ );
+ }
+ const raw = obj["rows"];
+ if (!Array.isArray(raw)) {
+ throw new Error(
+ `lessons approvals ledger rows is not an array: ${path}${CORRUPT_LEDGER_REMEDY}`,
+ );
+ }
+ const rows: LessonApprovalRow[] = [];
+ for (const entry of raw) {
+ rows.push(readRow(entry, path));
+ }
+ return rows.toSorted((a, b) => a.prefId.localeCompare(b.prefId));
+}
+
+/** One row, or a named refusal when the shape is not one this build reads. */
+function readRow(value: unknown, path: string): LessonApprovalRow {
+ if (value === null || typeof value !== "object" || Array.isArray(value)) {
+ throw new Error(`lessons approvals ledger holds a row that is not an object: ${path}`);
+ }
+ const row = value as Record<string, unknown>;
+ const prefId = row["prefId"];
+ const decision = row["decision"];
+ const decidedAt = row["decidedAt"];
+ const decidedBy = row["decidedBy"];
+ const approvedContentHash = row["approvedContentHash"];
+ const targets = row["targets"];
+ const blockId = row["blockId"];
+ const lastPromotedAt = row["lastPromotedAt"];
+ if (typeof prefId !== "string" || prefId.length === 0) {
+ throw new Error(`lessons approvals ledger holds a row without a prefId: ${path}`);
+ }
+ if (decision !== "approved" && decision !== "denied") {
+ throw new Error(
+ `lessons approvals ledger row ${prefId} carries decision ${String(decision)}: ${path}`,
+ );
+ }
+ if (typeof decidedAt !== "string" || decidedAt.length === 0) {
+ throw new Error(`lessons approvals ledger row ${prefId} carries no decidedAt: ${path}`);
+ }
+ if (decidedBy !== LESSON_DECISION_BY.yesFlag && decidedBy !== LESSON_DECISION_BY.interactiveYes) {
+ throw new Error(
+ `lessons approvals ledger row ${prefId} carries decidedBy ${String(decidedBy)}: ${path}`,
+ );
+ }
+ if (typeof approvedContentHash !== "string" || approvedContentHash.length === 0) {
+ throw new Error(`lessons approvals ledger row ${prefId} carries no approved hash: ${path}`);
+ }
+ if (!Array.isArray(targets) || targets.some((t) => typeof t !== "string" || t.length === 0)) {
+ throw new Error(`lessons approvals ledger row ${prefId} carries malformed targets: ${path}`);
+ }
+ if (blockId !== RULES_BLOCK_ID.usage && blockId !== RULES_BLOCK_ID.lessons) {
+ throw new Error(
+ `lessons approvals ledger row ${prefId} carries blockId ${String(blockId)}: ${path}`,
+ );
+ }
+ if (lastPromotedAt !== null && typeof lastPromotedAt !== "string") {
+ throw new Error(
+ `lessons approvals ledger row ${prefId} carries malformed lastPromotedAt: ${path}`,
+ );
+ }
+ return {
+ prefId,
+ decision,
+ decidedAt,
+ decidedBy,
+ approvedContentHash,
+ targets: Object.freeze(targets as ReadonlyArray<string>),
+ blockId,
+ lastPromotedAt,
+ };
+}
+
+/** Canonical ledger bytes: rows sorted by pref id, two-space JSON, trailing newline. */
+function serializeLedger(rows: ReadonlyArray<LessonApprovalRow>): string {
+ const sorted = rows.toSorted((a, b) => a.prefId.localeCompare(b.prefId));
+ const shape: LessonsApprovalsFileShape = {
+ schema_version: LESSONS_APPROVALS_SCHEMA_VERSION,
+ rows: sorted,
+ };
+ return JSON.stringify(shape, null, 2) + "\n";
+}
+
+/**
+ * Record (or supersede) one approval decision: the row keyed by `prefId`
+ * is replaced, so the ledger stays the state table of decisions currently
+ * in force. The read, merge and write are one critical section under the
+ * same file lock every other Brain read-modify-write takes; the write is
+ * atomic and a byte-identical no-op leaves the file untouched.
+ */
+export function recordLessonApproval(vault: string, row: LessonApprovalRow): void {
+ assertVaultIdentityForWrite(vault);
+ validateRow(row);
+ const path = lessonsApprovalsPath(vault);
+ const handle = acquireLockSyncWithRetry(path, undefined, { remedy: ingestLockRemedy });
+ try {
+ const existing = readLessonApprovals(vault).filter((r) => r.prefId !== row.prefId);
+ const next = serializeLedger([...existing, row]);
+ if (existsSync(path) && readFileSync(path, "utf8") === next) return;
+ atomicWriteFileSync(path, next);
+ } finally {
+ handle.release();
+ }
+}
+
+/**
+ * Stamp the moment the managed block last received a lesson's content.
+ * Only an approved row can be promoted; a missing or denied row is a
+ * named refusal - stamping a denial would dress suppression up as
+ * delivery.
+ */
+export function markLessonPromoted(vault: string, prefId: string, promotedAt: Date): void {
+ assertVaultIdentityForWrite(vault);
+ const path = lessonsApprovalsPath(vault);
+ const handle = acquireLockSyncWithRetry(path, undefined, { remedy: ingestLockRemedy });
+ try {
+ const rows = readLessonApprovals(vault);
+ const row = rows.find((r) => r.prefId === prefId);
+ if (row === undefined) {
+ throw new Error(`markLessonPromoted: no approval row on record for ${prefId}`);
+ }
+ if (row.decision !== "approved") {
+ throw new Error(
+ `markLessonPromoted: ${prefId} holds a ${row.decision} decision and cannot be stamped promoted`,
+ );
+ }
+ const next = serializeLedger(
+ rows.map((r) => (r.prefId === prefId ? { ...r, lastPromotedAt: isoSecond(promotedAt) } : r)),
+ );
+ if (existsSync(path) && readFileSync(path, "utf8") === next) return;
+ atomicWriteFileSync(path, next);
+ } finally {
+ handle.release();
+ }
+}
+
+/** Validate a row at the write boundary, so a half-formed row never lands. */
+function validateRow(row: LessonApprovalRow): void {
+ if (typeof row.prefId !== "string" || row.prefId.length === 0) {
+ throw new Error("recordLessonApproval: row carries no prefId");
+ }
+ if (row.decision !== "approved" && row.decision !== "denied") {
+ throw new Error(`recordLessonApproval: ${row.prefId} carries decision ${String(row.decision)}`);
+ }
+ if (
+ row.decidedBy !== LESSON_DECISION_BY.yesFlag &&
+ row.decidedBy !== LESSON_DECISION_BY.interactiveYes
+ ) {
+ throw new Error(
+ `recordLessonApproval: ${row.prefId} carries decidedBy ${String(row.decidedBy)}`,
+ );
+ }
+ if (typeof row.decidedAt !== "string" || Number.isNaN(Date.parse(row.decidedAt))) {
+ throw new Error(`recordLessonApproval: ${row.prefId} carries a non-ISO decidedAt`);
+ }
+ if (typeof row.approvedContentHash !== "string" || row.approvedContentHash.length === 0) {
+ throw new Error(`recordLessonApproval: ${row.prefId} carries no approved content hash`);
+ }
+ if (!Array.isArray(row.targets) || row.targets.some((t) => typeof t !== "string" || t === "")) {
+ throw new Error(`recordLessonApproval: ${row.prefId} carries malformed targets`);
+ }
+ if (row.blockId !== RULES_BLOCK_ID.usage && row.blockId !== RULES_BLOCK_ID.lessons) {
+ throw new Error(`recordLessonApproval: ${row.prefId} carries blockId ${String(row.blockId)}`);
+ }
+ if (row.lastPromotedAt !== null && typeof row.lastPromotedAt !== "string") {
+ throw new Error(`recordLessonApproval: ${row.prefId} carries a malformed lastPromotedAt`);
+ }
+}
+
+// ----- Vault-side inputs -----------------------------------------------------
+
+/** Everything one promotion pass reads from the vault, gathered once. */
+export interface LessonsPromotionInputs {
+ /** Every parseable active preference under `Brain/preferences/`. */
+ readonly preferences: ReadonlyArray<BrainPreference>;
+ /** The signed, recency-scored digest entries the tiers come from. */
+ readonly lessons: ReadonlyArray<LessonEntry>;
+ /** The resolved promotion scopes (a count of zero disables promotion). */
+ readonly scopes: LessonsPromotionScopesResolution;
+}
+
+export interface GatherLessonsPromotionInputsOptions {
+ /** Wall clock for the recency decay. Defaults to `new Date()`. */
+ readonly now?: Date;
+ /** The `o2b` config file the scopes resolve against; null for default discovery. */
+ readonly configPath?: string | null;
+}
+
+/**
+ * Gather the promotion inputs from one vault: the active preferences
+ * (corrupted files are omitted; doctor is the surface for them, exactly
+ * as the lessons digest reads), the dead ends, and the digest computed
+ * fresh at `opts.now` under the configured `lessons:` tuning. The digest
+ * is COMPUTED, not read off `Brain/lessons.md`: qualification and the
+ * doctor must grade what a refresh would render now, not what the last
+ * dream pass sealed. Config that cannot be read resolves the shared
+ * defaults - a config error is doctor's finding, never a promotion veto.
+ */
+export function gatherLessonsPromotionInputs(
+ vault: string,
+ opts: GatherLessonsPromotionInputsOptions = {},
+): LessonsPromotionInputs {
+ const preferences = readActivePreferencesForPromotion(vault);
+ const deadEnds = listDeadEnds(vault).entries;
+
+ let halfLifeDays = LESSONS_HALF_LIFE_DAYS_DEFAULT;
+ let corroborationMin = LESSONS_CORROBORATION_MIN_DEFAULT;
+ let limit = LESSONS_LIMIT_DEFAULT;
+ try {
+ const cfg = loadBrainConfig(vault);
+ if (cfg.lessons) {
+ halfLifeDays = cfg.lessons.half_life_days ?? halfLifeDays;
+ corroborationMin = cfg.lessons.corroboration_min ?? corroborationMin;
+ limit = cfg.lessons.limit ?? limit;
+ }
+ } catch {
+ // intentional fallback - config error is doctor's job to surface
+ }
+
+ const lessons = computeLessons(vault, preferences, deadEnds, {
+ ...(opts.now !== undefined ? { now: opts.now } : {}),
+ halfLifeDays,
+ corroborationMin,
+ limit,
+ });
+ // The strict resolution: a present-but-malformed scopes value refuses
+ // by name here (see resolvePromotionScopesStrict) rather than reading
+ // as an unset key. Callers surface the refusal; the doctor's per-file
+ // catches fold it into their named warnings.
+ const scopes = resolvePromotionScopesStrict(opts.configPath ?? undefined);
+ return { preferences, lessons, scopes };
+}
+
+/** The active preferences, parsed; a corrupted file is omitted, not fatal. */
+function readActivePreferencesForPromotion(vault: string): BrainPreference[] {
+ const dirs = brainDirs(vault);
+ if (!existsSync(dirs.preferences)) return [];
+ const out: BrainPreference[] = [];
+ for (const name of readdirSync(dirs.preferences)) {
+ if (!name.endsWith(".md")) continue;
+ try {
+ out.push(parsePreference(join(dirs.preferences, name)));
+ } catch {
+ // Corrupted frontmatter - doctor flags it; promotion reads the rest.
+ }
+ }
+ return out;
+}
+
+// ----- Managed-block plan and status counts (C3) ------------------------------
+
+/**
+ * What one managed lessons block would look like if a refresh ran now:
+ * the canonical body, the lessons it would carry, and the lessons whose
+ * approvals went stale for this file. The one derivation the verbs, the
+ * doctor check and the tests all consume, so "what a refresh would
+ * render" can never disagree between the surfaces that ask.
+ */
+export interface LessonsBlockPlan {
+ /** The rules file the plan is for (a basename from the fixed list). */
+ readonly file: string;
+ /**
+ * The canonical body, or null when no qualified lesson's approval
+ * covers this file - the caller removes the block (never renders an
+ * empty fence).
+ */
+ readonly body: string | null;
+ /** The pref ids the canonical body carries, in render order. */
+ readonly qualifiedIds: ReadonlyArray<string>;
+ /** Approved ids whose pinned hash no longer matches, for this file. */
+ readonly staleIds: ReadonlyArray<string>;
+ /**
+ * Qualified ids that fell past the `lessons.limit` cut of the render,
+ * in render order: the cap's shortfall, named so no lesson can leave
+ * the block silently (empty under the shipped wiring, where the digest
+ * and the block read the same bound).
+ */
+ readonly droppedIds: ReadonlyArray<string>;
+}
+
+export interface PlanLessonsBlockOptions {
+ /** The o2b config file scopes resolve against; null for discovery. */
+ readonly configPath?: string | null;
+ /** Wall clock for the recency decay; defaults to now. */
+ readonly now?: Date;
+}
+
+/**
+ * Derive the plan for one managed block: qualification over the vault's
+ * live inputs, the approvals covering this file, and the same render the
+ * verbs write. Read-only; throws only when the approvals ledger is
+ * damaged (fail-closed, the reader's contract).
+ */
+export function planLessonsBlock(
+ vault: string,
+ file: string,
+ opts: PlanLessonsBlockOptions = {},
+): LessonsBlockPlan {
+ const ledger = readLessonApprovals(vault);
+ const inputs = gatherLessonsPromotionInputs(vault, {
+ ...(opts.now !== undefined ? { now: opts.now } : {}),
+ ...(opts.configPath !== undefined ? { configPath: opts.configPath } : {}),
+ });
+ const { promotable, blocked } = lessonPromotionCandidates(
+ inputs.preferences,
+ inputs.lessons,
+ ledger,
+ { enabledScopes: inputs.scopes.scopes },
+ );
+ const covers = (id: string): boolean => {
+ const row = currentApprovalFor(ledger, id);
+ return row !== null && row.decision === "approved" && row.targets.includes(file);
+ };
+ const qualified = promotable.filter((candidate) => covers(candidate.prefId));
+ const staleIds = blocked
+ .filter((entry) => entry.reason === LESSON_PROMOTION_BLOCKED.staleApproval)
+ .map((entry) => entry.prefId)
+ .filter((id) => covers(id));
+ const render =
+ qualified.length === 0
+ ? null
+ : renderLessonsBlockWithDrops(qualified, { limit: lessonsBlockLimit(vault) });
+ return {
+ file,
+ body: render === null ? null : render.body,
+ qualifiedIds: qualified.map((candidate) => candidate.prefId),
+ staleIds,
+ droppedIds: render === null ? [] : render.droppedIds,
+ };
+}
+
+/**
+ * The pref ids a rendered block body carries, in render order. The
+ * parser lives beside the render so the one-line-per-lesson format
+ * couples only within this module; a line that is not a lesson entry
+ * yields nothing.
+ */
+export function lessonIdsInBlockBody(body: string): ReadonlyArray<string> {
+ const ids: string[] = [];
+ for (const line of body.split("\n")) {
+ const match = /^- `([^`]+)` /.exec(line);
+ if (match !== null) ids.push(match[1] as string);
+ }
+ return ids;
+}
+
+/** Approval counts for the status snapshot: the ledger plus staleness. */
+export interface LessonApprovalCounts {
+ readonly approved: number;
+ readonly denied: number;
+ /** Approvals whose pinned hash no longer matches the live text. */
+ readonly stale: number;
+}
+
+/**
+ * Count the approval decisions currently in force: approved, denied, and
+ * how many of the approved rows went STALE - the pinned hash no longer
+ * matches the live preference text, or the preference cannot be read at
+ * all (a missing or damaged preference cannot be promoted, so its
+ * approval holds nothing fresh). Reads only.
+ */
+export function lessonApprovalCounts(vault: string): LessonApprovalCounts {
+ const ledger = readLessonApprovals(vault);
+ let approved = 0;
+ let denied = 0;
+ let stale = 0;
+ for (const row of ledger) {
+ if (row.decision === "denied") {
+ denied += 1;
+ continue;
+ }
+ approved += 1;
+ try {
+ const pref = parsePreference(preferencePath(vault, row.prefId.replace(/^pref-/, "")));
+ if (computeContentHash(pref.principle, pref.scope) !== row.approvedContentHash) stale += 1;
+ } catch {
+ stale += 1;
+ }
+ }
+ return { approved, denied, stale };
+}
diff --git a/src/core/brain/paths.ts b/src/core/brain/paths.ts
index df2d7f46..1ee2bcd3 100644
--- a/src/core/brain/paths.ts
+++ b/src/core/brain/paths.ts
@@ -79,6 +79,13 @@ import {
HOOK_AUDIT_DIR,
} from "./path-constants.ts";
import { assertVaultIdentityForWrite } from "./vault-identity.ts";
+import {
+ SKILL_BENCHMARK_SPEC_FILE,
+ SKILL_BENCHMARK_TASKS_FILE,
+ SKILL_BENCH_SKILL_NAME_RE,
+ skillBenchmarkRelPath,
+} from "./skill-rewrite-tasks.ts";
+import { SKILL_REWRITE_ROUNDS_DIR } from "./skill-rewrite.ts";
import type { ScopedRuleAxis } from "./scoped-rule-axis.ts";
import type { WriteLane } from "./freeze-marker.ts";
@@ -471,6 +478,62 @@ export function skillAcceptJournalPath(vault: string, slug: string): string {
return ensureInsideVault(join(vault, BRAIN_SKILL_ACCEPT_JOURNAL_REL, `${s}.json`), vault);
}
+/**
+ * Prior-content copy for an in-flight rewrite accept:
+ * `Brain/skill-proposals/accept-journal/<slug>.prior.md`.
+ *
+ * A scored rewrite OVERWRITES an incumbent SKILL.md, so the accept
+ * sequence captures the incumbent bytes here before the overwrite and
+ * the rollback restores content from it, not just existence. It is a
+ * repair artifact like the marker beside it and is removed when the
+ * journal is cleared.
+ */
+export function skillAcceptPriorContentPath(vault: string, slug: string): string {
+ const s = validateSlug(slug);
+ return ensureInsideVault(join(vault, BRAIN_SKILL_ACCEPT_JOURNAL_REL, `${s}.prior.md`), vault);
+}
+
+/** Per-skill benchmark task set: `Brain/skill-benchmarks/<skill>/tasks.json`. */
+export function skillBenchmarkTasksPath(vault: string, skillName: string): string {
+ assertBenchmarkSkillName(skillName);
+ return ensureInsideVault(
+ join(vault, skillBenchmarkRelPath(skillName, SKILL_BENCHMARK_TASKS_FILE)),
+ vault,
+ );
+}
+
+/** Frozen rewrite spec: `Brain/skill-benchmarks/<skill>/spec.json`. */
+export function skillBenchmarkSpecPath(vault: string, skillName: string): string {
+ assertBenchmarkSkillName(skillName);
+ return ensureInsideVault(
+ join(vault, skillBenchmarkRelPath(skillName, SKILL_BENCHMARK_SPEC_FILE)),
+ vault,
+ );
+}
+
+/** Transcript drop site for gate rounds: `Brain/skill-benchmarks/<skill>/rounds/`. */
+export function skillBenchmarkRoundsDir(vault: string, skillName: string): string {
+ assertBenchmarkSkillName(skillName);
+ return ensureInsideVault(
+ join(vault, skillBenchmarkRelPath(skillName, SKILL_REWRITE_ROUNDS_DIR)),
+ vault,
+ );
+}
+
+/**
+ * The name becomes a directory under the benchmark root, so it follows
+ * the skill-directory rule, re-checked here the way every path builder
+ * in this module re-checks the slug it derives from.
+ */
+function assertBenchmarkSkillName(skillName: string): void {
+ if (!SKILL_BENCH_SKILL_NAME_RE.test(skillName)) {
+ throw new Error(
+ `skill benchmark name is not a skill directory name ` +
+ `(lowercase letters, digits and single hyphens): ${JSON.stringify(skillName)}`,
+ );
+ }
+}
+
/** Accepted procedure reference path: `Brain/procedures/proc-<slug>.md`. */
export function procedurePath(vault: string, slug: string): string {
const s = validateSlug(slug);
diff --git a/src/core/brain/policy/blocks/lessons.ts b/src/core/brain/policy/blocks/lessons.ts
index ac1d6ec6..61e9d9f4 100644
--- a/src/core/brain/policy/blocks/lessons.ts
+++ b/src/core/brain/policy/blocks/lessons.ts
@@ -8,14 +8,95 @@
* working-memory continuity decay (30 days); the corroboration floor
* (2 distinct results) keeps a one-off application from promoting
* straight to `preferred`.
+ *
+ * Also home of the promotion scope resolution (t_1e952e43): which scopes
+ * a lesson may promote from, read from the machine config and its
+ * environment twin rather than from `_brain.yaml`, because promotion is a
+ * consent-bearing operator decision, not a digest tuning knob.
*/
+import { discoverConfig, LESSONS_PROMOTION_SCOPES_ENV_KEY } from "../../../config.ts";
import type { BrainLessonsConfig } from "../../types.ts";
import { readBoundedInt } from "../field-checks.ts";
import { openBlock, warnUnknownKeys, type BlockParseContext } from "../key-index.ts";
const BLOCK = "lessons";
+// ----- Promotion scopes (t_1e952e43) -----------------------------------------
+
+/**
+ * The flat machine-config key holding the scope names a lesson may promote
+ * from (operator-approved lesson promotion, t_1e952e43). Comma-separated;
+ * the environment twin lives beside the other config keys in
+ * `src/core/config.ts` (`LESSONS_PROMOTION_SCOPES_ENV_KEY`). Absent or
+ * empty DISABLES promotion entirely - the safe direction, since promotion
+ * copies brain text into files agents read.
+ */
+export const LESSONS_PROMOTION_SCOPES_CONFIG_KEY = "lessons.promotion.scopes";
+
+/** Where a resolved scope list came from, named for honest reporting. */
+export const LESSONS_PROMOTION_SCOPES_ORIGIN = Object.freeze({
+ env: "env",
+ config: "config",
+ absent: "absent",
+} as const);
+export type LessonsPromotionScopesOrigin =
+ (typeof LESSONS_PROMOTION_SCOPES_ORIGIN)[keyof typeof LESSONS_PROMOTION_SCOPES_ORIGIN];
+
+export interface LessonsPromotionScopesResolution {
+ /** The enabled scope names, NFC-normalized and trimmed, in given order. */
+ readonly scopes: ReadonlyArray<string>;
+ /**
+ * The named count of enabled scopes. Zero means promotion is DISABLED
+ * (the key and its environment twin are absent or empty, or the value
+ * was malformed) - callers branch on this count rather than guessing
+ * from array emptiness.
+ */
+ readonly count: number;
+ /** Which layer supplied the value, or `absent` when none did. */
+ readonly origin: LessonsPromotionScopesOrigin;
+}
+
+/**
+ * Resolve the promotion scope list: the environment twin wins, then the
+ * flat machine-config key, then absent. Parsing follows the
+ * `resolveCounterpartyBriefTriggers` rules: entries are NFC-normalized and
+ * trimmed, empty entries dropped, and a bracket-shaped value (real YAML
+ * list syntax the flat config parser cannot represent) is malformed - it
+ * resolves `absent` rather than shipping scope names no preference ever
+ * carries. An empty result disables promotion, never widens it.
+ */
+/** Split a comma-separated raw value into normalized, trimmed scope names. */
+function parsePromotionScopes(raw: string): string[] {
+ const scopes: string[] = [];
+ for (const part of raw.split(",")) {
+ const scope = part.normalize("NFC").trim();
+ if (scope.length > 0) scopes.push(scope);
+ }
+ return scopes;
+}
+
+/** True when a value is bracket-shaped list syntax the flat parser cannot represent. */
+function isBracketShapedList(raw: string): boolean {
+ return raw.startsWith("[") && raw.endsWith("]");
+}
+
+export function resolveLessonsPromotionScopes(
+ configPath?: string,
+): LessonsPromotionScopesResolution {
+ const env = process.env[LESSONS_PROMOTION_SCOPES_ENV_KEY]?.trim();
+ if (env !== undefined && env !== "" && !isBracketShapedList(env)) {
+ const scopes = parsePromotionScopes(env);
+ return { scopes, count: scopes.length, origin: LESSONS_PROMOTION_SCOPES_ORIGIN.env };
+ }
+ const raw = discoverConfig(configPath).data[LESSONS_PROMOTION_SCOPES_CONFIG_KEY]?.trim();
+ if (raw !== undefined && raw !== "" && !isBracketShapedList(raw)) {
+ const scopes = parsePromotionScopes(raw);
+ return { scopes, count: scopes.length, origin: LESSONS_PROMOTION_SCOPES_ORIGIN.config };
+ }
+ return { scopes: [], count: 0, origin: LESSONS_PROMOTION_SCOPES_ORIGIN.absent };
+}
+
export const LESSONS_HALF_LIFE_DAYS_DEFAULT = 30;
export const LESSONS_HALF_LIFE_DAYS_MIN = 1;
export const LESSONS_HALF_LIFE_DAYS_MAX = 365;
diff --git a/src/core/brain/receipts/types.ts b/src/core/brain/receipts/types.ts
index aae1c15e..35893f15 100644
--- a/src/core/brain/receipts/types.ts
+++ b/src/core/brain/receipts/types.ts
@@ -194,6 +194,11 @@ export const FOLDABLE_CONTINUITY_KINDS: ReadonlyArray<ContinuityRecordKind> = Ob
* would sever the receipt-to-presence join for every record past the
* cutoff, turning "checked and verified/missed" into an
* `unjoined` read.
+ * - `skill_rewrite_eval_grade` - the benchmark-gated rewrite lane's
+ * completed gate-run verdicts (t_635e3e72), read back as data by the
+ * read-only rewrite status surface; the evidence an operator audits a
+ * staged scored_rewrite proposal against, per-record identity past
+ * any correlation window, and additive by design - kept never-folded.
*/
export const KEPT_CONTINUITY_KINDS: ReadonlyArray<ContinuityRecordKind> = Object.freeze([
"source_invalidation",
@@ -213,6 +218,7 @@ export const KEPT_CONTINUITY_KINDS: ReadonlyArray<ContinuityRecordKind> = Object
"receipt_compaction",
"skill_invoked",
"reply_presence",
+ "skill_rewrite_eval_grade",
]);
/** One shard selected for compaction, as a scan reported it. */
diff --git a/src/core/brain/skill-accept-journal.ts b/src/core/brain/skill-accept-journal.ts
index d066c7a0..5c326a8a 100644
--- a/src/core/brain/skill-accept-journal.ts
+++ b/src/core/brain/skill-accept-journal.ts
@@ -36,10 +36,37 @@
* The field is optional: a marker written before it existed names the
* procedure path implicitly, and the resolver falls back to that.
*
+ * The same guess problem applies to the TREE the path sits in: a caller
+ * (CLI flag, MCP server config) can resolve the skills root differently
+ * from what recovery would resolve on its next run. So a skill
+ * materialization also records the root its accept resolved
+ * ({@link SkillAcceptJournalEntry.skillsRoot}); the field is optional and
+ * absent on legacy markers and on procedure materializations, which never
+ * consult the skills tree.
+ *
* The journal is a repair marker, not history: it is removed as soon as
* the sequence completes or is resolved. A journal left on disk means a
* sequence is still outstanding.
*
+ * The marker file itself is agent-writable, and its `materializedPath`
+ * drives the rollback's deletion and the restore's rewrite, so the parser
+ * refuses (security audit M4, the deletion sink) a `materialized_path` the
+ * accept sequence cannot have produced on a marker whose target did not
+ * exist - the shape the rollback's `rmSync` reads with no at-use guard in
+ * front of it: a relative value (the module writes only absolute paths), or
+ * an absolute path resolving outside the vault and the skills root the
+ * materialize step used - the root the marker itself records when present,
+ * else the default resolution (a legacy marker names no root). On a legacy
+ * marker, the one shape left outside both roots stays admissible - a
+ * `mature_page` materialization under a caller's override skills root,
+ * which the marker cannot name - recognized as an absolute path ending in
+ * the skill page filename. On a marker whose target DID exist, the path
+ * reaches only the restore branch, which validates its own target at use;
+ * there the parser stays permissive so diagnosis can still read the marker.
+ * A refused marker is unreadable data, exactly like a corrupt one: named,
+ * retained, and blocking every accept until an operator removes it. A
+ * hand-edited journal is not a recovery input.
+ *
* A marker that cannot be READ is a third state, and it used to be a dead
* end: the sweep runs before every accept, so one unparseable file blocked
* the verb permanently and the refusal named no way out. There are now two
@@ -50,12 +77,18 @@
*/
import { existsSync, mkdirSync, readdirSync, readFileSync, rmSync } from "node:fs";
-import { dirname, join } from "node:path";
+import { basename, dirname, isAbsolute, join, resolve, sep } from "node:path";
+import { resolveSkillsDir } from "../config.ts";
import { atomicWriteFileSync } from "../fs-atomic.ts";
import { ensureInsideVault } from "../path-safety.ts";
+import { SKILL_FILE_NAME } from "../surface/skills.ts";
import { requireNextStep } from "./next-step.ts";
-import { BRAIN_SKILL_ACCEPT_JOURNAL_REL, skillAcceptJournalPath } from "./paths.ts";
+import {
+ BRAIN_SKILL_ACCEPT_JOURNAL_REL,
+ skillAcceptJournalPath,
+ skillAcceptPriorContentPath,
+} from "./paths.ts";
import { assertVaultIdentityForWrite } from "./vault-identity.ts";
/** Step the accept sequence was about to perform when the journal was stamped. */
@@ -76,6 +109,25 @@ export interface SkillAcceptJournalEntry {
* slug derives.
*/
readonly materializedPath?: string;
+ /**
+ * The skills root the accept sequence resolved for a skill
+ * materialization: the caller's override, the configured `skills_dir`,
+ * or the vault's own skills subtree. Recovery and the parse-time guard
+ * check the journal's materialized path against this root rather than
+ * re-deriving one. Absent on legacy markers and on procedure
+ * materializations, which never consult the skills tree; both fall back
+ * to the default resolved root.
+ */
+ readonly skillsRoot?: string;
+ /**
+ * Vault-side copy of the incumbent bytes, captured before a scored
+ * rewrite's materialize step OVERWRITES an existing SKILL.md. Present
+ * only when the sequence was about to displace content; the rollback
+ * restores the incumbent BODY from it, not just its existence. Absent
+ * on markers written before rewrites existed, and on sequences whose
+ * materialize target did not exist.
+ */
+ readonly priorContentPath?: string;
}
const JOURNAL_SCHEMA_VERSION = 1;
@@ -99,6 +151,8 @@ export function writeSkillAcceptJournal(vault: string, entry: SkillAcceptJournal
// is still readable by the build that shipped the key.
procedure_existed: entry.materializedExisted,
...(entry.materializedPath !== undefined ? { materialized_path: entry.materializedPath } : {}),
+ ...(entry.skillsRoot !== undefined ? { skills_root: entry.skillsRoot } : {}),
+ ...(entry.priorContentPath !== undefined ? { prior_content_path: entry.priorContentPath } : {}),
};
atomicWriteFileSync(path, `${JSON.stringify(payload, null, 2)}\n`);
}
@@ -114,11 +168,16 @@ export function removeSkillAcceptJournalFile(vault: string, path: string): void
rmSync(ensureInsideVault(path, vault), { force: true });
}
-/** Remove the journal for `slug`. Idempotent. */
+/**
+ * Remove the journal for `slug`, and the prior-content copy beside it
+ * when a rewrite captured one. Idempotent: both removals are forced, so
+ * clearing a journal that never captured anything is not an error.
+ */
export function clearSkillAcceptJournal(vault: string, slug: string): void {
// Vault-identity write guard (context-integrity-gates, Unit J).
assertVaultIdentityForWrite(vault);
rmSync(skillAcceptJournalPath(vault, slug), { force: true });
+ rmSync(skillAcceptPriorContentPath(vault, slug), { force: true });
}
/** Registry code for a marker file this module cannot parse. */
@@ -180,12 +239,16 @@ export function readSkillAcceptJournals(vault: string): SkillAcceptJournalState
if (!existsSync(dir)) {
return Object.freeze({ entries: Object.freeze([]), unreadable: Object.freeze([]) });
}
+ // Resolved once per read: the DEFAULT skills root, used by the
+ // parse-time materialized-path guard when a marker records no root of
+ // its own (legacy markers, procedure materializations).
+ const defaultSkillsRoot = resolveJournalSkillsRoot(vault);
const entries: SkillAcceptJournalEntry[] = [];
const unreadable: UnreadableSkillAcceptJournal[] = [];
for (const name of readdirSync(dir).toSorted()) {
if (!name.endsWith(JOURNAL_SUFFIX)) continue;
const path = join(dir, name);
- const parsed = parseJournal(path);
+ const parsed = parseJournal(path, vault, defaultSkillsRoot);
if ("detail" in parsed) unreadable.push(parsed);
else entries.push(parsed);
}
@@ -205,7 +268,11 @@ export function listSkillAcceptJournals(vault: string): ReadonlyArray<SkillAccep
return state.entries;
}
-function parseJournal(path: string): SkillAcceptJournalEntry | UnreadableSkillAcceptJournal {
+function parseJournal(
+ path: string,
+ vault: string,
+ defaultSkillsRoot: string,
+): SkillAcceptJournalEntry | UnreadableSkillAcceptJournal {
let raw: Record<string, unknown>;
try {
raw = JSON.parse(readFileSync(path, "utf8")) as Record<string, unknown>;
@@ -229,15 +296,109 @@ function parseJournal(path: string): SkillAcceptJournalEntry | UnreadableSkillAc
return Object.freeze({ path, detail: "a required field is missing or of the wrong type" });
}
const materializedPath = raw["materialized_path"];
+ const priorContentPath = raw["prior_content_path"];
+ const skillsRoot = raw["skills_root"];
+ const recordedSkillsRoot =
+ typeof skillsRoot === "string" && skillsRoot.length > 0 ? skillsRoot : undefined;
+ const materializedExisted = raw["procedure_existed"] === true;
+ // The rollback's rmSync is the one sink a hand-edited path reaches with
+ // no at-use guard in front of it. The restore branch validates its own
+ // target (security audit M4), and once the target existed mid-sequence
+ // the path feeds nothing else - so the parse boundary refuses an
+ // unproducible path exactly where the deletion sink reads it, against
+ // the skills root the marker itself records when present, else the
+ // default resolution.
+ if (!materializedExisted && typeof materializedPath === "string" && materializedPath.length > 0) {
+ const refusal = refusedMaterializedPathDetail(
+ materializedPath,
+ vault,
+ recordedSkillsRoot ?? defaultSkillsRoot,
+ recordedSkillsRoot !== undefined,
+ );
+ if (refusal !== null) return Object.freeze({ path, detail: refusal });
+ }
return Object.freeze({
slug,
id,
phase: phase as SkillAcceptPhase,
startedAt,
acceptedExisted: raw["accepted_existed"] === true,
- materializedExisted: raw["procedure_existed"] === true,
+ materializedExisted,
...(typeof materializedPath === "string" && materializedPath.length > 0
? { materializedPath }
: {}),
+ ...(recordedSkillsRoot !== undefined ? { skillsRoot: recordedSkillsRoot } : {}),
+ ...(typeof priorContentPath === "string" && priorContentPath.length > 0
+ ? { priorContentPath }
+ : {}),
});
}
+
+/**
+ * The DEFAULT skills root, used by the parse-time guard when a marker
+ * records no root of its own: the configured override, else the vault's
+ * own skills subtree. The same resolution a legacy accept performed, so
+ * the guard admits exactly the paths such an accept can write.
+ */
+function resolveJournalSkillsRoot(vault: string): string {
+ return resolveSkillsDir() ?? join(vault, "Brain", "skills");
+}
+
+/**
+ * The parse-time refusal for a journal-supplied `materialized_path` on a
+ * marker whose target did not exist (the rollback's deletion shape), or
+ * null when the accept sequence itself could have written it.
+ *
+ * `skillsRoot` is the root the marker itself recorded when it names one,
+ * else the default resolution; `skillsRootRecorded` says which. A value
+ * the module cannot have produced is refused at the boundary both readers
+ * share, before any recovery touches the filesystem: a relative value (the
+ * module writes only absolute paths), or an absolute path resolving
+ * outside the vault and that root - except on a LEGACY marker, where the
+ * one shape recovery cannot re-derive stays admissible: a `mature_page`
+ * materialization under a caller's override skills root the marker cannot
+ * name, recognized as an absolute path ending in the skill page filename
+ * (this also keeps legacy markers readable across a skills-dir config
+ * change between accept and recovery). A marker that records its root
+ * needs no such escape: its recorded root bounds the materialize tree, and
+ * only the module's own shape inside it is admitted.
+ */
+function refusedMaterializedPathDetail(
+ value: string,
+ vault: string,
+ skillsRoot: string,
+ skillsRootRecorded: boolean,
+): string | null {
+ if (!isAbsolute(value)) {
+ return (
+ `materialized_path '${value}' is not an absolute path; the accept sequence writes only ` +
+ "absolute paths, so this marker was hand-edited and is not a recovery input"
+ );
+ }
+ if (isLexicallyInside(value, vault)) return null;
+ if (isLexicallyInside(value, skillsRoot)) {
+ if (!skillsRootRecorded) return null;
+ if (basename(value) === SKILL_FILE_NAME) return null;
+ } else if (!skillsRootRecorded && basename(value) === SKILL_FILE_NAME) {
+ return null;
+ }
+ return skillsRootRecorded
+ ? `materialized_path '${value}' resolves outside the vault and the skills root the accept ` +
+ `recorded (${skillsRoot}) and is not a materialized ${SKILL_FILE_NAME} path; ` +
+ "a hand-edited journal is not a recovery input"
+ : `materialized_path '${value}' resolves outside the vault and the skills root ` +
+ `(${skillsRoot}) and is not a materialized ${SKILL_FILE_NAME} path; a hand-edited ` +
+ "journal is not a recovery input";
+}
+
+/**
+ * Lexical containment of `target` inside `root`, mirroring the rollback
+ * confinement predicate in `skill-proposals` (`isLexicallyInside` there):
+ * `path.resolve` normalisation plus the platform separator, so the
+ * parse-time guard and the at-use guard admit the same paths.
+ */
+function isLexicallyInside(target: string, root: string): boolean {
+ const resolvedTarget = resolve(target);
+ const resolvedRoot = resolve(root) + sep;
+ return resolvedTarget.startsWith(resolvedRoot);
+}
diff --git a/src/core/brain/skill-proposals.ts b/src/core/brain/skill-proposals.ts
index 9b74e634..5b53303c 100644
--- a/src/core/brain/skill-proposals.ts
+++ b/src/core/brain/skill-proposals.ts
@@ -9,16 +9,33 @@ import {
rmSync,
unlinkSync,
} from "node:fs";
-import { basename, dirname, join, relative } from "node:path";
+import { basename, dirname, join, relative, resolve, sep } from "node:path";
import { parseFrontmatter, slugify, writeFrontmatterAtomic } from "../vault.ts";
import { resolveSkillsDir } from "../config.ts";
import { SKILL_FILE_NAME } from "../surface/skills.ts";
import { atomicWriteFileSync } from "../fs-atomic.ts";
import { ensureInsideVault } from "../path-safety.ts";
+import { sha256Hex } from "../integrity/digest.ts";
import { verifySkillProposalCandidate } from "./skill-proposal-verifier.ts";
import { rebuildProceduralHints } from "./procedural-hints.ts";
import { rebuildProceduralGraph } from "./procedural-graph.ts";
+import type { RewriteGradeRecordPayload } from "./skill-rewrite.ts";
+import {
+ isSkillRewriteVerdict,
+ parseSkillRewriteSpec,
+ skillRewriteSpecHash,
+ verifyRewriteTake,
+ SKILL_REWRITE_METRIC,
+ SKILL_REWRITE_VERDICT,
+ type SkillRewriteSpec,
+ type SkillRewriteVerdict,
+} from "./skill-rewrite-spec.ts";
+import {
+ parseSkillBenchmarkTasks,
+ SKILL_BENCHMARK_SPEC_FILE,
+ skillBenchmarkRelPath,
+} from "./skill-rewrite-tasks.ts";
import {
listProceduralMemory,
proceduralEntryId,
@@ -39,14 +56,23 @@ import {
BRAIN_SKILL_PROPOSALS_REL,
procedurePath,
proposalWatermarkPath,
+ SHA256_HEX_RE,
skillAcceptJournalPath,
+ skillAcceptPriorContentPath,
+ skillBenchmarkSpecPath,
+ skillBenchmarkTasksPath,
skillProposalAcceptedPath,
skillProposalPendingPath,
skillProposalRejectedPath,
} from "./paths.ts";
import { JSONL_LEDGER_EXT, resolveAppendShardId, shardedFileName } from "./ledger-shards.ts";
import { assertVaultIdentityForWrite } from "./vault-identity.ts";
-import { listContinuityRecords, type ContinuityRecord } from "./continuity/store.ts";
+import {
+ appendContinuityRecord,
+ listContinuityRecords,
+ type ContinuityRecord,
+} from "./continuity/store.ts";
+import type { ContinuityPayload } from "./continuity/types.ts";
/**
* Pattern kind stamped on a proposal an author DECLARED through an
@@ -87,13 +113,36 @@ export const DECLARED_MARKER_PATTERN_KIND = "declared_marker";
*/
export const MATURE_PAGE_PATTERN_KIND = "mature_page";
+/**
+ * Pattern kind stamped on a proposal a benchmark-gated rewrite staged
+ * (agent-presence, Lane A) after the candidate won the selection gate
+ * and passed the held-out check.
+ *
+ * Like the declared and mature-page kinds it sits outside the mining
+ * verifier: its evidence is the preregistered benchmark receipt - the
+ * frozen spec hash and the three scores the gate decided on, carried in
+ * the frontmatter - not a continuity pattern, so a record-counting gate
+ * over it would reject every rewrite and make the lane a silent no-op.
+ * The gates that DO apply are the mechanical ones upstream of staging
+ * (the task-set receipt, the dev selection margin, the single held-out
+ * check) and the human one downstream: nothing lands on an incumbent
+ * skill until `acceptSkillProposal`.
+ *
+ * This is the one pattern kind whose acceptance OVERWRITES: it
+ * materializes a `SKILL.md` over the incumbent, so the accept journal
+ * captures the prior bytes first ({@link SkillAcceptJournalEntry.priorContentPath})
+ * and the rollback restores content, not just existence.
+ */
+export const SCORED_REWRITE_PATTERN_KIND = "scored_rewrite";
+
export type SkillProposalPatternKind =
| "repeated_action"
| "structural_similarity"
| "co_occurrence"
| "temporal_routine"
| typeof DECLARED_MARKER_PATTERN_KIND
- | typeof MATURE_PAGE_PATTERN_KIND;
+ | typeof MATURE_PAGE_PATTERN_KIND
+ | typeof SCORED_REWRITE_PATTERN_KIND;
/** The three phases a proposal file can live in, most terminal first. */
const PROPOSAL_PHASES = ["accepted", "rejected", "pending"] as const;
@@ -551,6 +600,49 @@ const SKILL_DRAFT_NAME_KEY = "skill_name";
const SKILL_DRAFT_DESCRIPTION_KEY = "skill_description";
const SKILL_DRAFT_TRIGGERS_KEY = "skill_triggers";
+/**
+ * Frontmatter keys of a MATERIALIZED `SKILL.md` - the incumbent spelling
+ * the accept materializer writes and every later reader of that file
+ * (the rewrite incumbent reader among them) must use. Declared beside the
+ * draft keys because this exact split - proposal-only `skill_*` spellings
+ * versus the incumbent's own - is what a mixed-up reader and writer pair
+ * would corrupt.
+ */
+const SKILL_DESCRIPTION_KEY = "description";
+const SKILL_TRIGGERS_KEY = "triggers";
+
+/**
+ * Scored-contract keys a `scored_rewrite` proposal carries beside the
+ * SKILL.md draft fields: which skill it rewrites, the spec hash the gate
+ * verified against, the three rates the gate decided on, and the sha-256
+ * of the staged document itself (the candidate binding - see
+ * {@link SKILL_CANDIDATE_SHA_KEY}). The writer and the accept-time
+ * validation are the only readers, so a second spelling would put an
+ * unreviewable claim on a working skill.
+ */
+const SKILL_REWRITES_SKILL_KEY = "rewrites_skill";
+const SKILL_SPEC_HASH_KEY = "spec_hash";
+const SKILL_BASELINE_SCORE_KEY = "baseline_score";
+const SKILL_CANDIDATE_SCORE_KEY = "candidate_score";
+const SKILL_HELDOUT_SCORE_KEY = "heldout_score";
+
+/**
+ * The candidate binding a `scored_rewrite` proposal stamps at staging:
+ * the sha-256 of the proposal document's body as written, whose
+ * `Suggested skill body` section IS the candidate the gate promoted.
+ * The accept-time gate recomputes it over the pending file's current
+ * bytes (so a post-staging edit is refused by name) and requires the
+ * matched promote grade record to carry the same value (so an older
+ * round's promote over a different candidate cannot bless this one).
+ * A digest is not content: it binds the candidate without carrying it.
+ */
+const SKILL_CANDIDATE_SHA_KEY = "candidate_sha256";
+
+/** The fixed three-decimal spelling a gate rate carries in frontmatter. */
+function formatRewriteScore(score: number): string {
+ return score.toFixed(3);
+}
+
/**
* A skill's `name` becomes a DIRECTORY under the skills root, so it is
* not free text. Declared here rather than beside the drafting check in
@@ -642,6 +734,227 @@ export function draftMaturePageSkillProposal(
return { id: plan.id, slug: plan.slug, path: plan.path, outcome: "created" };
}
+/** One rewritten skill draft, as a won gate round submits it for staging. */
+export interface ScoredRewriteSkillDraft {
+ /** Skill directory name; validated as such before anything is written. */
+ readonly name: string;
+ /** One-line description, carried verbatim into the SKILL.md frontmatter. */
+ readonly description: string;
+ /** Trigger keywords, carried verbatim into the SKILL.md frontmatter. */
+ readonly triggers: ReadonlyArray<string>;
+ /** The candidate SKILL.md body the gate round scored. */
+ readonly body: string;
+}
+
+export interface ScoredRewriteProposalInput {
+ /** The candidate the selection and held-out gates just promoted. */
+ readonly skill: ScoredRewriteSkillDraft;
+ /** The preregistration this round verified against (`verifyRewriteTake`). */
+ readonly spec: SkillRewriteSpec;
+ /** The spec hash stamped on the proposal, the grade record and the accept. */
+ readonly specHash: string;
+ readonly baselineScore: number;
+ readonly candidateScore: number;
+ readonly heldoutScore: number;
+ /**
+ * The incumbent SKILL.md's current `version`. The staged proposal carries
+ * one more, so the accept-time materialize lands the bumped version the
+ * evolve precedent expects - the version is decided at the gate, not at
+ * the accept, because the receipt that pinned it is the gate's.
+ */
+ readonly incumbentVersion: number;
+ readonly now?: Date;
+}
+
+/**
+ * What staging a scored rewrite produced. A `created` outcome carries the
+ * candidate binding (`documentSha256`) the staged proposal was stamped
+ * with: the gate round hands it to the grade record it appends next, so
+ * the promote record and the pending proposal name the same bytes.
+ */
+export type ScoredRewriteStagingResult = DeclaredSkillProposalResultBase &
+ (
+ | { readonly outcome: "created"; readonly documentSha256: string }
+ | { readonly outcome: "deduped" }
+ /** `reason` is required here: a decline the caller cannot explain is a silent drop. */
+ | { readonly outcome: "suppressed"; readonly reason: string }
+ );
+
+/**
+ * Stage a PENDING proposal from a benchmark-gated rewrite round that WON
+ * (agent-presence, Lane A).
+ *
+ * The write lands in `pending` and nowhere else, exactly like every other
+ * producer in this module: the skills root may sit outside the vault, and
+ * nothing automatic writes there - only {@link acceptSkillProposal}, on an
+ * explicit human accept, through the write-ahead journal. Because a
+ * `scored_rewrite` accept OVERWRITES an incumbent SKILL.md, the accept
+ * captures the incumbent bytes first ({@link SkillAcceptJournalEntry.priorContentPath})
+ * and its rollback restores content, not just existence.
+ *
+ * Identity is the declared path's, with one extension: the payload hash
+ * mixes in the spec hash and the three scores, so re-running the same
+ * gate on a changed receipt or a different result is a DIFFERENT proposal
+ * (a fresh reviewable artifact), while an identical re-stage dedupes to
+ * the one already pending. A sticky human rejection of the name still
+ * suppresses the whole family.
+ *
+ * The scores are written as fixed three-decimal strings: they are the
+ * frozen claims of a completed gate run, and a human reviewing the pending
+ * file reads them against the grade record, never recomputes them.
+ *
+ * The staged document is stamped with its own sha-256
+ * ({@link SKILL_CANDIDATE_SHA_KEY}) and the digest is returned beside the
+ * usual fields: the accept-time gate recomputes it over the pending bytes
+ * and requires the promote grade record to carry the same value, which is
+ * what stops an older round's promote from blessing a different candidate
+ * (review round-2, M1 residual R1).
+ */
+export function stageScoredRewriteProposal(
+ vault: string,
+ input: ScoredRewriteProposalInput,
+): ScoredRewriteStagingResult {
+ // Vault-identity write guard (context-integrity-gates, Unit J).
+ assertVaultIdentityForWrite(vault);
+ const name = input.skill.name.trim();
+ if (!name) {
+ throw new DeclaredSkillProposalError("scored rewrite proposal requires a skill name");
+ }
+ if (!SKILL_NAME_RE.test(name)) {
+ throw new DeclaredSkillProposalError(
+ `scored rewrite proposal '${name}' is not a skill directory name ` +
+ "(lowercase letters, digits and single hyphens)",
+ );
+ }
+ const body = input.skill.body.trim();
+ if (!body) {
+ throw new DeclaredSkillProposalError(`scored rewrite proposal '${name}' has no candidate body`);
+ }
+ const description = input.skill.description.trim();
+ if (!description) {
+ throw new DeclaredSkillProposalError(`scored rewrite proposal '${name}' has no description`);
+ }
+ if (typeof input.specHash !== "string" || input.specHash.length === 0) {
+ // The receipt location is named because the fix is re-reading it, not
+ // re-typing it: the hash must be the one `skillRewriteSpecHash` stamped.
+ throw new DeclaredSkillProposalError(
+ `scored rewrite proposal '${name}' requires the spec hash of the frozen receipt at ` +
+ skillBenchmarkRelPath(name, SKILL_BENCHMARK_SPEC_FILE),
+ );
+ }
+ for (const [label, score] of [
+ ["baseline", input.baselineScore],
+ ["candidate", input.candidateScore],
+ ["held-out", input.heldoutScore],
+ ] as const) {
+ if (typeof score !== "number" || !Number.isFinite(score) || score < 0 || score > 1) {
+ throw new DeclaredSkillProposalError(
+ `scored rewrite proposal '${name}' has a ${label} score that is not a number in [0, 1]: ` +
+ JSON.stringify(score),
+ );
+ }
+ }
+ if (
+ typeof input.incumbentVersion !== "number" ||
+ !Number.isInteger(input.incumbentVersion) ||
+ input.incumbentVersion < 1
+ ) {
+ throw new DeclaredSkillProposalError(
+ `scored rewrite proposal '${name}' has an incumbent version that is not a positive integer: ` +
+ JSON.stringify(input.incumbentVersion),
+ );
+ }
+
+ const salt = JSON.stringify({
+ specHash: input.specHash,
+ baseline: input.baselineScore,
+ candidate: input.candidateScore,
+ heldout: input.heldoutScore,
+ });
+ const planned = planDeclaredSkillProposal(
+ vault,
+ { name, body, sourceRefs: [] },
+ SCORED_REWRITE_PATTERN_KIND,
+ { payloadSalt: salt },
+ );
+ if ("declined" in planned) {
+ const declined = planned.declined;
+ // A re-stage declines only as a suppressed family or as a dedupe (an
+ // identical pending copy already there). The explicit reconstruction
+ // keeps the returned shape honest: a "created" decline would mean a
+ // freshly planned proposal was never written, which no caller could
+ // act on, so it refuses instead of wearing a borrowed shape.
+ if (declined.outcome === "suppressed") return declined;
+ if (declined.outcome !== "deduped") {
+ throw new DeclaredSkillProposalError(
+ `scored rewrite proposal '${name}' could not be staged: the planner declined a ` +
+ "freshly planned proposal",
+ );
+ }
+ return { id: declined.id, slug: declined.slug, path: declined.path, outcome: "deduped" };
+ }
+ const plan = planned.plan;
+
+ const now = (input.now ?? new Date()).toISOString();
+ const triggers = input.skill.triggers.map((t) => t.trim()).filter((t) => t.length > 0);
+ const fmt = formatRewriteScore;
+
+ // The candidate binding is computed over the EXACT document body this
+ // call writes: the parse round-trip (`formatFrontmatter` out,
+ // `parseFrontmatter` back) is byte-exact for this shape, so the accept
+ // gate can recompute the same digest over the pending file and refuse
+ // any post-staging edit. The document's Suggested skill body section is
+ // the candidate verbatim, so this binds the grade history to the
+ // candidate bytes without carrying them.
+ const document = renderProposalDocument({
+ title: plan.name,
+ patternKind: SCORED_REWRITE_PATTERN_KIND,
+ key: plan.key,
+ suggestedBody: body.split("\n"),
+ evidence: [
+ `- spec ${input.specHash} (seed ${input.spec.seed}, ${input.spec.splitRule})`,
+ `- baseline ${fmt(input.baselineScore)} / candidate ${fmt(input.candidateScore)} / ` +
+ `held-out ${fmt(input.heldoutScore)}`,
+ ],
+ });
+ const documentSha256 = sha256Hex(document);
+
+ writeFrontmatterAtomic(
+ plan.path,
+ {
+ schema_version: 1,
+ kind: "brain-skill-proposal",
+ id: plan.id,
+ slug: plan.slug,
+ status: "pending",
+ pattern_kind: SCORED_REWRITE_PATTERN_KIND,
+ name_key: plan.nameKey,
+ version: input.incumbentVersion + 1,
+ payload_hash: plan.payloadHash,
+ created_at: now,
+ updated_at: now,
+ evidence_count: "2",
+ [SKILL_DRAFT_NAME_KEY]: plan.name,
+ [SKILL_DRAFT_DESCRIPTION_KEY]: description,
+ [SKILL_DRAFT_TRIGGERS_KEY]: triggers,
+ [SKILL_REWRITES_SKILL_KEY]: plan.name,
+ [SKILL_SPEC_HASH_KEY]: input.specHash,
+ [SKILL_BASELINE_SCORE_KEY]: fmt(input.baselineScore),
+ [SKILL_CANDIDATE_SCORE_KEY]: fmt(input.candidateScore),
+ [SKILL_HELDOUT_SCORE_KEY]: fmt(input.heldoutScore),
+ [SKILL_CANDIDATE_SHA_KEY]: documentSha256,
+ },
+ document,
+ {
+ overwrite: false,
+ existsErrorKind: "skill proposal",
+ vaultForRelativePath: vault,
+ },
+ );
+
+ return { id: plan.id, slug: plan.slug, path: plan.path, outcome: "created", documentSha256 };
+}
+
/**
* What {@link draftDeclaredSkillProposal} would do, without writing.
*
@@ -685,6 +998,7 @@ function planDeclaredSkillProposal(
vault: string,
input: DeclaredSkillProposalInput,
patternKind: SkillProposalPatternKind = DECLARED_MARKER_PATTERN_KIND,
+ opts: { readonly payloadSalt?: string } = {},
):
| { readonly plan: DeclaredSkillProposalPlan }
| { readonly declined: DeclaredSkillProposalResult } {
@@ -695,8 +1009,41 @@ function planDeclaredSkillProposal(
const key = slugify(name);
const nameKey = nameKeyFor(patternKind, key);
+ // The payload hash is computed BEFORE the phase loop because a scored
+ // rewrite's ACCEPTED-phase suppression key needs it: an accepted rewrite
+ // must not pin the skill against the next changed candidate the gate's
+ // iterative mode stages, so acceptance suppresses on the complete
+ // payload identity (skill, body and salt) instead of the name alone.
+ // The pending and rejected phases keep the family match - one pending
+ // overwrite per skill at a time (two accepted drafts would stamp the
+ // same version over one SKILL.md and the second would silently drop the
+ // first) and an operator reject is sticky for the whole rewrite family,
+ // per the design. The family match also covers pending and rejected
+ // proposals staged before the payload key existed; a same-payload
+ // re-stage against a LEGACY accepted proposal is still caught by the
+ // slug-occupancy guard below, because an identical payload derives the
+ // identical slug. The salt joins the hashed payload ONLY when a
+ // producer supplies one, so the declared and mature-page hashes stay
+ // byte-identical to the pre-rewrite spellings.
+ const payloadHash = createHash("sha256")
+ .update(
+ JSON.stringify(
+ opts.payloadSalt !== undefined
+ ? { patternKind, key, body, salt: opts.payloadSalt }
+ : { patternKind, key, body },
+ ),
+ "utf8",
+ )
+ .digest("hex");
+ const rewritePayloadKey = `${nameKey}:${payloadHash}`;
+ const isScoredRewrite = patternKind === SCORED_REWRITE_PATTERN_KIND;
for (const phase of PROPOSAL_PHASES) {
- const existing = findProposalByNameKey(vault, phase, nameKey);
+ const existing = findProposalByNameKey(
+ vault,
+ phase,
+ isScoredRewrite && phase === "accepted" ? rewritePayloadKey : nameKey,
+ isScoredRewrite && phase !== "accepted",
+ );
if (existing === null) continue;
const found = { id: existing.id, slug: existing.slug, path: existing.path };
if (phase === "pending") return { declined: { ...found, outcome: "deduped" } };
@@ -711,9 +1058,6 @@ function planDeclaredSkillProposal(
};
}
- const payloadHash = createHash("sha256")
- .update(JSON.stringify({ patternKind, key, body }), "utf8")
- .digest("hex");
const slug = composeProposalSlug(patternKind, key, payloadHash);
const id = `prop-${slug}`;
@@ -741,7 +1085,7 @@ function planDeclaredSkillProposal(
name,
body,
key,
- nameKey,
+ nameKey: isScoredRewrite ? rewritePayloadKey : nameKey,
payloadHash,
},
};
@@ -788,6 +1132,11 @@ export function acceptSkillProposal(
if (fm["kind"] !== "brain-skill-proposal") {
throw new Error(`invalid skill proposal file: ${pendingPath}`);
}
+ // A scored rewrite is the one pattern kind whose acceptance OVERWRITES
+ // an incumbent: its scored contract is validated before the journal is
+ // stamped, so a corrupted draft cannot half-accept.
+ const isRewrite = fm["pattern_kind"] === SCORED_REWRITE_PATTERN_KIND;
+ if (isRewrite) validateScoredRewriteContract(fm);
const id = typeof fm["id"] === "string" ? fm["id"] : `prop-${slug}`;
const version = parseVersion(fm["version"]);
const acceptedPath = skillProposalAcceptedPath(vault, slug);
@@ -795,10 +1144,22 @@ export function acceptSkillProposal(
// proposal's pattern kind, once, here - so the journal, the write and
// the returned result all name the same file.
const skillDraft = readSkillDraft(fm);
+ // The rest of the gate is re-verified against the CURRENT vault state
+ // before the journal is stamped (review security M1): field presence
+ // and score ranges alone never overwrite an incumbent skill. A forged
+ // or stale scored_rewrite is refused here by name, with nothing
+ // written and the draft left pending for the operator.
+ if (isRewrite && skillDraft !== null) {
+ verifyScoredRewriteGate(vault, fm, skillDraft.name, body);
+ }
+ // The resolved root rides the journal for skill materializations:
+ // recovery must check the journal's path against the tree THIS accept
+ // used, not re-derive a root the caller may have resolved differently.
+ const skillsRoot = resolveSkillsRoot(vault, opts.skillsRoot);
const materializedPath =
skillDraft === null
? procedurePath(vault, slug)
- : join(resolveSkillsRoot(vault, opts.skillsRoot), skillDraft.name, SKILL_FILE_NAME);
+ : join(skillsRoot, skillDraft.name, SKILL_FILE_NAME);
let journal: SkillAcceptJournalEntry = {
slug,
@@ -810,6 +1171,9 @@ export function acceptSkillProposal(
acceptedExisted: existsSync(acceptedPath),
materializedExisted: existsSync(materializedPath),
materializedPath,
+ // Procedure materializations never consult the skills tree, so they
+ // record no root and recovery keeps its default resolution for them.
+ ...(skillDraft !== null ? { skillsRoot } : {}),
};
writeSkillAcceptJournal(vault, journal);
@@ -833,6 +1197,21 @@ export function acceptSkillProposal(
},
);
+ // Rewrite overwrite discipline: while the incumbent still exists,
+ // capture its bytes vault-side and stamp the journal with the copy's
+ // path BEFORE the overwrite - so a crash after the overwrite rolls
+ // back to the incumbent BODY, not just to its existence. The capture
+ // precedes the stamp deliberately: a crash in between leaves an
+ // orphan copy and an overwrite that never happened, which the next
+ // pass clears; the reverse order would leave a journal promising a
+ // copy that is not there.
+ if (isRewrite && journal.materializedExisted) {
+ const priorPath = skillAcceptPriorContentPath(vault, slug);
+ mkdirSync(dirname(priorPath), { recursive: true });
+ atomicWriteFileSync(priorPath, readFileSync(materializedPath, "utf8"));
+ journal = { ...journal, priorContentPath: priorPath };
+ }
+
journal = { ...journal, phase: "materialize" };
writeSkillAcceptJournal(vault, journal);
if (skillDraft === null) {
@@ -864,13 +1243,20 @@ export function acceptSkillProposal(
// still not free-form: `skillDraft.name` was validated as a skill
// directory name before the proposal was staged, and the root comes
// from config, never from the payload.
+ //
+ // A scored_rewrite is the ONE overwrite in this module: it replaces
+ // an incumbent SKILL.md, and only after the journal captured the
+ // incumbent bytes above. Every other producer here is still
+ // exclusive-create.
mkdirSync(dirname(materializedPath), { recursive: true });
writeFrontmatterAtomic(
materializedPath,
{
name: skillDraft.name,
- description: skillDraft.description,
- ...(skillDraft.triggers.length > 0 ? { triggers: skillDraft.triggers } : {}),
+ [SKILL_DESCRIPTION_KEY]: skillDraft.description,
+ ...(skillDraft.triggers.length > 0
+ ? { [SKILL_TRIGGERS_KEY]: skillDraft.triggers }
+ : {}),
source_proposal: id,
version,
created_at: now,
@@ -878,7 +1264,7 @@ export function acceptSkillProposal(
...contract,
},
renderAcceptedSkillBody(id, skillDraft.name, body),
- { overwrite: false, existsErrorKind: "skill" },
+ { overwrite: isRewrite, existsErrorKind: "skill" },
);
}
@@ -1054,6 +1440,13 @@ function resolveSkillAccept(
// Non-empty or already gone; either way nothing more to undo.
}
}
+ } else if (journal.priorContentPath !== undefined) {
+ // The incumbent EXISTED and a scored rewrite may have replaced its
+ // bytes mid-sequence: restore the captured incumbent body. This is
+ // the one rollback in the module that restores CONTENT, not just
+ // existence - a rewrite that could only be undone by deleting the
+ // incumbent would be worse than the crash it recovers from.
+ restorePriorSkillContent(vault, journal);
}
clearSkillAcceptJournal(vault, journal.slug);
return "rolled_back";
@@ -1064,6 +1457,79 @@ function resolveSkillAccept(
return "completed";
}
+/**
+ * Restore an incumbent SKILL.md's bytes from the journal's prior-content
+ * copy. Caller must already hold the accept lock and know
+ * `journal.priorContentPath` is set.
+ *
+ * A missing or unreadable copy is NOT papered over: the rollback would
+ * otherwise silently leave the CANDIDATE body on an incumbent's path,
+ * which is the one outcome worse than the crash being recovered from.
+ * Throwing keeps the journal on disk (the resolver's callers retain it),
+ * so the operator decides with the copy gone - the same named refusal
+ * posture as an unreadable journal marker.
+ */
+function restorePriorSkillContent(vault: string, journal: SkillAcceptJournalEntry): void {
+ const priorPath = journal.priorContentPath;
+ if (priorPath === undefined) return;
+ // The copy is a vault artifact the accept sequence wrote; a path that
+ // escapes the vault is a hand-edited journal, not a recovery input.
+ const source = ensureInsideVault(priorPath, vault);
+ let prior: string;
+ try {
+ prior = readFileSync(source, "utf8");
+ } catch (error) {
+ throw new Error(
+ `skill proposal accept rollback for '${journal.slug}' cannot restore the incumbent body: ` +
+ `the prior-content copy is missing or unreadable (${errorMessage(error)}); ` +
+ `journal retained for recovery: ${skillAcceptJournalPath(vault, journal.slug)}`,
+ { cause: error },
+ );
+ }
+ const target = journal.materializedPath;
+ if (target === undefined) {
+ throw new Error(
+ `skill proposal accept rollback for '${journal.slug}' cannot restore the incumbent body: ` +
+ `the journal records no materialized path; journal retained for recovery: ` +
+ skillAcceptJournalPath(vault, journal.slug),
+ );
+ }
+ // The target is a journal-supplied string, read from the same
+ // agent-writable file as the source above, so it gets the same distrust
+ // (review security M4): a restore may only land inside the vault or the
+ // skills root the materialize step itself resolved - the root the
+ // journal records, else the default resolution for a legacy marker that
+ // names none. A hand-edited journal is not a recovery input.
+ const skillsRoot = journal.skillsRoot ?? resolveSkillsRoot(vault, undefined);
+ if (!isLexicallyInside(target, vault) && !isLexicallyInside(target, skillsRoot)) {
+ throw new Error(
+ `skill proposal accept rollback for '${journal.slug}' refuses the journal's materialized ` +
+ `path ${target}: a restore target must resolve inside the vault or the skills root ` +
+ `(${skillsRoot}); a hand-edited journal is not a recovery input. ` +
+ `Journal retained for recovery: ${skillAcceptJournalPath(vault, journal.slug)}`,
+ );
+ }
+ // The restore rides the shared atomic writer: an interrupted rollback
+ // leaves either the incumbent or the candidate, never a hybrid.
+ atomicWriteFileSync(target, prior);
+}
+
+/**
+ * Lexical containment of `target` inside `root`, resolved the way
+ * `ensureInsideVault` resolves before it checks. The rollback validation
+ * is a pure path predicate - the target usually exists (it holds the
+ * candidate bytes), but the guard must not depend on that - and the
+ * symlink sweep is intentionally not repeated here: the accept that wrote
+ * the journal already refused symlinked skills roots, and the restore
+ * rides the rename-based atomic writer, which replaces a swapped-in link
+ * rather than following it.
+ */
+function isLexicallyInside(target: string, root: string): boolean {
+ const resolvedTarget = resolve(target);
+ const resolvedRoot = resolve(root) + sep;
+ return resolvedTarget.startsWith(resolvedRoot);
+}
+
/**
* Inline compensation for a THROWN step. Always rethrows: either the
* original error once the sequence has been resolved, or - when the
@@ -1160,6 +1626,371 @@ export function resolveSkillProposalEvidence(vault: string, slug: string): Skill
});
}
+export interface SkillRewriteGradeRecordInput {
+ /** The assembled gate-run payload from `buildRewriteGradeRecord`. */
+ readonly payload: RewriteGradeRecordPayload;
+ readonly now?: Date;
+}
+
+/**
+ * Append one `skill_rewrite_eval_grade` continuity record for a completed
+ * gate run (agent-presence, Lane A).
+ *
+ * This is the ONLY thing a failed gate round writes: a `hold` or a short
+ * `not_enough_evidence` stages nothing - the pending-proposal tree is
+ * untouched - so an operator can audit why a rewrite did not land by
+ * reading the record alone.
+ *
+ * The payload is REBUILT field by field from a validated input, never
+ * spread: the record carries identifiers, numbers, booleans and check ids
+ * with the spec hash, and anything else in the caller's object - task
+ * text, transcript text, an extra diagnostic blob - is dropped by
+ * construction rather than filtered after the fact. A malformed field is
+ * a named error, because a grade record with a junk rate in it is worse
+ * than no record: it is the evidence a human accept reads.
+ */
+export function recordSkillRewriteGrade(
+ vault: string,
+ input: SkillRewriteGradeRecordInput,
+): ContinuityRecord {
+ // Vault-identity write guard (context-integrity-gates, Unit J).
+ assertVaultIdentityForWrite(vault);
+ const payload = validateRewriteGradePayload(input.payload);
+ return appendContinuityRecord(vault, {
+ kind: "skill_rewrite_eval_grade",
+ createdAt: (input.now ?? new Date()).toISOString(),
+ payload,
+ });
+}
+
+/** One rebuilt per-task grade row: ids and check verdicts only. */
+function rebuildGradeTaskRow(
+ row: unknown,
+ arm: string,
+): {
+ readonly task_id: string;
+ readonly passed: boolean;
+ readonly failed_checks: ReadonlyArray<string>;
+} {
+ const raw = (row ?? {}) as Record<string, unknown>;
+ const taskId = raw["task_id"];
+ if (typeof taskId !== "string" || taskId.trim().length === 0) {
+ throw new Error(`skill rewrite grade record has a ${arm} row without a task id`);
+ }
+ const passed = raw["passed"];
+ if (typeof passed !== "boolean") {
+ throw new Error(
+ `skill rewrite grade record has a ${arm} row for '${taskId}' without a boolean 'passed'`,
+ );
+ }
+ const failedChecks = raw["failed_checks"];
+ if (
+ !Array.isArray(failedChecks) ||
+ failedChecks.some((check) => typeof check !== "string" || check.trim().length === 0)
+ ) {
+ throw new Error(
+ `skill rewrite grade record has a ${arm} row for '${taskId}' whose failed checks are not check-id strings`,
+ );
+ }
+ return { task_id: taskId, passed, failed_checks: [...failedChecks] };
+}
+
+function validateRewriteGradePayload(payload: RewriteGradeRecordPayload): ContinuityPayload {
+ if (typeof payload.skill !== "string" || !SKILL_NAME_RE.test(payload.skill)) {
+ throw new Error(
+ `skill rewrite grade record has a skill name that is not a skill directory name: ` +
+ JSON.stringify(payload.skill ?? null),
+ );
+ }
+ for (const field of ["spec_hash", "tasks_hash", "split_rule"] as const) {
+ const value = payload[field];
+ if (typeof value !== "string" || value.trim().length === 0) {
+ throw new Error(`skill rewrite grade record is missing '${field}'`);
+ }
+ }
+ if (payload.metric !== SKILL_REWRITE_METRIC) {
+ throw new Error(
+ `skill rewrite grade record has a metric other than '${SKILL_REWRITE_METRIC}': ` +
+ JSON.stringify(payload.metric ?? null),
+ );
+ }
+ if (typeof payload.seed !== "number" || !Number.isInteger(payload.seed) || payload.seed < 0) {
+ throw new Error(
+ `skill rewrite grade record has a seed that is not a non-negative integer: ` +
+ JSON.stringify(payload.seed ?? null),
+ );
+ }
+ if (!isSkillRewriteVerdict(payload.verdict)) {
+ throw new Error(
+ `skill rewrite grade record has an unknown verdict: ${JSON.stringify(payload.verdict ?? null)}`,
+ );
+ }
+ for (const field of ["baseline_rate", "candidate_rate"] as const) {
+ const rate = payload[field];
+ if (typeof rate !== "number" || !Number.isFinite(rate) || rate < 0 || rate > 1) {
+ throw new Error(
+ `skill rewrite grade record has a '${field}' that is not a number in [0, 1]: ` +
+ JSON.stringify(rate ?? null),
+ );
+ }
+ }
+ if (!Array.isArray(payload.dev) || !Array.isArray(payload.held_out)) {
+ throw new Error("skill rewrite grade record is missing its dev or held-out task rows");
+ }
+ // The candidate binding (review round-2, M1 residual R1): present only
+ // on the record a final promote wrote beside its staged proposal - hold
+ // rounds stage nothing and bind nothing. The accept-time grade match
+ // requires it, so a promote record without one can never satisfy an
+ // accept (fail-closed), and a malformed value refuses here at write
+ // time rather than failing a match later.
+ const candidateSha = payload.candidate_sha256;
+ if (
+ candidateSha !== undefined &&
+ (typeof candidateSha !== "string" || !SHA256_HEX_RE.test(candidateSha))
+ ) {
+ throw new Error(
+ `skill rewrite grade record has a 'candidate_sha256' that is not a sha-256 hex digest: ` +
+ JSON.stringify(candidateSha),
+ );
+ }
+ return Object.freeze({
+ skill: payload.skill,
+ spec_hash: payload.spec_hash,
+ tasks_hash: payload.tasks_hash,
+ metric: payload.metric,
+ seed: payload.seed,
+ split_rule: payload.split_rule,
+ verdict: payload.verdict,
+ baseline_rate: payload.baseline_rate,
+ candidate_rate: payload.candidate_rate,
+ dev: Object.freeze(payload.dev.map((row) => rebuildGradeTaskRow(row, "dev"))),
+ held_out: Object.freeze(payload.held_out.map((row) => rebuildGradeTaskRow(row, "held-out"))),
+ ...(candidateSha !== undefined ? { candidate_sha256: candidateSha } : {}),
+ });
+}
+
+export interface RewriteIncumbent {
+ readonly body: string;
+ readonly version: number;
+ readonly path: string;
+ /** Present when the incumbent frontmatter carries a usable description. */
+ readonly description?: string;
+ /** Present when the incumbent frontmatter carries usable triggers. */
+ readonly triggers?: ReadonlyArray<string>;
+}
+
+/**
+ * Read an incumbent SKILL.md as a rewrite round's baseline: its body (the
+ * baseline round's prompt text) and its `version` (what the staged
+ * proposal bumps).
+ *
+ * A rewrite gates the CANDIDATE against the INCUMBENT, so a skill with no
+ * incumbent is not a rewrite target and is refused by name rather than
+ * gated against nothing. This is the CLI and MCP face of the same
+ * resolution `acceptSkillProposal` uses, so the surfaces cannot disagree
+ * about where the incumbent lives.
+ */
+export function readRewriteIncumbent(
+ vault: string,
+ skillName: string,
+ opts: { readonly skillsRoot?: string } = {},
+): RewriteIncumbent {
+ if (!SKILL_NAME_RE.test(skillName)) {
+ throw new DeclaredSkillProposalError(
+ `rewrite incumbent requires a skill directory name ` +
+ `(lowercase letters, digits and single hyphens): ${JSON.stringify(skillName)}`,
+ );
+ }
+ const path = join(resolveSkillsRoot(vault, opts.skillsRoot), skillName, SKILL_FILE_NAME);
+ if (!existsSync(path)) {
+ throw new DeclaredSkillProposalError(
+ `no incumbent SKILL.md for '${skillName}' at ${path}; a rewrite gates a candidate ` +
+ "against an existing skill, not a fresh one",
+ );
+ }
+ const [fm, body] = parseFrontmatter(path);
+ // Unlike the proposal paths, there is no default here: the incumbent's
+ // version is what the staged proposal bumps, and inventing one would
+ // silently rewrite a skill's history. A corrupted incumbent is refused.
+ const versionRaw = fm["version"];
+ const version =
+ typeof versionRaw === "number"
+ ? versionRaw
+ : typeof versionRaw === "string"
+ ? Number.parseInt(versionRaw, 10)
+ : Number.NaN;
+ if (!Number.isInteger(version) || version < 1) {
+ throw new DeclaredSkillProposalError(
+ `the incumbent SKILL.md for '${skillName}' has no usable version frontmatter at ${path}`,
+ );
+ }
+ // The incumbent's OWN frontmatter keys, not the proposal-only draft
+ // spellings (`skill_description`/`skill_triggers` exist on staged
+ // proposals; a materialized SKILL.md carries `description`/`triggers`,
+ // the same keys the accept materializer writes below). Reading the draft
+ // keys made every real incumbent read as undescribed, so the staged
+ // rewrite wore the placeholder description and an empty trigger list,
+ // and the accept overwrote the incumbent's identity with them.
+ const description = fm[SKILL_DESCRIPTION_KEY];
+ const triggersRaw = fm[SKILL_TRIGGERS_KEY];
+ const triggers = Array.isArray(triggersRaw)
+ ? triggersRaw.filter((t): t is string => typeof t === "string" && t.trim().length > 0)
+ : typeof triggersRaw === "string" && triggersRaw.trim().length > 0
+ ? [triggersRaw.trim()]
+ : [];
+ return {
+ body,
+ version,
+ path,
+ ...(typeof description === "string" && description.trim().length > 0
+ ? { description: description.trim() }
+ : {}),
+ ...(triggers.length > 0 ? { triggers } : {}),
+ };
+}
+
+// ----- the rewrite status read (agent-presence, Lane A) -------------------------
+
+/** The frozen receipt as the read-only surfaces report it. */
+export interface SkillRewriteStatusReceipt {
+ readonly schema_version: string;
+ readonly tasks_hash: string;
+ readonly spec_hash: string;
+ readonly seed: number;
+ readonly split_rule: string;
+ readonly dev_task_ids: ReadonlyArray<string>;
+ readonly heldout_task_ids: ReadonlyArray<string>;
+ readonly required_margin: number;
+ readonly min_dev_tasks: number;
+ /** Whether the CURRENT task set still matches the receipt's frozen hash. */
+ readonly take_verifies: boolean;
+ readonly take_reason: string | null;
+}
+
+/** One completed gate run, as the read-only surfaces report it. */
+export interface SkillRewriteStatusGrade {
+ readonly created_at: string;
+ readonly verdict: SkillRewriteVerdict;
+ readonly baseline_rate: number;
+ readonly candidate_rate: number;
+ readonly spec_hash: string;
+}
+
+export interface SkillRewriteStatus {
+ readonly skill: string;
+ /** Null when the skill has no benchmark yet - a named empty, not an error. */
+ readonly receipt: SkillRewriteStatusReceipt | null;
+ /** Completed gate runs for this skill, oldest first, capped at the last 10. */
+ readonly grades: ReadonlyArray<SkillRewriteStatusGrade>;
+ /**
+ * Grade rows for this skill that failed the writer's own payload
+ * validation - external corruption only, since the writer rebuilds
+ * every field. They are dropped from `grades` (never rendered as a
+ * verdict) and counted here; doctor and the continuity reader are the
+ * surfaces that name the cause.
+ */
+ readonly unreadable_grades: number;
+ /** The slug of a staged-but-unaccepted scored_rewrite proposal, if any. */
+ readonly pending_rewrite_slug: string | null;
+}
+
+export const SKILL_REWRITE_STATUS_GRADE_CAP = 10;
+
+/**
+ * Read one skill's rewrite lane status: the verified receipt, the grade
+ * ledger's rows for this skill, and whether a rewrite proposal is sitting
+ * in pending awaiting a human accept.
+ *
+ * READ-ONLY, and deliberately terse: identifiers, hashes and rates - the
+ * same discipline as the grade record itself. The per-task check rows stay
+ * in the ledger where the accept review reads them; a status surface that
+ * dumped every task row on every call would be a bounded-output refusal
+ * waiting to happen, and would add nothing a human accept needs.
+ */
+export function readSkillRewriteStatus(vault: string, skillName: string): SkillRewriteStatus {
+ if (!SKILL_NAME_RE.test(skillName)) {
+ throw new DeclaredSkillProposalError(
+ `skill rewrite status requires a skill directory name ` +
+ `(lowercase letters, digits and single hyphens): ${JSON.stringify(skillName)}`,
+ );
+ }
+
+ let receipt: SkillRewriteStatusReceipt | null = null;
+ const tasksPath = skillBenchmarkTasksPath(vault, skillName);
+ const specPath = skillBenchmarkSpecPath(vault, skillName);
+ if (existsSync(tasksPath) && existsSync(specPath)) {
+ const tasks = parseSkillBenchmarkTasks(JSON.parse(readFileSync(tasksPath, "utf8")), tasksPath);
+ const spec = parseSkillRewriteSpec(JSON.parse(readFileSync(specPath, "utf8")), specPath);
+ const take = verifyRewriteTake(spec, tasks);
+ receipt = {
+ schema_version: spec.schemaVersion,
+ tasks_hash: spec.tasksHash,
+ spec_hash: skillRewriteSpecHash(spec),
+ seed: spec.seed,
+ split_rule: spec.splitRule,
+ dev_task_ids: spec.devTaskIds,
+ heldout_task_ids: spec.heldoutTaskIds,
+ required_margin: spec.requiredMargin,
+ min_dev_tasks: spec.minDevTasks,
+ take_verifies: take.ok,
+ take_reason: take.reason,
+ };
+ }
+
+ // Every row the status renders is re-validated with the writer's own
+ // boundary (validateRewriteGradePayload): the writer rebuilds each
+ // payload field by field, so a row that fails here is external
+ // corruption, and coercing it to a plausible verdict with zeroed rates
+ // would render corrupted grade history as ordinary gate output on the
+ // exact surface a human consults before accepting a rewrite. Such a
+ // row is dropped from `grades` and counted in `unreadable_grades`
+ // instead; the validator's cause text stays on the operator surfaces.
+ const gradeRows = listContinuityRecords(vault, { kind: "skill_rewrite_eval_grade" }).filter(
+ (record) => (record.payload as Record<string, unknown>)["skill"] === skillName,
+ );
+ const grades: SkillRewriteStatusGrade[] = [];
+ let unreadableGrades = 0;
+ for (const record of gradeRows) {
+ try {
+ // The validator's frozen return is the rebuilt payload; the cast
+ // only re-attaches the field types its own checks just proved.
+ const payload = validateRewriteGradePayload(
+ record.payload as unknown as RewriteGradeRecordPayload,
+ ) as unknown as RewriteGradeRecordPayload;
+ grades.push({
+ created_at: record.createdAt,
+ verdict: payload.verdict,
+ baseline_rate: payload.baseline_rate,
+ candidate_rate: payload.candidate_rate,
+ spec_hash: payload.spec_hash,
+ });
+ } catch {
+ unreadableGrades += 1;
+ }
+ }
+ const cappedGrades = grades.slice(-SKILL_REWRITE_STATUS_GRADE_CAP);
+
+ // The pending match reads the proposal's own `rewrites_skill` key: the
+ // name key would do, but the frontmatter claim is what the reviewer saw.
+ let pendingSlug: string | null = null;
+ for (const proposal of listPendingSkillProposals(vault)) {
+ if (proposal.patternKind !== SCORED_REWRITE_PATTERN_KIND) continue;
+ const [fm] = parseFrontmatter(skillProposalPendingPath(vault, proposal.slug));
+ if (fm[SKILL_REWRITES_SKILL_KEY] === skillName) {
+ pendingSlug = proposal.slug;
+ break;
+ }
+ }
+
+ return {
+ skill: skillName,
+ receipt,
+ grades: cappedGrades,
+ unreadable_grades: unreadableGrades,
+ pending_rewrite_slug: pendingSlug,
+ };
+}
+
function outcomeState(successes: number, failures: number): SkillEvidenceOutcomeState {
if (successes === 0 && failures === 0) return "unrecorded";
if (successes > 0 && failures > 0) return "mixed";
@@ -1337,11 +2168,21 @@ interface FoundProposal {
readonly body: string;
}
-/** Find the first proposal in `phase` whose stored name key matches. */
+/**
+ * Find the first proposal in `phase` whose stored name key matches.
+ *
+ * `familyPrefix` widens the match to the key's family: the stored key
+ * equals `nameKey` or carries it as the prefix before a `:` separator,
+ * which is the shape a scored rewrite's payload-scoped key
+ * (`<family>:<payload hash>`) shares with its bare family key. The
+ * rejected phase needs the family match - an operator reject is sticky
+ * for the skill name, not for one payload.
+ */
function findProposalByNameKey(
vault: string,
phase: SkillProposalPhase,
nameKey: string,
+ familyPrefix = false,
): FoundProposal | null {
const dir = ensureInsideVault(join(vault, BRAIN_SKILL_PROPOSALS_REL, phase), vault);
if (!existsSync(dir)) return null;
@@ -1350,7 +2191,11 @@ function findProposalByNameKey(
const path = ensureInsideVault(join(dir, name), vault);
const [fm, body] = parseFrontmatter(path);
if (fm["kind"] !== "brain-skill-proposal") continue;
- if (fm["name_key"] !== nameKey) continue;
+ const stored = fm["name_key"];
+ const matches =
+ stored === nameKey ||
+ (familyPrefix === true && typeof stored === "string" && stored.startsWith(`${nameKey}:`));
+ if (!matches) continue;
const slug =
typeof fm["slug"] === "string" ? fm["slug"] : name.replace(/^prop-/, "").replace(/\.md$/, "");
const id = typeof fm["id"] === "string" ? fm["id"] : `prop-${slug}`;
@@ -1664,13 +2509,14 @@ function candidateHash(candidate: ProposalCandidate): string {
}
/**
- * The SKILL.md contract a `mature_page` proposal carries, or null when the
- * proposal is not one - which is how the accept path chooses its
- * materializer. A proposal stamped `mature_page` but missing either
- * required field is a corrupted draft, not a procedure: it is refused by
- * name rather than materialized into the wrong tree.
+ * The SKILL.md contract a `mature_page` or `scored_rewrite` proposal
+ * carries, or null when the proposal is not one - which is how the accept
+ * path chooses its materializer. A proposal stamped with either skill
+ * kind but missing a required field is a corrupted draft, not a
+ * procedure: it is refused by name rather than materialized into the
+ * wrong tree.
*
- * The name's charset is re-checked here even though the draft path
+ * The name's charset is re-checked here even though the draft paths
* already refused anything else. This is the one write in the accept
* sequence that passes no `vaultForRelativePath` - the skills root may
* legitimately sit outside the vault - so the confinement check every
@@ -1681,7 +2527,12 @@ function candidateHash(candidate: ProposalCandidate): string {
function readSkillDraft(
fm: Readonly<Record<string, unknown>>,
): { name: string; description: string; triggers: string[] } | null {
- if (fm["pattern_kind"] !== MATURE_PAGE_PATTERN_KIND) return null;
+ if (
+ fm["pattern_kind"] !== MATURE_PAGE_PATTERN_KIND &&
+ fm["pattern_kind"] !== SCORED_REWRITE_PATTERN_KIND
+ ) {
+ return null;
+ }
const name = fm[SKILL_DRAFT_NAME_KEY];
const description = fm[SKILL_DRAFT_DESCRIPTION_KEY];
if (typeof name !== "string" || name.trim().length === 0) {
@@ -1706,6 +2557,198 @@ function readSkillDraft(
return { name: trimmedName, description: description.trim(), triggers };
}
+/**
+ * The scored contract a `scored_rewrite` proposal must carry at accept:
+ * which skill it rewrites, the spec hash it was gated against, and the
+ * three rates the gate decided on. Validated BEFORE the accept journal is
+ * stamped - a pending file missing any field is a corrupted draft, and
+ * the human accept must refuse it by name rather than overwrite an
+ * incumbent skill on an unverifiable claim.
+ *
+ * The rewrite claim and the materialize target must also name the SAME
+ * skill (review security M1d): staging writes both from one name, so a
+ * pending file where they diverge is hand-edited, and the divergence would
+ * aim the one overwrite in this module at a directory the receipt never
+ * mentioned.
+ */
+function validateScoredRewriteContract(fm: Readonly<Record<string, unknown>>): void {
+ const rewrites = fm[SKILL_REWRITES_SKILL_KEY];
+ if (typeof rewrites !== "string" || rewrites.trim().length === 0) {
+ throw new Error(`scored rewrite proposal is missing '${SKILL_REWRITES_SKILL_KEY}'`);
+ }
+ const specHash = fm[SKILL_SPEC_HASH_KEY];
+ if (typeof specHash !== "string" || specHash.trim().length === 0) {
+ throw new Error(`scored rewrite proposal is missing '${SKILL_SPEC_HASH_KEY}'`);
+ }
+ const candidateSha = fm[SKILL_CANDIDATE_SHA_KEY];
+ if (typeof candidateSha !== "string" || !SHA256_HEX_RE.test(candidateSha)) {
+ throw new Error(
+ `scored rewrite proposal is missing or malformed '${SKILL_CANDIDATE_SHA_KEY}'; the ` +
+ "candidate binding is what stops an older promote from blessing a different " +
+ "candidate, so a proposal without it predates the binding and its gate round " +
+ "must be re-run before this skill can be accepted",
+ );
+ }
+ const draftName = fm[SKILL_DRAFT_NAME_KEY];
+ if (rewrites !== draftName) {
+ throw new Error(
+ `scored rewrite proposal claims to rewrite '${String(rewrites)}' but its ` +
+ `'${SKILL_DRAFT_NAME_KEY}' materializes '${String(draftName)}'; ` +
+ "the two must name the same skill",
+ );
+ }
+ for (const key of [
+ SKILL_BASELINE_SCORE_KEY,
+ SKILL_CANDIDATE_SCORE_KEY,
+ SKILL_HELDOUT_SCORE_KEY,
+ ]) {
+ const value = fm[key];
+ const score = typeof value === "string" ? Number(value) : value;
+ if (typeof score !== "number" || !Number.isFinite(score) || score < 0 || score > 1) {
+ throw new Error(
+ `scored rewrite proposal has a '${key}' that is not a number in [0, 1]: ` +
+ JSON.stringify(value ?? null),
+ );
+ }
+ }
+}
+
+/**
+ * How closely a grade record's rate must sit to the proposal's
+ * three-decimal score for the two to be the same rate: the staged proposal
+ * carries the rate rounded to three places, so anything within half of the
+ * last written digit is the same number.
+ */
+const SCORE_MATCH_TOLERANCE = 0.0005 + Number.EPSILON;
+
+/**
+ * Re-verify a `scored_rewrite` proposal's gate claims against the CURRENT
+ * vault state at accept (review security M1).
+ *
+ * `validateScoredRewriteContract` proves the proposal's six fields exist
+ * and are shaped right; a hand-forged pending file passes that trivially.
+ * This is the part that cannot be forged into existence by editing one
+ * file, because it re-reads the vault:
+ *
+ * 1. the benchmark receipt on disk must still hash to the proposal's
+ * `spec_hash` - a swapped task set or an edited spec invalidates the
+ * proposal instead of quietly re-scoping its claim - and the take
+ * must still verify against the live task set;
+ * 2. the pending document must still be the bytes staging stamped: the
+ * recomputed sha-256 of the proposal body must equal the frontmatter
+ * `candidate_sha256`, so a candidate body swapped in after staging
+ * (the pending file is agent-writable) is refused by name;
+ * 3. the grade history must hold the gate's final promote for THIS
+ * proposal: a `skill_rewrite_eval_grade` record with verdict
+ * `promote`, the same spec hash and skill, a candidate rate that
+ * matches the proposal's candidate score, AND the same
+ * `candidate_sha256` binding. Rates collide - a historical promote
+ * over a different candidate at the same rate must not bless this
+ * one (review round-2, M1 residual R1) - but a document digest can
+ * only match the round that promoted these exact bytes. No promote
+ * record with this binding, no accept.
+ *
+ * Every refusal fires BEFORE the accept journal is stamped, so a refused
+ * accept writes nothing: the incumbent is untouched and the draft stays
+ * pending for the operator to judge. The residual is stated rather than
+ * hidden: an agent that can also forge the benchmark documents and the
+ * grade store can forge these inputs too - the MCP accept refusal is the
+ * boundary that removes this path from the agent's reach entirely.
+ */
+function verifyScoredRewriteGate(
+ vault: string,
+ fm: Readonly<Record<string, unknown>>,
+ skillName: string,
+ proposalBody: string,
+): void {
+ const specHash = String(fm[SKILL_SPEC_HASH_KEY]);
+ const tasksPath = skillBenchmarkTasksPath(vault, skillName);
+ const specPath = skillBenchmarkSpecPath(vault, skillName);
+ let spec: SkillRewriteSpec;
+ let tasks: ReturnType<typeof parseSkillBenchmarkTasks>;
+ try {
+ tasks = parseSkillBenchmarkTasks(JSON.parse(readFileSync(tasksPath, "utf8")), tasksPath);
+ spec = parseSkillRewriteSpec(JSON.parse(readFileSync(specPath, "utf8")), specPath);
+ } catch (error) {
+ throw new Error(
+ `scored rewrite gate for '${skillName}': the benchmark documents cannot be read to ` +
+ `re-verify the proposal's receipt against ${skillBenchmarkRelPath(skillName, "")} ` +
+ `(${errorMessage(error)}); the accept is refused`,
+ { cause: error },
+ );
+ }
+ const liveHash = skillRewriteSpecHash(spec);
+ if (liveHash !== specHash) {
+ throw new Error(
+ `scored rewrite gate for '${skillName}': the proposal's spec hash ${specHash} does not ` +
+ `match the benchmark receipt on disk (${liveHash}); a swapped task set or an edited ` +
+ "spec invalidates the proposal, so the accept is refused",
+ );
+ }
+ const take = verifyRewriteTake(spec, tasks);
+ if (!take.ok) {
+ throw new Error(
+ `scored rewrite gate for '${skillName}': the benchmark take no longer verifies ` +
+ `(${take.reason ?? "receipt mismatch"}); the accept is refused`,
+ );
+ }
+ // The candidate binding, recomputed over the pending file's CURRENT
+ // bytes: `parseFrontmatter` trims, and `formatFrontmatter` round-trips
+ // this document shape byte-exactly, so an unedited proposal recomputes
+ // the value staging stamped, and any post-staging edit - a swapped
+ // candidate body above all - breaks it.
+ const liveCandidateSha = sha256Hex(proposalBody);
+ const stagedCandidateSha = fm[SKILL_CANDIDATE_SHA_KEY];
+ if (stagedCandidateSha !== liveCandidateSha) {
+ throw new Error(
+ `scored rewrite gate for '${skillName}': the proposal's '${SKILL_CANDIDATE_SHA_KEY}' ` +
+ `(${String(stagedCandidateSha)}) does not match the pending document's bytes ` +
+ `(${liveCandidateSha}); the document was edited after staging, so the accept is ` +
+ "refused and the operator should re-run the gate round",
+ );
+ }
+ const candidateScore = Number(fm[SKILL_CANDIDATE_SCORE_KEY]);
+ const hasPromote = listContinuityRecords(vault, { kind: "skill_rewrite_eval_grade" }).some(
+ (record) => {
+ const payload = record.payload as Record<string, unknown>;
+ return (
+ payload["skill"] === skillName &&
+ payload["spec_hash"] === specHash &&
+ payload["verdict"] === SKILL_REWRITE_VERDICT.promote &&
+ typeof payload["candidate_rate"] === "number" &&
+ Math.abs(payload["candidate_rate"] - candidateScore) <= SCORE_MATCH_TOLERANCE &&
+ // The binding: a promote record from an earlier round over a
+ // DIFFERENT candidate body with the same rate satisfies every
+ // check above - rates collide, document digests do not.
+ payload[SKILL_CANDIDATE_SHA_KEY] === liveCandidateSha
+ );
+ },
+ );
+ if (!hasPromote) {
+ throw new Error(
+ `scored rewrite gate for '${skillName}': no skill_rewrite_eval_grade record with verdict ` +
+ `'${SKILL_REWRITE_VERDICT.promote}' matches this proposal's spec hash ${specHash}, ` +
+ `candidate rate ${candidateScore} and candidate_sha256 ${liveCandidateSha}; the gate's ` +
+ "final promote is missing from the grade history - or it was earned over a different " +
+ "candidate - so the accept is refused",
+ );
+ }
+}
+
+/**
+ * The pattern kind of the pending proposal at `slug`, or null when no
+ * readable pending file is there. Read by the MCP surface so it can
+ * refuse `scored_rewrite` accepts at the boundary the design names -
+ * MCP proposes, the operator accepts - without re-deriving the proposal
+ * paths or re-parsing frontmatter spelling rules outside this module.
+ */
+export function pendingSkillProposalPatternKind(vault: string, slug: string): string | null {
+ const pendingPath = skillProposalPendingPath(vault, slug);
+ if (!existsSync(pendingPath)) return null;
+ const [fm] = parseFrontmatter(pendingPath);
+ return typeof fm["pattern_kind"] === "string" ? fm["pattern_kind"] : null;
+}
+
/**
* Where an accepted `mature_page` skill is materialized: the caller's
* override, else the configured `skills_dir`, else the vault's own
diff --git a/src/core/brain/skill-rewrite-spec.ts b/src/core/brain/skill-rewrite-spec.ts
new file mode 100644
index 00000000..b0034dcb
--- /dev/null
+++ b/src/core/brain/skill-rewrite-spec.ts
@@ -0,0 +1,323 @@
+/**
+ * The preregistered skill-rewrite spec (agent-presence, Lane A).
+ *
+ * "Preregistered" is a commitment with mechanical teeth, copied from the
+ * decision-model eval specs: before any gate runs, a spec freezes (a) the
+ * content hash of the skill's committed benchmark task set, (b) the seed
+ * and the hash-order dev/held-out split rule with the derived membership
+ * as a frozen receipt, and (c) the selection gate's constants - the
+ * required margin and the minimum dev n. The whole spec is content-
+ * hashed; every grade record and every staged rewrite proposal stamps
+ * that hash, so a spec edited after grades were seen invalidates them
+ * instead of quietly re-scoping the claim.
+ *
+ * The dev arm is the only split the optimizer ever sees: envelopes are
+ * built from the receipt's dev members, and the held-out members are
+ * read exactly once, by the held-out gate on the candidate that earned
+ * promotion. The rule is the same pure derivation the decision-model
+ * take uses - rank ids by `sha256Hex(seed + ":" + id)`, ties by id, the
+ * first `ceil(0.7 n)` are dev - so the receipt compares equal regardless
+ * of derivation order.
+ *
+ * This module is a TRUE LEAF above the task kernel: it imports only the
+ * one digest encoding and `skill-rewrite-tasks.ts`. The import graph
+ * cannot grow a cycle rooted here.
+ */
+
+import { canonicalJson, sha256Hex } from "../integrity/digest.ts";
+import { SKILL_BENCH_SKILL_NAME_RE, type SkillBenchmarkTaskSet } from "./skill-rewrite-tasks.ts";
+
+/** Bumped on any deliberate re-registration; part of the spec hash. */
+export const SKILL_REWRITE_SPEC_SCHEMA = "o2b.skill-rewrite.v1";
+
+/** The only split rule this build derives receipts with. */
+export const SKILL_REWRITE_SPLIT_RULE = "hash-order-70-30";
+
+/** The only selection metric this build writes grade records for. */
+export const SKILL_REWRITE_METRIC = "tasks_passed_rate";
+
+/** Dev share of the task set; the held-out remainder is checked once. */
+export const SKILL_REWRITE_DEV_FRACTION = 0.7;
+
+/**
+ * The candidate must beat the baseline by MORE than this rate margin on
+ * the dev arm before promotion is on the table. A tie - and anything
+ * under the margin - holds.
+ */
+export const SKILL_REWRITE_REQUIRED_MARGIN = 0.1;
+
+/** Minimum dev tasks with scored transcripts on BOTH arms, below which
+ * the verdict is `not_enough_evidence` - a short dev n is its own arm,
+ * never a pass. */
+export const SKILL_REWRITE_MIN_DEV_TASKS = 2;
+
+/** The split seed when the operator names none. A constant, so the same
+ * task set always derives the same receipt. */
+export const SKILL_REWRITE_DEFAULT_SEED = 0;
+
+/**
+ * Minimum task count for which the 70-30 split leaves BOTH arms
+ * non-empty (ceil(0.7 n) < n first holds at n = 4: 3 dev, 1 held-out).
+ * Below it a spec would freeze a gate that can never run its held-out
+ * check, so building one is refused by name.
+ */
+export const SKILL_REWRITE_MIN_TASKS = 4;
+
+/**
+ * The preregistered three-arm verdict, the same shape the decision-model
+ * eval keeps: a candidate promotes only by a strict beat of the pinned
+ * margin with the dev n met, a tie holds, and a short dev n is not
+ * evidence of anything.
+ */
+export const SKILL_REWRITE_VERDICT = Object.freeze({
+ promote: "promote",
+ hold: "hold",
+ not_enough_evidence: "not_enough_evidence",
+} as const);
+
+export type SkillRewriteVerdict =
+ (typeof SKILL_REWRITE_VERDICT)[keyof typeof SKILL_REWRITE_VERDICT];
+
+/** The verdict members, for guard sharing and output validation. */
+export const SKILL_REWRITE_VERDICTS: ReadonlyArray<SkillRewriteVerdict> = Object.freeze(
+ Object.values(SKILL_REWRITE_VERDICT),
+);
+
+export function isSkillRewriteVerdict(value: unknown): value is SkillRewriteVerdict {
+ return (
+ typeof value === "string" && (SKILL_REWRITE_VERDICTS as ReadonlyArray<string>).includes(value)
+ );
+}
+
+/** sha-256 hex digest length. */
+const HASH_HEX_LENGTH = 64;
+const HASH_HEX_RE = new RegExp(`^[0-9a-f]{${HASH_HEX_LENGTH}}$`);
+
+/** The frozen receipt a gate run is held to. */
+export interface SkillRewriteSpec {
+ readonly schemaVersion: string;
+ readonly skillName: string;
+ /** sha256 over the canonical task list, frozen at preregistration. */
+ readonly tasksHash: string;
+ readonly seed: number;
+ readonly splitRule: string;
+ /** Dev members, sorted lexicographically. Envelopes see these only. */
+ readonly devTaskIds: ReadonlyArray<string>;
+ /** Held-out members, sorted lexicographically. Read by the one-shot
+ * held-out gate; never placed in an envelope before it. */
+ readonly heldoutTaskIds: ReadonlyArray<string>;
+ readonly requiredMargin: number;
+ readonly minDevTasks: number;
+}
+
+/**
+ * Build the spec for a parsed task set: hash the set, derive the split
+ * from the seed, freeze the receipt. Deterministic - the same task set
+ * and seed always produce the identical spec.
+ */
+export function buildSkillRewriteSpec(
+ skillName: string,
+ tasks: SkillBenchmarkTaskSet,
+ opts: { readonly seed?: number } = {},
+): SkillRewriteSpec {
+ if (tasks.tasks.length < SKILL_REWRITE_MIN_TASKS) {
+ throw new Error(
+ `skill rewrite spec: task set for '${skillName}' is too small to split ` +
+ `(has ${tasks.tasks.length} tasks, the ${SKILL_REWRITE_SPLIT_RULE} rule needs at least ${SKILL_REWRITE_MIN_TASKS} ` +
+ "so both arms stay non-empty)",
+ );
+ }
+ const seed = opts.seed ?? SKILL_REWRITE_DEFAULT_SEED;
+ const split = hashOrderSplit(
+ seed,
+ tasks.tasks.map((task) => task.id),
+ );
+ return Object.freeze({
+ schemaVersion: SKILL_REWRITE_SPEC_SCHEMA,
+ skillName,
+ tasksHash: tasks.hash,
+ seed,
+ splitRule: SKILL_REWRITE_SPLIT_RULE,
+ devTaskIds: split.dev,
+ heldoutTaskIds: split.heldout,
+ requiredMargin: SKILL_REWRITE_REQUIRED_MARGIN,
+ minDevTasks: SKILL_REWRITE_MIN_DEV_TASKS,
+ });
+}
+
+/**
+ * The runner-side preregistration guard: the task set must still hash to
+ * the receipt's frozen hash, still belong to the named skill, and still
+ * derive into exactly the receipted split. Any mismatch names what moved
+ * - a spec edited after grades were seen invalidates them, it never
+ * re-scopes the claim.
+ */
+export function verifyRewriteTake(
+ spec: SkillRewriteSpec,
+ tasks: SkillBenchmarkTaskSet,
+): { readonly ok: boolean; readonly reason: string | null } {
+ if (tasks.hash !== spec.tasksHash) {
+ return {
+ ok: false,
+ reason:
+ `task set hash ${tasks.hash} does not match the receipt's frozen hash ${spec.tasksHash}; ` +
+ "the benchmark changed under the spec",
+ };
+ }
+ if (tasks.skillName !== spec.skillName) {
+ return {
+ ok: false,
+ reason: `task set names skill '${tasks.skillName}' but the receipt names '${spec.skillName}'`,
+ };
+ }
+ const derived = hashOrderSplit(
+ spec.seed,
+ tasks.tasks.map((task) => task.id),
+ );
+ if (
+ !sameSortedIds(derived.dev, spec.devTaskIds) ||
+ !sameSortedIds(derived.heldout, spec.heldoutTaskIds)
+ ) {
+ return {
+ ok: false,
+ reason:
+ "the task set no longer derives into the receipted split " +
+ `(seed ${spec.seed}, rule ${spec.splitRule}); the receipt is stale`,
+ };
+ }
+ return { ok: true, reason: null };
+}
+
+/**
+ * The spec hash every grade record and staged proposal stamps: sha-256
+ * over the canonical JSON of the whole spec, so any edit - receipt,
+ * seed, margin, n floor - invalidates what came before.
+ */
+export function skillRewriteSpecHash(spec: SkillRewriteSpec): string {
+ return sha256Hex(canonicalJson(spec));
+}
+
+/**
+ * Parse a stored spec document (the JSON beside the tasks document).
+ * Field spellings match the stored file (`schema_version`,
+ * `held_out_task_ids`, ...). An unknown schema version is refused by
+ * name: a spec written by a different build is a different
+ * preregistration, not a compatible one.
+ */
+export function parseSkillRewriteSpec(raw: unknown, source: string): SkillRewriteSpec {
+ const at = (what: string): string => `skill rewrite spec (${source}): ${what}`;
+ if (raw === null || typeof raw !== "object" || Array.isArray(raw)) {
+ throw new Error(at("expected a JSON object"));
+ }
+ const record = raw as Record<string, unknown>;
+
+ if (record["schema_version"] !== SKILL_REWRITE_SPEC_SCHEMA) {
+ throw new Error(
+ at(
+ `unknown schema version ${JSON.stringify(record["schema_version"] ?? null)} ` +
+ `(expected '${SKILL_REWRITE_SPEC_SCHEMA}')`,
+ ),
+ );
+ }
+ const skillName = record["skill_name"];
+ if (typeof skillName !== "string" || !SKILL_BENCH_SKILL_NAME_RE.test(skillName)) {
+ throw new Error(at("skill_name must be a skill directory name"));
+ }
+ const tasksHash = record["tasks_hash"];
+ if (typeof tasksHash !== "string" || !HASH_HEX_RE.test(tasksHash)) {
+ throw new Error(at(`tasks_hash must be a ${HASH_HEX_LENGTH}-character sha-256 hex digest`));
+ }
+ const seed = record["seed"];
+ if (typeof seed !== "number" || !Number.isInteger(seed)) {
+ throw new Error(at("seed must be an integer"));
+ }
+ if (record["split_rule"] !== SKILL_REWRITE_SPLIT_RULE) {
+ throw new Error(at(`split rule must be '${SKILL_REWRITE_SPLIT_RULE}'`));
+ }
+ const devTaskIds = idList(record["dev_task_ids"], "dev_task_ids", at);
+ const heldoutTaskIds = idList(record["held_out_task_ids"], "held_out_task_ids", at);
+ if (devTaskIds.some((id) => heldoutTaskIds.includes(id))) {
+ throw new Error(at("dev_task_ids and held_out_task_ids must be disjoint"));
+ }
+ const requiredMargin = record["required_margin"];
+ if (
+ typeof requiredMargin !== "number" ||
+ !Number.isFinite(requiredMargin) ||
+ requiredMargin < 0 ||
+ requiredMargin >= 1
+ ) {
+ throw new Error(at("required_margin must be a number in [0, 1)"));
+ }
+ const minDevTasks = record["min_dev_tasks"];
+ if (typeof minDevTasks !== "number" || !Number.isInteger(minDevTasks) || minDevTasks < 1) {
+ throw new Error(at("min_dev_tasks must be a positive integer"));
+ }
+
+ return Object.freeze({
+ schemaVersion: SKILL_REWRITE_SPEC_SCHEMA,
+ skillName,
+ tasksHash,
+ seed,
+ splitRule: SKILL_REWRITE_SPLIT_RULE,
+ devTaskIds,
+ heldoutTaskIds,
+ requiredMargin,
+ minDevTasks,
+ });
+}
+
+// ----- the hash-order split -----------------------------------------------------
+
+interface RewriteSplit {
+ /** Dev ids, sorted lexicographically. Envelopes see these only. */
+ readonly dev: ReadonlyArray<string>;
+ /** Held-out ids, sorted lexicographically. Checked exactly once. */
+ readonly heldout: ReadonlyArray<string>;
+}
+
+/**
+ * The preregistered split: rank ids by `sha256Hex(seed + ":" + id)`
+ * (ties by id), the first `ceil(0.7 n)` are dev, the rest held out.
+ * Pure and reorder-stable; both lists come back sorted lexicographically
+ * so a receipt compares equal regardless of derivation order.
+ */
+function hashOrderSplit(seed: number, ids: ReadonlyArray<string>): RewriteSplit {
+ const ranked = ids
+ .map((id) => ({ id, hash: sha256Hex(`${seed}:${id}`) }))
+ .toSorted(
+ (left, right) =>
+ (left.hash < right.hash ? -1 : left.hash > right.hash ? 1 : 0) ||
+ left.id.localeCompare(right.id),
+ );
+ const devCount = Math.ceil(ids.length * SKILL_REWRITE_DEV_FRACTION);
+ return {
+ dev: ranked
+ .slice(0, devCount)
+ .map((entry) => entry.id)
+ .toSorted(),
+ heldout: ranked
+ .slice(devCount)
+ .map((entry) => entry.id)
+ .toSorted(),
+ };
+}
+
+/** Whether two lexicographically sorted id lists hold the same ids. */
+function sameSortedIds(left: ReadonlyArray<string>, right: ReadonlyArray<string>): boolean {
+ return left.length === right.length && left.every((id, index) => id === right[index]);
+}
+
+function idList(raw: unknown, field: string, at: (what: string) => string): ReadonlyArray<string> {
+ if (
+ !Array.isArray(raw) ||
+ raw.length === 0 ||
+ !raw.every((id) => typeof id === "string" && id.trim().length > 0)
+ ) {
+ throw new Error(at(`${field} must be a non-empty array of task ids`));
+ }
+ const list = raw as string[];
+ if (new Set(list).size !== list.length) {
+ throw new Error(at(`${field} carries a duplicate task id`));
+ }
+ return Object.freeze([...list].toSorted());
+}
diff --git a/src/core/brain/skill-rewrite-tasks.ts b/src/core/brain/skill-rewrite-tasks.ts
new file mode 100644
index 00000000..b90e9ad5
--- /dev/null
+++ b/src/core/brain/skill-rewrite-tasks.ts
@@ -0,0 +1,362 @@
+/**
+ * The per-skill benchmark task-set kernel (agent-presence, Lane A).
+ *
+ * A skill rewrite is gated by measured outcomes, never by vibes: before
+ * any candidate instructions are drafted, the skill carries a committed
+ * task set - a validated, content-hashed document listing the tasks an
+ * agent must perform while following the skill, and the structural
+ * predicates the resulting transcript must satisfy. This module is that
+ * document's only parser and its only hasher.
+ *
+ * Posture, pinned here because every later lane leans on it:
+ *
+ * - The predicates are STRUCTURAL. A check names a tool, a path shape,
+ * an order, a forbidden step, or an output field class. No check
+ * ever reads prose, and no scorer down-stream of this module ever
+ * will: task text lives in the committed fixture, opaque to the
+ * predicate layer.
+ * - The document is fail-fast: a malformed shape is a named error
+ * carrying the source the document was read from, in the
+ * `parseBenchFixture` style. Nothing partial ever reaches a spec.
+ * - The module is a TRUE LEAF: it imports only the one digest encoding
+ * and the Brain path-name constants, so the import graph cannot grow
+ * a cycle rooted here, and nothing above can be pulled in by
+ * accident - `import type` included, per the architecture ratchet.
+ *
+ * The task set's home is vault-side, `Brain/skill-benchmarks/<skill>/`,
+ * so an operator's benchmarks travel with the vault; the skills root
+ * itself may sit outside the vault and cannot carry them. The hash over
+ * the canonical task list is what a rewrite spec freezes as its receipt
+ * (`skill-rewrite-spec.ts`), so it must be stable across parses and key
+ * order and sensitive to any task byte - all three are pinned in tests.
+ */
+
+import { posix } from "node:path";
+
+import { canonicalJson, sha256Hex } from "../integrity/digest.ts";
+import { BRAIN_ROOT_REL } from "./path-constants.ts";
+
+/**
+ * The benchmark directory under `Brain/`, one skill-document folder per
+ * skill. A constant, not a literal scattered through callers: the state
+ * surface row, the paths builder and the CLI all name it from here.
+ */
+export const SKILL_BENCHMARKS_DIR = "skill-benchmarks";
+
+/** The vault-relative benchmark root: `Brain/skill-benchmarks`. */
+export const SKILL_BENCHMARKS_ROOT_REL = posix.join(BRAIN_ROOT_REL, SKILL_BENCHMARKS_DIR);
+
+/**
+ * Compose the vault-relative path of one benchmark artifact for `skill`
+ * (the tasks document, the spec receipt, a round's transcript drop site).
+ * The name was validated at parse time; composing here keeps the one
+ * spelling of the layout in the module that owns it.
+ */
+export function skillBenchmarkRelPath(skillName: string, ...segments: string[]): string {
+ return posix.join(SKILL_BENCHMARKS_ROOT_REL, skillName, ...segments);
+}
+
+/** The tasks document inside a skill's benchmark folder. */
+export const SKILL_BENCHMARK_TASKS_FILE = "tasks.json";
+/** The frozen rewrite spec beside the tasks document. */
+export const SKILL_BENCHMARK_SPEC_FILE = "spec.json";
+
+/** The closed task-kind vocabulary. One kind today; the union keeps a
+ * second kind from arriving as a string scattered across scorers. */
+export const SKILL_BENCH_TASK_KIND = Object.freeze({
+ invocation_transcript: "invocation_transcript",
+} as const);
+
+export type SkillBenchTaskKind = (typeof SKILL_BENCH_TASK_KIND)[keyof typeof SKILL_BENCH_TASK_KIND];
+
+/** The task-kind members, for parse-time refusal and guard sharing. */
+export const SKILL_BENCH_TASK_KINDS: ReadonlyArray<SkillBenchTaskKind> = Object.freeze(
+ Object.values(SKILL_BENCH_TASK_KIND),
+);
+
+export function isSkillBenchTaskKind(value: unknown): value is SkillBenchTaskKind {
+ return (
+ typeof value === "string" && (SKILL_BENCH_TASK_KINDS as ReadonlyArray<string>).includes(value)
+ );
+}
+
+/**
+ * The closed check vocabulary - the ONLY predicates a transcript is ever
+ * scored against. Structural by construction: a tool name, a path
+ * prefix, an order, a forbidden step, an output field class.
+ */
+export const SKILL_BENCH_CHECK = Object.freeze({
+ tool_used: "tool_used",
+ artifact_created: "artifact_created",
+ step_order: "step_order",
+ forbidden_step: "forbidden_step",
+ output_field: "output_field",
+} as const);
+
+export type SkillBenchCheck = (typeof SKILL_BENCH_CHECK)[keyof typeof SKILL_BENCH_CHECK];
+
+/** The check members, for parse-time refusal and guard sharing. */
+export const SKILL_BENCH_CHECKS: ReadonlyArray<SkillBenchCheck> = Object.freeze(
+ Object.values(SKILL_BENCH_CHECK),
+);
+
+export function isSkillBenchCheck(value: unknown): value is SkillBenchCheck {
+ return typeof value === "string" && (SKILL_BENCH_CHECKS as ReadonlyArray<string>).includes(value);
+}
+
+/**
+ * The closed value classes an `output_field` check can demand. Deliberately
+ * small: classes a scorer can decide without ever reading the value's
+ * content. `any` is not a member - a check that accepts anything is not a
+ * check.
+ */
+export const SKILL_BENCH_VALUE_CLASS = Object.freeze({
+ non_empty_string: "non_empty_string",
+ number: "number",
+ boolean: "boolean",
+ non_empty_array: "non_empty_array",
+} as const);
+
+export type SkillBenchValueClass =
+ (typeof SKILL_BENCH_VALUE_CLASS)[keyof typeof SKILL_BENCH_VALUE_CLASS];
+
+/** The value-class members, for parse-time refusal and guard sharing. */
+export const SKILL_BENCH_VALUE_CLASSES: ReadonlyArray<SkillBenchValueClass> = Object.freeze(
+ Object.values(SKILL_BENCH_VALUE_CLASS),
+);
+
+export function isSkillBenchValueClass(value: unknown): value is SkillBenchValueClass {
+ return (
+ typeof value === "string" &&
+ (SKILL_BENCH_VALUE_CLASSES as ReadonlyArray<string>).includes(value)
+ );
+}
+
+/**
+ * One structural predicate over the returned transcript. Field spellings
+ * match the committed JSON exactly (`path_prefix`, `value_class`) so the
+ * parse is a pass-through freeze and the canonical hash over the parsed
+ * tasks equals the hash over the document's task list.
+ */
+export type SkillBenchExpectation =
+ | { readonly check: "tool_used"; readonly tool: string }
+ | { readonly check: "artifact_created"; readonly path_prefix: string }
+ | { readonly check: "step_order"; readonly steps: ReadonlyArray<string> }
+ | { readonly check: "forbidden_step"; readonly step: string }
+ | {
+ readonly check: "output_field";
+ readonly field: string;
+ readonly value_class: SkillBenchValueClass;
+ };
+
+/** One benchmark task: what to do, and what the transcript must show. */
+export interface SkillBenchmarkTask {
+ /** Filename-safe id; names the transcript drop file for the round. */
+ readonly id: string;
+ readonly kind: SkillBenchTaskKind;
+ /** The task input, carried verbatim into the dev envelope prompt. */
+ readonly input: string;
+ readonly expects: ReadonlyArray<SkillBenchExpectation>;
+}
+
+/** A validated, content-hashed task set for one skill. */
+export interface SkillBenchmarkTaskSet {
+ readonly skillName: string;
+ readonly tasks: ReadonlyArray<SkillBenchmarkTask>;
+ /** sha256 over the canonical task list - the spec receipt's anchor. */
+ readonly hash: string;
+}
+
+/**
+ * A skill's benchmark name becomes a DIRECTORY under the benchmark root,
+ * so it follows the skill-directory rule: lowercase letters, digits and
+ * single hyphens. Spelled here rather than imported from the proposal
+ * module because this kernel is a true leaf and must not reach into the
+ * layer above; the materialize path re-checks the same rule (and has its
+ * own named constant), so a name that passes one but not the other is
+ * refused at whichever door it reaches first.
+ */
+export const SKILL_BENCH_SKILL_NAME_RE = /^[a-z0-9]+(?:-[a-z0-9]+)*$/;
+
+/**
+ * Task ids name transcript drop files inside a round directory, so they
+ * are filename-safe: letters, digits, dots, hyphens and underscores with
+ * a leading alphanumeric. No separators, no traversal.
+ */
+export const SKILL_BENCH_TASK_ID_RE = /^[A-Za-z0-9][A-Za-z0-9._-]*$/;
+
+/** The canonical content hash over a parsed task list. */
+export function skillBenchmarkTaskSetHash(tasks: ReadonlyArray<SkillBenchmarkTask>): string {
+ return sha256Hex(canonicalJson(tasks));
+}
+
+/**
+ * Parse and validate a raw task-set document. Throws named errors that
+ * always carry `source`, so an operator sees WHICH document refused.
+ */
+export function parseSkillBenchmarkTasks(raw: unknown, source: string): SkillBenchmarkTaskSet {
+ const at = (what: string): string => `skill benchmark tasks (${source}): ${what}`;
+ if (raw === null || typeof raw !== "object" || Array.isArray(raw)) {
+ throw new Error(at("expected a JSON object"));
+ }
+ const record = raw as Record<string, unknown>;
+
+ const skillName = record["skill"];
+ if (typeof skillName !== "string" || skillName.trim().length === 0) {
+ throw new Error(at("skill must be a non-empty string"));
+ }
+ if (!SKILL_BENCH_SKILL_NAME_RE.test(skillName)) {
+ throw new Error(
+ at(
+ `skill must be a skill directory name (lowercase letters, digits and single hyphens): ${JSON.stringify(skillName)}`,
+ ),
+ );
+ }
+
+ const tasksRaw = record["tasks"];
+ if (!Array.isArray(tasksRaw) || tasksRaw.length === 0) {
+ throw new Error(at("tasks must be a non-empty array"));
+ }
+
+ const tasks = tasksRaw.map((task, index) => parseTask(task, at, index));
+ const seen = new Set<string>();
+ for (const task of tasks) {
+ if (seen.has(task.id)) {
+ throw new Error(at(`duplicate task id: ${task.id}`));
+ }
+ seen.add(task.id);
+ }
+
+ return Object.freeze({
+ skillName,
+ tasks: Object.freeze(tasks),
+ hash: skillBenchmarkTaskSetHash(tasks),
+ });
+}
+
+function parseTask(raw: unknown, at: (what: string) => string, index: number): SkillBenchmarkTask {
+ if (raw === null || typeof raw !== "object" || Array.isArray(raw)) {
+ throw new Error(at(`task ${index} must be an object`));
+ }
+ const record = raw as Record<string, unknown>;
+
+ const id = record["id"];
+ if (typeof id !== "string" || id.trim().length === 0) {
+ throw new Error(at(`task ${index} needs a non-empty id`));
+ }
+ if (!SKILL_BENCH_TASK_ID_RE.test(id)) {
+ throw new Error(at(`task id must be filename-safe: ${JSON.stringify(id)}`));
+ }
+
+ if (!isSkillBenchTaskKind(record["kind"])) {
+ throw new Error(
+ at(`task ${id} has an unknown kind (expected one of ${SKILL_BENCH_TASK_KINDS.join(", ")})`),
+ );
+ }
+
+ const input = record["input"];
+ if (typeof input !== "string" || input.trim().length === 0) {
+ throw new Error(at(`task ${id} needs a non-empty input`));
+ }
+
+ const expectsRaw = record["expects"];
+ if (!Array.isArray(expectsRaw) || expectsRaw.length === 0) {
+ throw new Error(at(`task ${id} expects must be a non-empty array`));
+ }
+ const expects = expectsRaw.map((expectation) => parseExpectation(expectation, at, id));
+
+ return Object.freeze({ id, kind: record["kind"], input, expects: Object.freeze(expects) });
+}
+
+function parseExpectation(
+ raw: unknown,
+ at: (what: string) => string,
+ taskId: string,
+): SkillBenchExpectation {
+ if (raw === null || typeof raw !== "object" || Array.isArray(raw)) {
+ throw new Error(at(`task ${taskId} expectation must be an object`));
+ }
+ const record = raw as Record<string, unknown>;
+ const check = record["check"];
+ if (!isSkillBenchCheck(check)) {
+ throw new Error(
+ at(`task ${taskId} has an unknown check (expected one of ${SKILL_BENCH_CHECKS.join(", ")})`),
+ );
+ }
+ switch (check) {
+ case "tool_used": {
+ const tool = nonEmptyString(record["tool"]);
+ if (tool === undefined) throw new Error(at(`task ${taskId} tool_used needs a tool name`));
+ return Object.freeze({ check, tool });
+ }
+ case "artifact_created": {
+ const prefix = nonEmptyString(record["path_prefix"]);
+ if (prefix === undefined) {
+ throw new Error(at(`task ${taskId} artifact_created needs a path_prefix`));
+ }
+ if (isAbsoluteLike(prefix)) {
+ throw new Error(
+ at(`task ${taskId} artifact_created path_prefix must be vault-relative: ${prefix}`),
+ );
+ }
+ return Object.freeze({ check, path_prefix: prefix });
+ }
+ case "step_order": {
+ const stepsRaw = record["steps"];
+ if (
+ !Array.isArray(stepsRaw) ||
+ stepsRaw.length === 0 ||
+ !stepsRaw.every((step) => typeof step === "string" && step.trim().length > 0)
+ ) {
+ throw new Error(at(`task ${taskId} step_order steps must be a non-empty string array`));
+ }
+ const steps = stepsRaw as string[];
+ const seen = new Set<string>();
+ for (const step of steps) {
+ if (seen.has(step)) {
+ throw new Error(at(`task ${taskId} step_order carries a duplicate step: ${step}`));
+ }
+ seen.add(step);
+ }
+ return Object.freeze({ check, steps: Object.freeze([...steps]) });
+ }
+ case "forbidden_step": {
+ const step = nonEmptyString(record["step"]);
+ if (step === undefined) {
+ throw new Error(at(`task ${taskId} forbidden_step needs a step name`));
+ }
+ return Object.freeze({ check, step });
+ }
+ case "output_field": {
+ const field = nonEmptyString(record["field"]);
+ if (field === undefined) {
+ throw new Error(at(`task ${taskId} output_field needs a field name`));
+ }
+ const valueClass = record["value_class"];
+ if (!isSkillBenchValueClass(valueClass)) {
+ throw new Error(
+ at(
+ `task ${taskId} output_field has an unknown value_class (expected one of ${SKILL_BENCH_VALUE_CLASSES.join(", ")})`,
+ ),
+ );
+ }
+ return Object.freeze({ check, field, value_class: valueClass });
+ }
+ }
+}
+
+/** Non-empty-string reader used by the per-check parsers. */
+function nonEmptyString(value: unknown): string | undefined {
+ return typeof value === "string" && value.trim().length > 0 ? value.trim() : undefined;
+}
+
+/**
+ * Vault-relative shape check for an `artifact_created` prefix: no
+ * absolute form, no traversal segment, on either separator - the prefix
+ * is matched against vault-relative artifact paths, so an absolute or
+ * escaping prefix could never match and only ever misleads.
+ */
+function isAbsoluteLike(prefix: string): boolean {
+ const normalized = prefix.replaceAll("\\", "/");
+ return posix.isAbsolute(normalized) || normalized.split("/").includes("..");
+}
diff --git a/src/core/brain/skill-rewrite.ts b/src/core/brain/skill-rewrite.ts
new file mode 100644
index 00000000..248f9da7
--- /dev/null
+++ b/src/core/brain/skill-rewrite.ts
@@ -0,0 +1,793 @@
+/**
+ * The rewrite gate kernels (agent-presence, Lane A).
+ *
+ * One gated rewrite round, kernel by kernel. OSB never calls a model:
+ * the envelope builders hand the calling agent one `needs-llm-step` per
+ * task - dev members only, until the single held-out check after a
+ * promote - and the calling agent executes and submits transcripts. The
+ * scorer validates the submitted shape and grades STRUCTURAL predicates
+ * only; it refuses a submission that carries a self-reported success
+ * field, so nothing the agent claims about its own work can move the
+ * metric. Selection is the preregistered three arms from the
+ * decision-model eval, and the held-out gate runs once, on the candidate
+ * that earned promotion; a miss downgrades it.
+ *
+ * Coverage is part of the preregistration. The dev arms may only decide
+ * when every dev member has a scored transcript on BOTH arms, and the
+ * held-out gate runs only on the full held-out membership. A short dev
+ * arm - an n under the floor, or receipted ids that were never
+ * submitted - is `not_enough_evidence`, the same honest outcome either
+ * way: the comparison the receipt preregistered cannot be computed yet,
+ * and the round stays re-runnable while the missing transcripts are
+ * produced. A score for an id OUTSIDE the receipt's membership is
+ * different in kind - the arm scored something the receipt never
+ * registered - and is refused by name. The held-out gate refuses
+ * instead of holding on partial coverage, because a hold would be
+ * recorded in a grade record as a verdict the one-shot check never
+ * earned (and would leak which held-out tasks fail without the check
+ * having run in full); a refusal writes nothing.
+ *
+ * Round transcripts are bound to the candidate body they were produced
+ * against: every envelope carries `candidate_sha256`, the sha-256 of the
+ * body in its prompt, the prompt names the binding, and the scorer
+ * refuses - by name - a transcript whose `candidate_sha256` is missing
+ * or stale whenever the caller hands it the current candidate body's
+ * hash. No transcript can gate a candidate it was never run against.
+ *
+ * Every refusal here is a named {@link SkillRewriteError}: a stale task
+ * set, a phantom receipt id, a malformed submission, a self-report, a
+ * cross-arm leak, a stale or missing candidate binding, an unregistered
+ * task id, an incomplete held-out check, an unknown mode - none of them
+ * is ever a silent skip, because a gate that quietly passes is worse
+ * than no gate.
+ */
+
+import { sha256Hex } from "../integrity/digest.ts";
+import { runJsonCommandBridge } from "../reliability/command-bridge.ts";
+import { buildNeedsLlmStep, type NeedsLlmStep } from "./llm-step.ts";
+import {
+ SKILL_BENCH_CHECK,
+ skillBenchmarkRelPath,
+ SKILL_BENCHMARK_TASKS_FILE,
+ type SkillBenchExpectation,
+ type SkillBenchmarkTask,
+ type SkillBenchmarkTaskSet,
+ type SkillBenchValueClass,
+} from "./skill-rewrite-tasks.ts";
+import {
+ SKILL_REWRITE_METRIC,
+ SKILL_REWRITE_VERDICT,
+ type SkillRewriteSpec,
+ type SkillRewriteVerdict,
+} from "./skill-rewrite-spec.ts";
+
+// The verdict vocabulary rides the gate outputs: the CLI and MCP faces
+// read it from here, beside the verdicts they print.
+export {
+ isSkillRewriteVerdict,
+ SKILL_REWRITE_VERDICT,
+ SKILL_REWRITE_VERDICTS,
+} from "./skill-rewrite-spec.ts";
+
+/** The step name a rewrite task envelope answers. */
+export const SKILL_REWRITE_STEP = "skill-rewrite-task";
+
+/** Subdirectory of the skill's benchmark folder holding round transcripts. */
+export const SKILL_REWRITE_ROUNDS_DIR = "rounds";
+
+/** Which round an envelope belongs to. The dev rounds are the baseline
+ * (incumbent body) and the candidate; `heldout` exists but is never a
+ * dev round - its envelope builder is the single post-promotion check. */
+export const SKILL_REWRITE_ROUND_ARM = Object.freeze({
+ baseline: "baseline",
+ candidate: "candidate",
+ heldout: "heldout",
+} as const);
+
+export type SkillRewriteRoundArm =
+ (typeof SKILL_REWRITE_ROUND_ARM)[keyof typeof SKILL_REWRITE_ROUND_ARM];
+
+/** The round-arm members, for parse-time refusal and guard sharing. */
+export const SKILL_REWRITE_ROUND_ARMS: ReadonlyArray<SkillRewriteRoundArm> = Object.freeze(
+ Object.values(SKILL_REWRITE_ROUND_ARM),
+);
+
+/**
+ * One rewrite round envelope: the needs-llm-step spine plus the fields
+ * that tie the generated transcript back to the task it answers, the arm
+ * that asked for it, and the candidate body the task was rendered
+ * against. The submission scorer reads `task_id` and `candidate_sha256`
+ * off the TRANSCRIPT, not the envelope; these fields exist so a caller
+ * can correlate an envelope with its task, so the executing agent knows
+ * exactly which hash the transcript must carry, and so the dev-only
+ * containment assertion in the builder has a typed handle.
+ */
+export type RewriteTaskEnvelope = NeedsLlmStep & {
+ readonly task_id: string;
+ readonly round: SkillRewriteRoundArm;
+ /** sha-256 of the candidate body in this envelope's prompt; the
+ * transcript must echo it, and the scorer refuses a stale one. */
+ readonly candidate_sha256: string;
+};
+
+export function isSkillRewriteRoundArm(value: unknown): value is SkillRewriteRoundArm {
+ return (
+ typeof value === "string" && (SKILL_REWRITE_ROUND_ARMS as ReadonlyArray<string>).includes(value)
+ );
+}
+
+/** The closed rewrite-mode vocabulary. `gated` is one candidate per
+ * round; `iterative` reserves the explicitly opted-in bounded edit loop
+ * and is accepted but not implemented yet, so it currently resolves to
+ * the same single-candidate behavior. Both are gated before a write. */
+export const SKILL_REWRITE_MODE = Object.freeze({
+ gated: "gated",
+ iterative: "iterative",
+} as const);
+
+export type SkillRewriteMode = (typeof SKILL_REWRITE_MODE)[keyof typeof SKILL_REWRITE_MODE];
+
+/** The mode members, for guard sharing. */
+export const SKILL_REWRITE_MODES: ReadonlyArray<SkillRewriteMode> = Object.freeze(
+ Object.values(SKILL_REWRITE_MODE),
+);
+
+export function isSkillRewriteMode(value: unknown): value is SkillRewriteMode {
+ return (
+ typeof value === "string" && (SKILL_REWRITE_MODES as ReadonlyArray<string>).includes(value)
+ );
+}
+
+/** A gate refusal. Every refusal in this module is this error, by name. */
+export class SkillRewriteError extends Error {
+ constructor(message: string) {
+ super(message);
+ this.name = "SkillRewriteError";
+ }
+}
+
+/** One scored transcript: which dev or held-out task, and which checks failed. */
+export interface RewriteTaskScore {
+ readonly taskId: string;
+ readonly passed: boolean;
+ /** Check ids the transcript failed, deduped, in expectation order. */
+ readonly failedChecks: ReadonlyArray<string>;
+}
+
+/**
+ * One submitted transcript, in its serialized shape - the exact JSON the
+ * envelope's schema hints name, dropped at the envelope's target path.
+ * Field spellings are snake case to match the file on disk.
+ * `candidate_sha256` binds the transcript to the candidate body it was
+ * produced against; when the caller hands the scorer the current
+ * candidate hash, a transcript without it - or with a stale one - is
+ * refused, so scores from a previous body never gate this one.
+ */
+export interface RewriteSubmission {
+ readonly task_id: string;
+ readonly steps?: ReadonlyArray<string>;
+ readonly tools_used?: ReadonlyArray<string>;
+ readonly artifacts?: ReadonlyArray<string>;
+ readonly output?: Readonly<Record<string, unknown>>;
+ readonly candidate_sha256?: string;
+}
+
+/** The selection gate's outcome, with the rates it decided on. */
+export interface RewriteSelection {
+ readonly verdict: SkillRewriteVerdict;
+ readonly baselineRate: number;
+ readonly candidateRate: number;
+}
+
+/**
+ * Top-level submission keys that report the agent's own success. They are
+ * refused, not ignored: ignoring them would let a submitter believe the
+ * field meant something, and accepting them would put a self-report one
+ * refactor away from the metric.
+ */
+const SELF_REPORTED_KEYS: ReadonlyArray<string> = Object.freeze([
+ "success",
+ "passed",
+ "succeeded",
+ "ok",
+]);
+
+/** The closed top-level key set a submission may carry. */
+const KNOWN_SUBMISSION_KEYS: ReadonlyArray<string> = Object.freeze([
+ "task_id",
+ "steps",
+ "tools_used",
+ "artifacts",
+ "output",
+ "candidate_sha256",
+]);
+
+/** A transcript's `candidate_sha256` must be a sha-256 hex digest. */
+const SHA256_HEX_RE = /^[0-9a-f]{64}$/;
+
+/** Dev rounds an envelope builder may be asked for. */
+type DevRound = Extract<SkillRewriteRoundArm, "baseline" | "candidate">;
+
+/**
+ * Build one envelope per DEV task. The candidate body and the task input
+ * travel in the prompt; the target path names the transcript drop site
+ * under the skill's benchmark rounds tree. Held-out members are refused
+ * by construction: the builder walks `spec.devTaskIds` and nothing else,
+ * and a task set whose hash no longer matches the receipt is refused
+ * before any envelope exists.
+ */
+export function buildRewriteEnvelopes(
+ candidateBody: string,
+ spec: SkillRewriteSpec,
+ tasks: SkillBenchmarkTaskSet,
+ opts: { readonly round?: DevRound } = {},
+): ReadonlyArray<RewriteTaskEnvelope> {
+ const round = opts.round ?? SKILL_REWRITE_ROUND_ARM.candidate;
+ return buildRoundEnvelopes(candidateBody, spec, tasks, spec.devTaskIds, round);
+}
+
+/**
+ * The ONE held-out envelope builder, and the only place held-out task
+ * text may enter a prompt: after the dev selection promoted a candidate,
+ * the held-out check runs once, and its results are never fed back.
+ */
+export function buildRewriteHeldoutEnvelopes(
+ candidateBody: string,
+ spec: SkillRewriteSpec,
+ tasks: SkillBenchmarkTaskSet,
+): ReadonlyArray<RewriteTaskEnvelope> {
+ return buildRoundEnvelopes(
+ candidateBody,
+ spec,
+ tasks,
+ spec.heldoutTaskIds,
+ SKILL_REWRITE_ROUND_ARM.heldout,
+ );
+}
+
+function buildRoundEnvelopes(
+ candidateBody: string,
+ spec: SkillRewriteSpec,
+ tasks: SkillBenchmarkTaskSet,
+ memberIds: ReadonlyArray<string>,
+ round: SkillRewriteRoundArm,
+): ReadonlyArray<RewriteTaskEnvelope> {
+ if (tasks.hash !== spec.tasksHash) {
+ throw new SkillRewriteError(
+ `skill rewrite: task set hash ${tasks.hash} does not match the receipt's frozen hash ` +
+ `${spec.tasksHash}; the benchmark changed under the spec`,
+ );
+ }
+ const byId = new Map(tasks.tasks.map((task) => [task.id, task]));
+ const devMembers = new Set(spec.devTaskIds);
+ const candidateHash = sha256Hex(candidateBody);
+ const envelopes = memberIds.map((taskId) => {
+ const task = byId.get(taskId);
+ if (task === undefined) {
+ throw new SkillRewriteError(
+ `skill rewrite: receipt names task id '${taskId}' but the task set for ` +
+ `'${spec.skillName}' has no such task (${SKILL_BENCHMARK_TASKS_FILE} is stale or hand-edited)`,
+ );
+ }
+ const targetPath = skillBenchmarkRelPath(
+ spec.skillName,
+ SKILL_REWRITE_ROUNDS_DIR,
+ round,
+ `${task.id}.json`,
+ );
+ return buildNeedsLlmStep({
+ step: SKILL_REWRITE_STEP,
+ prompt: renderTaskPrompt(candidateBody, task, targetPath, candidateHash),
+ schema_hints: Object.freeze([SUBMISSION_SHAPE_HINT]),
+ target_path: targetPath,
+ task_id: task.id,
+ round,
+ candidate_sha256: candidateHash,
+ });
+ });
+ // The containment assertion the gate leans on: every envelope answers a
+ // dev member. True by construction here, asserted so a future edit that
+ // walks the wrong list fails here instead of leaking held-out text.
+ const leaking = envelopes.filter((envelope) => !devMembers.has(String(envelope["task_id"])));
+ if (leaking.length > 0 && round !== SKILL_REWRITE_ROUND_ARM.heldout) {
+ throw new SkillRewriteError(
+ `skill rewrite: envelope(s) for non-dev task(s) ${leaking
+ .map((envelope) => String(envelope["task_id"]))
+ .join(", ")} refused; held-out members never enter a dev round`,
+ );
+ }
+ return envelopes;
+}
+
+/** The transcript contract the submitting agent must honor. */
+const SUBMISSION_SHAPE_HINT =
+ "Return one JSON object per task with keys: task_id (string), steps (string array), " +
+ "tools_used (string array), artifacts (string array), output (object), " +
+ "candidate_sha256 (string, the sha-256 hex digest of the candidate skill body the " +
+ "task was performed against). " +
+ "No other top-level keys.";
+
+function renderTaskPrompt(
+ candidateBody: string,
+ task: SkillBenchmarkTask,
+ targetPath: string,
+ candidateHash: string,
+): string {
+ return [
+ "Perform the task exactly as the candidate skill body instructs, then record what you did.",
+ "",
+ "Candidate skill body:",
+ candidateBody,
+ "",
+ `Task ${task.id}:`,
+ task.input,
+ "",
+ `Set "candidate_sha256" to ${candidateHash} in the transcript: it binds the ` +
+ "transcript to the candidate body above, and a transcript for a different body " +
+ "is refused.",
+ "",
+ `Write the JSON transcript to ${targetPath} when the task is done.`,
+ ].join("\n");
+}
+
+/** Options for {@link scoreRewriteTranscripts}: which arm is being scored,
+ * against which receipt, and which candidate body the transcripts must be
+ * bound to. Omitted opts scores whatever was submitted, unbound. */
+export interface ScoreRewriteOptions {
+ readonly arm: "dev" | "heldout";
+ readonly spec: SkillRewriteSpec;
+ /** The sha-256 of the CURRENT candidate body. When given, every
+ * submission must carry a matching `candidate_sha256`; a missing or
+ * stale binding is a named refusal, so transcripts left over from a
+ * previous candidate can never gate this one. */
+ readonly candidateHash?: string;
+}
+
+/**
+ * Validate submitted transcripts and score them against the task set's
+ * structural predicates. Throws a named {@link SkillRewriteError} on any
+ * malformed shape, an unknown task id, a duplicate submission, a
+ * self-reported success field, a malformed or stale `candidate_sha256`
+ * binding, or - when the arm is named - a submission for a task the arm
+ * may not see. Scores come back sorted by task id.
+ */
+export function scoreRewriteTranscripts(
+ submissions: ReadonlyArray<unknown>,
+ tasks: SkillBenchmarkTaskSet,
+ opts?: ScoreRewriteOptions,
+): ReadonlyArray<RewriteTaskScore> {
+ const byId = new Map(tasks.tasks.map((task) => [task.id, task]));
+ const devMembers = new Set(opts?.spec.devTaskIds ?? []);
+ const heldoutMembers = new Set(opts?.spec.heldoutTaskIds ?? []);
+ const seen = new Set<string>();
+ const scores: RewriteTaskScore[] = [];
+ for (const raw of submissions) {
+ if (raw === null || typeof raw !== "object" || Array.isArray(raw)) {
+ throw new SkillRewriteError("rewrite submission must be an object");
+ }
+ const record = raw as Record<string, unknown>;
+ const taskId = record["task_id"];
+ if (typeof taskId !== "string" || taskId.trim().length === 0) {
+ throw new SkillRewriteError("rewrite submission needs a task_id");
+ }
+ const task = byId.get(taskId);
+ if (task === undefined) {
+ throw new SkillRewriteError(`rewrite submission names an unknown task id: ${taskId}`);
+ }
+ for (const key of SELF_REPORTED_KEYS) {
+ if (key in record) {
+ throw new SkillRewriteError(
+ `rewrite submission carries a self-reported success field ('${key}'); ` +
+ "the scorer reads structural predicates only",
+ );
+ }
+ }
+ for (const key of Object.keys(record)) {
+ if (!(KNOWN_SUBMISSION_KEYS as ReadonlyArray<string>).includes(key)) {
+ throw new SkillRewriteError(
+ `rewrite submission carries an unexpected key ('${key}'); ` +
+ `the transcript shape is ${KNOWN_SUBMISSION_KEYS.join(", ")}`,
+ );
+ }
+ }
+ const boundHash = record["candidate_sha256"];
+ if (
+ boundHash !== undefined &&
+ (typeof boundHash !== "string" || !SHA256_HEX_RE.test(boundHash))
+ ) {
+ throw new SkillRewriteError(
+ "rewrite submission candidate_sha256 must be a sha-256 hex digest of the " +
+ "candidate body the task was performed against",
+ );
+ }
+ if (opts?.candidateHash !== undefined) {
+ if (boundHash === undefined) {
+ throw new SkillRewriteError(
+ `rewrite submission for task '${taskId}' is missing candidate_sha256; transcripts ` +
+ `are bound to the candidate body they were run against (expected ${opts.candidateHash})`,
+ );
+ }
+ if (boundHash !== opts.candidateHash) {
+ throw new SkillRewriteError(
+ `rewrite submission for task '${taskId}' carries candidate_sha256 ${boundHash}, ` +
+ "which does not match the current candidate body " +
+ `(${opts.candidateHash}); a transcript from a different body never gates this one`,
+ );
+ }
+ }
+ if (seen.has(taskId)) {
+ throw new SkillRewriteError(`rewrite submission for task '${taskId}' appears twice`);
+ }
+ seen.add(taskId);
+ if (opts !== undefined) {
+ const memberOfArm = opts.arm === "dev" ? devMembers : heldoutMembers;
+ const otherArm = opts.arm === "dev" ? heldoutMembers : devMembers;
+ if (!memberOfArm.has(taskId)) {
+ const why = otherArm.has(taskId) ? "a held-out task" : "a task outside this arm";
+ const armName = opts.arm === "dev" ? "dev" : "held-out";
+ throw new SkillRewriteError(
+ `rewrite submission for '${taskId}' refused in the ${armName} arm: ` +
+ `'${taskId}' is ${why}` +
+ (otherArm.has(taskId) && opts.arm === "dev"
+ ? "; held-out members are scored by the single held-out check only"
+ : "; dev members are scored in the dev arm only"),
+ );
+ }
+ }
+ const steps = stringList(record["steps"], "steps");
+ const toolsUsed = stringList(record["tools_used"], "tools_used");
+ const artifacts = stringList(record["artifacts"], "artifacts");
+ const outputRaw = record["output"] ?? {};
+ if (outputRaw === null || typeof outputRaw !== "object" || Array.isArray(outputRaw)) {
+ throw new SkillRewriteError("rewrite submission output must be an object");
+ }
+ const output = outputRaw as Readonly<Record<string, unknown>>;
+ scores.push(scoreTask(task, { steps, toolsUsed, artifacts, output }));
+ }
+ return scores.toSorted((left, right) => left.taskId.localeCompare(right.taskId));
+}
+
+/**
+ * The selection gate, preregistered three arms: a candidate promotes only
+ * by strictly beating the baseline by more than the spec's margin with
+ * the dev n met; a tie - and anything under the margin - holds; a short
+ * dev n is its own arm, never a pass.
+ *
+ * "Met" means the receipt's full dev membership, scored on BOTH arms: a
+ * score for every dev task id. An arm that scored a subset - however
+ * large, and however good the subset's rate - has not produced the
+ * preregistered comparison, so the verdict is `not_enough_evidence`,
+ * exactly as for an n under the floor: both are the same shortfall
+ * (incomplete evidence for the receipted claim), and folding them keeps
+ * a mid-round invocation a verdict instead of an error, re-runnable once
+ * the missing transcripts land. A score for an id OUTSIDE the receipt's
+ * dev membership is different in kind - the arm scored something the
+ * receipt never registered - and is refused by name, matching the
+ * held-out gate's member refusal.
+ */
+export function selectRewriteCandidate(
+ baseline: ReadonlyArray<RewriteTaskScore>,
+ candidate: ReadonlyArray<RewriteTaskScore>,
+ spec: SkillRewriteSpec,
+): RewriteSelection {
+ assertDevMembers(baseline, "baseline", spec);
+ assertDevMembers(candidate, "candidate", spec);
+ const n = Math.min(baseline.length, candidate.length);
+ const baselineRate = passedRate(baseline);
+ const candidateRate = passedRate(candidate);
+ const fullyScored = coversAll(baseline, spec.devTaskIds) && coversAll(candidate, spec.devTaskIds);
+ if (!fullyScored || n < spec.minDevTasks) {
+ return {
+ verdict: SKILL_REWRITE_VERDICT.not_enough_evidence,
+ baselineRate,
+ candidateRate,
+ };
+ }
+ if (candidateRate > baselineRate + spec.requiredMargin) {
+ return { verdict: SKILL_REWRITE_VERDICT.promote, baselineRate, candidateRate };
+ }
+ return { verdict: SKILL_REWRITE_VERDICT.hold, baselineRate, candidateRate };
+}
+
+/**
+ * The dev arms score receipt members only: an id outside `spec.devTaskIds`
+ * in either arm means the caller bypassed the arm-checked scorer, so the
+ * selection refuses by name instead of letting an unregistered id move
+ * the metric.
+ */
+function assertDevMembers(
+ scores: ReadonlyArray<RewriteTaskScore>,
+ armName: string,
+ spec: SkillRewriteSpec,
+): void {
+ const devMembers = new Set(spec.devTaskIds);
+ for (const score of scores) {
+ if (!devMembers.has(score.taskId)) {
+ throw new SkillRewriteError(
+ `rewrite selection scored '${score.taskId}' in the ${armName} arm, which is not a ` +
+ "dev member of the receipt; the dev arms score the receipt's dev members only",
+ );
+ }
+ }
+}
+
+/** Whether every receipted id has a scored transcript in the arm. */
+function coversAll(
+ scores: ReadonlyArray<RewriteTaskScore>,
+ memberIds: ReadonlyArray<string>,
+): boolean {
+ const scored = new Set(scores.map((score) => score.taskId));
+ return memberIds.every((id) => scored.has(id));
+}
+
+/**
+ * The held-out gate, run ONCE, on the candidate that earned promotion: a
+ * full pass promotes, any miss holds. Every score must name a held-out
+ * member (a dev score array handed here is refused by name rather than
+ * folded in), and every held-out member must have a score: the one-shot
+ * check is incomplete until the whole preregistered membership has run.
+ * An incomplete check refuses by name - naming the unscored members -
+ * rather than hold, because a hold would be recorded in a grade record
+ * as a verdict the check never earned, and would tell the submitting
+ * agent which held-out tasks fail without the check having run in full.
+ * An empty arm is the degenerate partial coverage (zero of the
+ * receipted members scored) and refuses the same way; no verdict at all
+ * is the only honest output of a check that did not run.
+ */
+export function checkRewriteHeldout(
+ candidate: ReadonlyArray<RewriteTaskScore>,
+ spec: SkillRewriteSpec,
+): SkillRewriteVerdict {
+ const heldoutMembers = new Set(spec.heldoutTaskIds);
+ for (const score of candidate) {
+ if (!heldoutMembers.has(score.taskId)) {
+ throw new SkillRewriteError(
+ `held-out gate scored '${score.taskId}', which is not a held-out member of the receipt; ` +
+ "the held-out arm scores held-out members only",
+ );
+ }
+ }
+ const scored = new Set(candidate.map((score) => score.taskId));
+ const unscored = spec.heldoutTaskIds.filter((id) => !scored.has(id));
+ if (unscored.length > 0) {
+ throw new SkillRewriteError(
+ `the held-out check is incomplete: ${unscored.length} of ${spec.heldoutTaskIds.length} ` +
+ `held-out members were never scored (${unscored.join(", ")}); the one-shot check runs ` +
+ "on the full receipted membership or issues no verdict at all",
+ );
+ }
+ return candidate.every((score) => score.passed)
+ ? SKILL_REWRITE_VERDICT.promote
+ : SKILL_REWRITE_VERDICT.hold;
+}
+
+/**
+ * Resolve the rewrite mode. Absent (or blank) resolves to `gated`, the
+ * documented default; `gated` and `iterative` pass through; anything
+ * else is a named error, never a silent fallback to the default.
+ */
+export function resolveSkillRewriteMode(raw: string | undefined): SkillRewriteMode {
+ const value = raw?.trim() ?? "";
+ if (value === "") return SKILL_REWRITE_MODE.gated;
+ if (isSkillRewriteMode(value)) return value;
+ throw new SkillRewriteError(
+ `skill rewrite mode '${value}' is unknown (expected one of ${SKILL_REWRITE_MODES.join(", ")})`,
+ );
+}
+
+// ----- the advisory judge -------------------------------------------------------
+
+export interface RewriteJudgeOutcome {
+ readonly status: "skipped" | "error" | "ran";
+ readonly detail?: string;
+ /** Advisory per-task verdicts; never folded into the metric. */
+ readonly verdicts?: Readonly<Record<string, boolean>>;
+}
+
+/**
+ * Optional advisory judge over the score summary, through the one
+ * sanctioned external-command boundary. The deterministic scorer stays
+ * canonical in every message and every doc line: the judge's verdicts are
+ * reported for comparison and can never reach
+ * {@link selectRewriteCandidate}, whose signature takes score arrays and
+ * a spec only. A failing command is an error status, never a throw.
+ */
+export function runRewriteJudge(
+ cmd: string | undefined,
+ summary: Record<string, unknown>,
+): RewriteJudgeOutcome {
+ const result = runJsonCommandBridge(cmd, summary, { label: "skill rewrite judge command" });
+ if (result.status === "skipped") return Object.freeze({ status: "skipped" });
+ if (result.status === "error") {
+ return Object.freeze({ status: "error", detail: result.detail });
+ }
+ if (result.output === null || typeof result.output !== "object") {
+ return Object.freeze({ status: "error", detail: "judge output is not an object" });
+ }
+ const parsed = result.output as { verdicts?: Record<string, unknown> };
+ const verdicts: Record<string, boolean> = {};
+ for (const [id, value] of Object.entries(parsed.verdicts ?? {})) {
+ if (typeof value === "boolean") verdicts[id] = value;
+ }
+ return Object.freeze({ status: "ran", verdicts: Object.freeze(verdicts) });
+}
+
+// ----- the grade record ---------------------------------------------------------
+
+/** One per-task row of a grade record: ids and check verdicts only. */
+export interface RewriteGradeTaskRow {
+ readonly task_id: string;
+ readonly passed: boolean;
+ readonly failed_checks: ReadonlyArray<string>;
+}
+
+/**
+ * The `skill_rewrite_eval_grade` payload: identifiers, numbers, booleans
+ * and check ids, stamped with the spec hash. NEVER task text and NEVER
+ * transcript text - the payload is assembled from score rows, which carry
+ * no text by construction, and tests pin that over the serialized form.
+ * The one digest it may carry (`candidate_sha256`) binds the record to
+ * the staged proposal's bytes; a sha-256 is an identifier, not content.
+ */
+export interface RewriteGradeRecordPayload {
+ readonly skill: string;
+ readonly spec_hash: string;
+ readonly tasks_hash: string;
+ readonly metric: typeof SKILL_REWRITE_METRIC;
+ readonly seed: number;
+ readonly split_rule: string;
+ /** The final verdict: the selection verdict after the held-out gate. */
+ readonly verdict: SkillRewriteVerdict;
+ readonly baseline_rate: number;
+ readonly candidate_rate: number;
+ readonly dev: ReadonlyArray<RewriteGradeTaskRow>;
+ readonly held_out: ReadonlyArray<RewriteGradeTaskRow>;
+ /**
+ * The candidate binding (review round-2, M1 residual R1): the sha-256
+ * of the staged proposal document the final promote blessed, present
+ * ONLY when this record rode a staging - a hold round stages nothing
+ * and binds nothing. The accept-time grade match requires it, so a
+ * historical promote over a different candidate cannot bless a new
+ * proposal: rates collide, document digests do not.
+ */
+ readonly candidate_sha256?: string;
+}
+
+export interface RewriteGradeRecordInput {
+ readonly skill: string;
+ readonly spec: SkillRewriteSpec;
+ /** The spec hash stamped on the record and the staged proposal. */
+ readonly specHash: string;
+ readonly selection: RewriteSelection;
+ /** The held-out gate's verdict; `hold` when it has not run yet. */
+ readonly heldoutVerdict: SkillRewriteVerdict;
+ readonly devScores: ReadonlyArray<RewriteTaskScore>;
+ readonly heldoutScores: ReadonlyArray<RewriteTaskScore>;
+ /**
+ * The staged proposal's document sha-256 - exactly what staging stamped
+ * and returned; omit on a hold round, which staged nothing. The accept
+ * match refuses a promote record without the binding, so a final
+ * promote whose caller drops this field fails CLOSED at the accept,
+ * never open.
+ */
+ readonly candidateSha256?: string;
+}
+
+/**
+ * Assemble the grade-record payload for a completed gate run. The final
+ * verdict applies the one rule the held-out gate owns: a promoted
+ * candidate that misses held-out is downgraded to hold. A hold and a
+ * short dev n are already final from selection.
+ */
+export function buildRewriteGradeRecord(input: RewriteGradeRecordInput): RewriteGradeRecordPayload {
+ const verdict =
+ input.selection.verdict === SKILL_REWRITE_VERDICT.promote
+ ? input.heldoutVerdict
+ : input.selection.verdict;
+ return Object.freeze({
+ skill: input.skill,
+ spec_hash: input.specHash,
+ tasks_hash: input.spec.tasksHash,
+ metric: SKILL_REWRITE_METRIC,
+ seed: input.spec.seed,
+ split_rule: input.spec.splitRule,
+ verdict,
+ baseline_rate: input.selection.baselineRate,
+ candidate_rate: input.selection.candidateRate,
+ dev: input.devScores.map(toGradeRow),
+ held_out: input.heldoutScores.map(toGradeRow),
+ ...(input.candidateSha256 !== undefined ? { candidate_sha256: input.candidateSha256 } : {}),
+ });
+}
+
+function toGradeRow(score: RewriteTaskScore): RewriteGradeTaskRow {
+ return Object.freeze({
+ task_id: score.taskId,
+ passed: score.passed,
+ failed_checks: Object.freeze([...score.failedChecks]),
+ });
+}
+
+// ----- the structural predicates -------------------------------------------------
+
+interface NormalizedTranscript {
+ readonly steps: ReadonlyArray<string>;
+ readonly toolsUsed: ReadonlyArray<string>;
+ readonly artifacts: ReadonlyArray<string>;
+ readonly output: Readonly<Record<string, unknown>>;
+}
+
+function scoreTask(task: SkillBenchmarkTask, transcript: NormalizedTranscript): RewriteTaskScore {
+ const failed: string[] = [];
+ for (const expectation of task.expects) {
+ const passed = evaluateExpectation(expectation, transcript);
+ if (!passed && !failed.includes(expectation.check)) {
+ failed.push(expectation.check);
+ }
+ }
+ return Object.freeze({
+ taskId: task.id,
+ passed: failed.length === 0,
+ failedChecks: Object.freeze(failed),
+ });
+}
+
+function evaluateExpectation(
+ expectation: SkillBenchExpectation,
+ transcript: NormalizedTranscript,
+): boolean {
+ switch (expectation.check) {
+ case SKILL_BENCH_CHECK.tool_used:
+ return transcript.toolsUsed.includes(expectation.tool);
+ case SKILL_BENCH_CHECK.artifact_created: {
+ const prefix = normalizePath(expectation.path_prefix);
+ return transcript.artifacts.some((artifact) => normalizePath(artifact).startsWith(prefix));
+ }
+ case SKILL_BENCH_CHECK.step_order:
+ return isSubsequence(expectation.steps, transcript.steps);
+ case SKILL_BENCH_CHECK.forbidden_step:
+ return !transcript.steps.includes(expectation.step);
+ case SKILL_BENCH_CHECK.output_field:
+ return outputValueMatches(transcript.output[expectation.field], expectation.value_class);
+ }
+}
+
+function isSubsequence(needles: ReadonlyArray<string>, haystack: ReadonlyArray<string>): boolean {
+ let cursor = 0;
+ for (const step of haystack) {
+ if (cursor < needles.length && step === needles[cursor]) cursor++;
+ }
+ return cursor === needles.length;
+}
+
+function outputValueMatches(value: unknown, valueClass: SkillBenchValueClass): boolean {
+ switch (valueClass) {
+ case "non_empty_string":
+ return typeof value === "string" && value.trim().length > 0;
+ case "number":
+ return typeof value === "number" && Number.isFinite(value);
+ case "boolean":
+ return typeof value === "boolean";
+ case "non_empty_array":
+ return Array.isArray(value) && value.length > 0;
+ }
+}
+
+/** Absent means empty; present means a string array, else a named error. */
+function stringList(raw: unknown, field: string): ReadonlyArray<string> {
+ if (raw === undefined) return Object.freeze([]);
+ if (!Array.isArray(raw) || !raw.every((entry) => typeof entry === "string")) {
+ throw new SkillRewriteError(`rewrite submission ${field} must be a string array`);
+ }
+ return Object.freeze(raw as string[]);
+}
+
+/** Artifact path shapes compare on forward slashes on every platform. */
+function normalizePath(path: string): string {
+ return path.replaceAll("\\", "/");
+}
+
+function passedRate(scores: ReadonlyArray<RewriteTaskScore>): number {
+ if (scores.length === 0) return 0;
+ return scores.filter((score) => score.passed).length / scores.length;
+}
diff --git a/src/core/brain/status.ts b/src/core/brain/status.ts
index fc645f5c..23f63f5f 100644
--- a/src/core/brain/status.ts
+++ b/src/core/brain/status.ts
@@ -68,6 +68,7 @@ import { listLogDates, readLogDay } from "./log-jsonl.ts";
import { loadBrainConfig } from "./policy.ts";
import { parseSignal } from "./signal.ts";
import { BRAIN_LOG_EVENT_KIND, BRAIN_PREFERENCE_STATUS } from "./types.ts";
+import { lessonApprovalCounts, type LessonApprovalCounts } from "./lessons-promotion.ts";
// ----- Public types --------------------------------------------------------
@@ -131,6 +132,52 @@ export interface BrainStatusSnapshot {
*/
readonly signals_awaiting_dream: number;
};
+ /**
+ * Lesson-promotion approval counts (t_1e952e43): the decisions
+ * currently in force plus how many approved rows went stale,
+ * carried by the snapshot the MCP status tool already returns -
+ * report-only, no new surface minted for them. Fail-soft: a
+ * damaged ledger answers zeros and names itself in `read_error`;
+ * doctor is the surface for the damage itself.
+ */
+ readonly lessons: LessonApprovalCounts & {
+ /** Present only when the approvals ledger could not be read. */
+ readonly read_error?: string;
+ };
+}
+
+/** The lessons counts block for a vault with no Brain layer. */
+const LESSONS_COUNTS_ABSENT: LessonApprovalCounts = Object.freeze({
+ approved: 0,
+ denied: 0,
+ stale: 0,
+});
+
+/**
+ * The fail-soft read_error the snapshot carries when the approvals
+ * ledger cannot be read. Deliberately a fixed, generalized sentence:
+ * the ledger reader's error messages embed the ledger's absolute path,
+ * and machine paths stay out of MCP output - doctor is the surface that
+ * names the cause and the recovery in operator-facing output.
+ */
+const LESSONS_LEDGER_READ_ERROR =
+ "lessons-approvals.json could not be read (the ledger is damaged or unusable); " +
+ "o2b doctor names the cause and the recovery";
+
+/**
+ * Read the lessons counts fail-soft: the doctor is the surface for a
+ * damaged ledger, the status snapshot answers with zeros and names
+ * itself, because an MCP consumer must not lose the whole brain block
+ * over one unreadable file.
+ */
+function lessonsCountsSafe(vault: string): LessonApprovalCounts & {
+ readonly read_error?: string;
+} {
+ try {
+ return lessonApprovalCounts(vault);
+ } catch {
+ return { ...LESSONS_COUNTS_ABSENT, read_error: LESSONS_LEDGER_READ_ERROR };
+ }
}
export interface ComputeBrainStatusOptions {
@@ -148,6 +195,7 @@ export function computeBrainStatus(
if (!existsSync(dirs.brain)) {
return Object.freeze({
present: false,
+ lessons: LESSONS_COUNTS_ABSENT,
counts: {
inbox: 0,
inbox_processed: 0,
@@ -173,6 +221,7 @@ export function computeBrainStatus(
return Object.freeze({
present: true,
counts,
+ lessons: lessonsCountsSafe(vault),
last_dream_at: lastDreamAt,
last_apply_evidence_at: lastApplyEvidenceAt,
maintenance_debt: maintenanceDebt,
diff --git a/src/core/brain/types.ts b/src/core/brain/types.ts
index 4f9e281f..722d7fe9 100644
--- a/src/core/brain/types.ts
+++ b/src/core/brain/types.ts
@@ -588,6 +588,35 @@ export const BRAIN_LOG_EVENT_KIND = {
* target wrote nothing and records nothing.
*/
noteWrite: "note-write",
+ /**
+ * `lessons-approved` (operator-approved lesson promotion, t_1e952e43) -
+ * the operator approved one preference-derived lesson for promotion into
+ * the managed lessons block of the agent rules files. Operator CLI only:
+ * no agent-facing path can mint this event, and the approval pins the
+ * approved text by its content hash. Payload carries the `pref` wikilink,
+ * the `targets` (the rules files the approval covers), the
+ * `approved_content_hash`, the `consent` verdict (`yes-flag` or
+ * `interactive-yes`), and the `agent`.
+ */
+ lessonsApproved: "lessons-approved",
+ /**
+ * `lessons-denied` (operator-approved lesson promotion, t_1e952e43) - the
+ * operator denied one lesson: the ledger keeps the record and the lesson
+ * is suppressed from every future promotion until re-approved. Payload
+ * carries the `pref` wikilink, the `consent` verdict, and the `agent`.
+ * No rules file is written on a denial.
+ */
+ lessonsDenied: "lessons-denied",
+ /**
+ * `lessons-promoted` (operator-approved lesson promotion, t_1e952e43) - a
+ * `refresh-blocks` apply rewrote the lessons block of at least one agent
+ * rules file from the qualified and approved lesson set. Payload carries
+ * the `targets` that changed, the promoted `prefs` (one wikilink per
+ * line), and the `agent`. Derived-state maintenance only: the write goes
+ * through the shared rules-block writer under a consent verdict, and a
+ * no-op refresh emits nothing.
+ */
+ lessonsPromoted: "lessons-promoted",
} as const;
export type BrainLogEventKind = (typeof BRAIN_LOG_EVENT_KIND)[keyof typeof BRAIN_LOG_EVENT_KIND];
diff --git a/src/core/brain/writeback-contract.ts b/src/core/brain/writeback-contract.ts
index f0b8c6ca..e836bf5a 100644
--- a/src/core/brain/writeback-contract.ts
+++ b/src/core/brain/writeback-contract.ts
@@ -26,11 +26,15 @@
* fact is learned);
* - the atomic-fact rule (memory is written as atomic facts).
*
- * This module is the checker that defines conformance. NO INSTALLER
- * LIVES HERE, which is why a file with no block at all is reported as
- * `missing-block` (not installed, graded skipped by the readiness probe)
- * while a block that is present but broken is `malformed-block` or
- * `missing-clauses` (graded fail).
+ * This module is the checker that defines conformance. The installer
+ * lives in `src/core/install/instruction-block.ts` (sibling cards
+ * t_ba41a78a and t_1e952e43) and must keep satisfying this module's
+ * clauses: it writes exactly {@link CANONICAL_WRITEBACK_BLOCK_BODY},
+ * the canonical gate-and-usage body self-tested against
+ * {@link missingWritebackGateClauses}. A file with no block at all is
+ * still reported as `missing-block` (not installed, graded skipped by
+ * the readiness probe) while a block that is present but broken is
+ * `malformed-block` or `missing-clauses` (graded fail).
*
* Read posture: every candidate file is lstat'd first and a symbolic link
* is REFUSED, never followed - the upstream posture is that a reader that
@@ -186,6 +190,46 @@ export const WRITEBACK_CONTRACT_REQUIREMENTS: ReadonlyArray<WritebackContractReq
},
]);
+/**
+ * The canonical managed-block body the installer writes between the
+ * settled markers, and the body every audited file is graded against in
+ * practice: a block installed by `src/core/install/
+ * instruction-block.ts` carries exactly this text, so a drifted block is
+ * one that diverged from it.
+ *
+ * Content, by contract (t_ba41a78a K2): the same-turn atomic-fact write
+ * gate - the `marker_writeback` guardrail token verbatim, the same-turn
+ * rule, the atomic-fact rule - merged with the cross-project-pointer
+ * usage content (read `Brain/active.md` at session start, `brain_feedback`,
+ * `brain_apply_evidence`, the do-not-dream rule). One body, one block:
+ * the editor holds exactly one pair per spelling, so the docs' pointer
+ * block and the write gate must be the same block or they fight.
+ *
+ * Static by design. Paths are spelled relative to the file, which the
+ * installer writes at the vault root - the same workspace the readiness
+ * probe audits - so the body is byte-identical in every vault and a
+ * vault move never drifts an installed block. It quotes no vault memory
+ * content, ever: it is instructions, not memory.
+ */
+export const CANONICAL_WRITEBACK_BLOCK_BODY: string = [
+ "## Open Second Brain",
+ "",
+ "This project shares an Obsidian-compatible vault with an active",
+ "observing-memory layer. At session start, read the current preferences",
+ "from Brain/active.md (paths are relative to this file, the vault root).",
+ "",
+ "Record taste signals via `brain_feedback` (MCP) or `o2b brain feedback`",
+ "(CLI). After producing a durable artifact, call `brain_apply_evidence`",
+ "with `result: applied | violated | outdated` for any preference whose",
+ "`scope` matches.",
+ "",
+ "Do not run `o2b brain dream` here: the vault declares its primary",
+ "dream-running agent in `Brain/_brain.yaml` (key `primary_agent`).",
+ "",
+ "Memory write gate: apply the marker_writeback guardrail. Record memory",
+ "as atomic facts in the same turn each fact is learned, never batched.",
+].join("\n");
+
// ----- Types ----------------------------------------------------------------
/** Closed finding vocabulary of one audited instruction file. */
diff --git a/src/core/config.ts b/src/core/config.ts
index cd3cc9a4..f57507d2 100644
--- a/src/core/config.ts
+++ b/src/core/config.ts
@@ -22,6 +22,7 @@ import { resolvePointerVault } from "./brain/portability/pointer.ts";
import { parseBrainYaml } from "./brain/yaml-parse.ts";
import { BrainConfigError } from "./brain/policy/errors.ts";
import { BRAIN_CONFIG_FILE, BRAIN_ROOT_REL } from "./brain/path-constants.ts";
+import { resolveSkillRewriteMode, type SkillRewriteMode } from "./brain/skill-rewrite.ts";
import {
isWikiLinkFormat,
WIKI_LINK_FORMATS,
@@ -1011,6 +1012,18 @@ export const DECISION_RECALL_MIN_SPACING_TURNS_CONFIG_KEY = "decision_recall.min
export const DECISION_RECALL_MIN_SPACING_TURNS_ENV_KEY =
"OPEN_SECOND_BRAIN_DECISION_RECALL_MIN_SPACING_TURNS";
+/**
+ * Environment twin of the lessons promotion scope list (operator-approved
+ * lesson promotion, t_1e952e43). The flat machine-config key itself is
+ * `lessons.promotion.scopes`, declared beside its resolver in
+ * `src/core/brain/policy/blocks/lessons.ts` so the brain module owns its
+ * own key vocabulary. Comma-separated scope names; the same parsing rules
+ * as `resolveCounterpartyBriefTriggers` apply (entries NFC-normalized and
+ * trimmed, empty entries dropped, bracket-shaped values malformed). Absent
+ * or empty disables promotion entirely.
+ */
+export const LESSONS_PROMOTION_SCOPES_ENV_KEY = "OPEN_SECOND_BRAIN_LESSONS_PROMOTION_SCOPES";
+
/**
* Shared body for a non-negative-integer config value: env var (trimmed)
* wins, falling back to the config key (trimmed). Returns `null` when
@@ -1963,6 +1976,44 @@ export function resolveTelegramCaptureAllowlist(configPath?: string): string[] {
return ids;
}
+/**
+ * Rewrite-gate mode for benchmark-gated skill rewrites (agent-presence,
+ * Lane A). `gated` (the default) runs one candidate per gate round;
+ * `iterative` is accepted and currently behaves exactly like `gated` -
+ * one candidate per round - because the bounded edit loop it reserves is
+ * not implemented yet; the value is carried so operators can opt in
+ * without a config migration when the loop ships. The flat
+ * machine-config key is `skill_rewrite.mode`; an unknown value is a named
+ * error from the kernel's own resolver, never a silent fallback to the
+ * default.
+ */
+export const SKILL_REWRITE_MODE_CONFIG_KEY = "skill_rewrite.mode";
+export const SKILL_REWRITE_MODE_ENV_KEY = "OPEN_SECOND_BRAIN_SKILL_REWRITE_MODE";
+
+/** Resolve the rewrite mode: env twin first, then the config file's flat key. */
+export function resolveSkillRewriteModeConfig(configPath?: string): SkillRewriteMode {
+ const env = process.env[SKILL_REWRITE_MODE_ENV_KEY]?.trim();
+ const raw = env || discoverConfig(configPath).data[SKILL_REWRITE_MODE_CONFIG_KEY]?.trim();
+ return resolveSkillRewriteMode(raw);
+}
+
+/**
+ * Optional advisory judge command for rewrite gate rounds (agent-presence,
+ * Lane A). Same contract as `bench_judge_cmd` (t_882c396a): unset (the
+ * default) means the judge phase is skipped, and when set the judge is
+ * advisory only - it never moves the `tasks_passed_rate` metric the gate
+ * decides on. The deterministic scorer stays canonical in every message.
+ */
+export const SKILL_REWRITE_JUDGE_CMD_CONFIG_KEY = "skill_rewrite_judge_cmd";
+export const SKILL_REWRITE_JUDGE_CMD_ENV_KEY = "OPEN_SECOND_BRAIN_SKILL_REWRITE_JUDGE_CMD";
+
+/** Resolve the advisory rewrite judge: env twin first, then the config file. */
+export function resolveSkillRewriteJudgeCmd(configPath?: string): string | undefined {
+ const env = process.env[SKILL_REWRITE_JUDGE_CMD_ENV_KEY]?.trim();
+ const raw = env || discoverConfig(configPath).data[SKILL_REWRITE_JUDGE_CMD_CONFIG_KEY]?.trim();
+ return raw !== undefined && raw !== "" ? raw : undefined;
+}
+
/**
* `~` and `~/x` (and `~\x` on Windows) against `home`. The platform and
* home default to the running process; the injected-environment resolvers
diff --git a/src/core/install/adapters/codex.ts b/src/core/install/adapters/codex.ts
index eb50d581..f7795d28 100644
--- a/src/core/install/adapters/codex.ts
+++ b/src/core/install/adapters/codex.ts
@@ -93,6 +93,21 @@ const LABEL = "Codex CLI";
const FIX_HINT = `o2b install --target ${TARGET} --apply`;
const SERVER_NAMES: ReadonlyArray<string> = Object.freeze([OSB_KEY_FULL, OSB_KEY_WRITER]);
+/**
+ * ChatGPT desktop has no MCP registration of its own: it reads the same
+ * `$CODEX_HOME/config.toml` this adapter writes, so the codex
+ * registration serves it. It is named in the merge-lane detect note - a
+ * note, never a status or a target - because an operator on a machine
+ * with only the desktop app reads exactly this line in `o2b install`'s
+ * detect output and otherwise has no surface telling them this target is
+ * theirs. There is deliberately no ChatGPT install target id: a second
+ * target for one config file would claim bytes the codex target owns and
+ * report them as drift.
+ */
+const MERGE_LANE_NOTE =
+ "codex CLI not on PATH; registration goes through the config.toml merge, " +
+ "the same file ChatGPT desktop reads";
+
/**
* Codex's vendor token, combined with the operator's host segment into a
* host-qualified identity by `../identity.ts` - so a Brain write made
@@ -319,7 +334,7 @@ export const codexAdapter: InstallAdapter = {
const declared = declaredServers(readFileOrEmpty(path));
const cliNote = activeRunner.available()
? "codex CLI present; registration goes through `codex mcp add`"
- : "codex CLI not on PATH; registration goes through the config.toml merge";
+ : MERGE_LANE_NOTE;
if (declared.length === SERVER_NAMES.length) {
return { target: TARGET, status: "installed", configPath: path, notes: [cliNote] };
}
diff --git a/src/core/install/instruction-block.ts b/src/core/install/instruction-block.ts
new file mode 100644
index 00000000..8b18c169
--- /dev/null
+++ b/src/core/install/instruction-block.ts
@@ -0,0 +1,536 @@
+/**
+ * The brain-usage block installer step for agent instruction files
+ * (t_ba41a78a), the producer the write-back contract anticipated.
+ *
+ * Upstream installers finish by writing a "use the brain" instruction
+ * block into the harness's own rules file; without one, a host that never
+ * loads an OSB hook never learns the brain exists, and the audited
+ * write-gate block is graded `missing-block` forever. This module is the
+ * narrow missing half: an install step that writes the canonical
+ * write-gate block (t_ba41a78a K2, {@link CANONICAL_WRITEBACK_BLOCK_BODY})
+ * into the agent-instruction file the installed host actually reads, at
+ * the VAULT root - the same workspace `o2b doctor --readiness` audits, so
+ * the probe grades exactly what install wrote.
+ *
+ * Which file, per host: {@link instructionBlockTargetFor} reads
+ * `HOST_INSTRUCTION_PRECEDENCE` - codex, cursor, opencode and aider read
+ * AGENTS.md, gemini-cli reads GEMINI.md (name-implied only, an open
+ * question that table's docblock already carries, surfaced as a plan note
+ * here rather than resolved by pretending certainty), and targets with no
+ * entry are a named skip. The mapping never forks a second host-to-file
+ * table.
+ *
+ * Every byte goes through the shared rules-block writer
+ * (`src/core/install/rules-block.ts`), never through a direct fs write:
+ * operator content outside the block is preserved byte-for-byte, the
+ * first write backs up exclusively, a re-apply is a byte no-op, and a
+ * hand-edited block refuses with `user-modified-block` unless forced.
+ *
+ * The apply is bound to the approved preview (the `o2b brain protect`
+ * pattern): {@link applyInstructionBlock} re-derives the plan from the
+ * live disk and refuses with `preview-drift` unless every field the
+ * consent was shown still holds - a write of anything but the approved
+ * bytes is a typed refusal, never a fallback.
+ *
+ * Ownership is recorded in
+ * `<vault>/.open-second-brain/instruction-block.lock.json`
+ * ({@link INSTRUCTION_BLOCK_LOCK_FILE}, the derived store beside
+ * `install.lock.json`): per file, which block owns the fence, the begin
+ * marker, and the applied time that drives the hand-edit refusal. The
+ * lock is what uninstall reads to remove exactly the pair this tool
+ * wrote. It is machine state, not a credential, and is declared in the
+ * state-surface inventory.
+ *
+ * Layering: core here, so no stdout, no exit codes, no prompts - the CLI
+ * (`src/cli/install/install.ts`) owns consent, rendering and exits.
+ */
+
+import { existsSync, lstatSync, mkdirSync, readFileSync, statSync } from "node:fs";
+import { basename, dirname, join } from "node:path";
+
+import { DERIVED_STORE_DIR } from "../brain/path-constants.ts";
+import {
+ AGENT_INSTRUCTION_FILES,
+ CANONICAL_WRITEBACK_BLOCK_BODY,
+ HOST_INSTRUCTION_PRECEDENCE,
+} from "../brain/writeback-contract.ts";
+import { renderUnifiedDiff } from "../diff.ts";
+import { atomicWriteFileSync } from "../fs-atomic.ts";
+import { ManagedBlockError, insertManagedBlock, type BlockOpts } from "./managed-block.ts";
+import {
+ RULES_BLOCK_ERROR_KIND,
+ RULES_BLOCK_ID,
+ RULES_BLOCK_MARKERS,
+ type RulesBlockId,
+ RulesBlockError,
+ removeRulesBlock,
+ writeRulesBlock,
+} from "./rules-block.ts";
+import type { InstallEnv } from "./types.ts";
+import type { InstallTargetId } from "../runtime/host-facts.ts";
+
+// ----- Target mapping -------------------------------------------------------
+
+/**
+ * The agent-instruction file `target`'s host reads at the vault root, or
+ * null when the host has no entry in `HOST_INSTRUCTION_PRECEDENCE` - a
+ * NAMED SKIP: such a target installs its adapter but no instruction step,
+ * and the plan says so rather than guessing a file. Derived from the
+ * table, so the checker and the installer can never disagree about which
+ * file a host reads; if the table grows, this follows it.
+ */
+export function instructionBlockTargetFor(target: InstallTargetId): string | null {
+ const files = (HOST_INSTRUCTION_PRECEDENCE as Readonly<Record<string, readonly string[]>>)[
+ target
+ ];
+ return files?.[0] ?? null;
+}
+
+/**
+ * The named skip both install lanes record when `target` maps no
+ * agent-instruction file in `HOST_INSTRUCTION_PRECEDENCE`: one owner for
+ * the sentence the plan's post note, the uninstall payload's
+ * `skipped_reason` and the apply payload's `instruction_block` skip all
+ * carry, so the two JSON receipts cannot drift apart.
+ */
+export function instructionStepNoPrecedenceReason(target: InstallTargetId): string {
+ return `${target} reads no agent-instruction file in HOST_INSTRUCTION_PRECEDENCE`;
+}
+
+// ----- Plan -----------------------------------------------------------------
+
+export interface InstructionBlockPlan {
+ /** The vault-root file the step would rewrite. */
+ readonly path: string;
+ /** Whether the file exists today; false means apply would create it. */
+ readonly exists: boolean;
+ /** Whether applying would change the file's bytes. */
+ readonly changed: boolean;
+ /** Unified diff of the rewrite; empty when `changed` is false. */
+ readonly diff: string;
+ /**
+ * The caveat or named note the consent render owes the operator, or
+ * null when the step is unremarkable. The gemini-cli reading caveat
+ * and the absent-file creation note land here.
+ */
+ readonly note: string | null;
+}
+
+/**
+ * Plan notes keyed by instruction file, not by target: the caveat is
+ * about the FILE (how its host resolves it), and two targets mapping to
+ * one file must render the same honest sentence.
+ */
+const FILE_PLAN_NOTES: Readonly<Record<string, string>> = Object.freeze({
+ "GEMINI.md":
+ "gemini-cli reading GEMINI.md is name-implied only; upstream context.fileName can rename " +
+ "the surface, so the write follows the declared table and the readiness probe audits " +
+ "what the host actually sees",
+});
+
+/** The plan note for a file the apply would create. */
+function creationNote(name: string): string {
+ return `creates ${name} at the vault root; the file becomes visible to the host agent and the vault indexer`;
+}
+
+/** Plan for one instruction file, by name. Pure read plus diff render. */
+function planForFile(env: InstallEnv, name: string): InstructionBlockPlan {
+ const path = join(env.vault, name);
+ let exists: boolean;
+ let before: string;
+ try {
+ // The checker's posture: lstat first, refuse a link before any read.
+ const stat = lstatSync(path);
+ if (stat.isSymbolicLink()) {
+ throw new RulesBlockError(
+ `${path} is a symbolic link - the installer refuses to follow symlinks, because a ` +
+ "write through a link lands outside the file the write-back contract audits",
+ RULES_BLOCK_ERROR_KIND.symlink,
+ path,
+ );
+ }
+ exists = true;
+ before = readFileSync(path, "utf8");
+ } catch (err) {
+ if (err instanceof RulesBlockError) throw err;
+ if ((err as NodeJS.ErrnoException).code === "ENOENT") {
+ exists = false;
+ before = "";
+ } else {
+ throw new RulesBlockError(
+ `${path} could not be read: ${reasonOf(err)}`,
+ RULES_BLOCK_ERROR_KIND.unreadable,
+ path,
+ { cause: err },
+ );
+ }
+ }
+ let after: string;
+ try {
+ after = insertManagedBlock(before, CANONICAL_WRITEBACK_BLOCK_BODY, usageBlockOpts());
+ } catch (err) {
+ // A malformed pair of the block's own spelling refuses the plan the
+ // same way the write would; broken markers are a fix-by-hand state,
+ // never a repair the installer performs (the readiness probe is the
+ // surface that grades it `malformed-block`).
+ if (err instanceof ManagedBlockError) {
+ throw new RulesBlockError(
+ `${path}: ${err.message} - fix or remove the broken block; the installer refuses ` +
+ "to write into a file with malformed markers",
+ RULES_BLOCK_ERROR_KIND.markers,
+ path,
+ { cause: err },
+ );
+ }
+ throw err;
+ }
+ const changed = after !== before;
+ const notes: string[] = [];
+ const fileNote = FILE_PLAN_NOTES[name];
+ if (fileNote !== undefined) notes.push(fileNote);
+ if (!exists) notes.push(creationNote(name));
+ return {
+ path,
+ exists,
+ changed,
+ diff: changed ? renderUnifiedDiff(before, after, path) : "",
+ note: notes.length > 0 ? notes.join("; ") : null,
+ };
+}
+
+/** One line an fs error message, so a multi-line reason stays one detail. */
+function reasonOf(err: unknown): string {
+ const message = err instanceof Error ? err.message : String(err);
+ return message.replace(/\s+/g, " ").trim();
+}
+
+/**
+ * Plan the instruction step for `target` against the vault `env` names.
+ * Pure: reads the candidate file, renders what apply would write, writes
+ * nothing, records nothing. A target with no precedence entry has no
+ * plan - the caller renders the named skip from
+ * {@link instructionBlockTargetFor} instead.
+ */
+export function planInstructionBlock(
+ env: InstallEnv,
+ target: InstallTargetId,
+): InstructionBlockPlan {
+ const name = instructionBlockTargetFor(target);
+ if (name === null) {
+ throw new RulesBlockError(
+ `${target} installs no agent-instruction file: HOST_INSTRUCTION_PRECEDENCE has no ` +
+ "entry for it, so there is no instruction step to plan",
+ RULES_BLOCK_ERROR_KIND.invalidPlan,
+ target,
+ );
+ }
+ return planForFile(env, name);
+}
+
+/** The usage block's markers, as the editor's option shape. */
+function usageBlockOpts(): BlockOpts {
+ const markers = RULES_BLOCK_MARKERS[RULES_BLOCK_ID.usage];
+ return { beginMarker: markers.begin, endMarker: markers.end };
+}
+
+// ----- Apply ----------------------------------------------------------------
+
+export interface InstructionBlockApplyOptions {
+ /** Plan the write and touch nothing; refusals still fire. */
+ readonly dryRun?: boolean;
+ /** Override the hand-edit refusal and write the canonical body. */
+ readonly force?: boolean;
+ /** The plan the consent verdict was rendered from. Required. */
+ readonly approved: InstructionBlockPlan;
+}
+
+export interface InstructionBlockApplyResult {
+ /** The exclusive-create backup of the prior bytes; null when none was taken. */
+ readonly backupPath: string | null;
+ /** True when the apply changed the file's bytes (or would, under `dryRun`). */
+ readonly changed: boolean;
+ /**
+ * True when the apply CREATED the file: it did not exist when the plan
+ * was re-derived. A first install takes no backup (there are no prior
+ * bytes), so `backupPath === null` cannot distinguish "created" from
+ * "already current" - the CLI's post-apply line branches on this field.
+ */
+ readonly created: boolean;
+}
+
+/**
+ * Apply the approved instruction plan: re-derive it from the live disk
+ * and refuse unless it still holds, then write through the shared rules
+ * block writer and record the ownership lock.
+ *
+ * The preview binding: the apply recomputes the plan and every compared
+ * field (`path`, `exists`, `changed`, `diff`) must equal the approved
+ * one, else the on-disk bytes moved since consent and the refusal is
+ * `preview-drift` - the write of an unapproved rewrite is never a
+ * fallback. A plan naming anything but the vault-root agent-instruction
+ * file it claims is refused as `invalid-plan`.
+ *
+ * The hand-edit safety net rides the writer: a block diverged from the
+ * canonical body on a file newer than the lock's `applied_at` refuses
+ * with `user-modified-block` unless `force`; with no lock record at all,
+ * every diverged block refuses too, which is what protects a manually
+ * pasted docs snippet - `--force` is the documented upgrade path, and the
+ * backup it takes is the undo path.
+ *
+ * A successful non-dry-run apply records the lock entry even when nothing
+ * changed: the apply ran under consent and found or left the canonical
+ * block, so uninstall can find the pair it owns. `dryRun` runs the same
+ * refusals and writes nothing - no file change, no backup, no lock.
+ */
+export function applyInstructionBlock(
+ env: InstallEnv,
+ opts: InstructionBlockApplyOptions,
+): InstructionBlockApplyResult {
+ const approved = opts.approved;
+ const name = basename(approved.path);
+ if (
+ !(AGENT_INSTRUCTION_FILES as ReadonlyArray<string>).includes(name) ||
+ approved.path !== join(env.vault, name)
+ ) {
+ throw new RulesBlockError(
+ `the approved plan names ${approved.path}, which is not the vault-root agent-instruction ` +
+ `file ${name} for this vault; refusing to apply a plan that was not derived here`,
+ RULES_BLOCK_ERROR_KIND.invalidPlan,
+ approved.path,
+ );
+ }
+ const fresh = planForFile(env, name);
+ if (
+ fresh.exists !== approved.exists ||
+ fresh.changed !== approved.changed ||
+ fresh.diff !== approved.diff
+ ) {
+ throw new RulesBlockError(
+ `${approved.path} changed since the plan was approved; the apply refuses to write ` +
+ "anything but the approved bytes. Re-run `o2b install --target <host>` to refresh " +
+ "the plan, then apply again",
+ RULES_BLOCK_ERROR_KIND.previewDrift,
+ approved.path,
+ );
+ }
+ const stored = readInstructionBlockLock(env.vault).files[name];
+ const parsedAt = stored === undefined ? Number.NaN : Date.parse(stored.applied_at);
+ const installedAtMs = Number.isFinite(parsedAt) ? parsedAt : null;
+ const result = writeRulesBlock(
+ approved.path,
+ RULES_BLOCK_ID.usage,
+ CANONICAL_WRITEBACK_BLOCK_BODY,
+ {
+ dryRun: opts.dryRun ?? false,
+ force: opts.force ?? false,
+ installedAtMs,
+ },
+ );
+ if (!opts.dryRun) {
+ // Stamp the moment the bytes landed, as the written file's own mtime -
+ // the exact anchor the writer's hand-edit gate compares against.
+ // env.now predates the plan render, the consent prompt and the adapter
+ // apply, so a run-start stamp can sit more than the gate's one-second
+ // slack behind the file's mtime and make our OWN write read as a later
+ // hand edit on the next canonical-body upgrade: every interactive
+ // install would then refuse that upgrade with user-modified-block
+ // instead of taking the documented rewrite path. A file that cannot be
+ // re-statted falls back to the wall clock at record time, which still
+ // postdates the run start.
+ let landed = Date.now();
+ try {
+ landed = statSync(approved.path, { throwIfNoEntry: false })?.mtimeMs ?? landed;
+ } catch {
+ // Keep the wall-clock fallback: the same posture the writer's own
+ // mtime probe takes, so any stat failure (EACCES, ELOOP, EIO)
+ // records a real post-write stamp instead of leaving the fresh
+ // write unrecorded.
+ }
+ recordInstructionBlock(env.vault, name, {
+ block_id: RULES_BLOCK_ID.usage,
+ begin_marker: RULES_BLOCK_MARKERS.usage.begin,
+ applied_at: new Date(landed).toISOString(),
+ });
+ }
+ return {
+ backupPath: result.backupPath,
+ changed: result.changed,
+ created: result.changed && !fresh.exists,
+ };
+}
+
+// ----- Uninstall ------------------------------------------------------------
+
+export interface InstructionBlockUninstallOptions {
+ /** Plan the removal and touch nothing. */
+ readonly dryRun?: boolean;
+}
+
+export interface InstructionBlockUninstallResult {
+ /** True when the file's bytes changed: the pair existed and is gone. */
+ readonly removed: boolean;
+}
+
+/**
+ * Remove the usage block pair from one instruction file, the reverse of
+ * {@link applyInstructionBlock}. The removal goes through the shared
+ * writer's remove: only the pair this tool owns is rewritten away,
+ * operator bytes preserved, the file itself never removed. A file with
+ * no pair of that spelling is a NAMED SKIP (`removed: false`), and a
+ * stale lock entry is cleared either way so the lock never claims a pair
+ * that is gone. Malformed markers refuse - uninstall never repairs - and
+ * symbolic links refuse before any read.
+ */
+export function uninstallInstructionBlock(
+ env: InstallEnv,
+ name: string,
+ opts: InstructionBlockUninstallOptions = {},
+): InstructionBlockUninstallResult {
+ const path = join(env.vault, name);
+ const result = removeRulesBlock(path, RULES_BLOCK_ID.usage, opts);
+ if (!opts.dryRun) clearInstructionBlock(env.vault, name);
+ return { removed: result.removed };
+}
+
+// ----- Ownership lock -------------------------------------------------------
+
+/** The lock file this installer records its owned blocks in. */
+export const INSTRUCTION_BLOCK_LOCK_FILE = "instruction-block.lock.json";
+
+/** The one schema the lock parses. A different number refuses. */
+const INSTRUCTION_BLOCK_LOCK_SCHEMA_VERSION = 1;
+
+export interface InstructionBlockLockEntry {
+ /** The block id whose fence this file carries. Always `usage` today. */
+ readonly block_id: RulesBlockId;
+ /** The begin marker recorded at apply time, for audit. */
+ readonly begin_marker: string;
+ /** When this installer last wrote (or confirmed) the block, ISO 8601. */
+ readonly applied_at: string;
+}
+
+export interface InstructionBlockLock {
+ readonly schema_version: 1;
+ /** Instruction file basename to its ownership entry. */
+ readonly files: Record<string, InstructionBlockLockEntry>;
+}
+
+/** The lock's path in `vault`'s derived store. */
+export function instructionBlockLockPath(vault: string): string {
+ return join(vault, DERIVED_STORE_DIR, INSTRUCTION_BLOCK_LOCK_FILE);
+}
+
+/**
+ * Read the ownership lock. An absent file is the empty schema-1 document
+ * - nothing owns a block yet - never an error, because uninstall must be
+ * able to run before any install. A symbolic link refuses (a redirected
+ * lock would read state this vault never wrote); corrupted JSON, a
+ * non-object document and an unsupported schema version refuse with the
+ * path in the message, the same posture the install manifest's parser
+ * holds.
+ */
+export function readInstructionBlockLock(vault: string): InstructionBlockLock {
+ const path = instructionBlockLockPath(vault);
+ let stat;
+ try {
+ stat = lstatSync(path);
+ } catch (err) {
+ if ((err as NodeJS.ErrnoException).code === "ENOENT") {
+ return { schema_version: INSTRUCTION_BLOCK_LOCK_SCHEMA_VERSION, files: {} };
+ }
+ throw new RulesBlockError(
+ `${path} could not be stat'ed: ${reasonOf(err)}`,
+ RULES_BLOCK_ERROR_KIND.unreadable,
+ path,
+ { cause: err },
+ );
+ }
+ if (stat.isSymbolicLink()) {
+ throw new RulesBlockError(
+ `${path} is a symbolic link - the lock refuses to read through links, because a ` +
+ "redirected lock would report ownership this vault never recorded",
+ RULES_BLOCK_ERROR_KIND.symlink,
+ path,
+ );
+ }
+ let raw: string;
+ try {
+ raw = readFileSync(path, "utf8");
+ } catch (err) {
+ throw new RulesBlockError(
+ `${path} could not be read: ${reasonOf(err)}`,
+ RULES_BLOCK_ERROR_KIND.unreadable,
+ path,
+ { cause: err },
+ );
+ }
+ let parsed: unknown;
+ try {
+ parsed = JSON.parse(raw);
+ } catch (err) {
+ throw new Error(
+ `instruction-block lock is corrupted JSON: ${path}\nOriginal error: ${(err as Error).message}`,
+ { cause: err },
+ );
+ }
+ if (parsed === null || typeof parsed !== "object" || Array.isArray(parsed)) {
+ throw new Error(`instruction-block lock is not an object: ${path}`);
+ }
+ const obj = parsed as Record<string, unknown>;
+ const sv = obj["schema_version"];
+ if (sv !== INSTRUCTION_BLOCK_LOCK_SCHEMA_VERSION) {
+ throw new Error(
+ `instruction-block lock schema_version ${sv} not supported (expected ` +
+ `${INSTRUCTION_BLOCK_LOCK_SCHEMA_VERSION}): ${path}`,
+ );
+ }
+ const files = (obj["files"] ?? {}) as Record<string, InstructionBlockLockEntry>;
+ if (typeof files !== "object" || Array.isArray(files)) {
+ throw new Error(`instruction-block lock files field is not an object: ${path}`);
+ }
+ return { schema_version: INSTRUCTION_BLOCK_LOCK_SCHEMA_VERSION, files };
+}
+
+/**
+ * Record (or replace) one file's ownership entry and write the lock
+ * atomically. The derived store is created on demand; the write is the
+ * shared atomic writer's, so a crash leaves either the previous lock or
+ * the new one.
+ */
+export function recordInstructionBlock(
+ vault: string,
+ name: string,
+ entry: InstructionBlockLockEntry,
+): void {
+ const current = readInstructionBlockLock(vault);
+ writeInstructionBlockLock(vault, {
+ schema_version: INSTRUCTION_BLOCK_LOCK_SCHEMA_VERSION,
+ files: { ...current.files, [name]: entry },
+ });
+}
+
+/**
+ * Drop one file's ownership entry. A name the lock never recorded is a
+ * quiet no-op: uninstall of an install that never recorded must stay a
+ * skip, not an error.
+ */
+export function clearInstructionBlock(vault: string, name: string): void {
+ const current = readInstructionBlockLock(vault);
+ if (!(name in current.files)) return;
+ const files = { ...current.files };
+ delete files[name];
+ writeInstructionBlockLock(vault, {
+ schema_version: INSTRUCTION_BLOCK_LOCK_SCHEMA_VERSION,
+ files,
+ });
+}
+
+function writeInstructionBlockLock(vault: string, lock: InstructionBlockLock): void {
+ const path = instructionBlockLockPath(vault);
+ // The atomic writer creates the parent directory with the write; the
+ // explicit mkdir mirrors the install manifest's posture so a read-only
+ // store fails here, at the named call, rather than inside the writer.
+ const dir = dirname(path);
+ if (!existsSync(dir)) mkdirSync(dir, { recursive: true });
+ atomicWriteFileSync(path, JSON.stringify(lock, null, 2) + "\n");
+}
diff --git a/src/core/install/rules-block.ts b/src/core/install/rules-block.ts
new file mode 100644
index 00000000..c348e376
--- /dev/null
+++ b/src/core/install/rules-block.ts
@@ -0,0 +1,659 @@
+/**
+ * The shared marker-fenced rules-block writer for agent instruction files.
+ *
+ * ONE writer owns every byte that enters a managed block in a vault-root
+ * agent rules file (AGENTS.md / CLAUDE.md / GEMINI.md). Two producers call
+ * it and neither writes such a file any other way:
+ *
+ * - the `usage` producer (the installer, `src/core/install/
+ * instruction-block.ts`) writes the ambient write-back gate block,
+ * - the `lessons` producer (the operator verbs over
+ * `src/core/brain/lessons-promotion.ts`) promotes approved lessons
+ * into a sibling block.
+ *
+ * The two producers coexist in ONE file because each block id carries its
+ * OWN marker spelling: `usage` keeps the settled default managed-block
+ * markers (the write-back contract's contract spellings,
+ * `src/core/brain/writeback-contract.ts`), `lessons` uses a distinct
+ * HTML-comment pair. The editor below validates one pair per spelling, so
+ * a second block never fights the first (t_1e952e43, section 3.3).
+ *
+ * Invariants, each pinned by `tests/core/install/rules-block.test.ts`:
+ *
+ * - every operator byte OUTSIDE the block is preserved (the
+ * `managed-block.ts` editor guarantee);
+ * - a re-apply with the canonical body is a byte no-op (`changed:
+ * false`), so producers can run on every render;
+ * - CRLF files keep CRLF line endings, detected and restored by the
+ * editor;
+ * - the first write to an existing file takes an exclusive-create,
+ * collision-laddered backup beside the file and returns its path; a
+ * no-op takes none;
+ * - a block whose body diverges from the canonical body on a file
+ * NEWER than the recorded install time is a hand edit: refused with
+ * kind `user-modified-block` unless `force` (the aider adapter's
+ * safety net, generalised here so both producers share it). A
+ * diverged block on a file OLDER than the install time is a canonical
+ * body that moved under an untouched file: rewritten, not refused.
+ * No install time at all refuses too - a block nobody recorded cannot
+ * be proven ours, and silently replacing it would clobber operator
+ * text. The same refusal covers a file that cannot be re-statted at
+ * gate time and an install stamp that sits in the future: neither can
+ * prove the block untouched, and the gate fails closed;
+ * - the bytes the merge was based on are re-checked before anything is
+ * written, and again inside the atomic writer immediately before the
+ * rename. A mid-flight edit elsewhere refuses with kind
+ * `concurrent-modification`, leaving the file and any backup
+ * untouched; `force` is the deliberate overwrite;
+ * - symbolic links are refused before any read or write: a writer that
+ * follows a link has left the file the audit measures;
+ * - multiple, unpaired or reversed markers of the block's OWN spelling
+ * refuse with a wrapped `ManagedBlockError`; a different spelling's
+ * stray markers never block this block;
+ * - `dryRun` computes and refuses exactly like a real run and writes
+ * nothing on every path.
+ *
+ * This module reads and writes single files named by the caller and
+ * reaches the disk only through the shared atomic writers
+ * (`src/core/fs-atomic.ts`): it joins no vault path, keeps no state, and
+ * never removes a file - removal means rewriting the file without the
+ * block.
+ */
+
+import { lstatSync, readFileSync, statSync } from "node:fs";
+
+import {
+ atomicCreateFileSyncExclusive,
+ atomicWriteFileSync,
+ fileMatchesExpected,
+ isFileAlreadyExists,
+ isFileDrift,
+} from "../fs-atomic.ts";
+import {
+ DEFAULT_BEGIN_MARKER,
+ DEFAULT_END_MARKER,
+ ManagedBlockError,
+ extractManagedBlock,
+ insertManagedBlock,
+ removeManagedBlock,
+ type BlockOpts,
+} from "./managed-block.ts";
+
+// ----- Errors ---------------------------------------------------------------
+
+/** Why a rules-block operation refused, as a closed vocabulary. */
+export const RULES_BLOCK_ERROR_KIND = Object.freeze({
+ /** The path could not be stat'ed or read as a file. */
+ unreadable: "unreadable",
+ /** The path is a symbolic link; the operation refuses to follow it. */
+ symlink: "symlink",
+ /** The block's own markers are multiple, unpaired or reversed. */
+ markers: "markers",
+ /** The block diverged from the canonical body on a hand-edited file. */
+ userModifiedBlock: "user-modified-block",
+ /**
+ * The on-disk bytes moved since the caller's approved preview. Thrown
+ * by the installer's plan/apply binding
+ * (`src/core/install/instruction-block.ts`), which re-derives the
+ * preview at apply time and must refuse a write of anything else.
+ */
+ previewDrift: "preview-drift",
+ /**
+ * The approved preview does not name a file this installer could have
+ * derived: a path off the vault root, or not an agent-instruction file
+ * at all. A plan that was not produced against this vault must never
+ * be applied to it.
+ */
+ invalidPlan: "invalid-plan",
+ /**
+ * The on-disk bytes moved while the operation was being prepared: the
+ * merge or removal was based on bytes that are no longer current.
+ * Nothing was written and no backup was taken; the operator re-runs
+ * the command (a re-run re-reads the file and converges) or passes
+ * `--force` to overwrite the current bytes deliberately.
+ */
+ concurrentModification: "concurrent-modification",
+} as const);
+
+/** Closed union over {@link RULES_BLOCK_ERROR_KIND}. */
+export type RulesBlockErrorKind =
+ (typeof RULES_BLOCK_ERROR_KIND)[keyof typeof RULES_BLOCK_ERROR_KIND];
+
+/**
+ * A rules-block refusal, named so callers branch on `kind` and never on
+ * message text. Marker-shape refusals carry the editor's own
+ * `ManagedBlockError` as their `cause`: one validation vocabulary, two
+ * error surfaces.
+ */
+export class RulesBlockError extends Error {
+ constructor(
+ message: string,
+ public readonly kind: RulesBlockErrorKind,
+ public readonly path: string,
+ options?: { readonly cause?: unknown },
+ ) {
+ super(message, options);
+ this.name = "RulesBlockError";
+ }
+}
+
+// ----- Block identity -------------------------------------------------------
+
+/** The managed blocks this writer installs into agent rules files. */
+export const RULES_BLOCK_ID = Object.freeze({
+ /** The ambient write-back gate block, the write-back contract's subject. */
+ usage: "usage",
+ /** The operator-approved lessons block (t_1e952e43). */
+ lessons: "lessons",
+} as const);
+
+/** Closed union over {@link RULES_BLOCK_ID}. */
+export type RulesBlockId = (typeof RULES_BLOCK_ID)[keyof typeof RULES_BLOCK_ID];
+
+/**
+ * Each block id's marker spelling. The `usage` entry IS the settled
+ * default managed-block pair - the write-back contract audits those exact
+ * lines, so they are re-exported rather than re-spelled. The `lessons`
+ * entry is a distinct HTML-comment pair so both blocks can live in one
+ * file: the editor holds one pair per spelling, and spellings never share
+ * a marker line.
+ */
+export const RULES_BLOCK_MARKERS: Readonly<
+ Record<RulesBlockId, { readonly begin: string; readonly end: string }>
+> = Object.freeze({
+ usage: Object.freeze({ begin: DEFAULT_BEGIN_MARKER, end: DEFAULT_END_MARKER }),
+ lessons: Object.freeze({
+ begin: "<!-- >>> open-second-brain lessons >>> -->",
+ end: "<!-- >>> open-second-brain lessons <<< -->",
+ }),
+});
+
+/** The markers for `blockId`, as the editor's option shape. */
+function blockOpts(blockId: RulesBlockId): BlockOpts {
+ const markers = RULES_BLOCK_MARKERS[blockId];
+ return { beginMarker: markers.begin, endMarker: markers.end };
+}
+
+// ----- Rendering ------------------------------------------------------------
+
+export interface RenderedRulesBlock {
+ readonly beginMarker: string;
+ readonly endMarker: string;
+ /** The full file a NEW rules file starts as, trailing newline included. */
+ readonly document: string;
+}
+
+/**
+ * Render the fenced document `body` becomes in a rules file. The document
+ * is produced by the same editor call a write to an absent file takes, so
+ * a rendered preview and a real first write cannot disagree.
+ */
+export function renderRulesBlock(blockId: RulesBlockId, body: string): RenderedRulesBlock {
+ const markers = RULES_BLOCK_MARKERS[blockId];
+ return {
+ beginMarker: markers.begin,
+ endMarker: markers.end,
+ document: insertManagedBlock("", body, blockOpts(blockId)),
+ };
+}
+
+// ----- Reading --------------------------------------------------------------
+
+interface ReadResult {
+ /** Whether any file exists at the path. */
+ readonly exists: boolean;
+ /** The file's bytes as read; the empty string when it does not exist. */
+ readonly content: string;
+ /** The file's mtime in ms, from the same lstat the refusal used. */
+ readonly mtimeMs: number;
+ /** True when a well-formed pair of this spelling exists. */
+ readonly present: boolean;
+ /** The extracted body; null unless `present`. */
+ readonly body: string | null;
+}
+
+/**
+ * lstat the file, refusing symbolic links and absent paths by name, then
+ * read it and decide whether a well-formed pair of this spelling exists.
+ *
+ * The marker shapes are decided here so the refusals can be NAMED rather
+ * than collapsed into a null: multiple, unpaired or reversed markers of
+ * this spelling throw {@link RulesBlockError} wrapping the editor's
+ * `ManagedBlockError`, while a file with no marker line of this spelling
+ * at all is simply `present: false`. Extraction itself stays the editor's
+ * (`extractManagedBlock`), so reading can never disagree with writing.
+ */
+function readRulesFile(file: string, blockId: RulesBlockId): ReadResult {
+ let stat;
+ try {
+ stat = lstatSync(file);
+ } catch (err) {
+ if ((err as NodeJS.ErrnoException).code === "ENOENT") {
+ return { exists: false, content: "", mtimeMs: 0, present: false, body: null };
+ }
+ throw new RulesBlockError(
+ `${file} could not be stat'ed: ${reason(err)}`,
+ RULES_BLOCK_ERROR_KIND.unreadable,
+ file,
+ { cause: err },
+ );
+ }
+ if (stat.isSymbolicLink()) {
+ throw new RulesBlockError(
+ `${file} is a symbolic link - the rules-block writer refuses to follow symlinks, ` +
+ "because a write through a link lands outside the file the audit measures",
+ RULES_BLOCK_ERROR_KIND.symlink,
+ file,
+ );
+ }
+ let content: string;
+ try {
+ content = readFileSync(file, "utf8");
+ } catch (err) {
+ throw new RulesBlockError(
+ `${file} could not be read: ${reason(err)}`,
+ RULES_BLOCK_ERROR_KIND.unreadable,
+ file,
+ { cause: err },
+ );
+ }
+ return { exists: true, content, mtimeMs: stat.mtimeMs, ...blockStateIn(content, blockId, file) };
+}
+
+/**
+ * Whether `content` carries this block, and its body, without touching
+ * the filesystem. Absent is silent; a malformed pair of this spelling is
+ * a named refusal wrapping `ManagedBlockError`.
+ */
+function blockStateIn(
+ content: string,
+ blockId: RulesBlockId,
+ file: string,
+): { present: boolean; body: string | null } {
+ const markers = RULES_BLOCK_MARKERS[blockId];
+ const lines = content.replace(/\r\n/g, "\n").split("\n");
+ let begins = 0;
+ let ends = 0;
+ for (const line of lines) {
+ if (line === markers.begin) begins += 1;
+ if (line === markers.end) ends += 1;
+ }
+ if (begins === 0 && ends === 0) return { present: false, body: null };
+ // The editor's validator refuses every non-single-pair shape; drive it
+ // through a pure re-insert so the message vocabulary stays the editor's.
+ try {
+ insertManagedBlock(content, "shape probe", blockOpts(blockId));
+ } catch (err) {
+ if (err instanceof ManagedBlockError) {
+ throw new RulesBlockError(
+ `${markers.begin} / ${markers.end}: ${err.message} - fix or remove the broken ` +
+ "block before this operation can run",
+ RULES_BLOCK_ERROR_KIND.markers,
+ file,
+ { cause: err },
+ );
+ }
+ throw err;
+ }
+ const body = extractManagedBlock(content, blockOpts(blockId));
+ if (body === null) {
+ // One begin, one end, in order - yet the editor could not extract.
+ // Unreachable per the editor's contract; refused rather than guessed.
+ throw new RulesBlockError(
+ `${markers.begin} / ${markers.end}: a well-formed pair validated but extracted no body`,
+ RULES_BLOCK_ERROR_KIND.markers,
+ file,
+ );
+ }
+ return { present: true, body };
+}
+
+/** One line an fs error message, so a multi-line reason stays one detail. */
+function reason(err: unknown): string {
+ const message = err instanceof Error ? err.message : String(err);
+ return message.replace(/\s+/g, " ").trim();
+}
+
+/**
+ * The block body `file` carries for `blockId`, or null when the file (or
+ * the pair of this spelling) does not exist. Malformed pairs and symlinks
+ * refuse by name - a reader that silently ignored either would report a
+ * block absent that is in fact broken or unreadable.
+ */
+export function readRulesBlock(file: string, blockId: RulesBlockId): string | null {
+ return readRulesFile(file, blockId).body;
+}
+
+// ----- Drift ----------------------------------------------------------------
+
+/** How a managed block compares to the canonical body it should carry. */
+export const RULES_BLOCK_STATE = Object.freeze({
+ /** No file, or no pair of this spelling in it. */
+ absent: "absent",
+ /** The pair exists and its body matches the canonical body. */
+ current: "current",
+ /** The pair exists but its body diverged from the canonical body. */
+ drifted: "drifted",
+} as const);
+
+/** Closed union over {@link RULES_BLOCK_STATE}. */
+export type RulesBlockState = (typeof RULES_BLOCK_STATE)[keyof typeof RULES_BLOCK_STATE];
+
+export interface RulesBlockDriftResult {
+ readonly state: RulesBlockState;
+ /** The extracted body; null unless the pair exists. */
+ readonly extracted: string | null;
+}
+
+/** True when two block bodies are the same text, ignoring the fence-adjacent trailing newline. */
+function sameBlockBody(extracted: string, canonical: string): boolean {
+ return stripTrailingNewline(extracted) === stripTrailingNewline(canonical);
+}
+
+function stripTrailingNewline(text: string): string {
+ return text.replace(/[\r\n]+$/, "");
+}
+
+/**
+ * Compare `file`'s block for `blockId` against `canonicalBody`. READ-ONLY:
+ * producers call it to decide whether a write is owed, and doctor and
+ * status surfaces call it to grade a managed block without writing.
+ * Malformed pairs and symlinks refuse by name, as in
+ * {@link readRulesBlock}.
+ */
+export function rulesBlockDrift(
+ file: string,
+ blockId: RulesBlockId,
+ canonicalBody: string,
+): RulesBlockDriftResult {
+ const read = readRulesFile(file, blockId);
+ if (!read.present) return { state: RULES_BLOCK_STATE.absent, extracted: null };
+ return {
+ state: sameBlockBody(read.body as string, canonicalBody)
+ ? RULES_BLOCK_STATE.current
+ : RULES_BLOCK_STATE.drifted,
+ extracted: read.body,
+ };
+}
+
+// ----- Writing --------------------------------------------------------------
+
+export interface RulesBlockWriteOptions {
+ /** Plan the write and touch nothing. Refusals still fire. */
+ readonly dryRun?: boolean;
+ /** Override the hand-edit refusal and write the canonical body. */
+ readonly force?: boolean;
+ /**
+ * The install time recorded for this block, in ms. A diverged block on
+ * a file newer than this (plus a small clock slack) is a hand edit and
+ * refuses unless `force`; a diverged block on an older file is a
+ * canonical body that moved and is rewritten. `null` or omitted means
+ * no ownership record exists, so every diverged block refuses - a block
+ * nobody recorded cannot be proven ours. A stamp further than
+ * {@link FUTURE_ANCHOR_ALLOWANCE_MS} into the future counts as no
+ * record either: a future stamp would silently disarm the gate.
+ */
+ readonly installedAtMs?: number | null;
+ /** Test seams for the race-window refusals; production omits them. */
+ readonly seams?: RulesBlockSeams;
+}
+
+/**
+ * Test-only indirections over the two re-reads the fail-closed gates
+ * perform, so the race-window refusals can be pinned deterministically
+ * without racing a real second writer (the same pattern as
+ * `RenameRetrySeams` in `src/core/fs-atomic.ts`). Production callers
+ * never pass this.
+ */
+export interface RulesBlockSeams {
+ /**
+ * The mtime the hand-edit gate reads from the live file; null models a
+ * stat failure (a mid-flight move). Defaults to a real `statSync`.
+ */
+ readonly fileMtimeMs?: (path: string) => number | null;
+ /**
+ * The current-bytes comparison behind the drift refusal; false models
+ * the file having moved since the merge read it. Defaults to
+ * `fileMatchesExpected` from `src/core/fs-atomic.ts`.
+ */
+ readonly currentBytesMatch?: (target: string, expected: string | null) => boolean;
+}
+
+export interface RulesBlockWriteResult {
+ /** True when the file's bytes changed (or would, under `dryRun`). */
+ readonly changed: boolean;
+ /** The exclusive-create backup of the prior bytes; null when none was taken. */
+ readonly backupPath: string | null;
+}
+
+/**
+ * Bound on distinct backup names one stamp tries (`<file>.bak.<ms>`,
+ * `-2`, ...). Exhaustion is a typed refusal, never an overwrite.
+ */
+export const RULES_BLOCK_BACKUP_MAX_ATTEMPTS = 128;
+
+/**
+ * Clock slack between the recorded install time and the file mtime, in
+ * ms. The aider adapter's precedent: a write that lands within a second
+ * of its own record must not read as a later hand edit.
+ */
+const MTIME_SLACK_MS = 1000;
+
+/**
+ * How far past `Date.now()` an install or promotion anchor may sit and
+ * still count as a record: a small clock-skew allowance. An anchor any
+ * further into the future is treated as NO record - the fail-closed
+ * direction - because the anchor lives in agent-writable state, and a
+ * future-stamped record would make every later operator hand-edit read
+ * as a canonical move under an untouched file, silently disarming the
+ * hand-edit gate.
+ */
+export const FUTURE_ANCHOR_ALLOWANCE_MS = 5 * 60 * 1000;
+
+/** Candidate `attempt` of the backup-name ladder. */
+function collisionCandidate(base: string, attempt: number): string {
+ return attempt === 1 ? base : `${base}-${attempt}`;
+}
+
+/**
+ * Back the current bytes up beside `file` before the first rewrite.
+ * Exclusive create (`link(2)`, `src/core/fs-atomic.ts`), private 0600,
+ * same-millisecond collisions ladder the name, and an exhausted ladder is
+ * a typed refusal rather than a silent overwrite.
+ */
+function backupRulesFile(file: string, before: string): string {
+ const base = `${file}.bak.${Date.now()}`;
+ for (let attempt = 1; attempt <= RULES_BLOCK_BACKUP_MAX_ATTEMPTS; attempt++) {
+ try {
+ atomicCreateFileSyncExclusive(collisionCandidate(base, attempt), before, { mode: 0o600 });
+ return collisionCandidate(base, attempt);
+ } catch (err) {
+ if (!isFileAlreadyExists(err)) throw err;
+ }
+ }
+ throw new RulesBlockError(
+ `backup allocation exhausted for ${file} (${RULES_BLOCK_BACKUP_MAX_ATTEMPTS} candidates ` +
+ "taken); refusing to overwrite",
+ RULES_BLOCK_ERROR_KIND.unreadable,
+ file,
+ );
+}
+
+/**
+ * Write (or plan) the managed block for `blockId` in `file`, carrying
+ * `canonicalBody` between the markers.
+ *
+ * Absent file: the file is created with just the rendered block - no
+ * backup, because there are no prior bytes. Existing file: the editor
+ * inserts or replaces the pair of this spelling, every byte outside it
+ * preserved; the first byte-changing write takes an exclusive-create
+ * backup of the current bytes and returns its path. A byte-identical
+ * re-apply reports `changed: false` and takes no backup.
+ *
+ * Refusals, all named: symlinks (`symlink`), unreadable paths
+ * (`unreadable`), malformed marker pairs of this spelling (`markers`,
+ * wrapping `ManagedBlockError`), a hand-edited block
+ * (`user-modified-block`) when the body diverged from the canonical body
+ * and the file is newer than `installedAtMs` - or when no trustworthy
+ * install time is known at all, which includes a file that cannot be
+ * re-statted at gate time and a stamp sitting in the future - and a
+ * mid-flight edit elsewhere (`concurrent-modification`). `force`
+ * overrides the hand-edit refusal and the drift refusal; it is the
+ * operator's deliberate overwrite.
+ */
+export function writeRulesBlock(
+ file: string,
+ blockId: RulesBlockId,
+ canonicalBody: string,
+ opts: RulesBlockWriteOptions = {},
+): RulesBlockWriteResult {
+ const read = readRulesFile(file, blockId);
+ const absent = !read.exists;
+ const next = absent
+ ? renderRulesBlock(blockId, canonicalBody).document
+ : insertManagedBlock(read.content, canonicalBody, blockOpts(blockId));
+ if (next === read.content) return { changed: false, backupPath: null };
+
+ // The hand-edit safety net: a diverged block on a file the operator
+ // touched after the install (or with no trustworthy recorded install)
+ // is theirs until `force` says otherwise.
+ if (read.present) {
+ const diverged = !sameBlockBody(read.body as string, canonicalBody);
+ const anchor =
+ typeof opts.installedAtMs === "number" && Number.isFinite(opts.installedAtMs)
+ ? opts.installedAtMs
+ : null;
+ const anchorTrusted = anchor !== null && anchor <= Date.now() + FUTURE_ANCHOR_ALLOWANCE_MS;
+ const mtime = (opts.seams?.fileMtimeMs ?? fileMtimeMs)(file);
+ const touchedAfterInstall =
+ !anchorTrusted || mtime === null || mtime > (anchor as number) + MTIME_SLACK_MS;
+ if (diverged && touchedAfterInstall && !opts.force) {
+ const gateDetail =
+ anchor !== null && !anchorTrusted
+ ? " - the recorded install time is in the future and is treated as no record"
+ : mtime === null
+ ? " - the file could not be re-statted, so it cannot be proven untouched"
+ : "";
+ throw new RulesBlockError(
+ `${file} appears hand-edited after the last install (the ${blockId} block diverges ` +
+ `from canonical content${gateDetail}); refusing to overwrite. ` +
+ "Re-run with --force to overwrite, or uninstall first",
+ RULES_BLOCK_ERROR_KIND.userModifiedBlock,
+ file,
+ );
+ }
+ }
+
+ // The drift guard: the merge above was computed from the bytes the
+ // first read saw. If those are no longer current, writing would clobber
+ // an edit this run never saw - refused before the backup is taken, so
+ // the refused run touches nothing. The atomic writer re-checks the same
+ // expectation immediately before the rename, closing the window this
+ // pre-check leaves; a drift surfacing there is wrapped into the same
+ // named refusal.
+ const expected = absent ? null : read.content;
+ const concurrentMessage =
+ `${file} changed while the ${blockId} block write was being prepared; refusing to ` +
+ "overwrite bytes this run never saw. Re-run the command to converge, or pass " +
+ "--force to overwrite the current bytes deliberately";
+ if (!opts.force && !(opts.seams?.currentBytesMatch ?? fileMatchesExpected)(file, expected)) {
+ throw new RulesBlockError(
+ concurrentMessage,
+ RULES_BLOCK_ERROR_KIND.concurrentModification,
+ file,
+ );
+ }
+
+ if (opts.dryRun) {
+ return { changed: true, backupPath: null };
+ }
+ const backupPath = absent ? null : backupRulesFile(file, read.content);
+ try {
+ atomicWriteFileSync(file, next, opts.force ? {} : { expectBefore: expected });
+ } catch (err) {
+ if (isFileDrift(err)) {
+ throw new RulesBlockError(
+ concurrentMessage,
+ RULES_BLOCK_ERROR_KIND.concurrentModification,
+ file,
+ {
+ cause: err,
+ },
+ );
+ }
+ throw err;
+ }
+ return { changed: true, backupPath };
+}
+
+function fileMtimeMs(path: string): number | null {
+ try {
+ return statSync(path, { throwIfNoEntry: false })?.mtimeMs ?? null;
+ } catch {
+ return null;
+ }
+}
+
+export interface RulesBlockRemoveOptions {
+ /** Plan the removal and touch nothing. */
+ readonly dryRun?: boolean;
+ /** Test seams for the race-window refusal; production omits them. */
+ readonly seams?: RulesBlockSeams;
+}
+
+export interface RulesBlockRemoveResult {
+ /**
+ * True when the file will change (or changed): the pair of this
+ * spelling existed and the file is rewritten without it.
+ */
+ readonly removed: boolean;
+}
+
+/**
+ * Remove the managed block for `blockId` from `file`: rewrite the file
+ * without that marker pair and its body, collapsing the padding the pair
+ * carried, every other byte preserved. A file with no pair of this
+ * spelling is a NAMED SKIP (`removed: false`), not an error, so
+ * uninstalling an install that never landed stays quiet. The file itself
+ * is never removed. Symlinks refuse by name, as everywhere above, and
+ * the same drift guard as the write path refuses a mid-flight edit with
+ * kind `concurrent-modification`, leaving the file untouched.
+ */
+export function removeRulesBlock(
+ file: string,
+ blockId: RulesBlockId,
+ opts: RulesBlockRemoveOptions = {},
+): RulesBlockRemoveResult {
+ const read = readRulesFile(file, blockId);
+ const state = blockStateIn(read.content, blockId, file);
+ if (!state.present) return { removed: false };
+ const next = removeManagedBlock(read.content, blockOpts(blockId));
+ if (next === read.content) return { removed: false };
+ const concurrentMessage =
+ `${file} changed while the ${blockId} block removal was being prepared; refusing to ` +
+ "overwrite bytes this run never saw. Re-run the removal to converge";
+ if (!(opts.seams?.currentBytesMatch ?? fileMatchesExpected)(file, read.content)) {
+ throw new RulesBlockError(
+ concurrentMessage,
+ RULES_BLOCK_ERROR_KIND.concurrentModification,
+ file,
+ );
+ }
+ if (opts.dryRun) return { removed: true };
+ try {
+ atomicWriteFileSync(file, next, { expectBefore: read.content });
+ } catch (err) {
+ if (isFileDrift(err)) {
+ throw new RulesBlockError(
+ concurrentMessage,
+ RULES_BLOCK_ERROR_KIND.concurrentModification,
+ file,
+ {
+ cause: err,
+ },
+ );
+ }
+ throw err;
+ }
+ return { removed: true };
+}
diff --git a/src/core/search/visibility-surface-registry.ts b/src/core/search/visibility-surface-registry.ts
index 9f3a2d4f..8d6e8a6a 100644
--- a/src/core/search/visibility-surface-registry.ts
+++ b/src/core/search/visibility-surface-registry.ts
@@ -781,6 +781,17 @@ export const VISIBILITY_SURFACE_REGISTRY: ReadonlyArray<VisibilitySurfaceEntry>
"rule is live, because a corpus size taken before the filter states how many pages were " +
"withheld.",
},
+ {
+ surface: "brain_skill_rewrite_status",
+ kind: K.mcpTool,
+ category: C.excluded,
+ reason:
+ "reads one skill's benchmark-gated rewrite lane status: the frozen benchmark receipt, " +
+ "the grade ledger's verdict-and-rate rows for that skill, and the slug of a staged " +
+ "proposal awaiting a human accept. It names no note path, title or body at any reach - " +
+ "the same ids-and-rates discipline as the grade record itself - so there is no page " +
+ "content for a read root to withhold, and MCP never accepts or scores regardless.",
+ },
{
surface: "brain_procedural_memory",
kind: K.mcpTool,
diff --git a/src/core/state/surfaces.ts b/src/core/state/surfaces.ts
index 26e3ed42..34a841b6 100644
--- a/src/core/state/surfaces.ts
+++ b/src/core/state/surfaces.ts
@@ -88,6 +88,7 @@ import {
DERIVED_STORE_FILE,
HOOK_AUDIT_DIR,
} from "../brain/path-constants.ts";
+import { SKILL_BENCHMARKS_DIR } from "../brain/skill-rewrite-tasks.ts";
import { WATCHDOG_FALLBACK_AUDIT_DIR } from "../brain/audit-dirs.ts";
import { JSONL_LEDGER_EXT, jsonlLedgerGrammar, parseShardedName } from "../brain/ledger-shards.ts";
import { MAINTENANCE_JOURNAL_STEM } from "../brain/maintenance/journal.ts";
@@ -164,6 +165,9 @@ export const STATE_SURFACE_ID = Object.freeze({
captureWatermark: "capture_watermark",
decisionLedger: "decision_ledger",
sourceArchives: "source_archives",
+ instructionBlockLock: "instruction_block_lock",
+ lessonApprovals: "lesson_approvals",
+ skillBenchmarks: "skill_benchmarks",
} as const);
export type StateSurfaceId = (typeof STATE_SURFACE_ID)[keyof typeof STATE_SURFACE_ID];
@@ -296,6 +300,8 @@ const SESSION_MINING_LEDGER_FILE = "session-mining-ledger.json";
const SESSION_MINING_SURVEYS_FILE = "session-mining-surveys.json";
const INSTALL_MANIFEST_FILE = "install.lock.json";
const PROTECT_MANIFEST_FILE = "protect.lock.json";
+const INSTRUCTION_BLOCK_LOCK_FILE = "instruction-block.lock.json";
+const LESSONS_APPROVALS_LEDGER_FILE = "lessons-approvals.json";
const BOOTSTRAP_RECEIPT_FILE = "bootstrap.lock.json";
const MAINTENANCE_LEASE_FILE = "maintenance.sqlite";
const MAINTENANCE_JOURNAL_FILE = `${MAINTENANCE_JOURNAL_STEM}.${JSONL_LEDGER_EXT}`;
@@ -1171,6 +1177,69 @@ export const STATE_SURFACES: ReadonlyArray<StateSurface> = Object.freeze([
"there is no TTL to bring it back.",
sources: ["src/core/brain/provenance/source-archive.ts"],
},
+ {
+ // K5 append-only placement: this row joins at the end of the
+ // catalogue because three lanes share this array this wave and the
+ // integrator re-freezes the by-root order.
+ id: STATE_SURFACE_ID.instructionBlockLock,
+ label: "instruction block lock",
+ tier: STATE_TIER.derived,
+ derive: derivedStore(INSTRUCTION_BLOCK_LOCK_FILE),
+ override_env: null,
+ override_config_key: null,
+ carries_memory: false,
+ reason:
+ "Which vault-root agent instruction files carry an Open Second Brain write-gate block " +
+ "this tool wrote: per file, the block id, the begin marker and the applied time. " +
+ "Uninstall reads it to remove exactly the recorded pair, and the applied time is what " +
+ "makes the installer refuse a hand-edited block; without it the installer cannot prove " +
+ "a block is its own and refuses to rewrite any diverged one.",
+ sources: ["src/core/install/instruction-block.ts"],
+ },
+ {
+ // K5 append-only placement: rides the same tail the three lanes
+ // share; the integrator re-freezes the by-root order.
+ id: STATE_SURFACE_ID.lessonApprovals,
+ label: "lesson approvals ledger",
+ tier: STATE_TIER.derived,
+ derive: derivedStore(LESSONS_APPROVALS_LEDGER_FILE),
+ override_env: null,
+ override_config_key: null,
+ carries_memory: false,
+ reason:
+ "One JSON table of the lesson-promotion decisions currently in force, keyed by preference " +
+ "id: which lessons the operator approved for promotion into agent rules files, which they " +
+ "refused, and the content hash each approval pinned. It lives in the derived store rather " +
+ "than under Brain/ so an agent cannot read its own approval state as a note surface. " +
+ "Nothing rebuilds it: deleting it lifts every approval and refusal at once - the " +
+ "fail-closed direction, since a lifted approval blocks a lesson rather than promoting it.",
+ sources: [
+ "src/core/brain/lessons-promotion.ts",
+ "src/core/brain/doctor/lessons-block-check.ts",
+ ],
+ },
+ {
+ id: STATE_SURFACE_ID.skillBenchmarks,
+ label: "skill benchmarks",
+ tier: STATE_TIER.vaultContent,
+ derive: (vault) => join(vault, BRAIN_ROOT_REL, SKILL_BENCHMARKS_DIR),
+ override_env: null,
+ override_config_key: null,
+ carries_memory: false,
+ reason:
+ "Each skill's benchmark task set, its frozen rewrite receipt, and the submitted gate-round " +
+ "transcripts under rounds/. This is the preregistration an operator audits a staged " +
+ "rewrite against: the spec hash on a pending scored_rewrite proposal is a claim about " +
+ "these files, and the grade ledger's verdicts are only as trustworthy as the task set " +
+ "they gated on. Operator-authored content in the same sense the skills tree is - the " +
+ "vault is the primary home so the receipt travels with the skills it gates.",
+ sources: [
+ "src/core/brain/skill-rewrite-tasks.ts",
+ "src/core/brain/skill-rewrite.ts",
+ "src/core/brain/skill-proposals.ts",
+ "src/core/brain/paths.ts",
+ ],
+ },
]);
/**
diff --git a/src/mcp/brain/procedure-tools.ts b/src/mcp/brain/procedure-tools.ts
index 62f991d2..e9de0529 100644
--- a/src/mcp/brain/procedure-tools.ts
+++ b/src/mcp/brain/procedure-tools.ts
@@ -12,9 +12,12 @@ import {
discardUnreadableSkillAcceptJournals,
learnSkillProposals,
listPendingSkillProposals,
+ pendingSkillProposalPatternKind,
+ readSkillRewriteStatus,
recoverSkillProposalAccepts,
rejectSkillProposal,
resolveSkillProposalEvidence,
+ SCORED_REWRITE_PATTERN_KIND,
type SkillContractInput,
} from "../../core/brain/skill-proposals.ts";
import { commitSkillPageDraft, planSkillPageDrafts } from "../../core/brain/skill-page-drafts.ts";
@@ -66,6 +69,7 @@ async function toolBrainSkillProposals(
}
if (operation === "accept") {
const slug = requiredStringArg("brain_skill_proposals", args, "slug");
+ refuseScoredRewriteAccept(ctx.vault, slug);
const note = optionalStringArg("brain_skill_proposals", args, "note");
const contract = readSkillContract(args);
// Resolved from THIS server's config chain: a `mature_page` accept
@@ -187,6 +191,28 @@ function readSkillContract(args: Record<string, unknown>): SkillContractInput |
return { prerequisites, rollback, sideEffects, verification };
}
+/**
+ * Refuse the one accept the design keeps out of the agent's reach
+ * (review security M1c): a `scored_rewrite` proposal OVERWRITES an
+ * incumbent SKILL.md, and its acceptance is the operator's step - MCP
+ * proposes, the human accepts on the command line. The sibling read tool
+ * `brain_skill_rewrite_status` states this in its own description; this
+ * guard is what makes it true for the whole surface family.
+ *
+ * Mined, declared and mature-page accepts are unchanged: they create or
+ * fill vault pages, they never overwrite, and the calling agent has always
+ * been able to write those trees directly.
+ */
+function refuseScoredRewriteAccept(vault: string, slug: string): void {
+ if (pendingSkillProposalPatternKind(vault, slug) !== SCORED_REWRITE_PATTERN_KIND) return;
+ throw new MCPError(
+ INVALID_PARAMS,
+ `brain_skill_proposals: '${slug}' is a ${SCORED_REWRITE_PATTERN_KIND} proposal, whose accept ` +
+ "OVERWRITES an incumbent skill; MCP never accepts a benchmark-gated rewrite - the " +
+ "operator reviews and accepts it on the command line: o2b brain skill-proposals accept",
+ );
+}
+
async function toolBrainProceduralMemory(
ctx: ServerContext,
args: Record<string, unknown>,
@@ -288,6 +314,21 @@ async function toolBrainRecurrence(
);
}
+async function toolBrainSkillRewriteStatus(
+ ctx: ServerContext,
+ args: Record<string, unknown>,
+): Promise<Record<string, unknown>> {
+ const skillName = requiredStringArg("brain_skill_rewrite_status", args, "skill_name");
+ const status = readSkillRewriteStatus(ctx.vault, skillName);
+ return {
+ skill: status.skill,
+ receipt: status.receipt,
+ grades: status.grades,
+ unreadable_grades: status.unreadable_grades,
+ pending_rewrite_slug: status.pending_rewrite_slug,
+ };
+}
+
async function toolBrainProceduralGraph(
ctx: ServerContext,
args: Record<string, unknown>,
@@ -364,7 +405,9 @@ export const PROCEDURE_TOOLS: ReadonlyArray<ToolDefinition> = Object.freeze([
},
slug: {
type: "string",
- description: "Proposal slug for accept/reject/evidence.",
+ description:
+ "Proposal slug for accept/reject/evidence. scored_rewrite accepts are refused here: " +
+ "the operator accepts them on the command line.",
},
note: {
type: "string",
@@ -425,6 +468,24 @@ export const PROCEDURE_TOOLS: ReadonlyArray<ToolDefinition> = Object.freeze([
},
handler: toolBrainSkillProposals,
},
+ {
+ name: "brain_skill_rewrite_status",
+ kind: "read",
+ description:
+ "Read-only rewrite-lane status: the frozen benchmark receipt and whether the task set still verifies, completed gate runs' verdicts and rates, and any staged rewrite awaiting a human accept. MCP never accepts or scores.",
+ inputSchema: {
+ type: "object",
+ properties: {
+ skill_name: {
+ type: "string",
+ description: "Skill directory name: lowercase letters, digits, single hyphens.",
+ },
+ },
+ required: ["skill_name"],
+ additionalProperties: false,
+ },
+ handler: toolBrainSkillRewriteStatus,
+ },
{
name: "brain_procedural_memory",
kind: "write",
diff --git a/src/mcp/registry-guard.ts b/src/mcp/registry-guard.ts
index a9a71f72..287dc285 100644
--- a/src/mcp/registry-guard.ts
+++ b/src/mcp/registry-guard.ts
@@ -408,6 +408,9 @@ export const PREVIEW_BUDGET_EXEMPT: Readonly<Record<string, string>> = Object.fr
brain_context_presets: "small preset list",
brain_pre_compact_extract: "bounded extract; host injects it whole by design",
brain_skill_proposals: "bounded proposal list",
+ brain_skill_rewrite_status:
+ "bounded status: one benchmark receipt plus at most ten grade verdict rows for one skill; " +
+ "ids and rates only, never task or transcript text",
brain_procedural_memory: "bounded hint list",
brain_procedural_graph: "bounded graph summary",
brain_recurrence: "bounded recurrence records; learn/forget are writes",
diff --git a/tests/cli/brain-lessons.test.ts b/tests/cli/brain-lessons.test.ts
new file mode 100644
index 00000000..62308969
--- /dev/null
+++ b/tests/cli/brain-lessons.test.ts
@@ -0,0 +1,700 @@
+/**
+ * Tests for `o2b brain lessons` (t_1e952e43, task C2).
+ *
+ * Drives the operator verb family over the promotion kernel:
+ * - `candidates` is read-only and reports promotable plus
+ * blocked-with-reason, including the disabled state;
+ * - `approve` follows the install consent ladder: plan-only by default,
+ * headless `--apply` without `--yes` refuses with exit 6, the ledger
+ * row is recorded only after the rules-block write landed, and the
+ * approval event joins the shared log chain;
+ * - `deny` records without touching any rules file and suppresses the
+ * lesson from every later listing;
+ * - `refresh-blocks` is a dry run by default, is a named no-op when no
+ * block exists under management, never CREATES a block, drops a stale
+ * lesson by name, and stamps `lastPromotedAt` on what it wrote.
+ */
+
+import { afterEach, beforeEach, describe, expect, test } from "bun:test";
+import { existsSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from "node:fs";
+import { tmpdir } from "node:os";
+import { join } from "node:path";
+
+import { bootstrapBrain } from "../../src/core/brain/init.ts";
+import { computeContentHash } from "../../src/core/brain/content-hash.ts";
+import { listLogDates, readLogDay } from "../../src/core/brain/log-jsonl.ts";
+import {
+ LESSONS_APPROVALS_FILE,
+ lessonsApprovalsPath,
+ readLessonApprovals,
+ recordLessonApproval,
+} from "../../src/core/brain/lessons-promotion.ts";
+import { RULES_BLOCK_MARKERS } from "../../src/core/install/rules-block.ts";
+import { writePreference } from "../../src/core/brain/preference.ts";
+import { appendLogEvent } from "../../src/core/brain/log.ts";
+import { BRAIN_LOG_EVENT_KIND } from "../../src/core/brain/types.ts";
+import { runCli } from "../helpers/run-cli.ts";
+
+const SCOPE_ENV = "OPEN_SECOND_BRAIN_LESSONS_PROMOTION_SCOPES";
+const PRINCIPLE = "Always run the full test suite before pushing to main";
+
+let tmp: string;
+let vault: string;
+let configPath: string;
+let savedScopeEnv: string | undefined;
+
+beforeEach(() => {
+ tmp = mkdtempSync(join(tmpdir(), "o2b-lessons-cli-"));
+ vault = join(tmp, "vault");
+ configPath = join(tmp, "config.yaml");
+ writeFileSync(configPath, `vault: ${vault}\nagent_name: test-agent\n`);
+ bootstrapBrain(vault, { configPath });
+ savedScopeEnv = process.env[SCOPE_ENV];
+ process.env[SCOPE_ENV] = "backend";
+});
+
+afterEach(() => {
+ if (savedScopeEnv === undefined) delete process.env[SCOPE_ENV];
+ else process.env[SCOPE_ENV] = savedScopeEnv;
+ rmSync(tmp, { recursive: true, force: true });
+});
+
+const env = () => ({ OPEN_SECOND_BRAIN_CONFIG: configPath, [SCOPE_ENV]: "backend" });
+
+function seedPreferredLesson(
+ slug: string,
+ overrides: { scope?: string; confidence?: string; principle?: string } = {},
+): void {
+ writePreference(vault, {
+ slug,
+ topic: slug,
+ principle: overrides.principle ?? PRINCIPLE,
+ scope: overrides.scope ?? "backend",
+ created_at: "2026-05-01T00:00:00Z",
+ confirmed_at: "2026-05-02T00:00:00Z",
+ unconfirmed_until: "2026-05-08T00:00:00Z",
+ status: "confirmed",
+ evidenced_by: ["[[sig-1]]"],
+ applied_count: 2,
+ violated_count: 0,
+ last_evidence_at: "2026-05-10T00:00:00Z",
+ confidence: overrides.confidence ?? "high",
+ } as Parameters<typeof writePreference>[1]);
+ appendLogEvent(
+ vault,
+ {
+ timestamp: "2026-05-09T00:00:00Z",
+ eventType: BRAIN_LOG_EVENT_KIND.applyEvidence,
+ body: { preference: `[[pref-${slug}]]`, artifact: "[[a.ts]]", agent: "t", result: "applied" },
+ },
+ { deviceId: "" },
+ );
+ appendLogEvent(
+ vault,
+ {
+ timestamp: "2026-05-10T00:00:00Z",
+ eventType: BRAIN_LOG_EVENT_KIND.applyEvidence,
+ body: { preference: `[[pref-${slug}]]`, artifact: "[[b.ts]]", agent: "t", result: "applied" },
+ },
+ { deviceId: "" },
+ );
+}
+
+const NOW_FIXTURE_MS = Date.parse("2026-05-20T00:00:00Z");
+
+function ledgerEvents(): ReadonlyArray<string> {
+ const dates = listLogDates(vault);
+ const kinds: string[] = [];
+ for (const date of dates) {
+ for (const entry of readLogDay(vault, date).entries) kinds.push(entry.eventType);
+ }
+ return kinds;
+}
+
+describe("o2b brain lessons candidates", () => {
+ test("lists promotable and blocked with reasons, read-only", async () => {
+ seedPreferredLesson("approved-lesson");
+ seedPreferredLesson("norow-lesson");
+ recordLessonApproval(vault, {
+ prefId: "pref-approved-lesson",
+ decision: "approved",
+ decidedAt: "2026-05-15T00:00:00Z",
+ decidedBy: "yes-flag",
+ approvedContentHash: computeContentHash(PRINCIPLE, "backend"),
+ targets: ["AGENTS.md"],
+ blockId: "lessons",
+ lastPromotedAt: null,
+ });
+ const rulesBefore = existsSync(join(vault, "AGENTS.md"));
+ const ledgerBefore = existsSync(lessonsApprovalsPath(vault))
+ ? readFileSync(lessonsApprovalsPath(vault), "utf8")
+ : null;
+
+ const out = await runCli(["brain", "lessons", "candidates", "--json"], { env: env() });
+ expect(out.returncode).toBe(0);
+ const payload = JSON.parse(out.stdout) as {
+ promotable: Array<{ prefId: string }>;
+ blocked: Array<{ prefId: string; reason: string }>;
+ scopes: { count: number };
+ };
+ expect(payload.promotable.map((c) => c.prefId)).toEqual(["pref-approved-lesson"]);
+ expect(payload.blocked).toEqual([{ prefId: "pref-norow-lesson", reason: "not_approved" }]);
+ expect(payload.scopes.count).toBe(1);
+
+ // Read-only: no rules file appeared, the ledger is byte-identical.
+ expect(existsSync(join(vault, "AGENTS.md"))).toBe(rulesBefore);
+ expect(
+ existsSync(lessonsApprovalsPath(vault))
+ ? readFileSync(lessonsApprovalsPath(vault), "utf8")
+ : null,
+ ).toBe(ledgerBefore);
+ });
+
+ test("promotion disabled is a named count of zero with every lesson scope-blocked", async () => {
+ seedPreferredLesson("disabled-lesson");
+ recordLessonApproval(vault, {
+ prefId: "pref-disabled-lesson",
+ decision: "approved",
+ decidedAt: "2026-05-15T00:00:00Z",
+ decidedBy: "yes-flag",
+ approvedContentHash: computeContentHash(PRINCIPLE, "backend"),
+ targets: ["AGENTS.md"],
+ blockId: "lessons",
+ lastPromotedAt: null,
+ });
+ const out = await runCli(["brain", "lessons", "candidates", "--json"], {
+ env: { OPEN_SECOND_BRAIN_CONFIG: configPath },
+ });
+ expect(out.returncode).toBe(0);
+ const payload = JSON.parse(out.stdout) as {
+ promotable: unknown[];
+ blocked: Array<{ reason: string }>;
+ scopes: { count: number };
+ };
+ expect(payload.scopes.count).toBe(0);
+ expect(payload.promotable).toEqual([]);
+ expect(payload.blocked[0]?.reason).toBe("scope_not_enabled");
+ });
+
+ test("a present-but-malformed scopes value is a named refusal, never a silent disabled", async () => {
+ // A bracket-shaped paste (`scopes: [a, b]` into the flat key) used to
+ // resolve exactly like an unset key; the operator could not tell
+ // "configured wrong" from "never configured".
+ seedPreferredLesson("scoped-lesson");
+ const out = await runCli(["brain", "lessons", "candidates", "--json"], {
+ env: { OPEN_SECOND_BRAIN_CONFIG: configPath, [SCOPE_ENV]: "[backend, testing]" },
+ });
+ expect(out.returncode).toBe(1);
+ expect(out.stderr).toContain("malformed");
+ expect(out.stderr).toContain(SCOPE_ENV);
+ expect(out.stderr).toContain("promotion stays disabled");
+ // The mutating verbs refuse the same way, before any write.
+ const approved = await runCli(
+ ["brain", "lessons", "approve", "pref-scoped-lesson", "--apply", "--yes"],
+ { env: { OPEN_SECOND_BRAIN_CONFIG: configPath, [SCOPE_ENV]: "[backend]" } },
+ );
+ expect(approved.returncode).toBe(1);
+ expect(approved.stderr).toContain("malformed");
+ expect(existsSync(lessonsApprovalsPath(vault))).toBe(false);
+ });
+});
+
+describe("o2b brain lessons approve", () => {
+ test("plan-only default renders targets and writes nothing", async () => {
+ seedPreferredLesson("plan-lesson");
+ writeFileSync(join(vault, "AGENTS.md"), "# house rules\n\nbe careful.\n");
+ const before = readFileSync(join(vault, "AGENTS.md"), "utf8");
+ const out = await runCli(["brain", "lessons", "approve", "pref-plan-lesson"], { env: env() });
+ expect(out.returncode).toBe(0);
+ expect(out.stdout).toContain("AGENTS.md");
+ expect(readFileSync(join(vault, "AGENTS.md"), "utf8")).toBe(before);
+ expect(existsSync(lessonsApprovalsPath(vault))).toBe(false);
+ });
+
+ test("headless --apply without --yes refuses with exit 6 and writes nothing", async () => {
+ seedPreferredLesson("gate-lesson");
+ writeFileSync(join(vault, "AGENTS.md"), "# house rules\n\nbe careful.\n");
+ const out = await runCli(
+ ["brain", "lessons", "approve", "pref-gate-lesson", "--apply", "--json"],
+ { env: env() },
+ );
+ expect(out.returncode).toBe(6);
+ const payload = JSON.parse(out.stdout) as { consent: string; written: boolean };
+ expect(payload.consent).toBe("headless-refused");
+ expect(payload.written).toBe(false);
+ expect(readFileSync(join(vault, "AGENTS.md"), "utf8")).not.toContain(
+ RULES_BLOCK_MARKERS.lessons.begin,
+ );
+ expect(existsSync(lessonsApprovalsPath(vault))).toBe(false);
+ });
+
+ test("--apply --yes writes the block, records the row, and appends the event", async () => {
+ seedPreferredLesson("ok-lesson");
+ writeFileSync(join(vault, "AGENTS.md"), "# house rules\n\nbe careful.\n");
+ const out = await runCli(
+ [
+ "brain",
+ "lessons",
+ "approve",
+ "pref-ok-lesson",
+ "--apply",
+ "--yes",
+ "--target",
+ "AGENTS.md",
+ ],
+ { env: env() },
+ );
+ expect(out.returncode).toBe(0);
+ const rules = readFileSync(join(vault, "AGENTS.md"), "utf8");
+ expect(rules).toContain(RULES_BLOCK_MARKERS.lessons.begin);
+ expect(rules).toContain(PRINCIPLE);
+ expect(rules).toContain("# house rules");
+ const rows = readLessonApprovals(vault);
+ expect(rows.length).toBe(1);
+ expect(rows[0]?.decision).toBe("approved");
+ expect(rows[0]?.prefId).toBe("pref-ok-lesson");
+ expect(rows[0]?.targets).toEqual(["AGENTS.md"]);
+ expect(rows[0]?.approvedContentHash).toBe(computeContentHash(PRINCIPLE, "backend"));
+ expect(ledgerEvents()).toContain(BRAIN_LOG_EVENT_KIND.lessonsApproved);
+ // A rerun of candidates shows the lesson promotable.
+ const list = await runCli(["brain", "lessons", "candidates", "--json"], { env: env() });
+ const payload = JSON.parse(list.stdout) as { promotable: Array<{ prefId: string }> };
+ expect(payload.promotable.map((c) => c.prefId)).toEqual(["pref-ok-lesson"]);
+ });
+
+ test("an unknown pref id is a named error, exit 2", async () => {
+ const out = await runCli(["brain", "lessons", "approve", "pref-absent", "--apply", "--yes"], {
+ env: env(),
+ });
+ expect(out.returncode).toBe(2);
+ expect(out.stderr).toContain("pref-absent");
+ });
+
+ test("a lesson whose scope could forge a block marker refuses the approve by name", async () => {
+ // The enabled-scope twin carries the marker-shaped scope, so the
+ // lesson QUALIFIES - and the render must still refuse it, before any
+ // consent, write or ledger row. writePreference refuses a marker-
+ // shaped scope at write time, so the fixture seeds a normal file and
+ // then edits the persisted frontmatter directly: the preference file
+ // is vault state that can arrive by other means than this build's
+ // writer, which is exactly the shape the render must refuse.
+ const forgedScope = RULES_BLOCK_MARKERS.lessons.end;
+ seedPreferredLesson("forge-lesson");
+ const prefPath = join(vault, "Brain", "preferences", "pref-forge-lesson.md");
+ const persisted = readFileSync(prefPath, "utf8");
+ expect(persisted).toContain("scope:");
+ writeFileSync(prefPath, persisted.replace(/scope:.*/, `scope: "${forgedScope}"`));
+ writeFileSync(join(vault, "AGENTS.md"), "# house rules\n\nbe careful.\n");
+ const rulesBefore = readFileSync(join(vault, "AGENTS.md"), "utf8");
+
+ const planned = await runCli(["brain", "lessons", "approve", "pref-forge-lesson"], {
+ env: { OPEN_SECOND_BRAIN_CONFIG: configPath, [SCOPE_ENV]: forgedScope },
+ });
+ expect(planned.returncode).toBe(1);
+ expect(planned.stderr).toContain("pref-forge-lesson");
+ expect(planned.stderr).toContain("scope");
+
+ const applied = await runCli(
+ [
+ "brain",
+ "lessons",
+ "approve",
+ "pref-forge-lesson",
+ "--apply",
+ "--yes",
+ "--target",
+ "AGENTS.md",
+ ],
+ { env: { OPEN_SECOND_BRAIN_CONFIG: configPath, [SCOPE_ENV]: forgedScope } },
+ );
+ expect(applied.returncode).toBe(1);
+ expect(applied.stderr).toContain("pref-forge-lesson");
+ // Nothing was written: no block, no ledger row.
+ expect(readFileSync(join(vault, "AGENTS.md"), "utf8")).toBe(rulesBefore);
+ expect(existsSync(lessonsApprovalsPath(vault))).toBe(false);
+ });
+
+ test("a refusal on the second target refuses the whole approve before any write", async () => {
+ // The multi-target approve must compute the plan for ALL targets
+ // first (the installer's dry-pass discipline): a refusal on the
+ // second target must not leave the first written and unmanaged.
+ seedPreferredLesson("multi-lesson");
+ writeFileSync(join(vault, "AGENTS.md"), "# rules\n");
+ writeFileSync(
+ join(vault, "CLAUDE.md"),
+ [
+ "# claude rules",
+ "",
+ RULES_BLOCK_MARKERS.lessons.begin,
+ "hand-written lessons content",
+ RULES_BLOCK_MARKERS.lessons.end,
+ "",
+ ].join("\n"),
+ );
+ const out = await runCli(
+ [
+ "brain",
+ "lessons",
+ "approve",
+ "pref-multi-lesson",
+ "--apply",
+ "--yes",
+ "--target",
+ "AGENTS.md",
+ "--target",
+ "CLAUDE.md",
+ ],
+ { env: env() },
+ );
+ expect(out.returncode).toBe(1);
+ expect(out.stderr).toContain("CLAUDE.md");
+ expect(out.stderr).toContain("user-modified-block");
+ expect(out.stderr).toContain("nothing was written");
+ // Neither target moved and no approval row was recorded.
+ expect(readFileSync(join(vault, "AGENTS.md"), "utf8")).toBe("# rules\n");
+ expect(readFileSync(join(vault, "CLAUDE.md"), "utf8")).toContain(
+ "hand-written lessons content",
+ );
+ expect(existsSync(lessonsApprovalsPath(vault))).toBe(false);
+ });
+});
+
+describe("o2b brain lessons deny", () => {
+ test("deny records the decision without writing any rules file", async () => {
+ seedPreferredLesson("deny-lesson");
+ writeFileSync(join(vault, "AGENTS.md"), "# house rules\n\nbe careful.\n");
+ const before = readFileSync(join(vault, "AGENTS.md"), "utf8");
+ const out = await runCli(["brain", "lessons", "deny", "pref-deny-lesson", "--apply", "--yes"], {
+ env: env(),
+ });
+ expect(out.returncode).toBe(0);
+ const rows = readLessonApprovals(vault);
+ expect(rows.length).toBe(1);
+ expect(rows[0]?.decision).toBe("denied");
+ expect(rows[0]?.targets).toEqual([]);
+ expect(readFileSync(join(vault, "AGENTS.md"), "utf8")).toBe(before);
+ expect(ledgerEvents()).toContain(BRAIN_LOG_EVENT_KIND.lessonsDenied);
+ const list = await runCli(["brain", "lessons", "candidates", "--json"], { env: env() });
+ const payload = JSON.parse(list.stdout) as {
+ blocked: Array<{ prefId: string; reason: string }>;
+ };
+ expect(payload.blocked).toEqual([{ prefId: "pref-deny-lesson", reason: "denied" }]);
+ });
+
+ test("headless deny without --yes refuses with exit 6", async () => {
+ seedPreferredLesson("deny-gate");
+ const out = await runCli(["brain", "lessons", "deny", "pref-deny-gate", "--apply", "--json"], {
+ env: env(),
+ });
+ expect(out.returncode).toBe(6);
+ expect(existsSync(lessonsApprovalsPath(vault))).toBe(false);
+ });
+});
+
+describe("o2b brain lessons refresh-blocks", () => {
+ test("is a named no-op when no block exists under management", async () => {
+ seedPreferredLesson("lonely-lesson");
+ recordLessonApproval(vault, {
+ prefId: "pref-lonely-lesson",
+ decision: "approved",
+ decidedAt: "2026-05-15T00:00:00Z",
+ decidedBy: "yes-flag",
+ approvedContentHash: computeContentHash(PRINCIPLE, "backend"),
+ targets: ["AGENTS.md"],
+ blockId: "lessons",
+ lastPromotedAt: null,
+ });
+ const out = await runCli(["brain", "lessons", "refresh-blocks", "--apply", "--yes"], {
+ env: env(),
+ });
+ expect(out.returncode).toBe(0);
+ expect(out.stdout).toMatch(/no lessons block under management/i);
+ expect(existsSync(join(vault, "AGENTS.md"))).toBe(false);
+ });
+
+ test("updates an existing block, drops a stale lesson by name, and stamps lastPromotedAt", async () => {
+ seedPreferredLesson("stale-lesson");
+ writeFileSync(join(vault, "AGENTS.md"), "# house rules\n");
+ const approval = await runCli(
+ [
+ "brain",
+ "lessons",
+ "approve",
+ "pref-stale-lesson",
+ "--apply",
+ "--yes",
+ "--target",
+ "AGENTS.md",
+ ],
+ { env: env() },
+ );
+ expect(approval.returncode).toBe(0);
+ expect(readFileSync(join(vault, "AGENTS.md"), "utf8")).toContain(PRINCIPLE);
+
+ // The operator edits the approved preference: the pinned hash goes stale.
+ const prefPath = join(vault, "Brain", "preferences", "pref-stale-lesson.md");
+ const prefBytes = readFileSync(prefPath, "utf8");
+ writeFileSync(prefPath, prefBytes.replace(PRINCIPLE, `${PRINCIPLE}, amended`));
+
+ const refresh = await runCli(["brain", "lessons", "refresh-blocks", "--apply", "--yes"], {
+ env: env(),
+ });
+ expect(refresh.returncode).toBe(0);
+ expect(refresh.stdout).toContain("pref-stale-lesson");
+ const rules = readFileSync(join(vault, "AGENTS.md"), "utf8");
+ expect(rules).not.toContain(PRINCIPLE);
+ const rows = readLessonApprovals(vault);
+ expect(rows[0]?.lastPromotedAt).not.toBeNull();
+ expect(ledgerEvents()).toContain(BRAIN_LOG_EVENT_KIND.lessonsPromoted);
+ });
+
+ test("the refresh result names dropped lessons instead of truncating silently", async () => {
+ // Under the shipped wiring the digest cap and the block cap read the
+ // same `lessons.limit`, so the live renders drop nothing - the field
+ // is the named surface the render reports its cut through
+ // (`renderLessonsBlockWithDrops` pins the non-empty case at the
+ // kernel). The verb output and JSON carry it either way, so a future
+ // divergence between the two bounds can never truncate silently.
+ seedPreferredLesson("named-drop-lesson");
+ writeFileSync(join(vault, "AGENTS.md"), "# rules\n");
+ const approval = await runCli(
+ [
+ "brain",
+ "lessons",
+ "approve",
+ "pref-named-drop-lesson",
+ "--apply",
+ "--yes",
+ "--target",
+ "AGENTS.md",
+ ],
+ { env: env() },
+ );
+ expect(approval.returncode).toBe(0);
+ const refresh = await runCli(
+ ["brain", "lessons", "refresh-blocks", "--apply", "--yes", "--json"],
+ {
+ env: env(),
+ },
+ );
+ expect(refresh.returncode).toBe(0);
+ const payload = JSON.parse(refresh.stdout) as {
+ dropped: ReadonlyArray<{ target: string; ids: ReadonlyArray<string> }>;
+ };
+ expect(payload.dropped).toEqual([]);
+ });
+
+ test("skips a target whose block is absent by name and never creates it", async () => {
+ seedPreferredLesson("two-file-lesson");
+ writeFileSync(join(vault, "AGENTS.md"), "# rules\n");
+ const approval = await runCli(
+ [
+ "brain",
+ "lessons",
+ "approve",
+ "pref-two-file-lesson",
+ "--apply",
+ "--yes",
+ "--target",
+ "AGENTS.md",
+ ],
+ { env: env() },
+ );
+ expect(approval.returncode).toBe(0);
+ // Widen the row's targets to a file that carries no block.
+ const rows = readLessonApprovals(vault);
+ recordLessonApproval(vault, { ...rows[0]!, targets: ["AGENTS.md", "CLAUDE.md"] });
+ const claudePath = join(vault, "CLAUDE.md");
+ expect(existsSync(claudePath)).toBe(false);
+
+ const refresh = await runCli(["brain", "lessons", "refresh-blocks", "--apply", "--yes"], {
+ env: env(),
+ });
+ expect(refresh.returncode).toBe(0);
+ expect(refresh.stdout).toContain("CLAUDE.md");
+ expect(existsSync(claudePath)).toBe(false);
+ });
+
+ test("the default run is a dry preview that writes nothing", async () => {
+ seedPreferredLesson("dry-lesson");
+ writeFileSync(join(vault, "AGENTS.md"), "# rules\n");
+ const approval = await runCli(
+ [
+ "brain",
+ "lessons",
+ "approve",
+ "pref-dry-lesson",
+ "--apply",
+ "--yes",
+ "--target",
+ "AGENTS.md",
+ ],
+ { env: env() },
+ );
+ expect(approval.returncode).toBe(0);
+ const prefPath = join(vault, "Brain", "preferences", "pref-dry-lesson.md");
+ writeFileSync(
+ prefPath,
+ readFileSync(prefPath, "utf8").replace(PRINCIPLE, `${PRINCIPLE} with edits`),
+ );
+ const before = readFileSync(join(vault, "AGENTS.md"), "utf8");
+ const ledgerBefore = readFileSync(lessonsApprovalsPath(vault), "utf8");
+ const dry = await runCli(["brain", "lessons", "refresh-blocks"], { env: env() });
+ expect(dry.returncode).toBe(0);
+ expect(readFileSync(join(vault, "AGENTS.md"), "utf8")).toBe(before);
+ expect(readFileSync(lessonsApprovalsPath(vault), "utf8")).toBe(ledgerBefore);
+ });
+
+ test("a future-stamped lastPromotedAt is untrusted: the hand-edited block refuses without --force", async () => {
+ // The promotion stamp lives in agent-writable ledger state. Stamping
+ // it into the future would make every later operator hand-edit read
+ // as a canonical move under an untouched file, so the gate must
+ // treat it as no record - which refuses the removal path too.
+ seedPreferredLesson("future-stamp-lesson");
+ writeFileSync(join(vault, "AGENTS.md"), "# rules\n");
+ const approval = await runCli(
+ [
+ "brain",
+ "lessons",
+ "approve",
+ "pref-future-stamp-lesson",
+ "--apply",
+ "--yes",
+ "--target",
+ "AGENTS.md",
+ ],
+ { env: env() },
+ );
+ expect(approval.returncode).toBe(0);
+ // Re-stamp the row into the future, far past the clock-skew allowance.
+ const rows = readLessonApprovals(vault);
+ recordLessonApproval(vault, {
+ ...rows[0]!,
+ lastPromotedAt: new Date(Date.now() + 10 * 60_000).toISOString(),
+ });
+ // The approved text moves, so nothing qualifies any more and the
+ // refresh would REMOVE the block; a hand edit makes the file the
+ // operator's, not the writer's.
+ const rulesPath = join(vault, "AGENTS.md");
+ writeFileSync(
+ rulesPath,
+ readFileSync(rulesPath, "utf8").replace(PRINCIPLE, "HAND EDITED LINE"),
+ );
+ const refused = await runCli(["brain", "lessons", "refresh-blocks", "--apply", "--yes"], {
+ env: env(),
+ });
+ expect(refused.returncode).toBe(1);
+ expect(refused.stderr).toContain("user-modified-block");
+ expect(readFileSync(rulesPath, "utf8")).toContain("HAND EDITED LINE");
+ // --force stays the documented override.
+ const forced = await runCli(
+ ["brain", "lessons", "refresh-blocks", "--apply", "--yes", "--force"],
+ { env: env() },
+ );
+ expect(forced.returncode).toBe(0);
+ expect(existsSync(rulesPath) ? readFileSync(rulesPath, "utf8") : "").not.toContain(
+ "HAND EDITED LINE",
+ );
+ });
+
+ test("a hand-edited block refuses the refresh by name; --force overrides", async () => {
+ seedPreferredLesson("hand-lesson");
+ writeFileSync(join(vault, "AGENTS.md"), "# rules\n");
+ const approval = await runCli(
+ [
+ "brain",
+ "lessons",
+ "approve",
+ "pref-hand-lesson",
+ "--apply",
+ "--yes",
+ "--target",
+ "AGENTS.md",
+ ],
+ { env: env() },
+ );
+ expect(approval.returncode).toBe(0);
+ // A second approved lesson changes the canonical body; a hand edit to
+ // the block makes the file NEWER than the promotion stamp.
+ seedPreferredLesson("hand-lesson-2");
+ recordLessonApproval(vault, {
+ prefId: "pref-hand-lesson-2",
+ decision: "approved",
+ decidedAt: "2026-05-16T00:00:00Z",
+ decidedBy: "yes-flag",
+ approvedContentHash: computeContentHash(
+ "Always run the full test suite before pushing to main",
+ "backend",
+ ),
+ targets: ["AGENTS.md"],
+ blockId: "lessons",
+ lastPromotedAt: null,
+ });
+ const rulesPath = join(vault, "AGENTS.md");
+ // The shared writer grants hand edits a 1 s mtime slack over the
+ // recorded promotion stamp, and the stamp itself truncates to the
+ // second, so an immediate edit would be indistinguishable from the
+ // writer's own write. Sleep past stamp rounding (up to 999 ms) plus
+ // the writer slack (1000 ms) so this edit is decided by intent, not
+ // by where the second boundary happened to fall.
+ await Bun.sleep(2_200);
+ writeFileSync(
+ rulesPath,
+ readFileSync(rulesPath, "utf8").replace(PRINCIPLE, "HAND EDITED LINE"),
+ );
+ const refused = await runCli(["brain", "lessons", "refresh-blocks", "--apply", "--yes"], {
+ env: env(),
+ });
+ expect(refused.returncode).not.toBe(0);
+ expect(refused.stderr).toContain("user-modified-block");
+ const forced = await runCli(
+ ["brain", "lessons", "refresh-blocks", "--apply", "--yes", "--force"],
+ { env: env() },
+ );
+ expect(forced.returncode).toBe(0);
+ const rules = readFileSync(rulesPath, "utf8");
+ expect(rules).toContain("pref-hand-lesson");
+ expect(rules).not.toContain("HAND EDITED LINE");
+ });
+});
+
+describe("o2b brain lessons usage", () => {
+ test("a missing subcommand is a usage error", async () => {
+ const out = await runCli(["brain", "lessons"], { env: env() });
+ expect(out.returncode).toBe(2);
+ expect(out.stderr).toContain("candidates");
+ });
+});
+
+describe("the docs name the lane (docs drift fails a test)", () => {
+ const repoRoot = join(import.meta.dir, "..", "..");
+ const read = (rel: string): string => readFileSync(join(repoRoot, rel), "utf8");
+
+ test("the cli reference names the verb family, the approval tier and the trust boundary", () => {
+ const cli = read("docs/cli-reference.md");
+ expect(cli).toContain("o2b brain lessons");
+ for (const verb of ["candidates", "approve", "deny", "refresh-blocks"]) {
+ expect(`${verb} documented: ${cli.includes(verb)}`).toBe(`${verb} documented: true`);
+ }
+ expect(cli).toContain("operator-approved lesson promotion");
+ // The trust boundary is stated in the docs, not only in the docblocks.
+ expect(cli).toContain("no MCP tool exposes this verb family");
+ });
+
+ test("the observability guide names the audit events and the trust boundary", () => {
+ const obs = read("docs/observability.md");
+ for (const kind of ["lessons-approved", "lessons-denied", "lessons-promoted"]) {
+ expect(`${kind} documented: ${obs.includes(kind)}`).toBe(`${kind} documented: true`);
+ }
+ expect(obs).toContain("Operator CLI only");
+ expect(obs).toContain("no agent-facing surface can mint these events");
+ expect(obs).toContain("stale-lessons");
+ });
+});
+
+describe("surface registrations", () => {
+ test("the ledger fixture name and the NOW fixture stay honest", () => {
+ expect(LESSONS_APPROVALS_FILE).toBe("lessons-approvals.json");
+ expect(Number.isFinite(NOW_FIXTURE_MS)).toBe(true);
+ });
+});
diff --git a/tests/cli/completions.test.ts b/tests/cli/completions.test.ts
index b01a3a5f..c3443b01 100644
--- a/tests/cli/completions.test.ts
+++ b/tests/cli/completions.test.ts
@@ -30,6 +30,9 @@ describe("CLI command manifest", () => {
const brainVerbs = brain.commands.map((command: any) => command.name);
expect(brainVerbs).toContain("doctor");
expect(brainVerbs).toContain("mcp-landscape");
+ // t_1e952e43: the lessons verb family is a manifest entry, so shell
+ // completions and help --json offer it.
+ expect(brainVerbs).toContain("lessons");
});
});
diff --git a/tests/cli/help-surface-parity.test.ts b/tests/cli/help-surface-parity.test.ts
index 85887574..d47554f4 100644
--- a/tests/cli/help-surface-parity.test.ts
+++ b/tests/cli/help-surface-parity.test.ts
@@ -169,6 +169,33 @@ describe("the flags the branch added verbs for are advertised", () => {
expect(flags.get("brain pending list")).not.toContain("--dry-run");
expect(flags.get("brain pending list")).not.toContain("--reason");
});
+
+ // t_1e952e43: the lessons verb family rides the install consent ladder,
+ // so the consent-bearing subcommands advertise the ladder flags and the
+ // read-only one advertises no write flag at all.
+ test("brain lessons approve advertises the consent ladder flags", async () => {
+ const flags = await jsonFlags();
+ const approve = flags.get("brain lessons approve") ?? [];
+ expect(approve).toContain("--apply");
+ expect(approve).toContain("--yes");
+ expect(approve).toContain("--target");
+ expect(approve).toContain("--force");
+ });
+
+ test("brain lessons candidates advertises no write flag", async () => {
+ const flags = await jsonFlags();
+ const candidates = flags.get("brain lessons candidates") ?? [];
+ expect(candidates).not.toContain("--apply");
+ expect(candidates).not.toContain("--yes");
+ });
+
+ test("brain lessons refresh-blocks advertises the ladder and force", async () => {
+ const flags = await jsonFlags();
+ const refresh = flags.get("brain lessons refresh-blocks") ?? [];
+ expect(refresh).toContain("--apply");
+ expect(refresh).toContain("--yes");
+ expect(refresh).toContain("--force");
+ });
});
describe("the terse usage names the complete help", () => {
diff --git a/tests/cli/install-instruction-step.test.ts b/tests/cli/install-instruction-step.test.ts
new file mode 100644
index 00000000..1f8f458c
--- /dev/null
+++ b/tests/cli/install-instruction-step.test.ts
@@ -0,0 +1,356 @@
+/**
+ * `o2b install` instruction step, subprocess-level tests (t_ba41a78a B3).
+ *
+ * The instruction step rides `runTarget`: the plan renders it (or its
+ * named skip) for every target, ONE consent verdict covers the adapter
+ * write and the instruction write, a `user-modified-block` refusal exits
+ * 4, and a failure after the adapter applied still exits non-zero with a
+ * re-run converging. `--check` is untouched: the readiness probe remains
+ * the block auditor.
+ */
+
+import { afterEach, beforeEach, describe, expect, setDefaultTimeout, test } from "bun:test";
+import {
+ existsSync,
+ mkdirSync,
+ mkdtempSync,
+ readFileSync,
+ rmSync,
+ symlinkSync,
+ writeFileSync,
+} from "node:fs";
+import { tmpdir } from "node:os";
+import { join } from "node:path";
+
+import { CLI_SPAWN_BUDGET_MS } from "../helpers/cli-timeout.ts";
+import { runCli as baseRunCli, type RunCliOptions, type RunResult } from "../helpers/run-cli.ts";
+import { auditWritebackContractFile } from "../../src/core/brain/writeback-contract.ts";
+import { DEFAULT_BEGIN_MARKER, DEFAULT_END_MARKER } from "../../src/core/install/managed-block.ts";
+import { instructionBlockLockPath } from "../../src/core/install/instruction-block.ts";
+
+function runCli(args: ReadonlyArray<string>, opts: RunCliOptions = {}): Promise<RunResult> {
+ return baseRunCli(args, { ...opts, subprocess: true });
+}
+
+setDefaultTimeout(CLI_SPAWN_BUDGET_MS);
+
+let vault: string;
+let home: string;
+let configPath: string;
+
+beforeEach(() => {
+ vault = mkdtempSync(join(tmpdir(), "osb-install-step-v-"));
+ home = mkdtempSync(join(tmpdir(), "osb-install-step-h-"));
+ configPath = join(home, "config.yaml");
+ mkdirSync(vault, { recursive: true });
+ writeFileSync(configPath, `vault: "${vault}"\nagent_name: "claude-vps"\ntimezone: "UTC"\n`);
+});
+
+afterEach(() => {
+ for (const p of [vault, home]) {
+ try {
+ rmSync(p, { recursive: true, force: true });
+ } catch {}
+ }
+});
+
+function envBase(extra: Record<string, string> = {}) {
+ return {
+ HOME: home,
+ OPEN_SECOND_BRAIN_CONFIG: configPath,
+ VAULT_DIR: vault,
+ VAULT_AGENT_NAME: "claude-vps",
+ VAULT_TIMEZONE: "UTC",
+ ...extra,
+ };
+}
+
+describe("o2b install --target <host>: the instruction step in the plan", () => {
+ test("a cursor plan includes the managed-block step for the vault-root AGENTS.md", async () => {
+ const r = await runCli(["install", "--target", "cursor", "--json"], { env: envBase() });
+ expect(r.returncode).toBe(0);
+ const payload = JSON.parse(r.stdout) as {
+ plan: { steps: ReadonlyArray<{ kind: string; path: string | null; diff?: string }> };
+ };
+ const step = payload.plan.steps.find((s) => s.path !== null && s.path.endsWith("AGENTS.md"));
+ expect(step).toBeDefined();
+ expect(step?.kind).toBe("managed-block");
+ expect(step?.diff).not.toBe("");
+ // Plan-only writes nothing.
+ expect(existsSync(join(vault, "AGENTS.md"))).toBe(false);
+ });
+
+ test("a gemini-cli plan carries the name-implied reading caveat", async () => {
+ const r = await runCli(["install", "--target", "gemini-cli", "--json"], { env: envBase() });
+ expect(r.returncode).toBe(0);
+ const payload = JSON.parse(r.stdout) as {
+ plan: { steps: ReadonlyArray<{ path: string | null; preview: string }> };
+ };
+ const step = payload.plan.steps.find((s) => s.path !== null && s.path.endsWith("GEMINI.md"));
+ expect(step).toBeDefined();
+ expect(step?.preview).toContain("name-implied");
+ });
+
+ test("a target with no precedence entry plans the named skip and no instruction step", async () => {
+ const r = await runCli(["install", "--target", "copilot-cli", "--json"], { env: envBase() });
+ expect(r.returncode).toBe(0);
+ const payload = JSON.parse(r.stdout) as {
+ plan: { steps: ReadonlyArray<{ path: string | null }>; postNotes: ReadonlyArray<string> };
+ };
+ const instructionSteps = payload.plan.steps.filter(
+ (s) =>
+ s.path !== null &&
+ (s.path.endsWith("AGENTS.md") ||
+ s.path.endsWith("CLAUDE.md") ||
+ s.path.endsWith("GEMINI.md")),
+ );
+ expect(instructionSteps.length).toBe(0);
+ expect(payload.plan.postNotes.join("\n")).toContain("copilot-cli");
+ expect(payload.plan.postNotes.join("\n")).toContain("agent-instruction");
+ });
+
+ test("a symlinked instruction file refuses the plan by name, not with a crash", async () => {
+ // The checker's posture: a plan cannot even be computed against a
+ // link, because the file a write would land on is not the file the
+ // contract audits. The refusal must be the named one on stderr - the
+ // module throws before the consent gate, so an unhandled rejection
+ // here would print a stack trace and exit through the top-level
+ // handler instead.
+ const real = join(home, "real-agents.md");
+ writeFileSync(real, "# operator notes\n");
+ symlinkSync(real, join(vault, "AGENTS.md"));
+ const planned = await runCli(["install", "--target", "cursor", "--json"], { env: envBase() });
+ expect(planned.returncode).toBe(1);
+ expect(planned.stderr).toContain("error:");
+ expect(planned.stderr).toContain("symbolic link");
+ expect(planned.stderr).not.toMatch(/\n\s+at /);
+ // The apply path refuses the same way, before any consent or write.
+ const applied = await runCli(["install", "--target", "cursor", "--apply", "--yes"], {
+ env: envBase(),
+ });
+ expect(applied.returncode).toBe(1);
+ expect(applied.stderr).toContain("symbolic link");
+ expect(applied.stderr).not.toMatch(/\n\s+at /);
+ expect(existsSync(join(home, ".cursor", "mcp.json"))).toBe(false);
+ expect(existsSync(instructionBlockLockPath(vault))).toBe(false);
+ });
+});
+
+describe("o2b install --target <host> --apply: one consent verdict, both writes", () => {
+ test("headless apply without --yes refuses with exit 6 and writes nothing", async () => {
+ const r = await runCli(["install", "--target", "cursor", "--apply", "--json"], {
+ env: envBase(),
+ });
+ expect(r.returncode).toBe(6);
+ const payload = JSON.parse(r.stdout) as { consent: string; written: boolean };
+ expect(payload.consent).toBe("headless-refused");
+ expect(payload.written).toBe(false);
+ // Neither the adapter write nor the instruction write happened.
+ expect(existsSync(join(home, ".cursor", "mcp.json"))).toBe(false);
+ expect(existsSync(join(vault, "AGENTS.md"))).toBe(false);
+ expect(existsSync(instructionBlockLockPath(vault))).toBe(false);
+ });
+
+ test("apply with --yes writes the block, and the readiness auditor grades it conforming", async () => {
+ const r = await runCli(["install", "--target", "cursor", "--apply", "--yes"], {
+ env: envBase(),
+ });
+ expect(r.returncode).toBe(0);
+ const audit = auditWritebackContractFile(join(vault, "AGENTS.md"));
+ expect(audit.finding).toBe("conforming");
+ expect(r.stdout).toContain("AGENTS.md");
+ const lock = JSON.parse(readFileSync(instructionBlockLockPath(vault), "utf8")) as {
+ schema_version: number;
+ files: Record<string, { applied_at: string; begin_marker: string }>;
+ };
+ expect(lock.schema_version).toBe(1);
+ expect(lock.files["AGENTS.md"]?.begin_marker).toBe(DEFAULT_BEGIN_MARKER);
+ expect(Number.isFinite(Date.parse(lock.files["AGENTS.md"]?.applied_at ?? "never"))).toBe(true);
+ });
+
+ test("apply is idempotent: a re-apply converges with the same bytes", async () => {
+ await runCli(["install", "--target", "cursor", "--apply", "--yes"], { env: envBase() });
+ const once = readFileSync(join(vault, "AGENTS.md"), "utf8");
+ const r = await runCli(["install", "--target", "cursor", "--apply", "--yes"], {
+ env: envBase(),
+ });
+ expect(r.returncode).toBe(0);
+ expect(readFileSync(join(vault, "AGENTS.md"), "utf8")).toBe(once);
+ });
+
+ test("the post-apply line reports created, updated and already-current honestly", async () => {
+ // First install on a vault with no AGENTS.md: the block is CREATED,
+ // and the line must not claim the file already carried it.
+ const created = await runCli(["install", "--target", "cursor", "--apply", "--yes"], {
+ env: envBase(),
+ });
+ expect(created.returncode).toBe(0);
+ expect(created.stdout).toContain("instruction block: ");
+ expect(created.stdout).toContain("created with the write-gate block");
+ expect(created.stdout).not.toContain("already carries");
+
+ // A hand-edited block rewritten under --force is an UPDATE.
+ const rulesPath = join(vault, "AGENTS.md");
+ writeFileSync(
+ rulesPath,
+ readFileSync(rulesPath, "utf8").replace(
+ "observing-memory layer. At session start, read the current preferences",
+ "hand-edited wording that no longer matches the canonical body",
+ ),
+ );
+ const updated = await runCli(["install", "--target", "cursor", "--apply", "--yes", "--force"], {
+ env: envBase(),
+ });
+ expect(updated.returncode).toBe(0);
+ expect(updated.stdout).toContain("now carries the write-gate block");
+ expect(updated.stdout).not.toContain("already carries");
+
+ // A re-apply with nothing to change is already current.
+ const current = await runCli(["install", "--target", "cursor", "--apply", "--yes"], {
+ env: envBase(),
+ });
+ expect(current.returncode).toBe(0);
+ expect(current.stdout).toContain("already carries the current write-gate block");
+ });
+
+ test("the --apply --json payload carries the instruction-block outcome", async () => {
+ // A headless consumer consented to a plan whose JSON showed the
+ // managed-block step, so the apply receipt on the same stream must
+ // say what that step did - the same outcome the uninstall payload
+ // carries as `instruction_block` (mirrored shape, mirrored skip).
+ const created = await runCli(["install", "--target", "cursor", "--apply", "--yes", "--json"], {
+ env: envBase(),
+ });
+ expect(created.returncode).toBe(0);
+ const payload = JSON.parse(created.stdout) as {
+ instruction_block: {
+ file: string | null;
+ created: boolean;
+ changed: boolean;
+ backup_path: string | null;
+ skipped_reason: string | null;
+ };
+ };
+ expect(payload.instruction_block.file).toBe(join(vault, "AGENTS.md"));
+ expect(payload.instruction_block.created).toBe(true);
+ expect(payload.instruction_block.changed).toBe(true);
+ expect(payload.instruction_block.skipped_reason).toBeNull();
+
+ // A re-apply reports the no-op honestly: nothing changed, no backup.
+ const again = await runCli(["install", "--target", "cursor", "--apply", "--yes", "--json"], {
+ env: envBase(),
+ });
+ expect(again.returncode).toBe(0);
+ const second = JSON.parse(again.stdout) as {
+ instruction_block: { created: boolean; changed: boolean; backup_path: string | null };
+ };
+ expect(second.instruction_block.created).toBe(false);
+ expect(second.instruction_block.changed).toBe(false);
+ expect(second.instruction_block.backup_path).toBeNull();
+ });
+
+ test("the --apply --json payload names the skip for a target with no precedence entry", async () => {
+ const r = await runCli(["install", "--target", "copilot-cli", "--apply", "--yes", "--json"], {
+ env: envBase(),
+ });
+ expect(r.returncode).toBe(0);
+ const payload = JSON.parse(r.stdout) as {
+ instruction_block: { file: string | null; skipped_reason: string | null };
+ };
+ expect(payload.instruction_block.file).toBeNull();
+ expect(payload.instruction_block.skipped_reason).toContain("copilot-cli");
+ });
+
+ test("apply with --yes --dry-run writes nothing on either lane", async () => {
+ const r = await runCli(["install", "--target", "cursor", "--apply", "--yes", "--dry-run"], {
+ env: envBase(),
+ });
+ expect(r.returncode).toBe(0);
+ expect(existsSync(join(vault, "AGENTS.md"))).toBe(false);
+ expect(existsSync(instructionBlockLockPath(vault))).toBe(false);
+ });
+});
+
+describe("o2b install --apply: refusals and convergence", () => {
+ test("a hand-edited block on a fresh file refuses with exit 4 and a force upgrade exits 0", async () => {
+ // The docs-snippet block an older manual install pasted: present,
+ // non-conforming, and no lock record can prove it ours.
+ writeFileSync(
+ join(vault, "AGENTS.md"),
+ [
+ "# operator notes",
+ "",
+ DEFAULT_BEGIN_MARKER,
+ "## Open Second Brain",
+ "",
+ "This project shares an Obsidian-compatible vault. Read Brain/active.md.",
+ DEFAULT_END_MARKER,
+ "",
+ ].join("\n"),
+ );
+ const refused = await runCli(["install", "--target", "cursor", "--apply", "--yes"], {
+ env: envBase(),
+ });
+ expect(refused.returncode).toBe(4);
+ expect(refused.stderr).toContain("hand-edited");
+ // Nothing was written by the refused step.
+ expect(auditWritebackContractFile(join(vault, "AGENTS.md")).finding).not.toBe("conforming");
+ const forced = await runCli(["install", "--target", "cursor", "--apply", "--yes", "--force"], {
+ env: envBase(),
+ });
+ expect(forced.returncode).toBe(0);
+ expect(auditWritebackContractFile(join(vault, "AGENTS.md")).finding).toBe("conforming");
+ // The operator's own bytes survived the upgrade.
+ expect(readFileSync(join(vault, "AGENTS.md"), "utf8").startsWith("# operator notes")).toBe(
+ true,
+ );
+ });
+
+ test("a failure after the adapter apply exits non-zero; a re-run converges", async () => {
+ // A hand-pasted docs-snippet block refuses at APPLY time - after the
+ // adapter's config write has already landed. Symlinks refuse at PLAN
+ // time instead (the checker's posture), so the refusal that proves
+ // the ordering here is the hand-edit one.
+ writeFileSync(
+ join(vault, "AGENTS.md"),
+ [
+ "# operator notes",
+ "",
+ DEFAULT_BEGIN_MARKER,
+ "## Open Second Brain",
+ "",
+ "This project shares an Obsidian-compatible vault. Read Brain/active.md.",
+ DEFAULT_END_MARKER,
+ "",
+ ].join("\n"),
+ );
+ const failed = await runCli(["install", "--target", "cursor", "--apply", "--yes"], {
+ env: envBase(),
+ });
+ expect(failed.returncode).toBe(4);
+ // The adapter write is committed even though the run failed.
+ expect(existsSync(join(home, ".cursor", "mcp.json"))).toBe(true);
+ expect(auditWritebackContractFile(join(vault, "AGENTS.md")).finding).not.toBe("conforming");
+ // The re-run - with the documented --force override - converges: the
+ // adapter write is idempotent and the instruction block lands.
+ const converged = await runCli(
+ ["install", "--target", "cursor", "--apply", "--yes", "--force"],
+ { env: envBase() },
+ );
+ expect(converged.returncode).toBe(0);
+ expect(auditWritebackContractFile(join(vault, "AGENTS.md")).finding).toBe("conforming");
+ expect(readFileSync(join(vault, "AGENTS.md"), "utf8").startsWith("# operator notes")).toBe(
+ true,
+ );
+ expect(converged.stdout).toContain("instruction block");
+ });
+});
+
+describe("o2b install --check stays the block-free verifier", () => {
+ test("check after a successful install still exits 0 through the adapter's own verify", async () => {
+ await runCli(["install", "--target", "cursor", "--apply", "--yes"], { env: envBase() });
+ const r = await runCli(["install", "--check", "--target", "cursor"], { env: envBase() });
+ expect(r.returncode).toBe(0);
+ expect(r.stdout).toContain("ok");
+ });
+});
diff --git a/tests/cli/manifest-completeness.test.ts b/tests/cli/manifest-completeness.test.ts
index dc1ce3f6..38a51ab5 100644
--- a/tests/cli/manifest-completeness.test.ts
+++ b/tests/cli/manifest-completeness.test.ts
@@ -233,7 +233,7 @@ describe("the repaired manifest reaches its two consumers", () => {
/** Verbs the audit found missing; a spot check of each level. */
const REPAIRED = Object.freeze({
top: ["secrets", "partner"],
- brain: ["pending", "lint", "stale", "today", "obligation"],
+ brain: ["pending", "lint", "stale", "today", "obligation", "lessons"],
search: ["expand", "focus", "feedback", "weights", "rerank-provider", "rerank-fit", "plan"],
});
diff --git a/tests/cli/skill-rewrite-verb.test.ts b/tests/cli/skill-rewrite-verb.test.ts
new file mode 100644
index 00000000..c778cc51
--- /dev/null
+++ b/tests/cli/skill-rewrite-verb.test.ts
@@ -0,0 +1,787 @@
+/**
+ * `o2b brain skill-proposals rewrite-plan` and `rewrite-score` (Lane A, A5).
+ *
+ * The two verbs mirror the page-candidates/page-draft split for rewrite
+ * rounds: plan validates the frozen receipt and hands out the dev-round
+ * envelopes (the incumbent body and the candidate body, never held-out
+ * text); score grades the submitted transcripts, runs the selection and
+ * held-out gates, prints the verdict, writes the grade record, and stages
+ * the pending proposal ONLY on a final promote. The scorer binds every
+ * candidate-arm submission to the current candidate body through the
+ * `candidate_sha256` its envelope carried, so a transcript left over from
+ * a previous candidate never gates this one. Every refusal is a named
+ * stderr line and a non-zero exit.
+ */
+
+import { afterEach, beforeEach, describe, expect, setDefaultTimeout, test } from "bun:test";
+import { existsSync, mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from "node:fs";
+import { tmpdir } from "node:os";
+import { join } from "node:path";
+
+import {
+ appendContinuityRecord,
+ listContinuityRecords,
+} from "../../src/core/brain/continuity/store.ts";
+import { skillBenchmarkTasksPath } from "../../src/core/brain/paths.ts";
+import { listPendingSkillProposals } from "../../src/core/brain/skill-proposals.ts";
+import { parseFrontmatter } from "../../src/core/vault.ts";
+import { sha256Hex } from "../../src/core/integrity/digest.ts";
+import {
+ SKILL_REWRITE_JUDGE_CMD_ENV_KEY,
+ SKILL_REWRITE_MODE_ENV_KEY,
+} from "../../src/core/config.ts";
+import { _resetHeldLocksForTests } from "../../src/core/brain/sync-lockfile.ts";
+import { runCli } from "../helpers/run-cli.ts";
+import { CLI_SPAWN_BUDGET_MS } from "../helpers/cli-timeout.ts";
+
+// The wave's explicit per-test budget (test-audit F3): most tests here boot
+// the real CLI, and the budget keeps a loaded machine from turning process
+// start into a flaky verdict.
+setDefaultTimeout(CLI_SPAWN_BUDGET_MS);
+
+let vault: string;
+let scratch: string;
+
+beforeEach(() => {
+ vault = mkdtempSync(join(tmpdir(), "o2b-rewrite-verb-"));
+ scratch = mkdtempSync(join(tmpdir(), "o2b-rewrite-cand-"));
+ mkdirSync(join(vault, "Brain"), { recursive: true });
+});
+
+afterEach(() => {
+ _resetHeldLocksForTests();
+ rmSync(vault, { recursive: true, force: true });
+ rmSync(scratch, { recursive: true, force: true });
+ delete process.env[SKILL_REWRITE_MODE_ENV_KEY];
+ delete process.env[SKILL_REWRITE_JUDGE_CMD_ENV_KEY];
+});
+
+const FIXTURE_TASKS = JSON.parse(
+ readFileSync(
+ join(import.meta.dir, "..", "fixtures", "skill-bench", "example-skill", "tasks.json"),
+ "utf8",
+ ),
+) as { skill: string; tasks: ReadonlyArray<{ id: string }> };
+const FIXTURE_SPEC = JSON.parse(
+ readFileSync(
+ join(import.meta.dir, "..", "fixtures", "skill-bench", "example-skill", "spec.json"),
+ "utf8",
+ ),
+) as {
+ tasks_hash: string;
+ dev_task_ids: ReadonlyArray<string>;
+ held_out_task_ids: ReadonlyArray<string>;
+};
+
+const INCUMBENT_BODY = [
+ "---",
+ "name: example-skill",
+ "description: The incumbent instructions.",
+ "triggers:",
+ " - thing",
+ "version: 3",
+ "---",
+ "# example-skill",
+ "",
+ "Incumbent body: search, then write, then verify.",
+ "",
+].join("\n");
+
+const CANDIDATE_BODY =
+ "Candidate body: plan first, search twice, write once, and report the artifact path.";
+
+/** The hash every candidate-round envelope stamps: sha-256 of the candidate body. */
+const CANDIDATE_HASH = sha256Hex(CANDIDATE_BODY);
+/** The hash a STALE transcript carries: it was produced against a different body. */
+const STALE_HASH = sha256Hex("Candidate body from a round that has since been re-generated.");
+
+const DEV_TASKS = FIXTURE_SPEC.dev_task_ids;
+const HELDOUT_TASKS = FIXTURE_SPEC.held_out_task_ids;
+
+/** Seed the vault: benchmark receipt files and an incumbent skill at version 3. */
+function seedBenchmark(
+ mutateTasks?: (raw: { tasks: Array<Record<string, unknown>> }) => void,
+): void {
+ const tasks = JSON.parse(JSON.stringify(FIXTURE_TASKS)) as {
+ skill: string;
+ tasks: Array<Record<string, unknown>>;
+ };
+ if (mutateTasks) mutateTasks(tasks);
+ const tasksPath = skillBenchmarkTasksPath(vault, "example-skill");
+ mkdirSync(join(tasksPath, ".."), { recursive: true });
+ writeFileSync(tasksPath, `${JSON.stringify(tasks, null, 2)}\n`, "utf8");
+ const specPath = join(tasksPath, "..", "spec.json");
+ writeFileSync(specPath, `${JSON.stringify(FIXTURE_SPEC, null, 2)}\n`, "utf8");
+
+ const skillDir = join(vault, "Brain", "skills", "example-skill");
+ mkdirSync(skillDir, { recursive: true });
+ writeFileSync(join(skillDir, "SKILL.md"), INCUMBENT_BODY, "utf8");
+
+ const candidatePath = join(scratch, "candidate.md");
+ writeFileSync(candidatePath, CANDIDATE_BODY, "utf8");
+}
+
+interface Transcript {
+ readonly task_id: string;
+ readonly steps: ReadonlyArray<string>;
+ readonly tools_used: ReadonlyArray<string>;
+ readonly artifacts: ReadonlyArray<string>;
+ readonly output: Record<string, unknown>;
+ readonly candidate_sha256?: string;
+}
+
+/** A transcript that passes every structural predicate the fixture pins for the task. */
+function passingTranscript(taskId: string): Transcript {
+ const byTask: Record<string, Omit<Transcript, "task_id">> = {
+ "t-03": {
+ steps: ["read", "archive"],
+ tools_used: ["note_write"],
+ artifacts: ["Brain/retired/old-pref.md"],
+ output: {},
+ },
+ "t-04": {
+ steps: ["write"],
+ tools_used: ["note_write"],
+ artifacts: [],
+ output: { verdict: "promote" },
+ },
+ "t-06": {
+ steps: ["list"],
+ tools_used: ["note_search"],
+ artifacts: [],
+ output: { entries: ["example-skill"] },
+ },
+ "t-07": {
+ steps: ["read", "edit", "stage"],
+ tools_used: ["note_write"],
+ artifacts: ["Brain/skill-proposals/pending/x.md"],
+ output: {},
+ },
+ "t-08": {
+ steps: ["move"],
+ tools_used: ["note_move"],
+ artifacts: ["Brain/skill-proposals/accepted/x.md"],
+ output: {},
+ },
+ "t-09": { steps: ["check"], tools_used: [], artifacts: [], output: { enabled: true } },
+ "t-10": {
+ steps: ["read", "summarize", "write"],
+ tools_used: ["note_write"],
+ artifacts: [],
+ output: { summary: "three invocations, all offered" },
+ },
+ "t-01": {
+ steps: ["write"],
+ tools_used: ["note_write"],
+ artifacts: ["Brain/notes/meetings/today.md"],
+ output: {},
+ },
+ "t-02": {
+ steps: ["search", "read", "edit"],
+ tools_used: ["note_search"],
+ artifacts: [],
+ output: {},
+ },
+ "t-05": { steps: ["count"], tools_used: [], artifacts: [], output: { count: 2 } },
+ };
+ const row = byTask[taskId];
+ if (!row) throw new Error(`test setup: no transcript scripted for ${taskId}`);
+ return { task_id: taskId, ...row };
+}
+
+/** A transcript that fails every check: no steps, no tools, no artifacts, empty output. */
+function failingTranscript(taskId: string): Transcript {
+ return { task_id: taskId, steps: [], tools_used: [], artifacts: [], output: {} };
+}
+
+/** Echo the candidate_sha256 the envelope the transcript answers carried. */
+function boundWith(transcript: Transcript, hash: string): Transcript {
+ return { ...transcript, candidate_sha256: hash };
+}
+
+function writeRounds(
+ arm: "baseline" | "candidate" | "heldout",
+ entries: ReadonlyArray<Transcript>,
+): void {
+ const dir = join(vault, "Brain", "skill-benchmarks", "example-skill", "rounds", arm);
+ mkdirSync(dir, { recursive: true });
+ for (const entry of entries) {
+ writeFileSync(join(dir, `${entry.task_id}.json`), `${JSON.stringify(entry)}\n`, "utf8");
+ }
+}
+
+/**
+ * A complete gate round that PROMOTES: dev rounds at 3/7 baseline vs 7/7
+ * candidate plus a passing held-out arm, scored through the real CLI. The
+ * one write that matters to the accept tests is the staged pending
+ * proposal, whose slug this returns.
+ */
+async function stagePromotedRound(): Promise<string> {
+ seedBenchmark();
+ writeRounds(
+ "baseline",
+ DEV_TASKS.map((taskId, index) =>
+ index < 3 ? passingTranscript(taskId) : failingTranscript(taskId),
+ ),
+ );
+ writeRounds(
+ "candidate",
+ DEV_TASKS.map((taskId) => boundWith(passingTranscript(taskId), CANDIDATE_HASH)),
+ );
+ writeRounds(
+ "heldout",
+ HELDOUT_TASKS.map((taskId) => boundWith(passingTranscript(taskId), CANDIDATE_HASH)),
+ );
+ const scored = await runCli([
+ "brain",
+ "skill-proposals",
+ "rewrite-score",
+ "example-skill",
+ "--vault",
+ vault,
+ "--candidate-file",
+ join(scratch, "candidate.md"),
+ ]);
+ expect(scored.returncode).toBe(0);
+ expect(scored.stdout).toContain("promote");
+ const pending = listPendingSkillProposals(vault);
+ expect(pending.length).toBe(1);
+ return pending[0]!.slug;
+}
+
+describe("rewrite-plan", () => {
+ test("prints the frozen receipt and the dev envelopes for both rounds", async () => {
+ seedBenchmark();
+ const r = await runCli([
+ "brain",
+ "skill-proposals",
+ "rewrite-plan",
+ "example-skill",
+ "--vault",
+ vault,
+ "--candidate-file",
+ join(scratch, "candidate.md"),
+ ]);
+ expect(r.returncode).toBe(0);
+ // The receipt: schema, split rule, seed, hashes.
+ expect(r.stdout).toContain("o2b.skill-rewrite.v1");
+ expect(r.stdout).toContain("hash-order-70-30");
+ expect(r.stdout).toContain(FIXTURE_SPEC.tasks_hash);
+ // Dev envelopes for both rounds, with the drop sites named.
+ for (const taskId of DEV_TASKS) {
+ expect(r.stdout).toContain(taskId);
+ expect(r.stdout).toContain(`rounds/baseline/${taskId}.json`);
+ expect(r.stdout).toContain(`rounds/candidate/${taskId}.json`);
+ }
+ // The incumbent and candidate bodies travel in the prompts.
+ expect(r.stdout).toContain("Incumbent body: search, then write, then verify.");
+ expect(r.stdout).toContain("Candidate body: plan first");
+ // Held-out members never appear: not their ids, not their text.
+ for (const taskId of HELDOUT_TASKS) expect(r.stdout).not.toContain(`rounds/baseline/${taskId}`);
+ const heldoutTask = FIXTURE_TASKS.tasks.find((task) => task.id === HELDOUT_TASKS[0]);
+ expect(heldoutTask).toBeDefined();
+ });
+
+ test("a missing task set refuses by name", async () => {
+ const r = await runCli([
+ "brain",
+ "skill-proposals",
+ "rewrite-plan",
+ "example-skill",
+ "--vault",
+ vault,
+ "--candidate-file",
+ join(scratch, "candidate.md"),
+ ]);
+ expect(r.returncode).not.toBe(0);
+ expect(r.stderr).toContain("tasks.json");
+ });
+
+ test("a task set that no longer matches the receipt refuses with the reason", async () => {
+ seedBenchmark((tasks) => {
+ tasks.tasks[0] = { ...tasks.tasks[0], input: "A changed task input line." };
+ });
+ const r = await runCli([
+ "brain",
+ "skill-proposals",
+ "rewrite-plan",
+ "example-skill",
+ "--vault",
+ vault,
+ "--candidate-file",
+ join(scratch, "candidate.md"),
+ ]);
+ expect(r.returncode).not.toBe(0);
+ expect(r.stderr).toContain("hash");
+ });
+
+ test("an unknown mode refuses by name", async () => {
+ seedBenchmark();
+ process.env[SKILL_REWRITE_MODE_ENV_KEY] = "turbo";
+ const r = await runCli([
+ "brain",
+ "skill-proposals",
+ "rewrite-plan",
+ "example-skill",
+ "--vault",
+ vault,
+ "--candidate-file",
+ join(scratch, "candidate.md"),
+ ]);
+ expect(r.returncode).not.toBe(0);
+ expect(r.stderr).toContain("turbo");
+ });
+
+ test("the --json receipt aggregates held-out membership to a count, never ids", async () => {
+ // The verb docblock promises held-out members never appear on this
+ // surface. The JSON receipt is what the calling agent consumes, so the
+ // pin covers the serialized payload: a count, and no held-out id
+ // anywhere in it.
+ seedBenchmark();
+ const r = await runCli([
+ "brain",
+ "skill-proposals",
+ "rewrite-plan",
+ "example-skill",
+ "--vault",
+ vault,
+ "--json",
+ "--candidate-file",
+ join(scratch, "candidate.md"),
+ ]);
+ expect(r.returncode).toBe(0);
+ const payload = JSON.parse(r.stdout) as { receipt: Record<string, unknown> };
+ expect(payload.receipt["heldout_task_count"]).toBe(HELDOUT_TASKS.length);
+ expect(payload.receipt["heldout_task_ids"]).toBeUndefined();
+ const serialized = JSON.stringify(payload);
+ for (const taskId of HELDOUT_TASKS) expect(serialized).not.toContain(taskId);
+ });
+});
+
+describe("rewrite-score", () => {
+ test("a tie holds: the grade record lands, the proposal tree is untouched", async () => {
+ seedBenchmark();
+ const tie = DEV_TASKS.map((taskId, index) =>
+ index < 3 ? passingTranscript(taskId) : failingTranscript(taskId),
+ );
+ writeRounds("baseline", tie);
+ // The candidate arm's transcripts echo the candidate_sha256 their
+ // envelopes carried; the scorer binds them to the candidate body.
+ writeRounds(
+ "candidate",
+ tie.map((transcript) => boundWith(transcript, CANDIDATE_HASH)),
+ );
+
+ const r = await runCli([
+ "brain",
+ "skill-proposals",
+ "rewrite-score",
+ "example-skill",
+ "--vault",
+ vault,
+ "--candidate-file",
+ join(scratch, "candidate.md"),
+ ]);
+ expect(r.returncode).toBe(0);
+ expect(r.stdout).toContain("hold");
+ // The grade record is the one write.
+ const grades = listContinuityRecords(vault, { kind: "skill_rewrite_eval_grade" });
+ expect(grades.length).toBe(1);
+ // Gate failure stages nothing.
+ expect(listPendingSkillProposals(vault).length).toBe(0);
+ });
+
+ test("a stale candidate_sha256 refuses the score by name", async () => {
+ // The transcripts were produced against a DIFFERENT candidate body than
+ // the one on disk now. The scorer binds submissions to the current
+ // candidate, so a stale round never gates this candidate - and never
+ // reaches the gates at all.
+ seedBenchmark();
+ writeRounds(
+ "baseline",
+ DEV_TASKS.map((taskId, index) =>
+ index < 3 ? passingTranscript(taskId) : failingTranscript(taskId),
+ ),
+ );
+ writeRounds(
+ "candidate",
+ DEV_TASKS.map((taskId) => boundWith(passingTranscript(taskId), STALE_HASH)),
+ );
+
+ const r = await runCli([
+ "brain",
+ "skill-proposals",
+ "rewrite-score",
+ "example-skill",
+ "--vault",
+ vault,
+ "--candidate-file",
+ join(scratch, "candidate.md"),
+ ]);
+ expect(r.returncode).not.toBe(0);
+ expect(r.stderr).toContain("candidate_sha256");
+ expect(r.stderr).toContain("does not match the current candidate body");
+ // Refused before anything was decided: no grade record, no staged draft.
+ expect(listPendingSkillProposals(vault).length).toBe(0);
+ expect(listContinuityRecords(vault, { kind: "skill_rewrite_eval_grade" }).length).toBe(0);
+ });
+
+ test("a transcript with no candidate_sha256 refuses once the scorer binds to the candidate", async () => {
+ seedBenchmark();
+ writeRounds(
+ "baseline",
+ DEV_TASKS.map((taskId, index) =>
+ index < 3 ? passingTranscript(taskId) : failingTranscript(taskId),
+ ),
+ );
+ writeRounds(
+ "candidate",
+ DEV_TASKS.map((taskId) => passingTranscript(taskId)),
+ );
+
+ const r = await runCli([
+ "brain",
+ "skill-proposals",
+ "rewrite-score",
+ "example-skill",
+ "--vault",
+ vault,
+ "--candidate-file",
+ join(scratch, "candidate.md"),
+ ]);
+ expect(r.returncode).not.toBe(0);
+ expect(r.stderr).toContain("missing candidate_sha256");
+ expect(listPendingSkillProposals(vault).length).toBe(0);
+ expect(listContinuityRecords(vault, { kind: "skill_rewrite_eval_grade" }).length).toBe(0);
+ });
+
+ test("a promote with a held-out pass stages the scored_rewrite proposal", async () => {
+ seedBenchmark();
+ writeRounds(
+ "baseline",
+ DEV_TASKS.map((taskId, index) =>
+ index < 3 ? passingTranscript(taskId) : failingTranscript(taskId),
+ ),
+ );
+ writeRounds(
+ "candidate",
+ DEV_TASKS.map((taskId) => boundWith(passingTranscript(taskId), CANDIDATE_HASH)),
+ );
+ writeRounds(
+ "heldout",
+ HELDOUT_TASKS.map((taskId) => boundWith(passingTranscript(taskId), CANDIDATE_HASH)),
+ );
+
+ const r = await runCli([
+ "brain",
+ "skill-proposals",
+ "rewrite-score",
+ "example-skill",
+ "--vault",
+ vault,
+ "--candidate-file",
+ join(scratch, "candidate.md"),
+ ]);
+ expect(r.returncode).toBe(0);
+ expect(r.stdout).toContain("promote");
+
+ const pending = listPendingSkillProposals(vault);
+ expect(pending.length).toBe(1);
+ expect(pending[0]?.patternKind).toBe("scored_rewrite");
+ const grades = listContinuityRecords(vault, { kind: "skill_rewrite_eval_grade" });
+ expect(grades.length).toBe(1);
+ expect(grades[0]?.payload["verdict"]).toBe("promote");
+ });
+
+ test("the operator accept lands the rewrite end to end through the CLI", async () => {
+ // The designed flow, whole: the gate stages, the operator accepts on
+ // the command line, and the accept-time re-verification (security M1)
+ // passes against exactly what the gate round wrote - receipt, take,
+ // and its own promote grade record. The accept of an OVERWRITE carries
+ // the explicit --yes consent flag (review round-2, M1 residual R2),
+ // the same flag every other irreversible verb in the tree gates on.
+ const slug = await stagePromotedRound();
+
+ const accepted = await runCli([
+ "brain",
+ "skill-proposals",
+ "accept",
+ slug,
+ "--vault",
+ vault,
+ "--yes",
+ "--note",
+ "gate passed",
+ ]);
+ expect(accepted.returncode).toBe(0);
+ // The incumbent body was replaced by the candidate, and the draft is
+ // consumed - the accept the design promised, still human-initiated.
+ const skillPath = join(vault, "Brain", "skills", "example-skill", "SKILL.md");
+ expect(readFileSync(skillPath, "utf8")).toContain("Candidate body: plan first");
+ expect(listPendingSkillProposals(vault).length).toBe(0);
+ // The accepted skill keeps the incumbent's own description and
+ // triggers: the reader takes them from the incumbent's frontmatter,
+ // so the rewrite never degrades to the placeholder description and an
+ // empty trigger list.
+ const [acceptedFm] = parseFrontmatter(skillPath);
+ expect(acceptedFm["description"]).toBe("The incumbent instructions.");
+ expect(acceptedFm["triggers"]).toEqual(["thing"]);
+ });
+
+ test("a scored_rewrite accept without --yes refuses by name, prints the exact command, and writes nothing", async () => {
+ // The consent boundary (review round-2, M1 residual R2): an agent can
+ // run shell commands, so "MCP proposes" alone does not keep the
+ // overwrite out of its reach - the explicit flag does. Without it the
+ // accept is a named refusal before anything is written, and the
+ // refusal names the exact command to re-run.
+ const slug = await stagePromotedRound();
+ const skillPath = join(vault, "Brain", "skills", "example-skill", "SKILL.md");
+ const incumbentBefore = readFileSync(skillPath, "utf8");
+
+ const refused = await runCli([
+ "brain",
+ "skill-proposals",
+ "accept",
+ slug,
+ "--vault",
+ vault,
+ "--note",
+ "gate passed",
+ ]);
+ expect(refused.returncode).toBe(6);
+ expect(refused.stderr).toContain("scored_rewrite");
+ expect(refused.stderr).toContain("OVERWRITES");
+ expect(refused.stderr).toContain("--yes");
+ expect(refused.stderr).toContain(`o2b brain skill-proposals accept ${slug} --yes`);
+ // Nothing was written: the incumbent keeps its bytes and the draft is
+ // still pending for the operator.
+ expect(readFileSync(skillPath, "utf8")).toBe(incumbentBefore);
+ expect(listPendingSkillProposals(vault).length).toBe(1);
+ });
+
+ test("the --json consent refusal carries the registered headless-refused verdict", async () => {
+ // The consent vocabulary is the tree's one machine contract for
+ // refusals (CONSENT_VERDICTS in trust.ts): install, lessons, protect
+ // and doctor all emit `headless-refused` on this field with the same
+ // exit 6, so a script branching on the verdict string must not meet
+ // an unregistered spelling on this verb.
+ const slug = await stagePromotedRound();
+ const refused = await runCli([
+ "brain",
+ "skill-proposals",
+ "accept",
+ slug,
+ "--vault",
+ vault,
+ "--json",
+ ]);
+ expect(refused.returncode).toBe(6);
+ const payload = JSON.parse(refused.stdout) as { consent: string; written: boolean };
+ expect(payload.consent).toBe("headless-refused");
+ expect(payload.written).toBe(false);
+ expect(listPendingSkillProposals(vault).length).toBe(1);
+ });
+
+ test("a replayed promote record cannot bless a body swapped in after staging, through the CLI", async () => {
+ // The round-2 replay (M1 residual R1), end to end: rates collide, so
+ // after this gate round a hand-edit that swaps the staged candidate
+ // body must not be blessed by the promote record (or any other one) -
+ // the accept-time binding recomputes the staged document's hash.
+ const slug = await stagePromotedRound();
+ const pendingPath = join(vault, "Brain", "skill-proposals", "pending", `prop-${slug}.md`);
+ const forged = readFileSync(pendingPath, "utf8").replace(
+ "Candidate body: plan first, search twice, write once, and report the artifact path.",
+ "Hostile body: skip verification entirely.",
+ );
+ expect(forged).toContain("Hostile body: skip verification entirely.");
+ writeFileSync(pendingPath, forged, "utf8");
+ const skillPath = join(vault, "Brain", "skills", "example-skill", "SKILL.md");
+ const incumbentBefore = readFileSync(skillPath, "utf8");
+
+ const refused = await runCli([
+ "brain",
+ "skill-proposals",
+ "accept",
+ slug,
+ "--vault",
+ vault,
+ "--yes",
+ ]);
+ expect(refused.returncode).not.toBe(0);
+ expect(refused.stderr).toContain("candidate_sha256");
+ expect(refused.stderr).toContain("edited after staging");
+ expect(readFileSync(skillPath, "utf8")).toBe(incumbentBefore);
+ expect(existsSync(pendingPath)).toBe(true);
+ });
+
+ test("an ordinary proposal still accepts without --yes", async () => {
+ // The consent flag gates the OVERWRITE, nothing else: mined and
+ // declared proposals create or fill vault pages and accept exactly as
+ // before (unchanged UX is part of the pin).
+ for (const index of [0, 1, 2]) {
+ appendContinuityRecord(vault, {
+ kind: "session_turn",
+ createdAt: `2026-05-20T08:1${index}:00Z`,
+ sourceRefs: [{ id: `src-routine-${index}` }],
+ payload: { action: "routine_step", summary: `did routine_step run ${index}` },
+ });
+ }
+ const learned = await runCli(["brain", "skill-proposals", "learn", "--vault", vault]);
+ expect(learned.returncode).toBe(0);
+ const pending = listPendingSkillProposals(vault).find(
+ (proposal) => proposal.patternKind === "repeated_action",
+ );
+ expect(pending).toBeDefined();
+
+ const accepted = await runCli([
+ "brain",
+ "skill-proposals",
+ "accept",
+ pending!.slug,
+ "--vault",
+ vault,
+ ]);
+ expect(accepted.returncode).toBe(0);
+ // The accepted draft is consumed; the sibling pattern family learn
+ // also created is untouched - the consent gate changed nothing here.
+ const remaining = listPendingSkillProposals(vault).filter(
+ (proposal) => proposal.slug === pending!.slug,
+ );
+ expect(remaining.length).toBe(0);
+ });
+
+ test("rewrite-score refuses by name when --candidate-file is missing", async () => {
+ // The scorer binds every candidate-arm submission to the current
+ // candidate body, so the body is required on EVERY run - the flag's
+ // absence is a named usage refusal, never an unbound scoring run.
+ seedBenchmark();
+ writeRounds(
+ "baseline",
+ DEV_TASKS.map((taskId, index) =>
+ index < 3 ? passingTranscript(taskId) : failingTranscript(taskId),
+ ),
+ );
+ writeRounds(
+ "candidate",
+ DEV_TASKS.map((taskId) => boundWith(passingTranscript(taskId), CANDIDATE_HASH)),
+ );
+ const r = await runCli([
+ "brain",
+ "skill-proposals",
+ "rewrite-score",
+ "example-skill",
+ "--vault",
+ vault,
+ ]);
+ expect(r.returncode).not.toBe(0);
+ expect(r.stderr).toContain("--candidate-file is required");
+ expect(listPendingSkillProposals(vault).length).toBe(0);
+ expect(listContinuityRecords(vault, { kind: "skill_rewrite_eval_grade" }).length).toBe(0);
+ });
+
+ test("a promote without held-out transcripts prints the one held-out round and stages nothing", async () => {
+ seedBenchmark();
+ writeRounds(
+ "baseline",
+ DEV_TASKS.map((taskId, index) =>
+ index < 3 ? passingTranscript(taskId) : failingTranscript(taskId),
+ ),
+ );
+ writeRounds(
+ "candidate",
+ DEV_TASKS.map((taskId) => boundWith(passingTranscript(taskId), CANDIDATE_HASH)),
+ );
+
+ const r = await runCli([
+ "brain",
+ "skill-proposals",
+ "rewrite-score",
+ "example-skill",
+ "--vault",
+ vault,
+ "--candidate-file",
+ join(scratch, "candidate.md"),
+ ]);
+ expect(r.returncode).toBe(0);
+ // The single held-out check's envelopes, and nothing staged or graded yet.
+ for (const taskId of HELDOUT_TASKS) {
+ expect(r.stdout).toContain(taskId);
+ expect(r.stdout).toContain(`rounds/heldout/${taskId}.json`);
+ }
+ expect(listPendingSkillProposals(vault).length).toBe(0);
+ expect(listContinuityRecords(vault, { kind: "skill_rewrite_eval_grade" }).length).toBe(0);
+ });
+
+ test("a short dev arm is not_enough_evidence and stages nothing", async () => {
+ seedBenchmark();
+ writeRounds("baseline", [passingTranscript(DEV_TASKS[0]!)]);
+ writeRounds(
+ "candidate",
+ DEV_TASKS.map((taskId) => boundWith(passingTranscript(taskId), CANDIDATE_HASH)),
+ );
+
+ const r = await runCli([
+ "brain",
+ "skill-proposals",
+ "rewrite-score",
+ "example-skill",
+ "--vault",
+ vault,
+ "--candidate-file",
+ join(scratch, "candidate.md"),
+ ]);
+ expect(r.returncode).toBe(0);
+ expect(r.stdout).toContain("not_enough_evidence");
+ expect(listPendingSkillProposals(vault).length).toBe(0);
+ });
+
+ test("a refused take exits non-zero naming the reason", async () => {
+ seedBenchmark((tasks) => {
+ tasks.tasks[0] = { ...tasks.tasks[0], input: "A changed task input line." };
+ });
+ const r = await runCli([
+ "brain",
+ "skill-proposals",
+ "rewrite-score",
+ "example-skill",
+ "--vault",
+ vault,
+ ]);
+ expect(r.returncode).not.toBe(0);
+ expect(r.stderr).toContain("hash");
+ expect(listContinuityRecords(vault, { kind: "skill_rewrite_eval_grade" }).length).toBe(0);
+ });
+
+ test("a missing incumbent refuses by name when staging is reached", async () => {
+ seedBenchmark();
+ rmSync(join(vault, "Brain", "skills", "example-skill"), { recursive: true, force: true });
+ writeRounds(
+ "baseline",
+ DEV_TASKS.map((taskId, index) =>
+ index < 3 ? passingTranscript(taskId) : failingTranscript(taskId),
+ ),
+ );
+ writeRounds(
+ "candidate",
+ DEV_TASKS.map((taskId) => boundWith(passingTranscript(taskId), CANDIDATE_HASH)),
+ );
+ writeRounds(
+ "heldout",
+ HELDOUT_TASKS.map((taskId) => boundWith(passingTranscript(taskId), CANDIDATE_HASH)),
+ );
+
+ const r = await runCli([
+ "brain",
+ "skill-proposals",
+ "rewrite-score",
+ "example-skill",
+ "--vault",
+ vault,
+ "--candidate-file",
+ join(scratch, "candidate.md"),
+ ]);
+ expect(r.returncode).not.toBe(0);
+ expect(r.stderr).toContain("incumbent");
+ expect(listPendingSkillProposals(vault).length).toBe(0);
+ });
+});
diff --git a/tests/cli/stdin.test.ts b/tests/cli/stdin.test.ts
index b766341c..cddc6737 100644
--- a/tests/cli/stdin.test.ts
+++ b/tests/cli/stdin.test.ts
@@ -23,8 +23,30 @@ async function main() {
main().then(() => process.exit(0));
`;
-function run(input: string | Buffer) {
- return spawnSync(process.execPath, ["-e", CHILD], {
+/**
+ * A child that reads once and then checks the stream is free for the next
+ * reader in the SAME process - the lock-release regression the last test
+ * pins. Its stdin is the closed, empty pipe the runner hands it, so the
+ * read completes immediately and deterministically.
+ */
+const CHILD_LOCK = `
+import { readStdinText } from ${JSON.stringify(STDIN_MODULE)};
+async function main() {
+ await readStdinText();
+ let released = true;
+ try {
+ process.stdin.resume();
+ process.stdin.pause();
+ } catch {
+ released = false;
+ }
+ process.stdout.write(JSON.stringify({ released }));
+}
+main().then(() => process.exit(0));
+`;
+
+function run(input: string | Buffer, child: string = CHILD) {
+ return spawnSync(process.execPath, ["-e", child], {
input,
encoding: "utf8",
timeout: 30_000,
@@ -58,4 +80,21 @@ describe("readStdinText", () => {
expect(proc.status).toBe(0);
expect(JSON.parse(proc.stdout)).toEqual({ length: 0, head: "", tail: "" });
});
+
+ test("a completed read releases stdin for the next reader in the same process", () => {
+ // The CLI reads stdin once per process, but a long-lived embedder
+ // (the test runner among them) shares one stdin across files: an
+ // earlier file's in-process readStdinText left Bun's stdin body
+ // locked forever, so a later file's in-process y/N prompt
+ // (readSingleLine's event-listener read) threw `ReadableStream is
+ // locked` - and the suite's verdict depended on bun's file discovery
+ // order. A completed read must release the lock it took; only the
+ // lock is under test. The read runs in a child whose stdin is a
+ // closed, empty pipe: reading the RUNNER's own stdin here would hang
+ // a terminal `scripts/test` on the drain until EOF, the exact stall
+ // this file exists to rule out.
+ const proc = run("", CHILD_LOCK);
+ expect(proc.status).toBe(0);
+ expect(JSON.parse(proc.stdout)).toEqual({ released: true });
+ });
});
diff --git a/tests/cli/uninstall.test.ts b/tests/cli/uninstall.test.ts
index 89325b2b..dd7631e8 100644
--- a/tests/cli/uninstall.test.ts
+++ b/tests/cli/uninstall.test.ts
@@ -1,4 +1,4 @@
-import { afterEach, beforeEach, describe, expect, test } from "bun:test";
+import { afterEach, beforeEach, describe, expect, setDefaultTimeout, test } from "bun:test";
import { existsSync, mkdirSync, mkdtempSync, rmSync, writeFileSync } from "node:fs";
import { tmpdir } from "node:os";
import { join } from "node:path";
@@ -10,8 +10,11 @@ import {
planUninstall,
renderPlan,
} from "../../src/cli/uninstall.ts";
+import { CLI_SPAWN_BUDGET_MS } from "../helpers/cli-timeout.ts";
import { runCli } from "../helpers/run-cli.ts";
+setDefaultTimeout(CLI_SPAWN_BUDGET_MS);
+
let tmp: string;
beforeEach(() => {
@@ -280,6 +283,52 @@ describe("CLI uninstall", () => {
});
});
+describe("uninstall --target vault resolution", () => {
+ test("the vault resolves through the canonical chain: VAULT_DIR beats the config key", async () => {
+ // The install verb resolves through resolveInstallVault, whose chain
+ // puts VAULT_DIR first - install.ts documents the old order (config
+ // key, then VAULT_DIR) as the split-brain bug it fixed. The uninstall
+ // verb still carried that old order, so an install that resolved
+ // VAULT_DIR was uninstalled from the CONFIGURED vault: the manifest
+ // was not found there and the real install state stayed behind. The
+ // uninstall now resolves through the same chain, and this pins it
+ // end to end - install lands in the VAULT_DIR vault, then an
+ // uninstall with no --vault finds and plans the removal there.
+ const configured = join(tmp, "vault-configured");
+ const envVault = join(tmp, "vault-env");
+ const home = join(tmp, "home");
+ mkdirSync(configured, { recursive: true });
+ mkdirSync(envVault, { recursive: true });
+ mkdirSync(home, { recursive: true });
+ const config = join(tmp, "config.yaml");
+ writeFileSync(config, `vault: "${configured}"\n`);
+ const env = {
+ HOME: home,
+ OPEN_SECOND_BRAIN_CONFIG: config,
+ VAULT_AGENT_NAME: "uninstall-test",
+ VAULT_TIMEZONE: "UTC",
+ };
+ const seeded = await runCli(
+ ["install", "--target", "cursor", "--vault", envVault, "--apply", "--yes", "--json"],
+ { env, subprocess: true },
+ );
+ expect(seeded.returncode).toBe(0);
+ expect(existsSync(join(envVault, ".open-second-brain", "install.lock.json"))).toBe(true);
+
+ const r = await runCli(["uninstall", "--target", "cursor", "--json"], {
+ env: { ...env, VAULT_DIR: envVault },
+ subprocess: true,
+ });
+ expect(r.returncode).toBe(0);
+ // The verb's --json output is the CLI's ok-envelope with the payload
+ // nested in its `stdout` string.
+ const envelope = JSON.parse(r.stdout) as { ok: boolean; code: number; stdout: string };
+ expect(envelope.ok).toBe(true);
+ const payload = JSON.parse(envelope.stdout) as { target: string };
+ expect(payload.target).toBe("cursor");
+ });
+});
+
describe("safe names", () => {
test("only canonical Open Second Brain names", () => {
expect([...SAFE_CONFIG_DIR_NAMES].toSorted()).toEqual([
diff --git a/tests/core/architecture/claim-attribution-census.test.ts b/tests/core/architecture/claim-attribution-census.test.ts
index f5a8945b..ef959313 100644
--- a/tests/core/architecture/claim-attribution-census.test.ts
+++ b/tests/core/architecture/claim-attribution-census.test.ts
@@ -122,6 +122,13 @@ const PINNED_CONTINUITY_KINDS: ReadonlyArray<string> = Object.freeze([
// verdicts, session-keyed so the receipt read can join it. Written by
// the hook only; the join reads it, no truth module appends it.
"reply_presence",
+ // The agent-presence wave's additive kind (t_635e3e72, Lane A): one
+ // completed benchmark-gated skill rewrite gate run, written by
+ // `recordSkillRewriteGrade` in `skill-proposals.ts` after the gates
+ // finished. Review evidence only - identifiers, scores and per-check
+ // verdicts with the spec hash, never task or transcript text - and the
+ // human accept, not this record, is what moves a skill.
+ "skill_rewrite_eval_grade",
]);
function truthModulePaths(): ReadonlyArray<string> {
diff --git a/tests/core/architecture/state-surface-census.test.ts b/tests/core/architecture/state-surface-census.test.ts
index b9cbf603..24270fda 100644
--- a/tests/core/architecture/state-surface-census.test.ts
+++ b/tests/core/architecture/state-surface-census.test.ts
@@ -61,6 +61,7 @@ import { DERIVED_STORE_DIR } from "../../../src/core/brain/path-constants.ts";
import {
STATE_SURFACE_SWEEP_EXCLUSIONS,
STATE_SURFACES,
+ STATE_SURFACE_ID,
} from "../../../src/core/state/surfaces.ts";
import { lexSource } from "../../helpers/source-lexer.ts";
@@ -93,7 +94,16 @@ const STORE_DIR_IDENTIFIER = "DERIVED_STORE_DIR";
// verb LEFT the population - its runs dir was hoisted to `BENCH_RUNS_REL` in
// `path-constants.ts`, so it no longer spells the directory - taking its now
// stale exclusion with it.
-const SWEPT_POPULATION_SIZE = 30;
+// 30 -> 32, net, from the agent-presence wave: the approvals ledger writer
+// (`src/core/brain/lessons-promotion.ts`, t_1e952e43) spells the directory
+// for `lessons-approvals.json` and is answered by that surface's row, and
+// the instruction-block installer (`src/core/install/instruction-block.ts`,
+// t_ba41a78a) spells it for `instruction-block.lock.json` and is answered
+// by the `instruction_block_lock` row's `sources`.
+// 32 -> 33: the lessons-block readiness check
+// (`src/core/brain/doctor/lessons-block-check.ts`, t_1e952e43) joins with
+// the same wave, answered by the `lesson_approvals` row's `sources`.
+const SWEPT_POPULATION_SIZE = 33;
/** Declared surfaces today. Pinned for the same reason. */
// 50: the source-archives row (answer-trust Task C1) joins the population,
@@ -107,7 +117,15 @@ const SWEPT_POPULATION_SIZE = 30;
// population with two rows - the signed attestation records (attestations)
// and the operator's Ed25519 signing keypair (attestation_keys), the same
// derived-store join the ingest checkpoints row made.
-const DECLARED_SURFACE_COUNT = 55;
+// 55 -> 56: the instruction-block lock row (t_ba41a78a Task B4) joins the
+// catalogue - the ownership record uninstall reads to remove exactly the
+// recorded pair, the same derived-store join the install manifest made.
+// 56 -> 57: the skill-benchmarks row (t_635e3e72 Task A5) joins the
+// catalogue - the preregistration a staged scored_rewrite proposal is
+// audited against, the same vault-content join the skills tree made.
+// 57 -> 58: the lesson_approvals row joins the catalogue with the lessons lane's final
+// commit (t_1e952e43), the same join the session-mining ledger made.
+const DECLARED_SURFACE_COUNT = 58;
/** An exclusion reason has to be an argument, not a label. */
const MIN_REASON_LENGTH = 80;
@@ -248,6 +266,13 @@ describe("state surface census", () => {
// …and it has to have found something, or it is no alarm at all.
expect(naivePathBuilders().length).toBeGreaterThan(5);
});
+ test("the lesson approvals row attributes the ledger writer (t_1e952e43)", () => {
+ const row = STATE_SURFACES.find((r) => r.id === STATE_SURFACE_ID.lessonApprovals);
+ expect(row).toBeDefined();
+ expect(row?.sources).toContain("src/core/brain/lessons-promotion.ts");
+ // ...and the writer sits inside the swept population it answers.
+ expect(sweepPopulation()).toContain("src/core/brain/lessons-promotion.ts");
+ });
test("the census is not vacuous", () => {
expect(TREE.length).toBeGreaterThan(850);
diff --git a/tests/core/architecture/verdict-vocabulary-census.test.ts b/tests/core/architecture/verdict-vocabulary-census.test.ts
index cbcea000..acfc4621 100644
--- a/tests/core/architecture/verdict-vocabulary-census.test.ts
+++ b/tests/core/architecture/verdict-vocabulary-census.test.ts
@@ -114,6 +114,33 @@ import {
SCHEMA_PACK_UNVERIFIED_REASON,
SCHEMA_PACK_UNVERIFIED_REASONS,
} from "../../../src/core/brain/schema-integrity.ts";
+import {
+ isSkillBenchCheck,
+ isSkillBenchTaskKind,
+ isSkillBenchValueClass,
+ SKILL_BENCH_CHECK,
+ SKILL_BENCH_CHECKS,
+ SKILL_BENCH_TASK_KIND,
+ SKILL_BENCH_TASK_KINDS,
+ SKILL_BENCH_VALUE_CLASS,
+ SKILL_BENCH_VALUE_CLASSES,
+} from "../../../src/core/brain/skill-rewrite-tasks.ts";
+import {
+ isSkillRewriteMode,
+ isSkillRewriteRoundArm,
+ isSkillRewriteVerdict,
+ SKILL_REWRITE_MODE,
+ SKILL_REWRITE_MODES,
+ SKILL_REWRITE_ROUND_ARM,
+ SKILL_REWRITE_ROUND_ARMS,
+ SKILL_REWRITE_VERDICT,
+ SKILL_REWRITE_VERDICTS,
+} from "../../../src/core/brain/skill-rewrite.ts";
+import {
+ isLessonsBlockState,
+ LESSONS_BLOCK_STATE,
+ LESSONS_BLOCK_STATES,
+} from "../../../src/core/brain/doctor/lessons-block-check.ts";
import {
isNegativeRecallState,
isNegativeRecallUnknownReason,
@@ -164,6 +191,11 @@ import {
OPEN_DECISION_STATUS,
OPEN_DECISION_STATUSES,
} from "../../../src/core/brain/decisions/open-store.ts";
+import {
+ isLessonPromotionBlocked,
+ LESSON_PROMOTION_BLOCKED,
+ LESSON_PROMOTION_BLOCKED_MEMBERS,
+} from "../../../src/core/brain/lessons-promotion.ts";
import {
BRAIN_SNAPSHOT_REASON,
BRAIN_SNAPSHOT_REASONS,
@@ -685,6 +717,16 @@ const CENSUS: ReadonlyArray<VocabularyUnderCensus> = Object.freeze([
members: OPEN_DECISION_STATUSES,
guard: isOpenDecisionStatus,
},
+ {
+ // Operator-approved lesson promotion (t_1e952e43). Why a lesson is not
+ // promotable: the reason rides the CLI candidates listing and the JSON
+ // surfaces, so a reader can tell a scope that was never enabled from an
+ // approval that went stale on content drift.
+ name: "LESSON_PROMOTION_BLOCKED",
+ values: LESSON_PROMOTION_BLOCKED,
+ members: LESSON_PROMOTION_BLOCKED_MEMBERS,
+ guard: isLessonPromotionBlocked,
+ },
{
// U2. Three vocabularies, because a corpus verdict, the reason it
// could not be reached, and the stored edge that grounds a
@@ -1768,6 +1810,70 @@ const CENSUS: ReadonlyArray<VocabularyUnderCensus> = Object.freeze([
members: CONTENT_CLASSES,
guard: isContentClass,
},
+ {
+ // agent-presence, Lane A (t_635e3e72): the three-arm rewrite verdict,
+ // copied from the decision-model eval vocabulary the gate generalizes.
+ // Leaves TypeScript in grade records and the CLI/MCP status surfaces.
+ name: "SKILL_REWRITE_VERDICT",
+ values: SKILL_REWRITE_VERDICT,
+ members: SKILL_REWRITE_VERDICTS,
+ guard: isSkillRewriteVerdict,
+ },
+ {
+ // The closed task-kind vocabulary of a benchmark task set. Leaves
+ // TypeScript in the tasks.json fixtures and their named parse errors.
+ name: "SKILL_BENCH_TASK_KIND",
+ values: SKILL_BENCH_TASK_KIND,
+ members: SKILL_BENCH_TASK_KINDS,
+ guard: isSkillBenchTaskKind,
+ },
+ {
+ // The closed structural-predicate vocabulary a task's expectations are
+ // written against; the check ids leave TypeScript in grade-record rows
+ // and the score output.
+ name: "SKILL_BENCH_CHECK",
+ values: SKILL_BENCH_CHECK,
+ members: SKILL_BENCH_CHECKS,
+ guard: isSkillBenchCheck,
+ },
+ {
+ // agent-presence, Lane C (t_1e952e43): the four states a managed
+ // lessons block grades to in the doctor readiness check - the shared
+ // writer's drift vocabulary plus the named stale-lessons extension.
+ // Leaves TypeScript in doctor findings and the per-file readiness
+ // rows, both of which the refresh verb's own surfaces read back.
+ name: "LESSONS_BLOCK_STATE",
+ values: LESSONS_BLOCK_STATE,
+ members: LESSONS_BLOCK_STATES,
+ guard: isLessonsBlockState,
+ },
+ {
+ // The closed value-class vocabulary an output_field expectation
+ // asserts over; leaves TypeScript in the fixtures and their named
+ // parse errors.
+ name: "SKILL_BENCH_VALUE_CLASS",
+ values: SKILL_BENCH_VALUE_CLASS,
+ members: SKILL_BENCH_VALUE_CLASSES,
+ guard: isSkillBenchValueClass,
+ },
+ {
+ // Which round an envelope belongs to: the baseline and candidate dev
+ // rounds and the single held-out check. Leaves TypeScript in the
+ // transcript drop-site paths and the round reports.
+ name: "SKILL_REWRITE_ROUND_ARM",
+ values: SKILL_REWRITE_ROUND_ARM,
+ members: SKILL_REWRITE_ROUND_ARMS,
+ guard: isSkillRewriteRoundArm,
+ },
+ {
+ // The rewrite gate mode: gated (one candidate per round) or iterative
+ // (a bounded dev-only edit loop, still gated before any write).
+ // Resolved from `skill_rewrite.mode`, refused by name on other values.
+ name: "SKILL_REWRITE_MODE",
+ values: SKILL_REWRITE_MODE,
+ members: SKILL_REWRITE_MODES,
+ guard: isSkillRewriteMode,
+ },
]);
// ---------------------------------------------------------------------------
@@ -2050,7 +2156,14 @@ const SCANNED = scanVocabularies(SOURCE_TREE);
// 107/108: RECEIPT_VERIFY_VERDICT and RECEIPT_VERIFY_UNAVAILABLE_REASON
// (delivery-trust fix wave 1) - lane B's closed verify vocabularies ship
// their membership lists and guards so the scanner can see them.
-const VOCABULARY_POPULATION = 108;
+// 109: LESSON_PROMOTION_BLOCKED (operator-approved lesson promotion,
+// t_1e952e43) - the named reason a lesson fails the promotion gate,
+// rendered by the candidates listing and the JSON surfaces.
+// 110-115: the agent-presence rewrite lane's six closed vocabularies
+// (t_635e3e72) - SKILL_REWRITE_VERDICT, SKILL_BENCH_TASK_KIND,
+// SKILL_BENCH_CHECK, SKILL_BENCH_VALUE_CLASS, SKILL_REWRITE_ROUND_ARM and
+// SKILL_REWRITE_MODE - join, each with its membership list and guard.
+const VOCABULARY_POPULATION = 115;
const REGISTERED = new Map(CENSUS.map((entry) => [entry.name, entry] as const));
describe("verdict vocabulary census", () => {
@@ -2180,7 +2293,9 @@ describe("the census reads the tree", () => {
// Adding a vocabulary therefore means bumping this number, which is
// the point: the count is the measurement, and a measurement nobody
// has to keep true is not one.
- expect(SCANNED.length).toBe(VOCABULARY_POPULATION);
+ // 115 -> 116: the lessons-block state vocabulary (LESSONS_BLOCK_STATE) joins the
+ // population with the lessons lane's final commit (t_1e952e43).
+ expect(SCANNED.length).toBe(VOCABULARY_POPULATION + 1);
expect(SOURCE_TREE.length).toBeGreaterThan(500);
});
diff --git a/tests/core/architecture/visibility-surface-census.test.ts b/tests/core/architecture/visibility-surface-census.test.ts
index 7b3df121..6389722d 100644
--- a/tests/core/architecture/visibility-surface-census.test.ts
+++ b/tests/core/architecture/visibility-surface-census.test.ts
@@ -642,7 +642,10 @@ function reasonProblems(entries: ReadonlyArray<VisibilitySurfaceEntry>): {
* docblock above). Classified excluded: attestation evidence carries no
* page content at any reach.
*/
-const MCP_TOOL_POPULATION_SIZE = 88;
+/** 88 -> 89: `brain_skill_rewrite_status` (agent-presence, Lane A) joins as a
+ * read-only, excluded-class status surface - it names no note content.
+ */
+const MCP_TOOL_POPULATION_SIZE = 89;
/** Measured: MCP resources + templates. */
const MCP_RESOURCE_POPULATION_SIZE = 8;
/**
diff --git a/tests/core/architecture/write-site-census.test.ts b/tests/core/architecture/write-site-census.test.ts
index 95c0157f..5742fd9d 100644
--- a/tests/core/architecture/write-site-census.test.ts
+++ b/tests/core/architecture/write-site-census.test.ts
@@ -1549,8 +1549,25 @@ const DIRECT_WRITE_ROWS = 86;
* (`src/core/brain/attestation/signing.ts`) writes the keypair halves the
* same way - both committed through the shared writer, so both join the
* shared-helper population.
+ *
+ * 135 -> 136, from the operator-approved lesson promotion lane
+ * (t_1e952e43) and nothing else: the approvals ledger writer
+ * (`src/core/brain/lessons-promotion.ts`) commits
+ * `.open-second-brain/lessons-approvals.json` through the shared atomic
+ * writer under the file's own lock - derived-store machine state, not a
+ * note, so it joins the shared class needing no exclusion. The lane's
+ * rules-file writes ride the shared rules-block writer
+ * (`src/core/install/rules-block.ts`), which carries its own row.
+ *
+ * 136 -> 137, from the agent-presence wave (t_ba41a78a) and nothing
+ * else: the instruction-block installer
+ * (`src/core/install/instruction-block.ts`) commits the vault-root
+ * agent-instruction file through the shared rules-block writer and the
+ * `instruction-block.lock.json` ownership record through the shared
+ * atomic writer - every byte it writes rides a shared helper, so it
+ * joins the shared class needing no exclusion.
*/
-const SHARED_HELPER_ROWS = 135;
+const SHARED_HELPER_ROWS = 137;
// ----- Origin-channel coverage boundary (Unit C) ----------------------------
@@ -1732,8 +1749,20 @@ const UNSTAMPED_DIRECT_ROWS = 85;
* 131 -> 130 is the same wave's mutation channel stamp: the shared
* write-batch seam moved from the unstamped to the stamped shared class
* when note mutations began stamping the writing process's channel.
+ * 130 -> 131, from the operator-approved lesson promotion lane
+ * (t_1e952e43) and nothing else: the approvals ledger writer
+ * (`src/core/brain/lessons-promotion.ts`) commits the
+ * `lessons-approvals.json` state table through the shared atomic writer -
+ * machine state in the derived store, carrying no origin channel.
+ * 131 -> 132, from the agent-presence wave (t_ba41a78a) and nothing
+ * else: the instruction-block installer
+ * (`src/core/install/instruction-block.ts`) commits the vault-root
+ * agent-instruction file through the shared rules-block writer and the
+ * `instruction-block.lock.json` ownership record through the shared
+ * atomic writer - both under the apply arm only, the plan and the dry
+ * run write nothing, and neither write stamps an origin channel.
*/
-const UNSTAMPED_SHARED_ROWS = 130;
+const UNSTAMPED_SHARED_ROWS = 132;
describe("in-vault write-site census", () => {
test("every direct-fs write site carries a written exclusion", () => {
diff --git a/tests/core/brain.types.test.ts b/tests/core/brain.types.test.ts
index 34654a87..ba4f178c 100644
--- a/tests/core/brain.types.test.ts
+++ b/tests/core/brain.types.test.ts
@@ -147,6 +147,13 @@ describe("BRAIN_* const enums", () => {
"freeze",
"unfreeze",
"write-refused",
+ // operator-approved lesson promotion (t_1e952e43): the operator's
+ // approve / deny verdicts and a managed lessons block that a
+ // refresh-blocks apply actually rewrote. Operator CLI only - no
+ // agent-facing path can mint any of the three
+ "lessons-approved",
+ "lessons-denied",
+ "lessons-promoted",
// who-wrote-what Task A (t_662f4e82) one vault note created, updated,
// appended to or reverted - the event that makes the bulk of what an
// agent produces attributable at all
diff --git a/tests/core/brain/doctor/lessons-block-check.test.ts b/tests/core/brain/doctor/lessons-block-check.test.ts
new file mode 100644
index 00000000..5a8e36c2
--- /dev/null
+++ b/tests/core/brain/doctor/lessons-block-check.test.ts
@@ -0,0 +1,324 @@
+/**
+ * The lessons-block doctor check (t_1e952e43, task C3).
+ *
+ * A failSoft, read-only check over the managed lessons blocks of the
+ * agent rules files. One finding per candidate file, in a closed state
+ * vocabulary shared with the writer's own drift vocabulary plus the
+ * named `stale-lessons` extension:
+ *
+ * - a block still carrying a lesson whose approval went stale is the
+ * `stale-lessons` finding with the refresh command;
+ * - a block behind the canonical body (a new lesson qualified, or the
+ * block holds content nothing qualifies for any more) is `drifted`;
+ * - a file whose approvals name it but which carries no block is
+ * `absent` - creation is approve's write, so the remedy names
+ * approve, never refresh;
+ * - a current block is silent.
+ *
+ * The check never mutates a byte and never throws: a damaged approvals
+ * ledger folds into one warning naming the file and the recovery, and a
+ * per-file surprise folds into that file's warning.
+ */
+
+import { afterEach, beforeEach, describe, expect, test } from "bun:test";
+import { existsSync, mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from "node:fs";
+import { dirname } from "node:path";
+import { tmpdir } from "node:os";
+import { join } from "node:path";
+
+import { computeContentHash } from "../../../../src/core/brain/content-hash.ts";
+import {
+ LESSONS_APPROVALS_FILE,
+ lessonsApprovalsPath,
+ planLessonsBlock,
+ recordLessonApproval,
+} from "../../../../src/core/brain/lessons-promotion.ts";
+import {
+ LESSONS_BLOCK_MANAGED_FILES,
+ LESSONS_BLOCK_STATE,
+ lessonsBlockCheck,
+ lessonsBlockStates,
+} from "../../../../src/core/brain/doctor/lessons-block-check.ts";
+import { AGENT_INSTRUCTION_FILES } from "../../../../src/core/brain/writeback-contract.ts";
+import type {
+ DoctorCheckContext,
+ DoctorFindings,
+} from "../../../../src/core/brain/doctor/check.ts";
+import { appendLogEvent } from "../../../../src/core/brain/log.ts";
+import { writePreference } from "../../../../src/core/brain/preference.ts";
+import { writeVaultIdentity } from "../../../../src/core/brain/vault-identity.ts";
+import { BRAIN_LOG_EVENT_KIND } from "../../../../src/core/brain/types.ts";
+import { RULES_BLOCK_ID, writeRulesBlock } from "../../../../src/core/install/rules-block.ts";
+
+const PRINCIPLE = "Always run the full test suite before merging";
+const SCOPE_ENV = "OPEN_SECOND_BRAIN_LESSONS_PROMOTION_SCOPES";
+
+let tmp: string;
+let vault: string;
+
+beforeEach(() => {
+ tmp = mkdtempSync(join(tmpdir(), "o2b-doctor-lessons-"));
+ vault = join(tmp, "vault");
+ mkdirSync(join(vault, "Brain", "log"), { recursive: true });
+ writeFileSync(join(vault, "Brain", "_brain.yaml"), "schema_version: 1\n", "utf8");
+ writeVaultIdentity(vault);
+ process.env[SCOPE_ENV] = "backend";
+});
+
+afterEach(() => {
+ if (process.env[SCOPE_ENV] === "backend") delete process.env[SCOPE_ENV];
+ rmSync(tmp, { recursive: true, force: true });
+});
+
+/** Seed one confirmed, high-confidence preference with two applied events. */
+function seedLesson(slug: string, principle: string = PRINCIPLE): string {
+ writePreference(vault, {
+ slug,
+ topic: slug,
+ principle,
+ scope: "backend",
+ created_at: "2026-05-01T00:00:00Z",
+ confirmed_at: "2026-05-02T00:00:00Z",
+ unconfirmed_until: "2026-05-08T00:00:00Z",
+ status: "confirmed",
+ evidenced_by: ["[[sig-1]]"],
+ applied_count: 2,
+ violated_count: 0,
+ last_evidence_at: "2026-05-10T00:00:00Z",
+ confidence: "high",
+ } as Parameters<typeof writePreference>[1]);
+ const artifacts = ["[[a.ts]]", "[[b.ts]]"]; // distinct outcomes: corroboration 2
+ for (const [i, stamp] of ["2026-05-09T00:00:00Z", "2026-05-10T00:00:00Z"].entries()) {
+ appendLogEvent(
+ vault,
+ {
+ timestamp: stamp,
+ eventType: BRAIN_LOG_EVENT_KIND.applyEvidence,
+ body: {
+ preference: `[[pref-${slug}]]`,
+ artifact: artifacts[i] as string,
+ agent: "t",
+ result: "applied",
+ },
+ },
+ { deviceId: "" },
+ );
+ }
+ return `pref-${slug}`;
+}
+
+function approveFor(prefId: string, file: string, principle: string = PRINCIPLE): void {
+ recordLessonApproval(vault, {
+ prefId,
+ decision: "approved",
+ decidedAt: "2026-05-15T00:00:00Z",
+ decidedBy: "yes-flag",
+ approvedContentHash: computeContentHash(principle, "backend"),
+ targets: [file],
+ blockId: RULES_BLOCK_ID.lessons,
+ lastPromotedAt: null,
+ });
+}
+
+/**
+ * Approve `prefId` for AGENTS.md and write the block a refresh would
+ * render right now - the same derivation the check grades against, so
+ * the fixture block is current by construction.
+ */
+function approveAndWrite(prefId: string, principle: string = PRINCIPLE): void {
+ writeFileSync(join(vault, "AGENTS.md"), "# house rules\n");
+ approveFor(prefId, "AGENTS.md", principle);
+ const plan = planLessonsBlock(vault, "AGENTS.md");
+ if (plan.body === null) throw new Error(`fixture: nothing qualified for ${prefId}`);
+ writeRulesBlock(join(vault, "AGENTS.md"), RULES_BLOCK_ID.lessons, plan.body, {});
+}
+
+const NOW = new Date("2026-05-20T00:00:00Z");
+
+function fixtureContext(): DoctorCheckContext {
+ return {
+ vault,
+ now: NOW,
+ config: undefined,
+ dbPath: undefined,
+ configPath: undefined,
+ knownBasenames: new Set(),
+ idIndex: new Map(),
+ preferences: [],
+ logs: [],
+ };
+}
+
+function runCheck(): DoctorFindings {
+ const out: DoctorFindings = { issues: [], uncertain: [] };
+ lessonsBlockCheck.run(fixtureContext(), out);
+ return out;
+}
+
+describe("lessons-block doctor check", () => {
+ test("a block carrying a stale lesson is the named stale-lessons finding with the refresh command", () => {
+ const prefId = seedLesson("doctor-stale");
+ approveAndWrite(prefId);
+ // The operator amends the approved text; the pinned hash goes stale.
+ const prefPath = join(vault, "Brain", "preferences", `${prefId}.md`);
+ writeFileSync(
+ prefPath,
+ readFileSync(prefPath, "utf8").replace(PRINCIPLE, `${PRINCIPLE}, amended`),
+ );
+
+ const out = runCheck();
+ expect(out.issues.length).toBe(1);
+ expect(out.issues[0]?.severity).toBe("warning");
+ expect(out.issues[0]?.code).toBe("lessons-block-stale-lessons");
+ expect(out.issues[0]?.path).toBe("AGENTS.md");
+ expect(out.issues[0]?.message).toContain("refresh-blocks");
+ expect(out.issues[0]?.message).toContain(prefId);
+ });
+
+ test("a current block is silent", () => {
+ const prefId = seedLesson("doctor-current");
+ approveAndWrite(prefId);
+ const out = runCheck();
+ expect(out.issues).toEqual([]);
+ expect(out.uncertain).toEqual([]);
+ });
+
+ test("a block behind the canonical body is drifted", () => {
+ const first = seedLesson("doctor-drift-a");
+ approveAndWrite(first);
+ // A second lesson qualifies but the block was never refreshed.
+ const second = seedLesson("doctor-drift-b", "Write the failing test first");
+ approveFor(second, "AGENTS.md", "Write the failing test first");
+
+ const out = runCheck();
+ expect(out.issues.length).toBe(1);
+ expect(out.issues[0]?.code).toBe("lessons-block-drifted");
+ expect(out.issues[0]?.path).toBe("AGENTS.md");
+ expect(out.issues[0]?.message).toContain("refresh-blocks");
+ });
+
+ test("approvals naming a file that carries no block report absent and name approve", () => {
+ const prefId = seedLesson("doctor-absent");
+ approveFor(prefId, "AGENTS.md");
+ expect(existsSync(join(vault, "AGENTS.md"))).toBe(false);
+
+ const out = runCheck();
+ expect(out.issues.length).toBe(1);
+ expect(out.issues[0]?.code).toBe("lessons-block-absent");
+ expect(out.issues[0]?.path).toBe("AGENTS.md");
+ expect(out.issues[0]?.message).toContain("approve");
+ expect(out.issues[0]?.message).not.toContain("refresh-blocks");
+ });
+
+ test("a vault with approvals but no managed files and no approvals is silent", () => {
+ seedLesson("doctor-quiet");
+ expect(runCheck().issues).toEqual([]);
+ });
+
+ test("the check never mutates a byte", () => {
+ const prefId = seedLesson("doctor-frozen");
+ approveAndWrite(prefId);
+ const prefPath = join(vault, "Brain", "preferences", `${prefId}.md`);
+ writeFileSync(prefPath, readFileSync(prefPath, "utf8").replace(PRINCIPLE, `${PRINCIPLE} v2`));
+ const rulesBefore = readFileSync(join(vault, "AGENTS.md"), "utf8");
+ const ledgerBefore = readFileSync(lessonsApprovalsPath(vault), "utf8");
+ runCheck();
+ runCheck();
+ expect(readFileSync(join(vault, "AGENTS.md"), "utf8")).toBe(rulesBefore);
+ expect(readFileSync(lessonsApprovalsPath(vault), "utf8")).toBe(ledgerBefore);
+ });
+
+ test("a damaged approvals ledger is one warning, not a throw", () => {
+ seedLesson("doctor-corrupt");
+ mkdirSync(dirname(lessonsApprovalsPath(vault)), { recursive: true });
+ writeFileSync(lessonsApprovalsPath(vault), "{ not json at all");
+ const out = runCheck();
+ expect(out.issues.length).toBe(1);
+ expect(out.issues[0]?.severity).toBe("warning");
+ expect(out.issues[0]?.message).toContain(LESSONS_APPROVALS_FILE);
+ });
+
+ test("the states grade against the config the doctor run selected", () => {
+ // The doctor carries the config the operator selected; the check
+ // graded its blocks against the DISCOVERY config's scope list instead,
+ // so a selected config with a different `lessons.promotion.scopes`
+ // reported drifted for a block the selected config renders current.
+ // The env twin is cleared for the grading itself, so the selected
+ // file is the layer under test - discovery finds no config under the
+ // throwaway HOME, which disables promotion and drifts every block.
+ const configPath = join(tmp, "selected-config.yaml");
+ writeFileSync(configPath, "lessons.promotion.scopes: backend\n", "utf8");
+ const prefId = seedLesson("doctor-config-path");
+ approveAndWrite(prefId);
+ delete process.env[SCOPE_ENV];
+ const selected = lessonsBlockStates(vault, { now: NOW, configPath });
+ const discovery = lessonsBlockStates(vault, { now: NOW });
+ expect(selected.map((row) => row.state)).toEqual([LESSONS_BLOCK_STATE.current]);
+ expect(discovery.map((row) => row.state)).toEqual([LESSONS_BLOCK_STATE.drifted]);
+
+ // The check grades through the same selected config: a block the
+ // selected config renders current stays silent.
+ const out: DoctorFindings = { issues: [], uncertain: [] };
+ lessonsBlockCheck.run({ ...fixtureContext(), configPath }, out);
+ expect(out.issues).toEqual([]);
+ });
+
+ test("the per-file states cover the closed four-state vocabulary", () => {
+ const prefId = seedLesson("doctor-states");
+ approveAndWrite(prefId);
+ approveFor("pref-states-claude", "CLAUDE.md");
+ expect(existsSync(join(vault, "CLAUDE.md"))).toBe(false);
+
+ const states = lessonsBlockStates(vault, { now: NOW });
+ const byFile = new Map(states.map((row) => [row.file, row.state]));
+ expect(byFile.get("AGENTS.md")).toBe(LESSONS_BLOCK_STATE.current);
+ // CLAUDE.md is named by an approval but carries no block.
+ expect(byFile.get("CLAUDE.md")).toBe(LESSONS_BLOCK_STATE.absent);
+
+ const prefPath = join(vault, "Brain", "preferences", `${prefId}.md`);
+ writeFileSync(prefPath, readFileSync(prefPath, "utf8").replace(PRINCIPLE, `${PRINCIPLE} v3`));
+ const stale = lessonsBlockStates(vault, { now: NOW });
+ expect(stale.find((row) => row.file === "AGENTS.md")?.state).toBe(
+ LESSONS_BLOCK_STATE.staleLessons,
+ );
+ });
+
+ test("ledger targets off the fixed instruction-file list never touch a path", () => {
+ // The ledger is machine state in the derived store; a planted or
+ // damaged row naming a traversing path must not be joined onto the
+ // vault root and lstat'ed. Off-list targets are skipped, not graded.
+ const prefId = seedLesson("doctor-offlist");
+ recordLessonApproval(vault, {
+ prefId,
+ decision: "approved",
+ decidedAt: "2026-05-15T00:00:00Z",
+ decidedBy: "yes-flag",
+ approvedContentHash: computeContentHash(PRINCIPLE, "backend"),
+ targets: ["../../escape.md"],
+ blockId: RULES_BLOCK_ID.lessons,
+ lastPromotedAt: null,
+ });
+
+ const out = runCheck();
+ expect(out.issues).toEqual([]);
+ expect(out.uncertain).toEqual([]);
+ expect(lessonsBlockStates(vault, { now: NOW })).toEqual([]);
+ // Nothing outside the vault was touched: the escape target resolves
+ // above tmp, where no AGENTS.md-like surface exists to grade.
+ expect(existsSync(join(tmp, "escape.md"))).toBe(false);
+ });
+
+ test("the block plan carries the named-drop surface the verbs report", () => {
+ const prefId = seedLesson("doctor-drops");
+ approveAndWrite(prefId);
+ const plan = planLessonsBlock(vault, "AGENTS.md");
+ expect(plan.droppedIds).toEqual([]);
+ });
+
+ test("the doctor-local instruction-file list stays pinned to the contract list", () => {
+ // The check restates the fixed list because a static import of
+ // AGENT_INSTRUCTION_FILES would close the doctor import cycle; this
+ // pin is what keeps the copy from drifting when the list grows.
+ expect([...LESSONS_BLOCK_MANAGED_FILES]).toEqual([...AGENT_INSTRUCTION_FILES]);
+ });
+});
diff --git a/tests/core/brain/gitignore-guard.test.ts b/tests/core/brain/gitignore-guard.test.ts
index 398a825e..2265eea2 100644
--- a/tests/core/brain/gitignore-guard.test.ts
+++ b/tests/core/brain/gitignore-guard.test.ts
@@ -427,6 +427,10 @@ const DECLARED_SITES: ReadonlyMap<string, string> = new Map([
"core/brain/doctor/git-tracked-state-check.ts",
"composes the ls-files pathspec and the guard ignore line from the constant",
],
+ [
+ "core/brain/doctor/lessons-block-check.ts",
+ "lessons-block readiness probe naming the store-side approval ledger (t_1e952e43)",
+ ],
["core/brain/ingest/checkpoint.ts", "ingest checkpoints under the store"],
[
"core/brain/ingest/content-manifest.ts",
@@ -436,6 +440,10 @@ const DECLARED_SITES: ReadonlyMap<string, string> = new Map([
"core/brain/inject-failopen.ts",
"inject cache under the store, spelled as the private INJECT_CACHE_DIR beside its join",
],
+ [
+ "core/brain/lessons-promotion.ts",
+ "lesson-approval ledger under the store (t_1e952e43), the decisions-in-force table",
+ ],
["core/brain/maintenance/journal.ts", "maintenance journals under the store"],
["core/brain/maintenance/lease.ts", "maintenance lease sqlite under the store"],
["core/brain/path-constants.ts", "owns the directory name itself"],
@@ -469,6 +477,10 @@ const DECLARED_SITES: ReadonlyMap<string, string> = new Map([
"core/install/adapters/aider-wrapper.ts",
"aider context artifact under the store, spelled as a join literal",
],
+ [
+ "core/install/instruction-block.ts",
+ "instruction-block ownership lockfile under the store (t_ba41a78a)",
+ ],
["core/install/manifest.ts", "install lockfile under the store, spelled as a join literal"],
["core/maintenance/self-heal-upgrade-state.ts", "self-heal upgrade state under the store"],
["core/search/paths.ts", "composes the brain.sqlite path under the store from the constants"],
diff --git a/tests/core/brain/lessons-promotion.test.ts b/tests/core/brain/lessons-promotion.test.ts
new file mode 100644
index 00000000..b746e717
--- /dev/null
+++ b/tests/core/brain/lessons-promotion.test.ts
@@ -0,0 +1,772 @@
+/**
+ * Tests for `src/core/brain/lessons-promotion.ts` (t_1e952e43).
+ *
+ * Drives the operator-approved lesson promotion kernel:
+ * - the exact qualification conjunction (preference-derived, confirmed,
+ * high confidence, preferred tier, enabled scope, fresh approval) with
+ * every non-member carrying exactly one named blocked reason;
+ * - the deterministic, timestamp-free block body render;
+ * - the approvals ledger in the derived store (round-trip, upsert,
+ * named refusals, never under `Brain/`);
+ * - the three new log event kinds appending through the shared chain;
+ * - the writer-routing assertion: the kernel writes rules files only
+ * through the shared rules-block writer, never through `node:fs`.
+ */
+
+import { afterEach, beforeEach, describe, expect, test } from "bun:test";
+import {
+ existsSync,
+ mkdirSync,
+ mkdtempSync,
+ readFileSync,
+ readdirSync,
+ rmSync,
+ writeFileSync,
+} from "node:fs";
+import { tmpdir } from "node:os";
+import { join } from "node:path";
+
+import {
+ LESSONS_APPROVALS_FILE,
+ LESSON_PROMOTION_BLOCKED,
+ LESSONS_PROMOTION_SCOPES_CONFIG_KEY,
+ LessonRenderError,
+ LessonsPromotionScopesMalformedError,
+ lessonPromotionCandidates,
+ lessonsApprovalsPath,
+ markLessonPromoted,
+ readLessonApprovals,
+ recordLessonApproval,
+ renderLessonsBlockBody,
+ renderLessonsBlockWithDrops,
+ resolvePromotionScopesStrict,
+ lessonIdsInBlockBody,
+ type LessonApprovalRow,
+ type LessonPromotionCandidate,
+} from "../../../src/core/brain/lessons-promotion.ts";
+import { LESSON_TIER, type LessonEntry } from "../../../src/core/brain/lessons.ts";
+import { computeContentHash } from "../../../src/core/brain/content-hash.ts";
+import { appendLogEvent } from "../../../src/core/brain/log.ts";
+import { listLogDates, readLogDay } from "../../../src/core/brain/log-jsonl.ts";
+import { resolveLessonsPromotionScopes } from "../../../src/core/brain/policy/blocks/lessons.ts";
+import {
+ DEFAULT_BEGIN_MARKER,
+ DEFAULT_END_MARKER,
+} from "../../../src/core/install/managed-block.ts";
+import { RULES_BLOCK_ID, RULES_BLOCK_MARKERS } from "../../../src/core/install/rules-block.ts";
+import {
+ missingWritebackGateClauses,
+ WRITEBACK_CONTRACT_REQUIREMENTS,
+} from "../../../src/core/brain/writeback-contract.ts";
+import type { BrainPreference } from "../../../src/core/brain/types.ts";
+import { BRAIN_LOG_EVENT_KIND, BRAIN_PREFERENCE_STATUS } from "../../../src/core/brain/types.ts";
+
+// ----- Fixtures -------------------------------------------------------------
+
+const NOW = new Date("2026-05-20T12:00:00Z");
+
+function buildPref(id: string, overrides: Partial<BrainPreference> = {}): BrainPreference {
+ return {
+ kind: "brain-preference",
+ id,
+ created_at: "2026-01-01T00:00:00Z",
+ confirmed_at: "2026-01-02T00:00:00Z",
+ unconfirmed_until: "2026-01-08T00:00:00Z",
+ tags: [],
+ topic: id.replace(/^pref-/, ""),
+ status: BRAIN_PREFERENCE_STATUS.confirmed,
+ principle: `principle for ${id}`,
+ scope: "backend",
+ evidenced_by: [],
+ applied_count: 3,
+ violated_count: 0,
+ last_evidence_at: "2026-05-01T00:00:00Z",
+ confidence: "high",
+ confidence_value: 0.9,
+ pinned: false,
+ ...overrides,
+ };
+}
+
+function buildLesson(id: string, overrides: Partial<LessonEntry> = {}): LessonEntry {
+ return {
+ id,
+ kind: "preference",
+ title: `principle for ${id}`,
+ scope: "backend",
+ tier: LESSON_TIER.preferred,
+ signedScore: 1.5,
+ positiveMass: 1.5,
+ negativeMass: 0,
+ corroboration: 2,
+ stance: null,
+ lastOutcomeAt: "2026-05-01T00:00:00Z",
+ ...overrides,
+ };
+}
+
+function buildRow(prefId: string, overrides: Partial<LessonApprovalRow> = {}): LessonApprovalRow {
+ return {
+ prefId,
+ decision: "approved",
+ decidedAt: "2026-05-10T00:00:00Z",
+ decidedBy: "yes-flag",
+ approvedContentHash: computeContentHash(`principle for ${prefId}`, "backend"),
+ targets: ["AGENTS.md"],
+ blockId: RULES_BLOCK_ID.lessons,
+ lastPromotedAt: null,
+ ...overrides,
+ };
+}
+
+function promoteCase(prefId: string): {
+ pref: BrainPreference;
+ lesson: LessonEntry;
+ row: LessonApprovalRow;
+} {
+ return {
+ pref: buildPref(prefId),
+ lesson: buildLesson(prefId),
+ row: buildRow(prefId),
+ };
+}
+
+// ----- Qualification --------------------------------------------------------
+
+describe("lessonPromotionCandidates", () => {
+ test("the exact conjunction promotes, with the pinned candidate shape", () => {
+ const { pref, lesson, row } = promoteCase("pref-fresh");
+ const result = lessonPromotionCandidates([pref], [lesson], [row], {
+ enabledScopes: ["backend"],
+ });
+ expect(result.promotable.length).toBe(1);
+ const candidate: LessonPromotionCandidate = result.promotable[0]!;
+ expect(candidate.prefId).toBe("pref-fresh");
+ expect(candidate.principle).toBe("principle for pref-fresh");
+ expect(candidate.scope).toBe("backend");
+ expect(candidate.tier).toBe(LESSON_TIER.preferred);
+ expect(candidate.confidence).toBe("high");
+ expect(candidate.contentHash).toBe(computeContentHash("principle for pref-fresh", "backend"));
+ expect(result.blocked).toEqual([]);
+ });
+
+ test("an unconfirmed or quarantined preference is blocked unconfirmed", () => {
+ const { pref, lesson, row } = promoteCase("pref-un");
+ for (const status of [
+ BRAIN_PREFERENCE_STATUS.unconfirmed,
+ BRAIN_PREFERENCE_STATUS.quarantine,
+ ]) {
+ const result = lessonPromotionCandidates([{ ...pref, status }], [lesson], [row], {
+ enabledScopes: ["backend"],
+ });
+ expect(result.promotable).toEqual([]);
+ expect(result.blocked).toEqual([
+ { prefId: "pref-un", reason: LESSON_PROMOTION_BLOCKED.unconfirmed },
+ ]);
+ }
+ });
+
+ test("a preference without a scope, or outside the enabled scopes, is blocked scope_not_enabled", () => {
+ const { pref, lesson, row } = promoteCase("pref-scope");
+ for (const scope of [undefined, "frontend"]) {
+ const result = lessonPromotionCandidates(
+ [scope === undefined ? { ...pref, scope: undefined } : { ...pref, scope }],
+ [scope === undefined ? { ...lesson, scope: null } : lesson],
+ [row],
+ { enabledScopes: ["backend"] },
+ );
+ expect(result.promotable).toEqual([]);
+ expect(result.blocked).toEqual([
+ { prefId: "pref-scope", reason: LESSON_PROMOTION_BLOCKED.scopeNotEnabled },
+ ]);
+ }
+ });
+
+ test("a medium- or low-confidence preference is blocked low_confidence", () => {
+ const { pref, lesson, row } = promoteCase("pref-conf");
+ for (const confidence of ["medium", "low"] as const) {
+ const result = lessonPromotionCandidates([{ ...pref, confidence }], [lesson], [row], {
+ enabledScopes: ["backend"],
+ });
+ expect(result.promotable).toEqual([]);
+ expect(result.blocked).toEqual([
+ { prefId: "pref-conf", reason: LESSON_PROMOTION_BLOCKED.lowConfidence },
+ ]);
+ }
+ });
+
+ test("a non-preferred tier, or a preference with no lesson yet, is blocked tier_not_preferred", () => {
+ const { pref, lesson, row } = promoteCase("pref-tier");
+ for (const tier of [LESSON_TIER.tentative, LESSON_TIER.contested, LESSON_TIER.avoid]) {
+ const result = lessonPromotionCandidates([pref], [{ ...lesson, tier }], [row], {
+ enabledScopes: ["backend"],
+ });
+ expect(result.promotable).toEqual([]);
+ expect(result.blocked).toEqual([
+ { prefId: "pref-tier", reason: LESSON_PROMOTION_BLOCKED.tierNotPreferred },
+ ]);
+ }
+ // No lesson entry at all: the preference has not earned the tier.
+ const noLesson = lessonPromotionCandidates([pref], [], [row], { enabledScopes: ["backend"] });
+ expect(noLesson.promotable).toEqual([]);
+ expect(noLesson.blocked).toEqual([
+ { prefId: "pref-tier", reason: LESSON_PROMOTION_BLOCKED.tierNotPreferred },
+ ]);
+ });
+
+ test("a preference with no approval row is blocked not_approved", () => {
+ const { pref, lesson } = promoteCase("pref-norow");
+ const result = lessonPromotionCandidates([pref], [lesson], [], {
+ enabledScopes: ["backend"],
+ });
+ expect(result.promotable).toEqual([]);
+ expect(result.blocked).toEqual([
+ { prefId: "pref-norow", reason: LESSON_PROMOTION_BLOCKED.notApproved },
+ ]);
+ });
+
+ test("a stale approval (content-hash mismatch) drops the lesson and reports stale_approval", () => {
+ const { pref, lesson, row } = promoteCase("pref-stale");
+ const drifted = lessonPromotionCandidates(
+ [{ ...pref, principle: "principle for pref-stale, amended" }],
+ [{ ...lesson, title: "principle for pref-stale, amended" }],
+ [row],
+ { enabledScopes: ["backend"] },
+ );
+ expect(drifted.promotable).toEqual([]);
+ expect(drifted.blocked).toEqual([
+ { prefId: "pref-stale", reason: LESSON_PROMOTION_BLOCKED.staleApproval },
+ ]);
+ });
+
+ test("a denied row blocks by name, dominates the report, and suppresses a stale approval", () => {
+ const { pref, lesson, row } = promoteCase("pref-denied");
+ const denied = lessonPromotionCandidates([pref], [lesson], [{ ...row, decision: "denied" }], {
+ enabledScopes: ["backend"],
+ });
+ expect(denied.promotable).toEqual([]);
+ expect(denied.blocked).toEqual([
+ { prefId: "pref-denied", reason: LESSON_PROMOTION_BLOCKED.denied },
+ ]);
+ // The operator's will dominates the report even beside other gates.
+ const deniedAndUnconfirmed = lessonPromotionCandidates(
+ [{ ...pref, status: BRAIN_PREFERENCE_STATUS.unconfirmed }],
+ [lesson],
+ [{ ...row, decision: "denied" }],
+ { enabledScopes: ["backend"] },
+ );
+ expect(deniedAndUnconfirmed.blocked).toEqual([
+ { prefId: "pref-denied", reason: LESSON_PROMOTION_BLOCKED.denied },
+ ]);
+ });
+
+ test("every input preference is classified exactly once, with a closed-set reason", () => {
+ const fresh = promoteCase("pref-a");
+ const staleRow = buildRow("pref-b", {
+ approvedContentHash: "stale-hash-value-that-matches-nothing",
+ });
+ const prefs = [fresh.pref, buildPref("pref-b"), buildPref("pref-c")];
+ const lessons = [
+ fresh.lesson,
+ buildLesson("pref-b", { tier: LESSON_TIER.tentative }),
+ buildLesson("pref-c"),
+ ];
+ const approvals = [fresh.row, staleRow];
+ const result = lessonPromotionCandidates(prefs, lessons, approvals, {
+ enabledScopes: ["backend"],
+ });
+ expect(result.promotable.map((c) => c.prefId)).toEqual(["pref-a"]);
+ expect(result.blocked.map((b) => b.prefId).toSorted()).toEqual(["pref-b", "pref-c"]);
+ const members = new Set(Object.values(LESSON_PROMOTION_BLOCKED));
+ for (const blocked of result.blocked) {
+ expect(members.has(blocked.reason)).toBe(true);
+ }
+ expect(result.blocked.find((b) => b.prefId === "pref-b")?.reason).toBe(
+ LESSON_PROMOTION_BLOCKED.tierNotPreferred,
+ );
+ expect(result.blocked.find((b) => b.prefId === "pref-c")?.reason).toBe(
+ LESSON_PROMOTION_BLOCKED.notApproved,
+ );
+ });
+
+ test("dead-end lessons never promote: only preference entries match", () => {
+ const deadEnd: LessonEntry = buildLesson("de-2026-05-01-fail", {
+ kind: "dead-end",
+ tier: LESSON_TIER.avoid,
+ scope: null,
+ });
+ const result = lessonPromotionCandidates([], [deadEnd], [], { enabledScopes: ["backend"] });
+ expect(result.promotable).toEqual([]);
+ expect(result.blocked).toEqual([]);
+ });
+});
+
+// ----- Render ---------------------------------------------------------------
+
+describe("renderLessonsBlockBody", () => {
+ test("identical inputs produce identical bytes", () => {
+ const a = promoteCase("pref-x");
+ const b = promoteCase("pref-y");
+ const input = [a, b].map((c) => ({
+ prefId: c.pref.id,
+ principle: c.pref.principle,
+ scope: c.pref.scope ?? "",
+ tier: c.lesson.tier,
+ confidence: c.pref.confidence,
+ contentHash: c.row.approvedContentHash,
+ }));
+ expect(renderLessonsBlockBody(input)).toBe(renderLessonsBlockBody(input));
+ });
+
+ test("orders by tier, then scope, then id, with no timestamps", () => {
+ const candidates: LessonPromotionCandidate[] = [
+ {
+ prefId: "pref-zeta",
+ principle: "zeta rule",
+ scope: "backend",
+ tier: LESSON_TIER.preferred,
+ confidence: "high",
+ contentHash: "hash-zeta-000000000000000000000000000000000000000000000000",
+ },
+ {
+ prefId: "pref-alpha",
+ principle: "alpha rule",
+ scope: "testing",
+ tier: LESSON_TIER.preferred,
+ confidence: "high",
+ contentHash: "hash-alpha-00000000000000000000000000000000000000000000000",
+ },
+ {
+ prefId: "pref-beta",
+ principle: "beta rule",
+ scope: "backend",
+ tier: LESSON_TIER.preferred,
+ confidence: "high",
+ contentHash: "hash-beta-0000000000000000000000000000000000000000000000000",
+ },
+ ];
+ const body = renderLessonsBlockBody(candidates);
+ const lines = body.split("\n").filter((line) => line.startsWith("- `pref-"));
+ expect(lines.map((line) => line.match(/`([^`]+)`/)?.[1])).toEqual([
+ "pref-beta", // scope backend before testing, id order within scope
+ "pref-zeta",
+ "pref-alpha",
+ ]);
+ // No timestamp can appear in a deterministic body.
+ expect(body).not.toMatch(/\d{4}-\d{2}-\d{2}T/);
+ });
+
+ test("the limit caps the render in order; non-positive or fractional limits refuse by name", () => {
+ const candidates: LessonPromotionCandidate[] = ["a", "b", "c"].map((suffix) => ({
+ prefId: `pref-${suffix}`,
+ principle: `rule ${suffix}`,
+ scope: "backend",
+ tier: LESSON_TIER.preferred,
+ confidence: "high",
+ contentHash: `hash-${suffix}`,
+ }));
+ const capped = renderLessonsBlockBody(candidates, { limit: 2 });
+ expect(capped.split("\n").filter((line) => line.startsWith("- `pref-")).length).toBe(2);
+ expect(capped).toContain("pref-a");
+ expect(capped).toContain("pref-b");
+ expect(capped).not.toContain("pref-c");
+ for (const limit of [0, -1, 1.5]) {
+ expect(() => renderLessonsBlockBody(candidates, { limit })).toThrow(RangeError);
+ }
+ });
+
+ test("the drops render names the lessons the limit cut, in render order", () => {
+ const candidates: LessonPromotionCandidate[] = ["a", "b", "c"].map((suffix) => ({
+ prefId: `pref-${suffix}`,
+ principle: `rule ${suffix}`,
+ scope: "backend",
+ tier: LESSON_TIER.preferred,
+ confidence: "high",
+ contentHash: `hash-${suffix}`,
+ }));
+ const rendered = renderLessonsBlockWithDrops(candidates, { limit: 2 });
+ // The body is exactly what the plain render produces.
+ expect(rendered.body).toBe(renderLessonsBlockBody(candidates, { limit: 2 }));
+ // The cut is named, not silent: the lesson past the cap is reported.
+ expect(rendered.droppedIds).toEqual(["pref-c"]);
+ // Under the cap everything renders and nothing is dropped.
+ expect(renderLessonsBlockWithDrops(candidates).droppedIds).toEqual([]);
+ expect(renderLessonsBlockWithDrops(candidates, { limit: 3 }).droppedIds).toEqual([]);
+ });
+
+ test("an empty promotable set is a named refusal: removal is the writer's job", () => {
+ expect(() => renderLessonsBlockBody([])).toThrow(/remove/i);
+ });
+
+ test("multi-line principles collapse to one line", () => {
+ const body = renderLessonsBlockBody([
+ {
+ prefId: "pref-multi",
+ principle: "first line\nsecond line",
+ scope: "backend",
+ tier: LESSON_TIER.preferred,
+ confidence: "high",
+ contentHash: "hash-multi",
+ },
+ ]);
+ expect(body.split("\n").filter((line) => line.startsWith("- `pref-")).length).toBe(1);
+ expect(body).toContain("first line second line");
+ });
+
+ test("the lessons body satisfies no usage-block clause and carries no usage marker", () => {
+ const body = renderLessonsBlockBody([
+ {
+ prefId: "pref-ind",
+ principle: "an approved rule",
+ scope: "backend",
+ tier: LESSON_TIER.preferred,
+ confidence: "high",
+ contentHash: "hash-ind",
+ },
+ ]);
+ // The blocks are independent: the lessons body satisfies none of the
+ // usage block's gate clauses, and carries none of its marker spellings.
+ expect(missingWritebackGateClauses(body).length).toBe(WRITEBACK_CONTRACT_REQUIREMENTS.length);
+ expect(body).not.toContain(DEFAULT_BEGIN_MARKER);
+ expect(body).not.toContain(DEFAULT_END_MARKER);
+ expect(RULES_BLOCK_MARKERS.lessons.begin).not.toBe(RULES_BLOCK_MARKERS.usage.begin);
+ });
+
+ test("a scope carrying a line break refuses the render by name (marker forgery attempt)", () => {
+ // A multi-line scope (a YAML block scalar in agent-authored
+ // frontmatter) could carry a whole-line lessons end marker and brick
+ // every later lessons-block operation. The render refuses the lesson
+ // instead of emitting it.
+ const forged: LessonPromotionCandidate = {
+ prefId: "pref-forge",
+ principle: "an approved rule",
+ scope: `backend\n${RULES_BLOCK_MARKERS.lessons.end}`,
+ tier: LESSON_TIER.preferred,
+ confidence: "high",
+ contentHash: "hash-forge",
+ };
+ let thrown: unknown = null;
+ try {
+ renderLessonsBlockBody([forged]);
+ } catch (err) {
+ thrown = err;
+ }
+ expect(thrown).toBeInstanceOf(LessonRenderError);
+ const err = thrown as InstanceType<typeof LessonRenderError>;
+ expect(err.prefId).toBe("pref-forge");
+ expect(err.field).toBe("scope");
+ expect(err.message).toContain("pref-forge");
+ expect(err.message).not.toMatch(/\n/);
+ });
+
+ test("a scope carrying a marker string on one line refuses the render too", () => {
+ const shaped: LessonPromotionCandidate = {
+ prefId: "pref-shape",
+ principle: "an approved rule",
+ scope: RULES_BLOCK_MARKERS.lessons.end,
+ tier: LESSON_TIER.preferred,
+ confidence: "high",
+ contentHash: "hash-shape",
+ };
+ expect(() => renderLessonsBlockBody([shaped])).toThrow(LessonRenderError);
+ // Every spelling is checked, not just the lessons pair.
+ const usageShaped: LessonPromotionCandidate = {
+ ...shaped,
+ prefId: "pref-usage-shape",
+ scope: DEFAULT_BEGIN_MARKER,
+ };
+ expect(() => renderLessonsBlockBody([usageShaped])).toThrow(LessonRenderError);
+ });
+
+ test("a pref id carrying whitespace or a backtick refuses the render by name", () => {
+ const base: LessonPromotionCandidate = {
+ prefId: "pref-ok",
+ principle: "an approved rule",
+ scope: "backend",
+ tier: LESSON_TIER.preferred,
+ confidence: "high",
+ contentHash: "hash-ok",
+ };
+ for (const prefId of ["pref-two words", "pref-new\nline", "pref-`backtick`"]) {
+ let thrown: unknown = null;
+ try {
+ renderLessonsBlockBody([{ ...base, prefId }]);
+ } catch (err) {
+ thrown = err;
+ }
+ expect(thrown).toBeInstanceOf(LessonRenderError);
+ const err = thrown as InstanceType<typeof LessonRenderError>;
+ expect(err.field).toBe("prefId");
+ }
+ });
+
+ test("a single-line scope with inner spaces still renders", () => {
+ const body = renderLessonsBlockBody([
+ {
+ prefId: "pref-space",
+ principle: "an approved rule",
+ scope: "code review",
+ tier: LESSON_TIER.preferred,
+ confidence: "high",
+ contentHash: "hash-space",
+ },
+ ]);
+ expect(body).toContain("(scope: code review)");
+ });
+});
+
+// ----- Approvals ledger -----------------------------------------------------
+
+let tmp: string;
+let vault: string;
+
+beforeEach(() => {
+ tmp = mkdtempSync(join(tmpdir(), "o2b-lessons-promotion-"));
+ vault = join(tmp, "vault");
+ mkdirSync(vault, { recursive: true });
+});
+
+afterEach(() => {
+ rmSync(tmp, { recursive: true, force: true });
+});
+
+describe("lesson approvals ledger", () => {
+ test("the ledger lives in the derived store, never under Brain/", () => {
+ const path = lessonsApprovalsPath(vault);
+ expect(path).toContain(join(".open-second-brain", LESSONS_APPROVALS_FILE));
+ expect(path).not.toContain("Brain");
+ expect(LESSONS_APPROVALS_FILE).toBe("lessons-approvals.json");
+ });
+
+ test("record then read round-trips the row atomically", () => {
+ const { row } = promoteCase("pref-ledger");
+ recordLessonApproval(vault, row);
+ expect(readLessonApprovals(vault)).toEqual([row]);
+ const dir = join(vault, ".open-second-brain");
+ expect(existsSync(join(dir, LESSONS_APPROVALS_FILE))).toBe(true);
+ // Atomic write discipline: no temp leftovers beside the ledger.
+ const leftovers = readdirSync(dir).filter((name) => name.startsWith(LESSONS_APPROVALS_FILE));
+ expect(leftovers).toEqual([LESSONS_APPROVALS_FILE]);
+ });
+
+ test("a second decision for the same id replaces the row (state table, not history)", () => {
+ const { row } = promoteCase("pref-twice");
+ recordLessonApproval(vault, row);
+ recordLessonApproval(vault, buildRow("pref-other"));
+ recordLessonApproval(vault, { ...row, decision: "denied", decidedBy: "interactive-yes" });
+ const rows = readLessonApprovals(vault);
+ expect(rows.length).toBe(2);
+ const twice = rows.find((r) => r.prefId === "pref-twice");
+ expect(twice?.decision).toBe("denied");
+ expect(twice?.decidedBy).toBe("interactive-yes");
+ });
+
+ test("reads are sorted by pref id, so identical states are byte-identical files", () => {
+ recordLessonApproval(vault, buildRow("pref-z"));
+ recordLessonApproval(vault, buildRow("pref-a"));
+ const rows = readLessonApprovals(vault);
+ expect(rows.map((r) => r.prefId)).toEqual(["pref-a", "pref-z"]);
+ const bytes = readFileSync(lessonsApprovalsPath(vault), "utf8");
+ expect(bytes.indexOf("pref-a")).toBeGreaterThan(-1);
+ expect(bytes.indexOf("pref-a")).toBeLessThan(bytes.indexOf("pref-z"));
+ });
+
+ test("a missing ledger reads as empty", () => {
+ expect(readLessonApprovals(vault)).toEqual([]);
+ });
+
+ test("corrupt JSON, an unknown schema version and a damaged row refuse by name", () => {
+ const { row } = promoteCase("pref-corrupt");
+ recordLessonApproval(vault, row);
+ const path = lessonsApprovalsPath(vault);
+ const original = readFileSync(path, "utf8");
+ const patterns: ReadonlyArray<RegExp> = [/corrupted/, /schema_version/, /decision/];
+ const mutations: ReadonlyArray<string> = [
+ original.replaceAll("{", "{broken"),
+ original.replace('"schema_version": 1', '"schema_version": 99'),
+ original.replace('"decision": "approved"', '"decision": "maybe"'),
+ ];
+ for (let i = 0; i < mutations.length; i++) {
+ writeFileSync(path, mutations[i]!);
+ let message = "";
+ try {
+ readLessonApprovals(vault);
+ } catch (err) {
+ message = (err as Error).message;
+ }
+ expect(`${i}: matched: ${patterns[i]!.test(message)}`).toBe(`${i}: matched: true`);
+ expect(message).toContain(path);
+ }
+ // The ledger survives untouched for the operator to repair by hand.
+ writeFileSync(path, original);
+ expect(readLessonApprovals(vault).length).toBe(1);
+ });
+
+ test("markLessonPromoted stamps the row, and a missing row refuses by name", () => {
+ const { row } = promoteCase("pref-promoted");
+ recordLessonApproval(vault, row);
+ markLessonPromoted(vault, "pref-promoted", NOW);
+ const rows = readLessonApprovals(vault);
+ expect(rows[0]?.lastPromotedAt).toBe("2026-05-20T12:00:00Z");
+ expect(() => markLessonPromoted(vault, "pref-absent", NOW)).toThrow(/pref-absent/);
+ });
+});
+
+// ----- Config resolution ----------------------------------------------------
+
+describe("resolveLessonsPromotionScopes", () => {
+ const ENV_KEY = "OPEN_SECOND_BRAIN_LESSONS_PROMOTION_SCOPES";
+ let savedEnv: string | undefined;
+
+ beforeEach(() => {
+ savedEnv = process.env[ENV_KEY];
+ delete process.env[ENV_KEY];
+ });
+
+ afterEach(() => {
+ if (savedEnv === undefined) delete process.env[ENV_KEY];
+ else process.env[ENV_KEY] = savedEnv;
+ });
+
+ test("the pinned config key is exported from the kernel", () => {
+ expect(LESSONS_PROMOTION_SCOPES_CONFIG_KEY).toBe("lessons.promotion.scopes");
+ });
+
+ test("absent-or-empty resolves to a named count of zero (promotion disabled)", () => {
+ const resolution = resolveLessonsPromotionScopes();
+ expect(resolution.scopes).toEqual([]);
+ expect(resolution.count).toBe(0);
+ expect(resolution.origin).toBe("absent");
+ });
+
+ test("the env twin wins and parses a comma-separated list", () => {
+ process.env[ENV_KEY] = "backend, testing ,, frontend";
+ const resolution = resolveLessonsPromotionScopes();
+ expect(resolution.scopes).toEqual(["backend", "testing", "frontend"]);
+ expect(resolution.count).toBe(3);
+ expect(resolution.origin).toBe("env");
+ });
+
+ test("a bracket-shaped value is malformed and resolves disabled", () => {
+ process.env[ENV_KEY] = "[backend, testing]";
+ const resolution = resolveLessonsPromotionScopes();
+ expect(resolution.count).toBe(0);
+ expect(resolution.origin).toBe("absent");
+ });
+
+ test("a present-but-malformed scopes value is a named refusal at the kernel boundary", () => {
+ // The policy block's resolver keeps its documented fallback; the
+ // kernel wrapper - which every promotion caller reads - refuses a
+ // value that is PRESENT but malformed, so an operator can tell
+ // "configured wrong" from "never configured".
+ process.env[ENV_KEY] = "[backend, testing]";
+ let thrown: unknown = null;
+ try {
+ resolvePromotionScopesStrict();
+ } catch (err) {
+ thrown = err;
+ }
+ expect(thrown).toBeInstanceOf(LessonsPromotionScopesMalformedError);
+ const err = thrown as InstanceType<typeof LessonsPromotionScopesMalformedError>;
+ expect(err.source).toBe("env");
+ expect(err.message).toContain(ENV_KEY);
+ expect(err.message).toContain("malformed");
+ expect(err.message).toContain("promotion stays disabled");
+ expect(err.message).not.toMatch(/\n/);
+ // The config layer refuses by name the same way.
+ delete process.env[ENV_KEY];
+ let configThrown: unknown = null;
+ try {
+ resolvePromotionScopesStrict(join(tmp, "missing-config.yaml"));
+ } catch (configError) {
+ configThrown = configError;
+ }
+ // No config file exists here, so the config arm stays silent and the
+ // resolution is the plain disabled one - the refusal above is the
+ // malformed case, not a missing-file case.
+ expect(configThrown).toBeNull();
+ });
+});
+
+// ----- Log event kinds ------------------------------------------------------
+
+describe("lessons log event kinds", () => {
+ test("the three kinds append through the shared chain and read back", () => {
+ const kinds = [
+ BRAIN_LOG_EVENT_KIND.lessonsApproved,
+ BRAIN_LOG_EVENT_KIND.lessonsDenied,
+ BRAIN_LOG_EVENT_KIND.lessonsPromoted,
+ ];
+ for (const kind of kinds) {
+ appendLogEvent(
+ vault,
+ {
+ eventType: kind,
+ timestamp: "2026-05-20T12:00:00Z",
+ agent: "test-agent",
+ body: { pref: "[[pref-x]]" },
+ },
+ { deviceId: "" },
+ );
+ }
+ const dates = listLogDates(vault);
+ expect(dates.length).toBe(1);
+ const day = readLogDay(vault, dates[0]!);
+ expect(day.entries.map((e) => e.eventType)).toEqual(kinds);
+ });
+
+ test("the kind spellings are pinned", () => {
+ expect(BRAIN_LOG_EVENT_KIND.lessonsApproved).toBe("lessons-approved");
+ expect(BRAIN_LOG_EVENT_KIND.lessonsDenied).toBe("lessons-denied");
+ expect(BRAIN_LOG_EVENT_KIND.lessonsPromoted).toBe("lessons-promoted");
+ });
+});
+
+// ----- Writer routing -------------------------------------------------------
+
+describe("writer routing", () => {
+ test("the kernel never imports node:fs write functions; rules writes ride the K1 writer", () => {
+ const source = readFileSync(
+ join(import.meta.dir, "..", "..", "..", "src", "core", "brain", "lessons-promotion.ts"),
+ "utf8",
+ );
+ expect(source).toMatch(/from "node:fs"/);
+ // Read-only fs names only; every write-shaped name is absent.
+ for (const banned of [
+ "writeFileSync",
+ "appendFileSync",
+ "writeSync",
+ "openSync",
+ "renameSync",
+ "unlinkSync",
+ "rmSync",
+ "insertManagedBlock",
+ ]) {
+ expect(`${banned}: ${new RegExp(`\\b${banned}\\b`).test(source)}`).toBe(`${banned}: false`);
+ }
+ expect(source).toContain("atomicWriteFileSync");
+ });
+});
+
+// ----- Block body ids (t_1e952e43 C3: the doctor and the verb read back
+// which lessons a managed block carries; the parser lives beside the
+// render so the format coupling stays in one module) ------------------------
+
+describe("lessonIdsInBlockBody", () => {
+ test("extracts the pref ids a rendered body carries, in render order", () => {
+ const prefs = [buildPref("pref-b"), buildPref("pref-a")];
+ const lessons = [buildLesson("pref-b"), buildLesson("pref-a")];
+ const rows = [buildRow("pref-b"), buildRow("pref-a")];
+ const { promotable } = lessonPromotionCandidates(prefs, lessons, rows, {
+ enabledScopes: ["backend"],
+ });
+ const body = renderLessonsBlockBody(promotable, { limit: 20 });
+ // Same scope and tier, so the render order is the id order.
+ expect(lessonIdsInBlockBody(body)).toEqual(["pref-a", "pref-b"]);
+ });
+
+ test("a body with no lesson lines yields no ids", () => {
+ expect(lessonIdsInBlockBody("# house rules\n")).toEqual([]);
+ expect(lessonIdsInBlockBody("- not a lesson line\n- `unterminated\n")).toEqual([]);
+ });
+});
diff --git a/tests/core/brain/owner-stamp.test.ts b/tests/core/brain/owner-stamp.test.ts
index 865c980a..9d2da8fc 100644
--- a/tests/core/brain/owner-stamp.test.ts
+++ b/tests/core/brain/owner-stamp.test.ts
@@ -625,6 +625,10 @@ const NO_PREFERENCE_BYTES: Readonly<Record<string, string>> = Object.freeze({
"builds preference paths only to detect install conflicts; its preferences land through " +
"`restorePreferences`, and its one direct write adds the install fingerprint to a page it " +
"just staged under `OKF Review/`, never to a preference.",
+ "src/core/brain/lessons-promotion.ts":
+ "builds a preference path only to READ the lesson's source preference; its two atomic " +
+ "writes land the lessons-approvals ledger in the derived store, outside Brain/ and outside " +
+ "any note surface, so there are no preference bytes to own (t_1e952e43).",
});
test("every module that writes preference bytes reaches the ownership resolver", async () => {
diff --git a/tests/core/brain/session-identity-check.test.ts b/tests/core/brain/session-identity-check.test.ts
index 89826d9f..5b13f60d 100644
--- a/tests/core/brain/session-identity-check.test.ts
+++ b/tests/core/brain/session-identity-check.test.ts
@@ -376,6 +376,15 @@ const KIND_WRITERS: ReadonlyArray<{
sessionScoped: false,
writers: ["core/decision-model/record.ts"],
},
+ {
+ // Agent-presence (t_635e3e72): one record per COMPLETED benchmark-gated
+ // rewrite gate run. Machine-side evidence keyed by skill, spec hash and
+ // round ids - a scoring pass no host session took part in, so
+ // sessionless exactly like the decision-model eval grade beside it.
+ kind: "skill_rewrite_eval_grade",
+ sessionScoped: false,
+ writers: ["core/brain/skill-proposals.ts"],
+ },
{
kind: "decision_model_extract_commit",
sessionScoped: true,
diff --git a/tests/core/brain/skill-accept-dead-ends.test.ts b/tests/core/brain/skill-accept-dead-ends.test.ts
index 4ceca7c6..47439112 100644
--- a/tests/core/brain/skill-accept-dead-ends.test.ts
+++ b/tests/core/brain/skill-accept-dead-ends.test.ts
@@ -18,7 +18,7 @@
*/
import { afterEach, beforeEach, describe, expect, test } from "bun:test";
-import { existsSync, mkdirSync, mkdtempSync, rmSync, writeFileSync } from "node:fs";
+import { existsSync, mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from "node:fs";
import { tmpdir } from "node:os";
import { dirname, join } from "node:path";
@@ -82,6 +82,42 @@ function corruptJournal(slug: string): string {
return path;
}
+/**
+ * Write a well-formed marker the way a hand edit (or a sync merge) would:
+ * raw JSON on disk, not the module's own writer, naming a
+ * `materialized_path` the accept sequence never produced. `extra` carries
+ * additional raw payload keys a hand edit can plant, such as a recorded
+ * `skills_root`.
+ */
+function handEditedJournal(
+ slug: string,
+ materializedPath: string,
+ extra: Record<string, unknown> = {},
+): string {
+ const path = skillAcceptJournalPath(vault, slug);
+ mkdirSync(dirname(path), { recursive: true });
+ writeFileSync(
+ path,
+ `${JSON.stringify(
+ {
+ schema_version: 1,
+ slug,
+ id: `prop-${slug}`,
+ phase: "materialize",
+ started_at: ACCEPTED_AT.toISOString(),
+ accepted_existed: false,
+ procedure_existed: false,
+ materialized_path: materializedPath,
+ ...extra,
+ },
+ null,
+ 2,
+ )}\n`,
+ "utf8",
+ );
+ return path;
+}
+
/** Leave a lock on disk the way a hard crash does. */
function stampAcceptLock(): string {
const path = skillAcceptLockPath(vault);
@@ -154,6 +190,142 @@ describe("an unreadable accept journal names the command that clears it", () =>
});
});
+describe("a hand-edited materialized path is refused at the journal boundary", () => {
+ test("a materialized path outside the vault and the skills root refuses recovery by name and is never deleted", () => {
+ // The file a planted journal would make the rollback's rmSync remove.
+ const outside = join(dirname(vault), "planted-escape.md");
+ writeFileSync(outside, "operator file\n", "utf8");
+ const journal = handEditedJournal("ghost", outside);
+ try {
+ // The partitioned read reports the marker as unreadable, naming the
+ // field that refused it.
+ const state = readSkillAcceptJournals(vault);
+ expect(state.entries).toEqual([]);
+ expect(state.unreadable.map((u) => u.path)).toEqual([journal]);
+ expect(state.unreadable[0]!.detail).toContain("materialized_path");
+
+ // The transaction path refuses through the same named error, and a
+ // hand-edited journal is not a recovery input: retained, and the path
+ // it named is untouched.
+ expect(() => recoverSkillProposalAccepts(vault)).toThrow(SkillAcceptJournalUnreadableError);
+ expect(existsSync(journal)).toBe(true);
+ expect(existsSync(outside)).toBe(true);
+ } finally {
+ rmSync(outside, { force: true });
+ }
+ });
+
+ test("a relative materialized path is refused even when it names a SKILL.md", () => {
+ const journal = handEditedJournal("ghost", join("..", "elsewhere", "SKILL.md"));
+ const state = readSkillAcceptJournals(vault);
+ expect(state.entries).toEqual([]);
+ expect(state.unreadable.map((u) => u.path)).toEqual([journal]);
+ });
+
+ test("a marker whose target existed still parses - the restore branch owns that refusal at use", () => {
+ // On this shape the journal-supplied path reaches only the restore
+ // branch, which validates its target itself and refuses by name; the
+ // parser stays permissive so the diagnosis surface can still read the
+ // marker's other fields.
+ const outside = join(dirname(vault), "victim.md");
+ const journal = handEditedJournal("ghost", outside);
+ // handEditedJournal writes procedure_existed: false, so flip the marker
+ // to the restore shape by rewriting it.
+ const marker = JSON.parse(readFileSync(journal, "utf8")) as Record<string, unknown>;
+ marker["procedure_existed"] = true;
+ marker["prior_content_path"] = join(vault, "Brain", "ghost.prior.md");
+ writeFileSync(journal, `${JSON.stringify(marker, null, 2)}\n`, "utf8");
+
+ const state = readSkillAcceptJournals(vault);
+ expect(state.unreadable).toEqual([]);
+ expect(state.entries.map((entry) => entry.slug)).toEqual(["ghost"]);
+ expect(state.entries[0]?.materializedPath).toBe(outside);
+ });
+
+ test("the designed mature_page rollback under an override skills root still rolls back", () => {
+ // A real accept CAN stamp a materialized path outside both the vault and
+ // the configured skills root: the caller's override root, which recovery
+ // cannot re-derive - the whole reason the field exists. The parse guard
+ // admits the module's own materialization shape (an absolute path ending
+ // in the skill page file) so this rollback keeps working.
+ const externalRoot = mkdtempSync(join(tmpdir(), "o2b-journal-skills-"));
+ try {
+ const skillDir = join(externalRoot, "some-skill");
+ const skillFile = join(skillDir, "SKILL.md");
+ mkdirSync(skillDir, { recursive: true });
+ writeFileSync(skillFile, "half-written\n", "utf8");
+ writeSkillAcceptJournal(vault, {
+ slug: "ghost",
+ id: "prop-ghost",
+ phase: "materialize",
+ startedAt: ACCEPTED_AT.toISOString(),
+ acceptedExisted: false,
+ materializedExisted: false,
+ materializedPath: skillFile,
+ });
+
+ const recovered = recoverSkillProposalAccepts(vault);
+ expect(recovered.map((entry) => entry.action)).toEqual(["rolled_back"]);
+ expect(existsSync(skillFile)).toBe(false);
+ } finally {
+ rmSync(externalRoot, { recursive: true, force: true });
+ }
+ });
+
+ test("a recorded skills root admits its own subtree the same way the default one does", () => {
+ // A marker that RECORDS the root its accept resolved no longer needs
+ // the path-shape escape: the recorded root itself bounds the subtree,
+ // and the parse guard admits a materialized path inside it exactly as
+ // it admits a vault-side one. The half-written first accept under an
+ // override root rolls back like any other.
+ const externalRoot = mkdtempSync(join(tmpdir(), "o2b-journal-recorded-"));
+ try {
+ const skillDir = join(externalRoot, "some-skill");
+ const skillFile = join(skillDir, "SKILL.md");
+ mkdirSync(skillDir, { recursive: true });
+ writeFileSync(skillFile, "half-written\n", "utf8");
+ writeSkillAcceptJournal(vault, {
+ slug: "ghost",
+ id: "prop-ghost",
+ phase: "materialize",
+ startedAt: ACCEPTED_AT.toISOString(),
+ acceptedExisted: false,
+ materializedExisted: false,
+ materializedPath: skillFile,
+ skillsRoot: externalRoot,
+ });
+
+ const state = readSkillAcceptJournals(vault);
+ expect(state.unreadable).toEqual([]);
+ const recovered = recoverSkillProposalAccepts(vault);
+ expect(recovered.map((entry) => entry.action)).toEqual(["rolled_back"]);
+ expect(existsSync(skillFile)).toBe(false);
+ } finally {
+ rmSync(externalRoot, { recursive: true, force: true });
+ }
+ });
+
+ test("a recorded skills root bounds the boundary: outside both vault and that root still refuses", () => {
+ // Naming a root in the marker must not unlock arbitrary paths: the
+ // recorded root bounds the materialize tree exactly as the default one
+ // does, so a path outside the vault AND outside the recorded root stays
+ // a hand edit and is refused at parse, skill-page name or not.
+ const externalRoot = mkdtempSync(join(tmpdir(), "o2b-journal-recorded-"));
+ const victimDir = mkdtempSync(join(tmpdir(), "o2b-journal-victim-"));
+ try {
+ const planted = join(victimDir, "planted-skill", "SKILL.md");
+ const journal = handEditedJournal("ghost", planted, { skills_root: externalRoot });
+ const state = readSkillAcceptJournals(vault);
+ expect(state.entries).toEqual([]);
+ expect(state.unreadable.map((u) => u.path)).toEqual([journal]);
+ expect(state.unreadable[0]!.detail).toContain("materialized_path");
+ } finally {
+ rmSync(externalRoot, { recursive: true, force: true });
+ rmSync(victimDir, { recursive: true, force: true });
+ }
+ });
+});
+
describe("a lock left by a crash refuses by name and is never broken", () => {
test("the accept path names the lock file and the command that inspects it", () => {
const slug = seedAndLearn("rotate_keys");
diff --git a/tests/core/brain/skill-proposals-rewrite.test.ts b/tests/core/brain/skill-proposals-rewrite.test.ts
new file mode 100644
index 00000000..4b567fd9
--- /dev/null
+++ b/tests/core/brain/skill-proposals-rewrite.test.ts
@@ -0,0 +1,862 @@
+/**
+ * The scored-rewrite apply path (agent-presence, Lane A, A4).
+ *
+ * A promoted candidate goes through the SAME pipeline every skill write
+ * goes through: a pending proposal under `Brain/skill-proposals/`, a
+ * human accept, a write-ahead journal, a compensating transaction. The
+ * one growth the rewrite needs is content, not just existence: a rewrite
+ * OVERWRITES an incumbent SKILL.md, so the journal captures the prior
+ * bytes before the overwrite and a crash mid-accept rolls back to the
+ * incumbent body. Gate failures stage nothing - a hold round writes only
+ * the grade record.
+ */
+
+import { afterEach, beforeEach, describe, expect, test } from "bun:test";
+import { existsSync, mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from "node:fs";
+import { tmpdir } from "node:os";
+import { dirname, join } from "node:path";
+
+import {
+ CONTINUITY_RECORD_KINDS,
+ isContinuityRecordKind,
+} from "../../../src/core/brain/continuity/types.ts";
+import { listContinuityRecords } from "../../../src/core/brain/continuity/store.ts";
+import {
+ parseSkillBenchmarkTasks,
+ skillBenchmarkRelPath,
+ SKILL_BENCHMARK_SPEC_FILE,
+} from "../../../src/core/brain/skill-rewrite-tasks.ts";
+import {
+ skillAcceptJournalPath,
+ skillAcceptPriorContentPath,
+ skillBenchmarkRoundsDir,
+ skillBenchmarkSpecPath,
+ skillBenchmarkTasksPath,
+} from "../../../src/core/brain/paths.ts";
+import {
+ buildSkillRewriteSpec,
+ skillRewriteSpecHash,
+ SKILL_REWRITE_SPEC_SCHEMA,
+ SKILL_REWRITE_SPLIT_RULE,
+ SKILL_REWRITE_VERDICT,
+} from "../../../src/core/brain/skill-rewrite-spec.ts";
+import {
+ listPendingSkillProposals,
+ readRewriteIncumbent,
+ recoverSkillProposalAccepts,
+ SCORED_REWRITE_PATTERN_KIND,
+ stageScoredRewriteProposal,
+ recordSkillRewriteGrade,
+ acceptSkillProposal,
+ rejectSkillProposal,
+} from "../../../src/core/brain/skill-proposals.ts";
+import {
+ readSkillAcceptJournals,
+ writeSkillAcceptJournal,
+} from "../../../src/core/brain/skill-accept-journal.ts";
+import {
+ resolveSkillRewriteJudgeCmd,
+ SKILL_REWRITE_JUDGE_CMD_CONFIG_KEY,
+ SKILL_REWRITE_JUDGE_CMD_ENV_KEY,
+ SKILL_REWRITE_MODE_CONFIG_KEY,
+ SKILL_REWRITE_MODE_ENV_KEY,
+ resolveSkillRewriteModeConfig,
+} from "../../../src/core/config.ts";
+import { parseFrontmatter } from "../../../src/core/vault.ts";
+import { sha256Hex } from "../../../src/core/integrity/digest.ts";
+import { _resetHeldLocksForTests } from "../../../src/core/brain/sync-lockfile.ts";
+
+let vault: string;
+let skillsRoot: string;
+
+beforeEach(() => {
+ vault = mkdtempSync(join(tmpdir(), "o2b-rewrite-apply-"));
+ skillsRoot = mkdtempSync(join(tmpdir(), "o2b-rewrite-skills-"));
+ mkdirSync(join(vault, "Brain"), { recursive: true });
+});
+
+afterEach(() => {
+ _resetHeldLocksForTests();
+ rmSync(vault, { recursive: true, force: true });
+ rmSync(skillsRoot, { recursive: true, force: true });
+ delete process.env[SKILL_REWRITE_MODE_ENV_KEY];
+ delete process.env[SKILL_REWRITE_JUDGE_CMD_ENV_KEY];
+});
+
+const FIXTURE_DIR = join(import.meta.dir, "..", "..", "fixtures", "skill-bench", "example-skill");
+const TASKS_DOCUMENT = readFileSync(join(FIXTURE_DIR, "tasks.json"), "utf8");
+const SPEC_DOCUMENT = readFileSync(join(FIXTURE_DIR, "spec.json"), "utf8");
+const TASKS = parseSkillBenchmarkTasks(JSON.parse(TASKS_DOCUMENT), "tasks.json");
+const SPEC = buildSkillRewriteSpec(TASKS.skillName, TASKS);
+
+const INCUMBENT_BODY = [
+ "---",
+ "name: example-skill",
+ "description: The incumbent instructions.",
+ "triggers:",
+ " - thing",
+ "version: 3",
+ "---",
+ "# example-skill",
+ "",
+ "Incumbent body: search, then write, then verify.",
+ "",
+].join("\n");
+
+const CANDIDATE_BODY = [
+ "# example-skill",
+ "",
+ "Candidate body: plan first, search twice, write once, and report the artifact path.",
+].join("\n");
+
+function writeIncumbent(): string {
+ const skillDir = join(skillsRoot, "example-skill");
+ mkdirSync(skillDir, { recursive: true });
+ const path = join(skillDir, "SKILL.md");
+ writeFileSync(path, INCUMBENT_BODY, "utf8");
+ return path;
+}
+
+/**
+ * The incumbent at the vault's own default skills root. The rollback
+ * validation (review security M4) confines a restore target to the vault
+ * and the resolved skills root, so the crash-recovery fixtures stage their
+ * incumbents here - a path both arms of that confinement admit.
+ */
+function writeIncumbentUnderVaultSkills(): string {
+ const skillPath = join(vault, "Brain", "skills", "example-skill", "SKILL.md");
+ mkdirSync(dirname(skillPath), { recursive: true });
+ writeFileSync(skillPath, INCUMBENT_BODY, "utf8");
+ return skillPath;
+}
+
+/** The benchmark receipt files on disk, as a completed gate round leaves them. */
+function seedBenchmark(
+ mutateTasks?: (raw: { tasks: Array<Record<string, unknown>> }) => void,
+): void {
+ const raw = JSON.parse(TASKS_DOCUMENT) as { tasks: Array<Record<string, unknown>> };
+ if (mutateTasks) mutateTasks(raw);
+ const tasksPath = skillBenchmarkTasksPath(vault, TASKS.skillName);
+ mkdirSync(dirname(tasksPath), { recursive: true });
+ writeFileSync(tasksPath, `${JSON.stringify(raw, null, 2)}\n`, "utf8");
+ writeFileSync(skillBenchmarkSpecPath(vault, TASKS.skillName), SPEC_DOCUMENT, "utf8");
+}
+
+/**
+ * The gate's final promote, as rewrite-score appends it after staging.
+ * The record's candidate binding defaults to the sha-256 of the staged
+ * proposal's own document bytes - the same derivation the verb performs
+ * on the value staging returns - so a helper-built round passes the
+ * accept-time candidate match by construction.
+ */
+function recordPromoteGrade(
+ slug: string,
+ opts: { readonly candidateRate?: number; readonly candidateSha256?: string } = {},
+): string {
+ const [fm, documentBody] = parseFrontmatter(pendingPathFor(slug));
+ const explicitSha = opts.candidateSha256;
+ const candidateSha256 = explicitSha ?? sha256Hex(documentBody);
+ if (explicitSha === undefined) {
+ // The default derivation must equal what staging stamped: a drift
+ // here would make the happy-path accept pin vacuous. An explicit
+ // override (the replay fixtures) deliberately differs.
+ expect(fm["candidate_sha256"]).toBe(candidateSha256);
+ }
+ return recordSkillRewriteGrade(vault, {
+ payload: {
+ skill: TASKS.skillName,
+ spec_hash: skillRewriteSpecHash(SPEC),
+ tasks_hash: SPEC.tasksHash,
+ metric: "tasks_passed_rate",
+ seed: SPEC.seed,
+ split_rule: SPEC.splitRule,
+ verdict: SKILL_REWRITE_VERDICT.promote,
+ baseline_rate: 0.4,
+ candidate_rate: opts.candidateRate ?? 0.7,
+ dev: [],
+ held_out: [],
+ candidate_sha256: candidateSha256,
+ },
+ }).id;
+}
+
+function stagePromoted(): { slug: string; specHash: string } {
+ const specHash = skillRewriteSpecHash(SPEC);
+ const result = stageScoredRewriteProposal(vault, {
+ skill: {
+ name: TASKS.skillName,
+ description: "Does a thing, safely.",
+ triggers: ["thing"],
+ body: CANDIDATE_BODY,
+ },
+ spec: SPEC,
+ specHash,
+ baselineScore: 0.4,
+ candidateScore: 0.7,
+ heldoutScore: 1,
+ incumbentVersion: 3,
+ });
+ if (result.outcome !== "created")
+ throw new Error(`test setup: staging declined: ${result.outcome}`);
+ return { slug: result.slug, specHash };
+}
+
+/** Everything a completed gate round leaves behind, incumbent included. */
+function seedCompletedGateRound(): { slug: string; skillPath: string } {
+ const { slug } = stagePromoted();
+ seedBenchmark();
+ recordPromoteGrade(slug);
+ const skillPath = writeIncumbent();
+ return { slug, skillPath };
+}
+
+function pendingPathFor(slug: string): string {
+ return join(vault, "Brain", "skill-proposals", "pending", `prop-${slug}.md`);
+}
+
+describe("the scored_rewrite pattern kind", () => {
+ test("is exported and joins the pattern-kind union", () => {
+ expect(SCORED_REWRITE_PATTERN_KIND).toBe("scored_rewrite");
+ });
+
+ test("a promoted candidate stages a pending proposal with the scored contract", () => {
+ const { slug, specHash } = stagePromoted();
+ const pending = listPendingSkillProposals(vault);
+ expect(pending.map((proposal) => proposal.slug)).toEqual([slug]);
+ expect(pending[0]?.patternKind).toBe(SCORED_REWRITE_PATTERN_KIND);
+
+ const [fm, documentBody] = parseFrontmatter(
+ join(vault, "Brain", "skill-proposals", "pending", `prop-${slug}.md`),
+ );
+ expect(fm["rewrites_skill"]).toBe("example-skill");
+ expect(fm["spec_hash"]).toBe(specHash);
+ expect(fm["baseline_score"]).toBe("0.400");
+ expect(fm["candidate_score"]).toBe("0.700");
+ expect(fm["heldout_score"]).toBe("1.000");
+ expect(fm["skill_name"]).toBe("example-skill");
+ // The version bump rides staging: incumbent 3, staged proposal 4.
+ expect(Number(fm["version"])).toBe(4);
+ // The candidate binding (review round-2, M1 residual R1): staging
+ // stamps the sha-256 of the document it wrote, whose Suggested skill
+ // body section IS the candidate, so the accept-time match can bind a
+ // promote grade to the exact staged bytes.
+ expect(fm["candidate_sha256"]).toBe(sha256Hex(documentBody));
+ });
+
+ test("acceptance goes through acceptSkillProposal unchanged and bumps the version", () => {
+ // The designed flow: a completed gate round leaves the benchmark receipt
+ // and the promote grade record behind, and the human accept re-verifies
+ // both before anything is written (review security M1).
+ const { slug } = seedCompletedGateRound();
+ const accepted = acceptSkillProposal(vault, slug, { skillsRoot, note: "gate passed" });
+ expect(accepted.status).toBe("accepted");
+ expect(accepted.skillPath).toBe(join(skillsRoot, "example-skill", "SKILL.md"));
+ expect(existsSync(join(vault, "Brain", "skill-proposals", "pending", `prop-${slug}.md`))).toBe(
+ false,
+ );
+
+ const [fm, body] = parseFrontmatter(join(skillsRoot, "example-skill", "SKILL.md"));
+ expect(Number(fm["version"])).toBe(4);
+ expect(body).toContain("Candidate body: plan first");
+ expect(existsSync(join(vault, "Brain", "skill-proposals", "accepted", `prop-${slug}.md`))).toBe(
+ true,
+ );
+ });
+
+ test("the incumbent reader takes description and triggers from the incumbent's own frontmatter", () => {
+ // An incumbent SKILL.md stores `description` and `triggers` - the same
+ // keys the accept materializer writes - not the proposal-only
+ // `skill_description`/`skill_triggers` spellings. Reading the draft
+ // keys here made every real incumbent read as undescribed, so the
+ // staged rewrite carried the placeholder description and empty
+ // triggers, and the accept dropped the incumbent's own.
+ writeIncumbent();
+ const incumbent = readRewriteIncumbent(vault, TASKS.skillName, { skillsRoot });
+ expect(incumbent.description).toBe("The incumbent instructions.");
+ expect(incumbent.triggers).toEqual(["thing"]);
+ });
+
+ test("a changed rewrite stages after its predecessor was accepted", () => {
+ // The rewrite gate is iterative by design (the reserved `iterative`
+ // mode is rounds over the SAME skill), so an accepted proposal must
+ // not pin the skill name against the next changed candidate. The
+ // payload identity - body and salt - is what dedupes a scored
+ // rewrite; the bare name is what a REJECTION pins.
+ const first = seedCompletedGateRound();
+ acceptSkillProposal(vault, first.slug, { skillsRoot, note: "gate passed" });
+ const second = stageScoredRewriteProposal(vault, {
+ skill: {
+ name: TASKS.skillName,
+ description: "Does a thing, safely.",
+ triggers: ["thing"],
+ body: `${CANDIDATE_BODY}\nRefined after the first accepted round.`,
+ },
+ spec: SPEC,
+ specHash: skillRewriteSpecHash(SPEC),
+ baselineScore: 0.4,
+ candidateScore: 0.75,
+ heldoutScore: 1,
+ incumbentVersion: 4,
+ });
+ expect(second.outcome).toBe("created");
+ });
+
+ test("an identical pending payload still dedupes", () => {
+ stagePromoted();
+ const again = stageScoredRewriteProposal(vault, {
+ skill: {
+ name: TASKS.skillName,
+ description: "Does a thing, safely.",
+ triggers: ["thing"],
+ body: CANDIDATE_BODY,
+ },
+ spec: SPEC,
+ specHash: skillRewriteSpecHash(SPEC),
+ baselineScore: 0.4,
+ candidateScore: 0.7,
+ heldoutScore: 1,
+ incumbentVersion: 3,
+ });
+ expect(again.outcome).toBe("deduped");
+ });
+
+ test("a changed payload while a rewrite is still pending dedupes, naming the pending draft", () => {
+ // One pending overwrite per skill at a time: two accepted drafts would
+ // stamp the same version over one SKILL.md and the second would
+ // silently drop the first, and the accept path does not re-check the
+ // live incumbent version. A new gate round queues behind the pending
+ // draft until the operator accepts or rejects it.
+ const { slug } = stagePromoted();
+ const changed = stageScoredRewriteProposal(vault, {
+ skill: {
+ name: TASKS.skillName,
+ description: "Does a thing, safely.",
+ triggers: ["thing"],
+ body: `${CANDIDATE_BODY}\nRefined while the first round is still pending.`,
+ },
+ spec: SPEC,
+ specHash: skillRewriteSpecHash(SPEC),
+ baselineScore: 0.4,
+ candidateScore: 0.75,
+ heldoutScore: 1,
+ incumbentVersion: 3,
+ });
+ expect(changed.outcome).toBe("deduped");
+ expect(listPendingSkillProposals(vault).map((proposal) => proposal.slug)).toEqual([slug]);
+ });
+
+ test("a rejected rewrite family stays suppressed for the skill name", () => {
+ // The design pins the reject: sticky for the skill name, so a
+ // re-proposed rewrite of the same skill - changed payload included -
+ // stays suppressed until an operator reopens the lane by hand.
+ const { slug } = stagePromoted();
+ rejectSkillProposal(vault, slug, { note: "not this direction" });
+ const changed = stageScoredRewriteProposal(vault, {
+ skill: {
+ name: TASKS.skillName,
+ description: "Does a thing, safely.",
+ triggers: ["thing"],
+ body: `${CANDIDATE_BODY}\nRefined after the rejection.`,
+ },
+ spec: SPEC,
+ specHash: skillRewriteSpecHash(SPEC),
+ baselineScore: 0.4,
+ candidateScore: 0.75,
+ heldoutScore: 1,
+ incumbentVersion: 3,
+ });
+ expect(changed.outcome).toBe("suppressed");
+ });
+});
+
+describe("the journal captures prior content", () => {
+ test("priorContentPath round-trips through the journal", () => {
+ const { slug } = stagePromoted();
+ const priorPath = join(vault, "Brain", "skill-proposals", "accept-journal", `${slug}.prior.md`);
+ writeSkillAcceptJournal(vault, {
+ slug,
+ id: `prop-${slug}`,
+ phase: "materialize",
+ startedAt: "2026-06-01T09:00:00.000Z",
+ acceptedExisted: false,
+ materializedExisted: true,
+ materializedPath: join(skillsRoot, "example-skill", "SKILL.md"),
+ priorContentPath: priorPath,
+ });
+ const [entry] = readSkillAcceptJournals(vault).entries;
+ expect(entry?.priorContentPath).toBe(priorPath);
+
+ writeSkillAcceptJournal(vault, {
+ slug,
+ id: `prop-${slug}`,
+ phase: "archive",
+ startedAt: "2026-06-01T09:00:00.000Z",
+ acceptedExisted: false,
+ materializedExisted: false,
+ });
+ const [without] = readSkillAcceptJournals(vault).entries;
+ expect(without?.priorContentPath).toBeUndefined();
+ });
+
+ test("the journal records the skills root the accept resolved, alongside the path", () => {
+ // A mature_page accept resolves the skills root from its caller; the
+ // journal records that root next to the path it produced, so recovery
+ // can check the pair against the tree the accept actually used instead
+ // of re-deriving a root the caller may have overridden.
+ const slug = "recorded-root-slug";
+ const skillPath = join(skillsRoot, "example-skill", "SKILL.md");
+ writeSkillAcceptJournal(vault, {
+ slug,
+ id: `prop-${slug}`,
+ phase: "archive",
+ startedAt: "2026-06-01T09:00:00.000Z",
+ acceptedExisted: false,
+ materializedExisted: false,
+ materializedPath: skillPath,
+ skillsRoot,
+ });
+ const marker = JSON.parse(readFileSync(skillAcceptJournalPath(vault, slug), "utf8")) as Record<
+ string,
+ unknown
+ >;
+ expect(marker["skills_root"]).toBe(skillsRoot);
+ const [entry] = readSkillAcceptJournals(vault).entries;
+ expect(entry?.skillsRoot).toBe(skillsRoot);
+
+ // A legacy marker carries no root: it parses with the field absent,
+ // and recovery keeps its default-root resolution for it.
+ writeSkillAcceptJournal(vault, {
+ slug,
+ id: `prop-${slug}`,
+ phase: "archive",
+ startedAt: "2026-06-01T09:00:00.000Z",
+ acceptedExisted: false,
+ materializedExisted: false,
+ });
+ const [legacy] = readSkillAcceptJournals(vault).entries;
+ expect(legacy?.skillsRoot).toBeUndefined();
+ });
+
+ test("a crash under an explicit skills root restores the incumbent from the recorded root", () => {
+ // The accept ran against a caller-supplied skills root outside the
+ // vault, so the journal it stamped records that root next to the
+ // materialized path. Recovery reads the pair back: the restore target
+ // sits inside the root the accept itself resolved, so the rollback
+ // restores the incumbent body instead of refusing a path it cannot
+ // re-derive.
+ const { slug } = stagePromoted();
+ const skillPath = writeIncumbent();
+ // The overwrite landed, then the process died before the commit.
+ writeFileSync(
+ skillPath,
+ "---\nname: example-skill\ndescription: x\nversion: 4\n---\n\nCandidate body: plan first\n",
+ "utf8",
+ );
+ const priorPath = join(vault, "Brain", "skill-proposals", "accept-journal", `${slug}.prior.md`);
+ mkdirSync(dirname(priorPath), { recursive: true });
+ writeFileSync(priorPath, INCUMBENT_BODY, "utf8");
+ writeSkillAcceptJournal(vault, {
+ slug,
+ id: `prop-${slug}`,
+ phase: "materialize",
+ startedAt: "2026-06-01T09:00:00.000Z",
+ acceptedExisted: false,
+ materializedExisted: true,
+ materializedPath: skillPath,
+ skillsRoot,
+ priorContentPath: priorPath,
+ });
+
+ const recovered = recoverSkillProposalAccepts(vault);
+ expect(recovered.map((entry) => entry.action)).toEqual(["rolled_back"]);
+ // Content, not just existence: the incumbent bytes are back.
+ expect(readFileSync(skillPath, "utf8")).toBe(INCUMBENT_BODY);
+ expect(existsSync(priorPath)).toBe(false);
+ expect(readSkillAcceptJournals(vault).entries).toEqual([]);
+ });
+
+ test("a crash mid-accept rolls back to the incumbent BODY, not just existence", () => {
+ const { slug } = stagePromoted();
+ // The restore target sits under the vault's own skills root: a
+ // hand-edited journal naming a path outside the vault and the resolved
+ // skills root is refused by name (pinned in the rollback-confinement
+ // describe below), so the recovery fixtures stage the incumbent where a
+ // real accept would resolve it.
+ const skillPath = writeIncumbentUnderVaultSkills();
+ // The overwrite landed, then the process died before the commit.
+ writeFileSync(
+ skillPath,
+ "---\nname: example-skill\ndescription: x\nversion: 4\n---\n\nCandidate body: plan first\n",
+ "utf8",
+ );
+ const priorPath = join(vault, "Brain", "skill-proposals", "accept-journal", `${slug}.prior.md`);
+ mkdirSync(dirname(priorPath), { recursive: true });
+ writeFileSync(priorPath, INCUMBENT_BODY, "utf8");
+ writeSkillAcceptJournal(vault, {
+ slug,
+ id: `prop-${slug}`,
+ phase: "materialize",
+ startedAt: "2026-06-01T09:00:00.000Z",
+ acceptedExisted: false,
+ materializedExisted: true,
+ materializedPath: skillPath,
+ priorContentPath: priorPath,
+ });
+
+ const recovered = recoverSkillProposalAccepts(vault);
+ expect(recovered.map((entry) => entry.action)).toEqual(["rolled_back"]);
+ // Content, not just existence: the incumbent bytes are back.
+ expect(readFileSync(skillPath, "utf8")).toBe(INCUMBENT_BODY);
+ // The repair artifacts are consumed once the sequence is resolved.
+ expect(existsSync(priorPath)).toBe(false);
+ expect(readSkillAcceptJournals(vault).entries).toEqual([]);
+ });
+
+ test("without a captured prior copy the incumbent is left untouched", () => {
+ const { slug } = stagePromoted();
+ const skillPath = writeIncumbent();
+ writeSkillAcceptJournal(vault, {
+ slug,
+ id: `prop-${slug}`,
+ phase: "materialize",
+ startedAt: "2026-06-01T09:00:00.000Z",
+ acceptedExisted: false,
+ materializedExisted: true,
+ materializedPath: skillPath,
+ });
+ const recovered = recoverSkillProposalAccepts(vault);
+ expect(recovered.map((entry) => entry.action)).toEqual(["rolled_back"]);
+ expect(readFileSync(skillPath, "utf8")).toBe(INCUMBENT_BODY);
+ });
+});
+
+describe("the accept-time gate re-verification", () => {
+ // The five refusals below are the accept boundary the security review
+ // asked for (M1): field presence alone never overwrites an incumbent.
+ // Each test hands `acceptSkillProposal` a proposal that passes the old
+ // field checks and asserts the new gate refuses it by name, with the
+ // incumbent bytes untouched and the draft still pending.
+
+ test("a swapped task set invalidates the proposal and refuses the accept", () => {
+ const { slug, skillPath } = seedCompletedGateRound();
+ // The task set moved AFTER the gate ran; the spec receipt is unchanged,
+ // so the take re-verification is the layer that names the swap.
+ seedBenchmark((raw) => {
+ raw.tasks[0] = { ...raw.tasks[0], input: "A changed task input line." };
+ });
+
+ expect(() => acceptSkillProposal(vault, slug, { skillsRoot })).toThrow(
+ /does not match the receipt's frozen hash/,
+ );
+ expect(readFileSync(skillPath, "utf8")).toBe(INCUMBENT_BODY);
+ expect(existsSync(pendingPathFor(slug))).toBe(true);
+ });
+
+ test("an edited spec invalidates the proposal and refuses the accept by spec hash", () => {
+ const { slug, skillPath } = seedCompletedGateRound();
+ // The spec receipt itself was rewritten after the gate ran: its hash no
+ // longer equals the proposal's spec_hash, so the proposal is refused
+ // before the gate's claim is re-scoped.
+ const editedSpec = JSON.parse(SPEC_DOCUMENT) as Record<string, unknown>;
+ editedSpec["min_dev_tasks"] = 1;
+ writeFileSync(
+ skillBenchmarkSpecPath(vault, TASKS.skillName),
+ `${JSON.stringify(editedSpec, null, 2)}\n`,
+ "utf8",
+ );
+
+ expect(() => acceptSkillProposal(vault, slug, { skillsRoot })).toThrow(/spec hash/);
+ expect(readFileSync(skillPath, "utf8")).toBe(INCUMBENT_BODY);
+ expect(existsSync(pendingPathFor(slug))).toBe(true);
+ });
+
+ test("a benchmark missing from the vault refuses the accept by name", () => {
+ const { slug } = stagePromoted();
+ recordPromoteGrade(slug);
+ const skillPath = writeIncumbent();
+
+ expect(() => acceptSkillProposal(vault, slug, { skillsRoot })).toThrow(/benchmark/);
+ expect(readFileSync(skillPath, "utf8")).toBe(INCUMBENT_BODY);
+ expect(existsSync(pendingPathFor(slug))).toBe(true);
+ });
+
+ test("no promote grade record matching the spec hash, no accept", () => {
+ const { slug } = stagePromoted();
+ seedBenchmark();
+ const skillPath = writeIncumbent();
+ // A hold round wrote its record, but the gate's final promote is absent.
+ recordSkillRewriteGrade(vault, {
+ payload: {
+ skill: TASKS.skillName,
+ spec_hash: skillRewriteSpecHash(SPEC),
+ tasks_hash: SPEC.tasksHash,
+ metric: "tasks_passed_rate",
+ seed: SPEC.seed,
+ split_rule: SPEC.splitRule,
+ verdict: SKILL_REWRITE_VERDICT.hold,
+ baseline_rate: 0.5,
+ candidate_rate: 0.5,
+ dev: [],
+ held_out: [],
+ },
+ });
+
+ expect(() => acceptSkillProposal(vault, slug, { skillsRoot })).toThrow(
+ /no skill_rewrite_eval_grade record/,
+ );
+ expect(readFileSync(skillPath, "utf8")).toBe(INCUMBENT_BODY);
+ expect(existsSync(pendingPathFor(slug))).toBe(true);
+ });
+
+ test("a promote record for a different candidate rate does not satisfy the gate", () => {
+ const { slug } = stagePromoted();
+ seedBenchmark();
+ recordPromoteGrade(slug, { candidateRate: 0.9 });
+ const skillPath = writeIncumbent();
+
+ expect(() => acceptSkillProposal(vault, slug, { skillsRoot })).toThrow(
+ /no skill_rewrite_eval_grade record/,
+ );
+ expect(readFileSync(skillPath, "utf8")).toBe(INCUMBENT_BODY);
+ expect(existsSync(pendingPathFor(slug))).toBe(true);
+ });
+
+ test("a promote record left over from an earlier round over a different candidate refuses the accept", () => {
+ // Review round-2, M1 residual R1 (the replay): rates collide. A
+ // historical promote for the SAME benchmark at the SAME candidate rate
+ // but over a DIFFERENT candidate body must not bless this proposal -
+ // the grade match binds the record to the candidate the proposal
+ // stages, so only the round that promoted THIS document can satisfy
+ // the gate.
+ const { slug } = stagePromoted();
+ seedBenchmark();
+ recordPromoteGrade(slug, {
+ candidateSha256: sha256Hex("an earlier round staged a different candidate document"),
+ });
+ const skillPath = writeIncumbent();
+
+ expect(() => acceptSkillProposal(vault, slug, { skillsRoot })).toThrow(
+ /no skill_rewrite_eval_grade record/,
+ );
+ expect(() => acceptSkillProposal(vault, slug, { skillsRoot })).toThrow(/candidate_sha256/);
+ expect(readFileSync(skillPath, "utf8")).toBe(INCUMBENT_BODY);
+ expect(existsSync(pendingPathFor(slug))).toBe(true);
+ });
+
+ test("a suggested body edited after staging refuses the accept by its candidate binding", () => {
+ // The pending file is agent-writable, so the binding must be anchored
+ // to the staged BYTES: recomputing the document hash at accept turns
+ // any post-staging edit - a swapped candidate body above all - into a
+ // named refusal, even with every other gate input intact.
+ const { slug, skillPath } = seedCompletedGateRound();
+ const pendingPath = pendingPathFor(slug);
+ const forged = readFileSync(pendingPath, "utf8").replace(
+ "Candidate body: plan first, search twice, write once, and report the artifact path.",
+ "Hostile body: ship without verification.",
+ );
+ expect(forged).toContain("Hostile body: ship without verification.");
+ writeFileSync(pendingPath, forged, "utf8");
+
+ expect(() => acceptSkillProposal(vault, slug, { skillsRoot })).toThrow(/candidate_sha256/);
+ expect(() => acceptSkillProposal(vault, slug, { skillsRoot })).toThrow(/edited after staging/);
+ expect(readFileSync(skillPath, "utf8")).toBe(INCUMBENT_BODY);
+ expect(existsSync(pendingPath)).toBe(true);
+ });
+
+ test("a proposal claiming to rewrite one skill while materializing another refuses", () => {
+ const { slug, skillPath } = seedCompletedGateRound();
+ // Hand-edited frontmatter: the rewrite claim and the materialize target
+ // must name the same skill (self-review B-3, security M1d).
+ const pendingPath = pendingPathFor(slug);
+ const forged = readFileSync(pendingPath, "utf8").replace(
+ /^rewrites_skill: .*$/m,
+ "rewrites_skill: other-skill",
+ );
+ expect(forged).toContain("rewrites_skill: other-skill");
+ writeFileSync(pendingPath, forged, "utf8");
+
+ expect(() => acceptSkillProposal(vault, slug, { skillsRoot })).toThrow(
+ /other-skill.*example-skill|example-skill.*other-skill/,
+ );
+ expect(readFileSync(skillPath, "utf8")).toBe(INCUMBENT_BODY);
+ expect(existsSync(pendingPath)).toBe(true);
+ });
+
+ test("a corrupted scored draft refuses the accept before anything is written", () => {
+ // Test-audit F2(b): the scored-contract validation runs before the
+ // journal is stamped. Every other gate input here is valid, so
+ // deleting the validation call would let this accept succeed and fail
+ // this test - the pin is load-bearing, not decorative.
+ const { slug, skillPath } = seedCompletedGateRound();
+ const pendingPath = pendingPathFor(slug);
+ const corrupted = readFileSync(pendingPath, "utf8").replace(
+ /^baseline_score: .*$/m,
+ "baseline_score: abc",
+ );
+ expect(corrupted).toContain("baseline_score: abc");
+ writeFileSync(pendingPath, corrupted, "utf8");
+
+ expect(() => acceptSkillProposal(vault, slug, { skillsRoot })).toThrow(/baseline_score/);
+ expect(readFileSync(skillPath, "utf8")).toBe(INCUMBENT_BODY);
+ expect(existsSync(pendingPath)).toBe(true);
+ });
+});
+
+describe("the rollback guards", () => {
+ test("a missing prior-content copy is a named refusal that keeps the journal", () => {
+ // Test-audit F2(a): swallowing the read error would silently leave the
+ // CANDIDATE body on an incumbent's path, so the refusal is pinned
+ // exactly - message names the copy, journal survives, nothing restored.
+ const { slug } = stagePromoted();
+ const skillPath = writeIncumbentUnderVaultSkills();
+ writeFileSync(
+ skillPath,
+ "---\nname: example-skill\ndescription: x\nversion: 4\n---\n\nCandidate body: plan first\n",
+ "utf8",
+ );
+ const priorPath = join(vault, "Brain", "skill-proposals", "accept-journal", `${slug}.prior.md`);
+ // The copy itself is NOT written: it is missing, the way a crash or a
+ // hand-cleaned repair directory leaves it.
+ writeSkillAcceptJournal(vault, {
+ slug,
+ id: `prop-${slug}`,
+ phase: "materialize",
+ startedAt: "2026-06-01T09:00:00.000Z",
+ acceptedExisted: false,
+ materializedExisted: true,
+ materializedPath: skillPath,
+ priorContentPath: priorPath,
+ });
+
+ expect(() => recoverSkillProposalAccepts(vault)).toThrow(/prior-content copy is missing/);
+ // The journal is retained so the operator decides, and the candidate
+ // body was not quietly ratified by a cleared journal.
+ expect(readSkillAcceptJournals(vault).entries.length).toBe(1);
+ expect(readFileSync(skillPath, "utf8")).toContain("Candidate body: plan first");
+ });
+
+ test("a restore target outside the vault and the skills root refuses by name", () => {
+ // Review security M4: the journal's materialized_path is not a recovery
+ // input. A hand-edited journal aiming the restore at a file outside the
+ // vault and the resolved skills root must be refused, leaving the
+ // target untouched and the journal on disk.
+ const { slug } = stagePromoted();
+ const victimDir = mkdtempSync(join(tmpdir(), "o2b-rewrite-victim-"));
+ try {
+ const victim = join(victimDir, "victim.md");
+ writeFileSync(victim, "operator bytes", "utf8");
+ const priorPath = join(
+ vault,
+ "Brain",
+ "skill-proposals",
+ "accept-journal",
+ `${slug}.prior.md`,
+ );
+ mkdirSync(dirname(priorPath), { recursive: true });
+ writeFileSync(priorPath, INCUMBENT_BODY, "utf8");
+ writeSkillAcceptJournal(vault, {
+ slug,
+ id: `prop-${slug}`,
+ phase: "materialize",
+ startedAt: "2026-06-01T09:00:00.000Z",
+ acceptedExisted: false,
+ materializedExisted: true,
+ materializedPath: victim,
+ priorContentPath: priorPath,
+ });
+
+ expect(() => recoverSkillProposalAccepts(vault)).toThrow(/materialized path/);
+ expect(readSkillAcceptJournals(vault).entries.length).toBe(1);
+ expect(readFileSync(victim, "utf8")).toBe("operator bytes");
+ } finally {
+ rmSync(victimDir, { recursive: true, force: true });
+ }
+ });
+});
+
+describe("the skill_rewrite_eval_grade continuity kind", () => {
+ test("is in the union and the runtime kind list in the same edit", () => {
+ expect(isContinuityRecordKind("skill_rewrite_eval_grade")).toBe(true);
+ expect(CONTINUITY_RECORD_KINDS).toContain("skill_rewrite_eval_grade");
+ });
+
+ test("a hold round writes only the grade record and stages nothing", () => {
+ const before = listPendingSkillProposals(vault).length;
+ const record = recordSkillRewriteGrade(vault, {
+ payload: {
+ skill: TASKS.skillName,
+ spec_hash: skillRewriteSpecHash(SPEC),
+ tasks_hash: SPEC.tasksHash,
+ metric: "tasks_passed_rate",
+ seed: SPEC.seed,
+ split_rule: SPEC.splitRule,
+ verdict: SKILL_REWRITE_VERDICT.hold,
+ baseline_rate: 0.5,
+ candidate_rate: 0.5,
+ dev: [],
+ held_out: [],
+ },
+ });
+ expect(record.kind).toBe("skill_rewrite_eval_grade");
+ const grades = listContinuityRecords(vault, { kind: "skill_rewrite_eval_grade" });
+ expect(grades.length).toBe(1);
+ expect(grades[0]?.payload["verdict"]).toBe(SKILL_REWRITE_VERDICT.hold);
+ expect(grades[0]?.payload).not.toHaveProperty("task_text");
+ // A hold round stages nothing, so it carries no candidate document
+ // binding: only a promote record that blessed a staged proposal does.
+ expect(grades[0]?.payload).not.toHaveProperty("candidate_sha256");
+ // The proposal tree is unchanged: gate failures stage nothing.
+ expect(listPendingSkillProposals(vault).length).toBe(before);
+ });
+});
+
+describe("the config keys", () => {
+ test("skill_rewrite.mode resolves from the env twin and refuses unknown values by name", () => {
+ expect(resolveSkillRewriteModeConfig()).toBe("gated");
+ process.env[SKILL_REWRITE_MODE_ENV_KEY] = "iterative";
+ expect(resolveSkillRewriteModeConfig()).toBe("iterative");
+ process.env[SKILL_REWRITE_MODE_ENV_KEY] = "turbo";
+ expect(() => resolveSkillRewriteModeConfig()).toThrow(/turbo/);
+ });
+
+ test("skill_rewrite.mode resolves from the config file's flat dotted key", () => {
+ const configPath = join(vault, "brain-config.yaml");
+ writeFileSync(configPath, `${SKILL_REWRITE_MODE_CONFIG_KEY}: iterative\n`, "utf8");
+ expect(resolveSkillRewriteModeConfig(configPath)).toBe("iterative");
+ });
+
+ test("skill_rewrite_judge_cmd resolves from the env twin and the config file", () => {
+ expect(resolveSkillRewriteJudgeCmd()).toBeUndefined();
+ process.env[SKILL_REWRITE_JUDGE_CMD_ENV_KEY] = "jq .verdicts";
+ expect(resolveSkillRewriteJudgeCmd()).toBe("jq .verdicts");
+ delete process.env[SKILL_REWRITE_JUDGE_CMD_ENV_KEY];
+ const configPath = join(vault, "brain-config.yaml");
+ writeFileSync(configPath, `${SKILL_REWRITE_JUDGE_CMD_CONFIG_KEY}: jq .verdicts\n`, "utf8");
+ expect(resolveSkillRewriteJudgeCmd(configPath)).toBe("jq .verdicts");
+ });
+});
+
+describe("the benchmark paths", () => {
+ test("the spec receipt names the committed fixture layout", () => {
+ expect(skillBenchmarkRelPath("example-skill", SKILL_BENCHMARK_SPEC_FILE)).toBe(
+ "Brain/skill-benchmarks/example-skill/spec.json",
+ );
+ expect(SKILL_REWRITE_SPEC_SCHEMA).toBe("o2b.skill-rewrite.v1");
+ expect(SKILL_REWRITE_SPLIT_RULE).toBe("hash-order-70-30");
+ });
+
+ test("the vault-side resolvers stay inside the vault", () => {
+ expect(skillBenchmarkTasksPath(vault, "example-skill")).toBe(
+ join(vault, "Brain", "skill-benchmarks", "example-skill", "tasks.json"),
+ );
+ expect(skillBenchmarkSpecPath(vault, "example-skill")).toBe(
+ join(vault, "Brain", "skill-benchmarks", "example-skill", "spec.json"),
+ );
+ expect(skillBenchmarkRoundsDir(vault, "example-skill")).toBe(
+ join(vault, "Brain", "skill-benchmarks", "example-skill", "rounds"),
+ );
+ expect(skillAcceptPriorContentPath(vault, "some-slug")).toBe(
+ join(vault, "Brain", "skill-proposals", "accept-journal", "some-slug.prior.md"),
+ );
+ });
+});
diff --git a/tests/core/brain/skill-rewrite-spec.test.ts b/tests/core/brain/skill-rewrite-spec.test.ts
new file mode 100644
index 00000000..44c8f697
--- /dev/null
+++ b/tests/core/brain/skill-rewrite-spec.test.ts
@@ -0,0 +1,255 @@
+/**
+ * The rewrite-spec kernel (agent-presence, Lane A, A2).
+ *
+ * A rewrite spec is a preregistration with mechanical teeth: it freezes
+ * the task-set hash, the seed, the split rule and the derived dev and
+ * held-out membership into one content-hashed receipt, so a benchmark
+ * that changes under a gate run is refused by name instead of quietly
+ * re-scoping the claim. The committed fixture spec pins the receipt for
+ * the example task set; the tests bind the two.
+ */
+
+import { describe, expect, test } from "bun:test";
+import { readFileSync } from "node:fs";
+import { join } from "node:path";
+
+import {
+ SKILL_REWRITE_DEFAULT_SEED,
+ SKILL_REWRITE_DEV_FRACTION,
+ SKILL_REWRITE_METRIC,
+ SKILL_REWRITE_MIN_DEV_TASKS,
+ SKILL_REWRITE_MIN_TASKS,
+ SKILL_REWRITE_REQUIRED_MARGIN,
+ SKILL_REWRITE_SPEC_SCHEMA,
+ SKILL_REWRITE_SPLIT_RULE,
+ SKILL_REWRITE_VERDICT,
+ SKILL_REWRITE_VERDICTS,
+ buildSkillRewriteSpec,
+ isSkillRewriteVerdict,
+ parseSkillRewriteSpec,
+ skillRewriteSpecHash,
+ verifyRewriteTake,
+} from "../../../src/core/brain/skill-rewrite-spec.ts";
+import { parseSkillBenchmarkTasks } from "../../../src/core/brain/skill-rewrite-tasks.ts";
+
+const REPO_ROOT = join(import.meta.dir, "..", "..", "..");
+const FIXTURE_PATH = join(REPO_ROOT, "tests", "fixtures", "skill-bench", "example-skill");
+
+const TASKS = parseSkillBenchmarkTasks(
+ JSON.parse(readFileSync(join(FIXTURE_PATH, "tasks.json"), "utf8")),
+ "tasks.json",
+);
+const SPEC = JSON.parse(readFileSync(join(FIXTURE_PATH, "spec.json"), "utf8"));
+
+describe("spec constants and verdict vocabulary", () => {
+ test("the schema, split rule and metric are pinned", () => {
+ expect(SKILL_REWRITE_SPEC_SCHEMA).toBe("o2b.skill-rewrite.v1");
+ expect(SKILL_REWRITE_SPLIT_RULE).toBe("hash-order-70-30");
+ expect(SKILL_REWRITE_METRIC).toBe("tasks_passed_rate");
+ expect(SKILL_REWRITE_DEV_FRACTION).toBe(0.7);
+ });
+
+ test("the verdict vocabulary is frozen and answered by its guard", () => {
+ expect(Object.isFrozen(SKILL_REWRITE_VERDICT)).toBe(true);
+ expect(Object.isFrozen(SKILL_REWRITE_VERDICTS)).toBe(true);
+ expect([...SKILL_REWRITE_VERDICTS].toSorted()).toEqual([
+ "hold",
+ "not_enough_evidence",
+ "promote",
+ ]);
+ for (const verdict of SKILL_REWRITE_VERDICTS) expect(isSkillRewriteVerdict(verdict)).toBe(true);
+ expect(isSkillRewriteVerdict("ship_it")).toBe(false);
+ expect(isSkillRewriteVerdict(undefined)).toBe(false);
+ });
+
+ test("gate constants carry their reasons in one place", () => {
+ expect(SKILL_REWRITE_REQUIRED_MARGIN).toBeGreaterThan(0);
+ expect(SKILL_REWRITE_MIN_DEV_TASKS).toBeGreaterThanOrEqual(1);
+ expect(SKILL_REWRITE_MIN_TASKS).toBeGreaterThanOrEqual(2);
+ expect(Number.isInteger(SKILL_REWRITE_DEFAULT_SEED)).toBe(true);
+ });
+});
+
+describe("buildSkillRewriteSpec", () => {
+ test("derives the receipt deterministically from the seed and split rule", () => {
+ const first = buildSkillRewriteSpec(TASKS.skillName, TASKS);
+ const second = buildSkillRewriteSpec(TASKS.skillName, TASKS);
+ expect(second).toEqual(first);
+ expect(first.schemaVersion).toBe(SKILL_REWRITE_SPEC_SCHEMA);
+ expect(first.tasksHash).toBe(TASKS.hash);
+ expect(first.splitRule).toBe(SKILL_REWRITE_SPLIT_RULE);
+ expect(first.seed).toBe(SKILL_REWRITE_DEFAULT_SEED);
+ expect(first.requiredMargin).toBe(SKILL_REWRITE_REQUIRED_MARGIN);
+ expect(first.minDevTasks).toBe(SKILL_REWRITE_MIN_DEV_TASKS);
+ });
+
+ test("an explicit seed changes the receipt deterministically", () => {
+ const seeded = buildSkillRewriteSpec(TASKS.skillName, TASKS, { seed: 7 });
+ expect(seeded.seed).toBe(7);
+ const again = buildSkillRewriteSpec(TASKS.skillName, TASKS, { seed: 7 });
+ expect(again).toEqual(seeded);
+ });
+
+ test("the receipt covers every task id exactly once across the two arms", () => {
+ const spec = buildSkillRewriteSpec(TASKS.skillName, TASKS);
+ const every = [...spec.devTaskIds, ...spec.heldoutTaskIds].toSorted();
+ const taskIds = TASKS.tasks.map((task) => task.id).toSorted();
+ expect(every).toEqual(taskIds);
+ expect(spec.devTaskIds.length + spec.heldoutTaskIds.length).toBe(TASKS.tasks.length);
+ });
+
+ test("the dev share follows the split rule and both arms stay non-empty", () => {
+ const spec = buildSkillRewriteSpec(TASKS.skillName, TASKS);
+ expect(spec.devTaskIds.length).toBe(Math.ceil(TASKS.tasks.length * SKILL_REWRITE_DEV_FRACTION));
+ expect(spec.devTaskIds.length).toBeGreaterThan(0);
+ expect(spec.heldoutTaskIds.length).toBeGreaterThan(0);
+ });
+
+ test("a task set too small to split is refused by name", () => {
+ const raw = {
+ skill: "tiny-skill",
+ tasks: [
+ {
+ id: "only-1",
+ kind: "invocation_transcript",
+ input: "one",
+ expects: [{ check: "tool_used", tool: "note_search" }],
+ },
+ {
+ id: "only-2",
+ kind: "invocation_transcript",
+ input: "two",
+ expects: [{ check: "tool_used", tool: "note_search" }],
+ },
+ ],
+ };
+ const set = parseSkillBenchmarkTasks(raw, "tiny.json");
+ expect(() => buildSkillRewriteSpec(set.skillName, set)).toThrow(/too small to split|minimum/i);
+ });
+});
+
+describe("verifyRewriteTake", () => {
+ test("accepts the matching task set", () => {
+ const spec = buildSkillRewriteSpec(TASKS.skillName, TASKS);
+ const verdict = verifyRewriteTake(spec, TASKS);
+ expect(verdict).toEqual({ ok: true, reason: null });
+ });
+
+ test("refuses a changed task set with the hash in the reason", () => {
+ const spec = buildSkillRewriteSpec(TASKS.skillName, TASKS);
+ const touched = structuredClone(
+ JSON.parse(readFileSync(join(FIXTURE_PATH, "tasks.json"), "utf8")),
+ ) as { skill: string; tasks: Array<{ input: string }> };
+ touched.tasks[0]!.input = `${touched.tasks[0]!.input} edited`;
+ const moved = parseSkillBenchmarkTasks(touched, "moved.json");
+ const verdict = verifyRewriteTake(spec, moved);
+ expect(verdict.ok).toBe(false);
+ expect(verdict.reason).toContain(moved.hash);
+ });
+
+ test("refuses a receipt the split no longer derives", () => {
+ const spec = buildSkillRewriteSpec(TASKS.skillName, TASKS);
+ const swapped = {
+ ...spec,
+ devTaskIds: [spec.devTaskIds[0]!, ...spec.heldoutTaskIds.slice(0, 1)],
+ heldoutTaskIds: [...spec.heldoutTaskIds.slice(1), spec.devTaskIds[1]!],
+ };
+ const verdict = verifyRewriteTake(swapped, TASKS);
+ expect(verdict.ok).toBe(false);
+ expect(verdict.reason).not.toBeNull();
+ expect(verdict.reason?.toLowerCase()).toContain("split");
+ });
+
+ test("refuses a spec naming a different skill", () => {
+ const spec = buildSkillRewriteSpec(TASKS.skillName, TASKS);
+ const renamed = { ...spec, skillName: "other-skill" };
+ const verdict = verifyRewriteTake(renamed, TASKS);
+ expect(verdict.ok).toBe(false);
+ expect(verdict.reason?.toLowerCase()).toContain("skill");
+ });
+});
+
+describe("parseSkillRewriteSpec", () => {
+ test("accepts the committed fixture spec", () => {
+ const spec = parseSkillRewriteSpec(SPEC, "spec.json");
+ expect(spec.skillName).toBe("example-skill");
+ expect(spec.tasksHash).toBe(TASKS.hash);
+ expect(spec.devTaskIds.length + spec.heldoutTaskIds.length).toBe(TASKS.tasks.length);
+ expect(Object.isFrozen(spec)).toBe(true);
+ });
+
+ test("the committed fixture receipt verifies against the committed task set", () => {
+ const spec = parseSkillRewriteSpec(SPEC, "spec.json");
+ expect(verifyRewriteTake(spec, TASKS)).toEqual({ ok: true, reason: null });
+ });
+
+ test("an unknown schema version is refused by name", () => {
+ const mutated = {
+ ...(SPEC as Record<string, unknown>),
+ schema_version: "o2b.skill-rewrite.v9",
+ };
+ expect(() => parseSkillRewriteSpec(mutated, "spec.json")).toThrow(/schema version/);
+ });
+
+ test("refuses malformed fields by name", () => {
+ const base = SPEC as Record<string, unknown>;
+ const refusing = (mutate: (draft: Record<string, unknown>) => void, fragment: string): void => {
+ const draft = structuredClone(base);
+ mutate(draft);
+ try {
+ parseSkillRewriteSpec(draft, "spec.json");
+ } catch (error) {
+ expect((error as Error).message).toContain(fragment);
+ return;
+ }
+ throw new Error(`expected a refusal containing "${fragment}"`);
+ };
+ refusing((draft) => delete draft["skill_name"], "skill");
+ refusing((draft) => delete draft["tasks_hash"], "tasks_hash");
+ refusing((draft) => (draft["tasks_hash"] = "short"), "sha-256");
+ refusing((draft) => (draft["split_rule"] = "hash-order-30-70"), "split rule");
+ refusing((draft) => (draft["required_margin"] = 1.5), "required_margin");
+ refusing((draft) => (draft["required_margin"] = -1), "required_margin");
+ refusing((draft) => (draft["min_dev_tasks"] = 0), "min_dev_tasks");
+ refusing((draft) => (draft["seed"] = "zero"), "seed");
+ refusing((draft) => {
+ draft["dev_task_ids"] = [
+ ...(draft["dev_task_ids"] as string[]),
+ (draft["held_out_task_ids"] as string[])[0],
+ ];
+ }, "disjoint");
+ refusing((draft) => (draft["dev_task_ids"] = []), "dev_task_ids must be a non-empty array");
+ refusing(
+ (draft) => (draft["held_out_task_ids"] = []),
+ "held_out_task_ids must be a non-empty array",
+ );
+ });
+});
+
+describe("skillRewriteSpecHash", () => {
+ test("is stable across calls and moves when the spec moves", () => {
+ const spec = buildSkillRewriteSpec(TASKS.skillName, TASKS);
+ expect(skillRewriteSpecHash(spec)).toBe(skillRewriteSpecHash(spec));
+ const tightened = { ...spec, requiredMargin: spec.requiredMargin + 0.05 };
+ expect(skillRewriteSpecHash(tightened)).not.toBe(skillRewriteSpecHash(spec));
+ });
+
+ test("the built spec hash matches the committed fixture hash", () => {
+ const spec = parseSkillRewriteSpec(SPEC, "spec.json");
+ const rebuilt = buildSkillRewriteSpec(spec.skillName, TASKS, { seed: spec.seed });
+ expect(skillRewriteSpecHash(rebuilt)).toBe(skillRewriteSpecHash(spec));
+ });
+});
+
+describe("the kernel stays a true leaf", () => {
+ test("it imports nothing beyond the digest and the task kernel", () => {
+ const text = readFileSync(
+ join(REPO_ROOT, "src", "core", "brain", "skill-rewrite-spec.ts"),
+ "utf8",
+ );
+ const imports = [...text.matchAll(/^import\s[^;]*?from\s*"([^"]+)"/gm)].map((m) => m[1]!);
+ const allowed = new Set(["../integrity/digest.ts", "./skill-rewrite-tasks.ts"]);
+ const unexpected = imports.filter((specifier) => !allowed.has(specifier));
+ expect(unexpected).toEqual([]);
+ });
+});
diff --git a/tests/core/brain/skill-rewrite-tasks.test.ts b/tests/core/brain/skill-rewrite-tasks.test.ts
new file mode 100644
index 00000000..96155e58
--- /dev/null
+++ b/tests/core/brain/skill-rewrite-tasks.test.ts
@@ -0,0 +1,464 @@
+/**
+ * The per-skill benchmark task-set kernel (agent-presence, Lane A, A1).
+ *
+ * The parser is the only door to a task set: every malformed shape is a
+ * named error carrying the source the document was read from, the
+ * vocabularies are frozen and answered by their guards, and the hash is
+ * the one digest encoding over the canonical task list - stable across
+ * parses and key order, sensitive to any task byte, because a spec
+ * freezes that hash as its receipt.
+ */
+
+import { describe, expect, test } from "bun:test";
+import { readFileSync } from "node:fs";
+import { join } from "node:path";
+
+import {
+ SKILL_BENCHMARKS_DIR,
+ SKILL_BENCHMARKS_ROOT_REL,
+ SKILL_BENCH_CHECK,
+ SKILL_BENCH_CHECKS,
+ SKILL_BENCH_TASK_ID_RE,
+ SKILL_BENCH_TASK_KIND,
+ SKILL_BENCH_TASK_KINDS,
+ SKILL_BENCH_VALUE_CLASS,
+ SKILL_BENCH_VALUE_CLASSES,
+ isSkillBenchCheck,
+ isSkillBenchTaskKind,
+ isSkillBenchValueClass,
+ parseSkillBenchmarkTasks,
+ skillBenchmarkRelPath,
+ skillBenchmarkTaskSetHash,
+} from "../../../src/core/brain/skill-rewrite-tasks.ts";
+
+const REPO_ROOT = join(import.meta.dir, "..", "..", "..");
+const FIXTURE_PATH = join(REPO_ROOT, "tests", "fixtures", "skill-bench", "example-skill");
+
+function loadFixture(name: string): unknown {
+ return JSON.parse(readFileSync(join(FIXTURE_PATH, name), "utf8"));
+}
+
+describe("skill-benchmark path constants", () => {
+ test("the benchmark root composes from the Brain root and the directory name", () => {
+ expect(SKILL_BENCHMARKS_DIR).toBe("skill-benchmarks");
+ expect(SKILL_BENCHMARKS_ROOT_REL).toBe("Brain/skill-benchmarks");
+ expect(skillBenchmarkRelPath("example-skill", "tasks.json")).toBe(
+ "Brain/skill-benchmarks/example-skill/tasks.json",
+ );
+ });
+});
+
+describe("closed vocabularies", () => {
+ test("task kinds are frozen and answered by their guard", () => {
+ expect(Object.isFrozen(SKILL_BENCH_TASK_KIND)).toBe(true);
+ expect(Object.isFrozen(SKILL_BENCH_TASK_KINDS)).toBe(true);
+ expect([...SKILL_BENCH_TASK_KINDS]).toEqual(["invocation_transcript"]);
+ expect(isSkillBenchTaskKind("invocation_transcript")).toBe(true);
+ expect(isSkillBenchTaskKind("freeform_chat")).toBe(false);
+ expect(isSkillBenchTaskKind(42)).toBe(false);
+ });
+
+ test("checks are frozen and answered by their guard", () => {
+ expect(Object.isFrozen(SKILL_BENCH_CHECK)).toBe(true);
+ expect(Object.isFrozen(SKILL_BENCH_CHECKS)).toBe(true);
+ expect([...SKILL_BENCH_CHECKS]).toEqual([
+ "tool_used",
+ "artifact_created",
+ "step_order",
+ "forbidden_step",
+ "output_field",
+ ]);
+ for (const check of SKILL_BENCH_CHECKS) expect(isSkillBenchCheck(check)).toBe(true);
+ expect(isSkillBenchCheck("vibe_score")).toBe(false);
+ expect(isSkillBenchCheck(undefined)).toBe(false);
+ });
+
+ test("output value classes are frozen and answered by their guard", () => {
+ expect(Object.isFrozen(SKILL_BENCH_VALUE_CLASS)).toBe(true);
+ expect(Object.isFrozen(SKILL_BENCH_VALUE_CLASSES)).toBe(true);
+ expect([...SKILL_BENCH_VALUE_CLASSES].toSorted()).toEqual([
+ "boolean",
+ "non_empty_array",
+ "non_empty_string",
+ "number",
+ ]);
+ for (const valueClass of SKILL_BENCH_VALUE_CLASSES) {
+ expect(isSkillBenchValueClass(valueClass)).toBe(true);
+ }
+ expect(isSkillBenchValueClass("any")).toBe(false);
+ });
+
+ test("task ids stay filename-safe", () => {
+ expect(SKILL_BENCH_TASK_ID_RE.test("t-01")).toBe(true);
+ expect(SKILL_BENCH_TASK_ID_RE.test("step_2.json")).toBe(true);
+ expect(SKILL_BENCH_TASK_ID_RE.test("../escape")).toBe(false);
+ expect(SKILL_BENCH_TASK_ID_RE.test("has space")).toBe(false);
+ });
+});
+
+describe("parseSkillBenchmarkTasks", () => {
+ test("accepts the committed example fixture", () => {
+ const set = parseSkillBenchmarkTasks(loadFixture("tasks.json"), "tasks.json");
+ expect(set.skillName).toBe("example-skill");
+ expect(set.tasks.length).toBe(10);
+ expect(set.tasks[0]?.kind).toBe("invocation_transcript");
+ expect(set.tasks[0]?.expects[0]).toEqual({ check: "tool_used", tool: "note_write" });
+ // The parsed set is frozen at every level, so a caller cannot mutate
+ // a receipt after the hash was taken over it.
+ expect(Object.isFrozen(set)).toBe(true);
+ expect(Object.isFrozen(set.tasks)).toBe(true);
+ expect(Object.isFrozen(set.tasks[0]?.expects)).toBe(true);
+ });
+
+ test("every parsed task id is filename-safe", () => {
+ const set = parseSkillBenchmarkTasks(loadFixture("tasks.json"), "tasks.json");
+ for (const task of set.tasks) {
+ expect(SKILL_BENCH_TASK_ID_RE.test(task.id)).toBe(true);
+ }
+ });
+
+ test("the hash is 64 hex characters", () => {
+ const set = parseSkillBenchmarkTasks(loadFixture("tasks.json"), "tasks.json");
+ expect(set.hash).toMatch(/^[0-9a-f]{64}$/);
+ });
+
+ test("the hash is stable across parses and key order", () => {
+ const raw = loadFixture("tasks.json") as Record<string, unknown>;
+ const first = parseSkillBenchmarkTasks(raw, "a");
+ const second = parseSkillBenchmarkTasks(raw, "b");
+ expect(first.hash).toBe(second.hash);
+ // The same tasks under a different OBJECT key order hash identically:
+ // the digest is taken over the canonical form, never the file bytes.
+ // (Array order is list meaning and stays significant.)
+ const tasks = raw["tasks"] as ReadonlyArray<Record<string, unknown>>;
+ const reordered = {
+ tasks: tasks.map((task) => {
+ const entries = Object.entries(task).toSorted(([a], [b]) => (a < b ? -1 : a > b ? 1 : 0));
+ return Object.fromEntries(entries);
+ }),
+ skill: raw["skill"],
+ };
+ expect(parseSkillBenchmarkTasks(reordered, "c").hash).toBe(first.hash);
+ });
+
+ test("the hash moves when any single task moves", () => {
+ const raw = loadFixture("tasks.json") as {
+ skill: string;
+ tasks: Array<Record<string, unknown>>;
+ };
+ const baseline = parseSkillBenchmarkTasks(raw, "baseline").hash;
+ const unmoved: string[] = [];
+ for (let index = 0; index < raw.tasks.length; index++) {
+ const touched = structuredClone(raw);
+ const task = touched.tasks[index] as { input: string };
+ task.input = `${task.input}x`;
+ const hash = parseSkillBenchmarkTasks(touched, `touched-${index}`).hash;
+ if (hash === baseline) unmoved.push(touched.tasks[index]!.id as string);
+ }
+ expect(unmoved).toEqual([]);
+ });
+
+ test("the hash moves when an expectation moves", () => {
+ const raw = loadFixture("tasks.json") as {
+ skill: string;
+ tasks: Array<{ expects: Array<Record<string, unknown>> }>;
+ };
+ const baseline = parseSkillBenchmarkTasks(raw, "baseline").hash;
+ const touched = structuredClone(raw);
+ const expectation = touched.tasks[0]!.expects[0] as { tool: string };
+ expectation.tool = "other_tool";
+ expect(parseSkillBenchmarkTasks(touched, "touched").hash).not.toBe(baseline);
+ });
+
+ test("the task-set hash helper agrees with the parse", () => {
+ const set = parseSkillBenchmarkTasks(loadFixture("tasks.json"), "tasks.json");
+ expect(skillBenchmarkTaskSetHash(set.tasks)).toBe(set.hash);
+ });
+
+ test("refuses every malformed shape by name, naming the source", () => {
+ const source = "Brain/skill-benchmarks/example-skill/tasks.json";
+ const refusing = (raw: unknown, fragment: string): void => {
+ try {
+ parseSkillBenchmarkTasks(raw, source);
+ } catch (error) {
+ expect((error as Error).message).toContain(source);
+ expect((error as Error).message).toContain(fragment);
+ return;
+ }
+ throw new Error(`expected a refusal containing "${fragment}"`);
+ };
+
+ refusing(null, "expected a JSON object");
+ refusing("tasks", "expected a JSON object");
+ refusing([], "expected a JSON object");
+ refusing({}, "skill");
+ refusing({ skill: "example-skill" }, "tasks must be a non-empty array");
+ refusing({ skill: "example-skill", tasks: [] }, "tasks must be a non-empty array");
+ refusing({ tasks: [] }, "skill");
+ refusing(
+ {
+ skill: "Example Skill",
+ tasks: [
+ {
+ id: "t",
+ kind: "invocation_transcript",
+ input: "x",
+ expects: [{ check: "tool_used", tool: "y" }],
+ },
+ ],
+ },
+ "skill directory name",
+ );
+ refusing(
+ {
+ skill: "../escape",
+ tasks: [
+ {
+ id: "t",
+ kind: "invocation_transcript",
+ input: "x",
+ expects: [{ check: "tool_used", tool: "y" }],
+ },
+ ],
+ },
+ "skill directory name",
+ );
+ refusing({ skill: "example-skill", tasks: [{}] }, "needs a non-empty id");
+ refusing({ skill: "example-skill", tasks: [{ id: "" }] }, "needs a non-empty id");
+ refusing(
+ {
+ skill: "example-skill",
+ tasks: [
+ {
+ id: "t-01",
+ kind: "freeform_chat",
+ input: "x",
+ expects: [{ check: "tool_used", tool: "y" }],
+ },
+ ],
+ },
+ "unknown kind",
+ );
+ refusing(
+ {
+ skill: "example-skill",
+ tasks: [
+ {
+ id: "t-01",
+ kind: "invocation_transcript",
+ expects: [{ check: "tool_used", tool: "y" }],
+ },
+ ],
+ },
+ "input",
+ );
+ refusing(
+ {
+ skill: "example-skill",
+ tasks: [
+ {
+ id: "t-01",
+ kind: "invocation_transcript",
+ input: 7,
+ expects: [{ check: "tool_used", tool: "y" }],
+ },
+ ],
+ },
+ "input",
+ );
+ refusing(
+ {
+ skill: "example-skill",
+ tasks: [{ id: "t-01", kind: "invocation_transcript", input: "x" }],
+ },
+ "expects must be a non-empty array",
+ );
+ refusing(
+ {
+ skill: "example-skill",
+ tasks: [{ id: "t-01", kind: "invocation_transcript", input: "x", expects: [] }],
+ },
+ "expects must be a non-empty array",
+ );
+ refusing(
+ {
+ skill: "example-skill",
+ tasks: [{ id: "t-01", kind: "invocation_transcript", input: "x", expects: [{}] }],
+ },
+ "unknown check",
+ );
+ refusing(
+ {
+ skill: "example-skill",
+ tasks: [
+ {
+ id: "t-01",
+ kind: "invocation_transcript",
+ input: "x",
+ expects: [{ check: "vibe_score" }],
+ },
+ ],
+ },
+ "unknown check",
+ );
+ refusing(
+ {
+ skill: "example-skill",
+ tasks: [
+ {
+ id: "t-01",
+ kind: "invocation_transcript",
+ input: "x",
+ expects: [{ check: "tool_used" }],
+ },
+ ],
+ },
+ "tool",
+ );
+ refusing(
+ {
+ skill: "example-skill",
+ tasks: [
+ {
+ id: "t-01",
+ kind: "invocation_transcript",
+ input: "x",
+ expects: [{ check: "artifact_created", path_prefix: "/abs" }],
+ },
+ ],
+ },
+ "path_prefix",
+ );
+ refusing(
+ {
+ skill: "example-skill",
+ tasks: [
+ {
+ id: "t-01",
+ kind: "invocation_transcript",
+ input: "x",
+ expects: [{ check: "artifact_created", path_prefix: "a/../b" }],
+ },
+ ],
+ },
+ "path_prefix",
+ );
+ refusing(
+ {
+ skill: "example-skill",
+ tasks: [
+ {
+ id: "t-01",
+ kind: "invocation_transcript",
+ input: "x",
+ expects: [{ check: "step_order", steps: [] }],
+ },
+ ],
+ },
+ "steps must be a non-empty string array",
+ );
+ refusing(
+ {
+ skill: "example-skill",
+ tasks: [
+ {
+ id: "t-01",
+ kind: "invocation_transcript",
+ input: "x",
+ expects: [{ check: "step_order", steps: ["a", "a"] }],
+ },
+ ],
+ },
+ "duplicate step",
+ );
+ refusing(
+ {
+ skill: "example-skill",
+ tasks: [
+ {
+ id: "t-01",
+ kind: "invocation_transcript",
+ input: "x",
+ expects: [{ check: "forbidden_step" }],
+ },
+ ],
+ },
+ "step",
+ );
+ refusing(
+ {
+ skill: "example-skill",
+ tasks: [
+ {
+ id: "t-01",
+ kind: "invocation_transcript",
+ input: "x",
+ expects: [{ check: "output_field", field: "f" }],
+ },
+ ],
+ },
+ "value_class",
+ );
+ refusing(
+ {
+ skill: "example-skill",
+ tasks: [
+ {
+ id: "t-01",
+ kind: "invocation_transcript",
+ input: "x",
+ expects: [{ check: "output_field", field: "f", value_class: "any" }],
+ },
+ ],
+ },
+ "value_class",
+ );
+ refusing(
+ {
+ skill: "example-skill",
+ tasks: [
+ {
+ id: "t-01",
+ kind: "invocation_transcript",
+ input: "x",
+ expects: [{ check: "output_field", value_class: "number" }],
+ },
+ ],
+ },
+ "field",
+ );
+ refusing(
+ {
+ skill: "example-skill",
+ tasks: [
+ {
+ id: "t-01",
+ kind: "invocation_transcript",
+ input: "x",
+ expects: [{ check: "tool_used", tool: "y" }],
+ },
+ {
+ id: "t-01",
+ kind: "invocation_transcript",
+ input: "z",
+ expects: [{ check: "tool_used", tool: "y" }],
+ },
+ ],
+ },
+ "duplicate task id",
+ );
+ });
+});
+
+describe("the kernel stays a true leaf", () => {
+ test("it imports nothing beyond the digest and path-name leaves", () => {
+ const text = readFileSync(
+ join(REPO_ROOT, "src", "core", "brain", "skill-rewrite-tasks.ts"),
+ "utf8",
+ );
+ const imports = [...text.matchAll(/^import\s[^;]*?from\s*"([^"]+)"/gm)].map((m) => m[1]!);
+ const allowed = new Set(["../integrity/digest.ts", "./path-constants.ts", "node:path"]);
+ const unexpected = imports.filter((specifier) => !allowed.has(specifier));
+ expect(unexpected).toEqual([]);
+ });
+});
diff --git a/tests/core/brain/skill-rewrite.test.ts b/tests/core/brain/skill-rewrite.test.ts
new file mode 100644
index 00000000..8e4c643b
--- /dev/null
+++ b/tests/core/brain/skill-rewrite.test.ts
@@ -0,0 +1,686 @@
+/**
+ * The rewrite gate kernels (agent-presence, Lane A, A3).
+ *
+ * OSB never calls a model. The envelope builder hands the calling agent
+ * one step per DEV task - held-out ids are refused by construction and
+ * their task text never reaches a prompt before the single held-out
+ * check. The scorer reads structural predicates only and refuses any
+ * submission carrying a self-reported success field, so nothing the
+ * agent claims about its own work can move the metric. Selection is the
+ * preregistered three arms over the receipt's FULL dev membership (a
+ * self-selected subset is not enough evidence, and an unregistered id
+ * is a refusal), the held-out gate runs once on the full held-out
+ * membership and downgrades a promoted candidate on a miss, and every
+ * transcript is bound to the candidate body it was produced against.
+ * The grade record carries ids, scores and check verdicts with the spec
+ * hash - never task text, never transcript text.
+ */
+
+import { describe, expect, test } from "bun:test";
+import { readFileSync } from "node:fs";
+import { join } from "node:path";
+
+import { NEEDS_LLM_STEP } from "../../../src/core/brain/llm-step.ts";
+import {
+ SKILL_BENCH_CHECK,
+ type SkillBenchmarkTask,
+} from "../../../src/core/brain/skill-rewrite-tasks.ts";
+import {
+ SKILL_REWRITE_ROUND_ARM,
+ SKILL_REWRITE_STEP,
+ SKILL_REWRITE_VERDICT,
+ buildRewriteEnvelopes,
+ buildRewriteGradeRecord,
+ buildRewriteHeldoutEnvelopes,
+ checkRewriteHeldout,
+ resolveSkillRewriteMode,
+ runRewriteJudge,
+ scoreRewriteTranscripts,
+ selectRewriteCandidate,
+ type RewriteSubmission,
+ type RewriteTaskScore,
+} from "../../../src/core/brain/skill-rewrite.ts";
+import {
+ buildSkillRewriteSpec,
+ SKILL_REWRITE_METRIC,
+ type SkillRewriteSpec,
+} from "../../../src/core/brain/skill-rewrite-spec.ts";
+import { parseSkillBenchmarkTasks } from "../../../src/core/brain/skill-rewrite-tasks.ts";
+import { sha256Hex } from "../../../src/core/integrity/digest.ts";
+
+const REPO_ROOT = join(import.meta.dir, "..", "..", "..");
+const FIXTURE_PATH = join(REPO_ROOT, "tests", "fixtures", "skill-bench", "example-skill");
+
+const TASKS = parseSkillBenchmarkTasks(
+ JSON.parse(readFileSync(join(FIXTURE_PATH, "tasks.json"), "utf8")),
+ "tasks.json",
+);
+const SPEC = buildSkillRewriteSpec(TASKS.skillName, TASKS);
+const CANDIDATE_BODY =
+ "# example-skill\n\nRewritten instructions: search first, then write, and report the path.";
+
+/** One structurally passing transcript for a task. */
+function passingSubmission(task: SkillBenchmarkTask): RewriteSubmission {
+ const expectations = task.expects.map((expectation) => {
+ switch (expectation.check) {
+ case "tool_used":
+ return { tools: [expectation.tool] };
+ case "artifact_created":
+ return { artifacts: [expectation.path_prefix + "result.md"] };
+ case "step_order":
+ return { steps: [...expectation.steps] };
+ case "forbidden_step":
+ return { steps: ["search"] };
+ case "output_field":
+ return {
+ output:
+ expectation.value_class === "non_empty_string"
+ ? { [expectation.field]: "recorded" }
+ : expectation.value_class === "number"
+ ? { [expectation.field]: 3 }
+ : expectation.value_class === "boolean"
+ ? { [expectation.field]: true }
+ : { [expectation.field]: ["a"] },
+ };
+ }
+ });
+ return {
+ task_id: task.id,
+ steps: expectations.flatMap((entry) => entry.steps ?? ["search"]),
+ tools_used: expectations.flatMap((entry) => entry.tools ?? []),
+ artifacts: expectations.flatMap((entry) => entry.artifacts ?? []),
+ output: Object.assign({}, ...expectations.map((entry) => entry.output ?? {})),
+ };
+}
+
+function failingSubmission(task: SkillBenchmarkTask): RewriteSubmission {
+ return { task_id: task.id, steps: [], tools_used: [], artifacts: [], output: {} };
+}
+
+describe("buildRewriteEnvelopes", () => {
+ test("emits one needs-llm-step per DEV task carrying the body and the task input", () => {
+ const envelopes = buildRewriteEnvelopes(CANDIDATE_BODY, SPEC, TASKS);
+ expect(envelopes.length).toBe(SPEC.devTaskIds.length);
+ for (const envelope of envelopes) {
+ expect(envelope.status).toBe(NEEDS_LLM_STEP);
+ expect(envelope.step).toBe(SKILL_REWRITE_STEP);
+ expect(SPEC.devTaskIds).toContain(String(envelope["task_id"]));
+ expect(String(envelope["round"])).toBe(SKILL_REWRITE_ROUND_ARM.candidate);
+ expect(envelope.prompt).toContain(CANDIDATE_BODY);
+ }
+ const inputs = TASKS.tasks.filter((task) => SPEC.devTaskIds.includes(task.id));
+ for (const task of inputs) {
+ const envelope = envelopes.find((candidate) => candidate["task_id"] === task.id);
+ expect(envelope?.prompt).toContain(task.input);
+ }
+ });
+
+ test("target paths drop into the skill's benchmark rounds tree", () => {
+ const envelopes = buildRewriteEnvelopes(CANDIDATE_BODY, SPEC, TASKS, {
+ round: SKILL_REWRITE_ROUND_ARM.baseline,
+ });
+ for (const envelope of envelopes) {
+ expect(envelope.target_path).toBe(
+ `Brain/skill-benchmarks/example-skill/rounds/baseline/${String(envelope["task_id"])}.json`,
+ );
+ expect(String(envelope["round"])).toBe(SKILL_REWRITE_ROUND_ARM.baseline);
+ }
+ });
+
+ test("envelopes carry the candidate body hash the transcript must echo", () => {
+ const envelopes = buildRewriteEnvelopes(CANDIDATE_BODY, SPEC, TASKS);
+ const heldout = buildRewriteHeldoutEnvelopes(CANDIDATE_BODY, SPEC, TASKS);
+ const expected = sha256Hex(CANDIDATE_BODY);
+ for (const envelope of [...envelopes, ...heldout]) {
+ expect(envelope.candidate_sha256).toBe(expected);
+ // The prompt names the binding too: the executing agent reads the
+ // prompt, not the envelope fields.
+ expect(envelope.prompt).toContain(expected);
+ }
+ });
+
+ test("the baseline round never names the candidate body a held-out task", () => {
+ const envelopes = buildRewriteEnvelopes(CANDIDATE_BODY, SPEC, TASKS);
+ const heldout = TASKS.tasks.filter((task) => SPEC.heldoutTaskIds.includes(task.id));
+ expect(heldout.length).toBeGreaterThan(0);
+ for (const envelope of envelopes) {
+ expect(SPEC.heldoutTaskIds).not.toContain(String(envelope["task_id"]));
+ for (const task of heldout) {
+ expect(envelope.prompt).not.toContain(task.input);
+ }
+ }
+ });
+
+ test("refuses by name when the task set cannot cover the dev receipt", () => {
+ const spec: SkillRewriteSpec = {
+ ...SPEC,
+ devTaskIds: [...SPEC.devTaskIds, "phantom-task"],
+ };
+ expect(() => buildRewriteEnvelopes(CANDIDATE_BODY, spec, TASKS)).toThrow(/phantom-task/);
+ });
+
+ test("refuses by name when the task set hash no longer matches the receipt", () => {
+ expect(() => buildRewriteEnvelopes(CANDIDATE_BODY, SPEC, TASKS)).not.toThrow();
+ const staleSpec: SkillRewriteSpec = { ...SPEC, tasksHash: `${SPEC.tasksHash.slice(0, 8)}dead` };
+ expect(() => buildRewriteEnvelopes(CANDIDATE_BODY, staleSpec, TASKS)).toThrow(/hash/);
+ });
+});
+
+describe("buildRewriteHeldoutEnvelopes", () => {
+ test("emits envelopes for the held-out members only, after promotion", () => {
+ const envelopes = buildRewriteHeldoutEnvelopes(CANDIDATE_BODY, SPEC, TASKS);
+ expect(envelopes.length).toBe(SPEC.heldoutTaskIds.length);
+ for (const envelope of envelopes) {
+ expect(SPEC.heldoutTaskIds).toContain(String(envelope["task_id"]));
+ expect(String(envelope["round"])).toBe(SKILL_REWRITE_ROUND_ARM.heldout);
+ expect(envelope.prompt).toContain(CANDIDATE_BODY);
+ }
+ const heldoutInputs = TASKS.tasks.filter((task) => SPEC.heldoutTaskIds.includes(task.id));
+ for (const task of heldoutInputs) {
+ const envelope = envelopes.find((candidate) => candidate["task_id"] === task.id);
+ expect(envelope?.prompt).toContain(task.input);
+ }
+ });
+});
+
+describe("scoreRewriteTranscripts", () => {
+ test("scores structural predicates and reports failures by check id", () => {
+ const devTasks = TASKS.tasks.filter((task) => SPEC.devTaskIds.includes(task.id));
+ const passing = devTasks.map(passingSubmission);
+ const scores = scoreRewriteTranscripts(passing, TASKS, { arm: "dev", spec: SPEC });
+ expect(scores.length).toBe(devTasks.length);
+ for (const score of scores) expect(score.passed).toBe(true);
+
+ const failing = devTasks.map(failingSubmission);
+ const failedScores = scoreRewriteTranscripts(failing, TASKS, { arm: "dev", spec: SPEC });
+ for (const score of failedScores) {
+ expect(score.passed).toBe(false);
+ // Every check an empty transcript can fail shows up by check id.
+ // The exception is forbidden_step, which an empty transcript
+ // satisfies: the step was not taken.
+ const task = TASKS.tasks.find((candidate) => candidate.id === score.taskId)!;
+ const expectedChecks = task.expects.map((expectation) => expectation.check);
+ for (const check of expectedChecks) {
+ if (check === SKILL_BENCH_CHECK.forbidden_step) {
+ expect(score.failedChecks).not.toContain(check);
+ } else {
+ expect(score.failedChecks).toContain(check);
+ }
+ }
+ }
+ });
+
+ test("a partial pass reports exactly the checks that failed", () => {
+ const toolCheckTask = TASKS.tasks.find(
+ (task) =>
+ SPEC.devTaskIds.includes(task.id) &&
+ task.expects.some((expectation) => expectation.check === "tool_used"),
+ );
+ if (toolCheckTask === undefined) throw new Error("fixture has no tool_used task");
+ const submission = passingSubmission(toolCheckTask);
+ const score = scoreRewriteTranscripts([submission], TASKS, { arm: "dev", spec: SPEC })[0]!;
+ expect(score.passed).toBe(true);
+
+ const withoutTool = { ...submission, tools_used: [] };
+ const broken = scoreRewriteTranscripts([withoutTool], TASKS, { arm: "dev", spec: SPEC })[0]!;
+ expect(broken.passed).toBe(false);
+ expect(broken.failedChecks).toEqual([SKILL_BENCH_CHECK.tool_used]);
+ });
+
+ test("step_order passes on a subsequence, not only an exact list", () => {
+ const orderTask = TASKS.tasks.find(
+ (task) =>
+ SPEC.devTaskIds.includes(task.id) &&
+ task.expects.some((expectation) => expectation.check === "step_order"),
+ );
+ if (orderTask === undefined) throw new Error("fixture has no step_order task");
+ const expectation = orderTask.expects.find((candidate) => candidate.check === "step_order") as {
+ steps: ReadonlyArray<string>;
+ };
+ const withExtraSteps: RewriteSubmission = {
+ task_id: orderTask.id,
+ steps: ["plan", ...expectation.steps, "verify"],
+ tools_used: [],
+ artifacts: [],
+ output: {},
+ };
+ // Only the step_order check is guaranteed here; other checks on the
+ // same task may fail, so assert on the one predicate under test.
+ const score = scoreRewriteTranscripts([withExtraSteps], TASKS, { arm: "dev", spec: SPEC })[0]!;
+ expect(score.failedChecks).not.toContain(SKILL_BENCH_CHECK.step_order);
+ });
+
+ test("refuses malformed submissions by name", () => {
+ const refusing = (submission: unknown, fragment: string): void => {
+ try {
+ scoreRewriteTranscripts([submission], TASKS);
+ } catch (error) {
+ expect((error as Error).message).toContain(fragment);
+ return;
+ }
+ throw new Error(`expected a refusal containing "${fragment}"`);
+ };
+ refusing(null, "submission must be an object");
+ refusing({ steps: [] }, "task_id");
+ refusing({ task_id: "ghost-task" }, "unknown task id");
+ refusing({ task_id: TASKS.tasks[0]!.id, steps: "read" }, "steps must be a string array");
+ refusing({ task_id: TASKS.tasks[0]!.id, tools_used: [7] }, "tools_used must be a string array");
+ refusing({ task_id: TASKS.tasks[0]!.id, artifacts: [{}] }, "artifacts must be a string array");
+ refusing({ task_id: TASKS.tasks[0]!.id, output: "done" }, "output must be an object");
+ refusing({ task_id: TASKS.tasks[0]!.id, success: true }, "self-reported");
+ refusing({ task_id: TASKS.tasks[0]!.id, passed: true }, "self-reported");
+ refusing({ task_id: TASKS.tasks[0]!.id, verdict: true }, "unexpected key");
+ });
+
+ test("refuses a duplicate submission for the same task", () => {
+ const submission = passingSubmission(TASKS.tasks[0]!);
+ expect(() => scoreRewriteTranscripts([submission, submission], TASKS)).toThrow(/twice/);
+ });
+
+ test("the dev arm refuses held-out submissions and the held-out arm refuses dev ones", () => {
+ const heldoutTask = TASKS.tasks.find((task) => SPEC.heldoutTaskIds.includes(task.id))!;
+ const devTask = TASKS.tasks.find((task) => SPEC.devTaskIds.includes(task.id))!;
+ expect(() =>
+ scoreRewriteTranscripts([passingSubmission(heldoutTask)], TASKS, { arm: "dev", spec: SPEC }),
+ ).toThrow(/held-out/);
+ expect(() =>
+ scoreRewriteTranscripts([passingSubmission(devTask)], TASKS, { arm: "heldout", spec: SPEC }),
+ ).toThrow(/dev/);
+ });
+
+ test("with the current candidate hash required, a bound transcript scores and stale or missing bindings refuse", () => {
+ const devTask = TASKS.tasks.find((task) => SPEC.devTaskIds.includes(task.id))!;
+ const candidateHash = sha256Hex(CANDIDATE_BODY);
+ const bound: RewriteSubmission = {
+ ...passingSubmission(devTask),
+ candidate_sha256: candidateHash,
+ };
+ const scores = scoreRewriteTranscripts([bound], TASKS, {
+ arm: "dev",
+ spec: SPEC,
+ candidateHash,
+ });
+ expect(scores[0]?.passed).toBe(true);
+
+ // A transcript left over from a previous candidate body never gates
+ // this one.
+ const stale: RewriteSubmission = {
+ ...passingSubmission(devTask),
+ candidate_sha256: "0".repeat(64),
+ };
+ expect(() =>
+ scoreRewriteTranscripts([stale], TASKS, { arm: "dev", spec: SPEC, candidateHash }),
+ ).toThrow(/does not match the current candidate body/);
+
+ const unbound = passingSubmission(devTask);
+ expect(() =>
+ scoreRewriteTranscripts([unbound], TASKS, { arm: "dev", spec: SPEC, candidateHash }),
+ ).toThrow(/candidate_sha256/);
+ });
+
+ test("candidate_sha256 is shape-checked even when no binding is enforced", () => {
+ const devTask = TASKS.tasks.find((task) => SPEC.devTaskIds.includes(task.id))!;
+ const malformed: RewriteSubmission = { ...passingSubmission(devTask), candidate_sha256: "zz" };
+ expect(() => scoreRewriteTranscripts([malformed], TASKS)).toThrow(/candidate_sha256/);
+ const wellFormed: RewriteSubmission = {
+ ...passingSubmission(devTask),
+ candidate_sha256: sha256Hex(CANDIDATE_BODY),
+ };
+ expect(() => scoreRewriteTranscripts([wellFormed], TASKS)).not.toThrow();
+ });
+
+ test("scores come back sorted by task id", () => {
+ const devTasks = TASKS.tasks.filter((task) => SPEC.devTaskIds.includes(task.id));
+ const submissions = devTasks.map(passingSubmission).toSorted(() => -1);
+ const scores = scoreRewriteTranscripts(submissions, TASKS, { arm: "dev", spec: SPEC });
+ const ids = scores.map((score) => score.taskId);
+ expect(ids).toEqual([...ids].toSorted());
+ });
+});
+
+describe("selectRewriteCandidate", () => {
+ const devTasks = TASKS.tasks.filter((task) => SPEC.devTaskIds.includes(task.id));
+
+ test("a strict beat beyond the margin with n met promotes", () => {
+ const baseline = scoreRewriteTranscripts(devTasks.map(failingSubmission), TASKS, {
+ arm: "dev",
+ spec: SPEC,
+ });
+ const candidate = scoreRewriteTranscripts(devTasks.map(passingSubmission), TASKS, {
+ arm: "dev",
+ spec: SPEC,
+ });
+ const outcome = selectRewriteCandidate(baseline, candidate, SPEC);
+ expect(outcome.verdict).toBe(SKILL_REWRITE_VERDICT.promote);
+ expect(outcome.candidateRate).toBeGreaterThan(outcome.baselineRate);
+ });
+
+ test("a tie holds", () => {
+ const baseline = scoreRewriteTranscripts(devTasks.map(passingSubmission), TASKS, {
+ arm: "dev",
+ spec: SPEC,
+ });
+ const candidate = scoreRewriteTranscripts(devTasks.map(passingSubmission), TASKS, {
+ arm: "dev",
+ spec: SPEC,
+ });
+ const outcome = selectRewriteCandidate(baseline, candidate, SPEC);
+ expect(outcome.verdict).toBe(SKILL_REWRITE_VERDICT.hold);
+ expect(outcome.baselineRate).toBe(outcome.candidateRate);
+ });
+
+ test("a beat under the margin holds", () => {
+ const baseline = scoreRewriteTranscripts(devTasks.map(passingSubmission), TASKS, {
+ arm: "dev",
+ spec: SPEC,
+ });
+ // Drop exactly one pass: a small rate loss that must stay under the
+ // margin for a task set this size.
+ const partial = devTasks.map((task, index) =>
+ index === 0 ? failingSubmission(task) : passingSubmission(task),
+ );
+ const candidate = scoreRewriteTranscripts(partial, TASKS, { arm: "dev", spec: SPEC });
+ const outcome = selectRewriteCandidate(baseline, candidate, SPEC);
+ expect(outcome.verdict).toBe(SKILL_REWRITE_VERDICT.hold);
+ expect(outcome.candidateRate).toBeLessThan(outcome.baselineRate);
+ });
+
+ test("a short dev n is its own arm", () => {
+ const baseline = scoreRewriteTranscripts(devTasks.slice(0, 1).map(passingSubmission), TASKS, {
+ arm: "dev",
+ spec: SPEC,
+ });
+ const candidate = scoreRewriteTranscripts(devTasks.slice(0, 1).map(passingSubmission), TASKS, {
+ arm: "dev",
+ spec: SPEC,
+ });
+ const outcome = selectRewriteCandidate(baseline, candidate, SPEC);
+ expect(outcome.verdict).toBe(SKILL_REWRITE_VERDICT.not_enough_evidence);
+ });
+
+ test("a candidate promoting on a self-selected dev subset is not_enough_evidence", () => {
+ // The A-1 exploit: baseline runs the whole receipted dev arm, the
+ // candidate runs only its two easiest tasks. n = 2 meets the floor
+ // and the subset rate is 1.0, but five receipted dev tasks were
+ // never attempted, so the preregistered comparison cannot be
+ // computed and the gate must not promote.
+ const baseline = scoreRewriteTranscripts(devTasks.map(failingSubmission), TASKS, {
+ arm: "dev",
+ spec: SPEC,
+ });
+ const candidate = scoreRewriteTranscripts(devTasks.slice(0, 2).map(passingSubmission), TASKS, {
+ arm: "dev",
+ spec: SPEC,
+ });
+ const outcome = selectRewriteCandidate(baseline, candidate, SPEC);
+ expect(outcome.verdict).toBe(SKILL_REWRITE_VERDICT.not_enough_evidence);
+ });
+
+ test("a dev arm missing one receipted member is not_enough_evidence even with n met", () => {
+ const baseline = scoreRewriteTranscripts(devTasks.map(failingSubmission), TASKS, {
+ arm: "dev",
+ spec: SPEC,
+ });
+ const candidate = scoreRewriteTranscripts(devTasks.slice(1).map(passingSubmission), TASKS, {
+ arm: "dev",
+ spec: SPEC,
+ });
+ const outcome = selectRewriteCandidate(baseline, candidate, SPEC);
+ expect(outcome.verdict).toBe(SKILL_REWRITE_VERDICT.not_enough_evidence);
+ });
+
+ test("a score outside the receipt's dev membership refuses the selection by name", () => {
+ // Reachable only by bypassing the arm-checked scorer; the selection
+ // refuses it the way the held-out gate refuses a non-member, rather
+ // than letting an unregistered id move the metric.
+ const heldoutTask = TASKS.tasks.find((task) => SPEC.heldoutTaskIds.includes(task.id))!;
+ const baseline = scoreRewriteTranscripts(devTasks.map(passingSubmission), TASKS, {
+ arm: "dev",
+ spec: SPEC,
+ });
+ const strayCandidate = scoreRewriteTranscripts(
+ [...devTasks.map(passingSubmission), passingSubmission(heldoutTask)],
+ TASKS,
+ );
+ expect(() => selectRewriteCandidate(baseline, strayCandidate, SPEC)).toThrow(
+ /not a dev member/,
+ );
+ const strayBaseline = scoreRewriteTranscripts([passingSubmission(heldoutTask)], TASKS);
+ expect(() => selectRewriteCandidate(strayBaseline, baseline, SPEC)).toThrow(/not a dev member/);
+ });
+});
+
+// Rates on this synthetic 8-id dev arm are exact binary fractions, so
+// the boundary case is bit-exact by construction: baseline 2/8 = 0.25,
+// candidate 4/8 = 0.5, margin 0.25, and 0.25 + 0.25 is exactly 0.5 in
+// IEEE doubles. A `>` relaxed to `>=` promotes here; nothing else in
+// the suite lands on the boundary.
+const GATE_IDS = [
+ "gate-01",
+ "gate-02",
+ "gate-03",
+ "gate-04",
+ "gate-05",
+ "gate-06",
+ "gate-07",
+ "gate-08",
+];
+
+const gateScore = (id: string, passed: boolean): RewriteTaskScore => ({
+ taskId: id,
+ passed,
+ failedChecks: [],
+});
+
+const gateArm = (passCount: number): ReadonlyArray<RewriteTaskScore> =>
+ GATE_IDS.map((id, index) => gateScore(id, index < passCount));
+
+const gateSpec = (margin: number): SkillRewriteSpec => ({
+ ...SPEC,
+ devTaskIds: GATE_IDS,
+ requiredMargin: margin,
+});
+
+describe("selectRewriteCandidate strict-beat boundary", () => {
+ test("a beat exactly at the required margin holds", () => {
+ const outcome = selectRewriteCandidate(gateArm(2), gateArm(4), gateSpec(0.25));
+ expect(outcome.baselineRate).toBe(0.25);
+ expect(outcome.candidateRate).toBe(0.5);
+ expect(outcome.verdict).toBe(SKILL_REWRITE_VERDICT.hold);
+ });
+
+ test("a real beat under the margin holds", () => {
+ const outcome = selectRewriteCandidate(gateArm(2), gateArm(3), gateSpec(0.25));
+ expect(outcome.candidateRate).toBeGreaterThan(outcome.baselineRate);
+ expect(outcome.verdict).toBe(SKILL_REWRITE_VERDICT.hold);
+ });
+
+ test("a beat beyond the margin promotes", () => {
+ const outcome = selectRewriteCandidate(gateArm(2), gateArm(5), gateSpec(0.25));
+ expect(outcome.verdict).toBe(SKILL_REWRITE_VERDICT.promote);
+ });
+});
+
+describe("checkRewriteHeldout", () => {
+ const heldoutTasks = TASKS.tasks.filter((task) => SPEC.heldoutTaskIds.includes(task.id));
+
+ test("a full held-out pass promotes", () => {
+ const scores = scoreRewriteTranscripts(heldoutTasks.map(passingSubmission), TASKS, {
+ arm: "heldout",
+ spec: SPEC,
+ });
+ expect(checkRewriteHeldout(scores, SPEC)).toBe(SKILL_REWRITE_VERDICT.promote);
+ });
+
+ test("a held-out miss downgrades to hold", () => {
+ const scores = scoreRewriteTranscripts(
+ heldoutTasks.map((task, index) =>
+ index === 0 ? failingSubmission(task) : passingSubmission(task),
+ ),
+ TASKS,
+ { arm: "heldout", spec: SPEC },
+ );
+ expect(checkRewriteHeldout(scores, SPEC)).toBe(SKILL_REWRITE_VERDICT.hold);
+ });
+
+ test("a partial held-out pass refuses: every held-out member must be scored", () => {
+ // A-2: one passing transcript for the first two members; t-05 was
+ // never run. The one-shot check is incomplete, and an incomplete
+ // check refuses by name (naming the unscored member) instead of
+ // recording a hold the check never earned.
+ const scores = scoreRewriteTranscripts(heldoutTasks.slice(0, 2).map(passingSubmission), TASKS, {
+ arm: "heldout",
+ spec: SPEC,
+ });
+ expect(() => checkRewriteHeldout(scores, SPEC)).toThrow(/t-05/);
+ expect(() => checkRewriteHeldout(scores, SPEC)).toThrow(/incomplete/);
+ });
+
+ test("a dev score array handed to the held-out gate refuses by name", () => {
+ const devTask = TASKS.tasks.find((task) => SPEC.devTaskIds.includes(task.id))!;
+ const devScores = scoreRewriteTranscripts([passingSubmission(devTask)], TASKS, {
+ arm: "dev",
+ spec: SPEC,
+ });
+ expect(() => checkRewriteHeldout(devScores, SPEC)).toThrow(/not a held-out member/);
+ });
+
+ test("no held-out evidence refuses the check rather than passing or holding quietly", () => {
+ // An empty arm is the degenerate partial coverage: zero of the
+ // receipted members were scored, so the one-shot check refuses
+ // instead of issuing any verdict.
+ expect(() => checkRewriteHeldout([], SPEC)).toThrow(/incomplete/);
+ });
+});
+
+describe("resolveSkillRewriteMode", () => {
+ test("gated and iterative are accepted, absent resolves to gated", () => {
+ expect(resolveSkillRewriteMode(undefined)).toBe("gated");
+ expect(resolveSkillRewriteMode("")).toBe("gated");
+ expect(resolveSkillRewriteMode(" ")).toBe("gated");
+ expect(resolveSkillRewriteMode("gated")).toBe("gated");
+ expect(resolveSkillRewriteMode("iterative")).toBe("iterative");
+ });
+
+ test("an unknown value is a named error", () => {
+ expect(() => resolveSkillRewriteMode("turbo")).toThrow(/turbo/);
+ });
+});
+
+describe("runRewriteJudge", () => {
+ test("skipped without a command", () => {
+ expect(runRewriteJudge(undefined, { metric: SKILL_REWRITE_METRIC }).status).toBe("skipped");
+ });
+
+ test("a failing command is an error status, never a throw", () => {
+ const outcome = runRewriteJudge("exit 3", { metric: SKILL_REWRITE_METRIC });
+ expect(outcome.status).toBe("error");
+ });
+
+ test("advisory verdicts never move the metric", () => {
+ // The judge's verdict field is reported, never folded into selection:
+ // selectRewriteCandidate takes only RewriteTaskScore arrays and the
+ // spec, so no judge output type can reach it. Pinned by a run whose
+ // judge output contradicts the deterministic scores.
+ const devTasks = TASKS.tasks.filter((task) => SPEC.devTaskIds.includes(task.id));
+ const baseline = scoreRewriteTranscripts(devTasks.map(failingSubmission), TASKS, {
+ arm: "dev",
+ spec: SPEC,
+ });
+ const candidate = scoreRewriteTranscripts(devTasks.map(passingSubmission), TASKS, {
+ arm: "dev",
+ spec: SPEC,
+ });
+ expect(selectRewriteCandidate(baseline, candidate, SPEC).verdict).toBe(
+ SKILL_REWRITE_VERDICT.promote,
+ );
+ });
+});
+
+describe("buildRewriteGradeRecord", () => {
+ test("carries ids, scores and check verdicts with the spec hash", () => {
+ const devTasks = TASKS.tasks.filter((task) => SPEC.devTaskIds.includes(task.id));
+ const heldoutTasks = TASKS.tasks.filter((task) => SPEC.heldoutTaskIds.includes(task.id));
+ const baseline = scoreRewriteTranscripts(devTasks.map(failingSubmission), TASKS, {
+ arm: "dev",
+ spec: SPEC,
+ });
+ const candidate = scoreRewriteTranscripts(devTasks.map(passingSubmission), TASKS, {
+ arm: "dev",
+ spec: SPEC,
+ });
+ const selection = selectRewriteCandidate(baseline, candidate, SPEC);
+ const heldout = scoreRewriteTranscripts(heldoutTasks.map(passingSubmission), TASKS, {
+ arm: "heldout",
+ spec: SPEC,
+ });
+ const verdict = checkRewriteHeldout(heldout, SPEC);
+ // The candidate binding (review round-2, M1 residual R1): the final
+ // promote rides a staging, and the record carries the sha-256 the
+ // staged proposal stamps, so a promote grade can only bless the exact
+ // document it was earned against.
+ const candidateSha256 = sha256Hex(CANDIDATE_BODY);
+ const record = buildRewriteGradeRecord({
+ skill: TASKS.skillName,
+ spec: SPEC,
+ specHash: "spec-hash-value",
+ selection,
+ heldoutVerdict: verdict,
+ devScores: candidate,
+ heldoutScores: heldout,
+ candidateSha256,
+ });
+ expect(record.skill).toBe(TASKS.skillName);
+ expect(record.spec_hash).toBe("spec-hash-value");
+ expect(record.metric).toBe(SKILL_REWRITE_METRIC);
+ expect(record.verdict).toBe(SKILL_REWRITE_VERDICT.promote);
+ expect(record.tasks_hash).toBe(SPEC.tasksHash);
+ expect(record.candidate_sha256).toBe(candidateSha256);
+ expect(record.dev.map((row) => row.task_id).toSorted()).toEqual(
+ [...SPEC.devTaskIds].toSorted(),
+ );
+ expect(record.held_out.map((row) => row.task_id).toSorted()).toEqual(
+ [...SPEC.heldoutTaskIds].toSorted(),
+ );
+ for (const row of record.dev) {
+ expect(typeof row.passed).toBe("boolean");
+ expect(Array.isArray(row.failed_checks)).toBe(true);
+ }
+ });
+
+ test("the serialized record never carries task or transcript text", () => {
+ const devTasks = TASKS.tasks.filter((task) => SPEC.devTaskIds.includes(task.id));
+ const candidate = scoreRewriteTranscripts(devTasks.map(passingSubmission), TASKS, {
+ arm: "dev",
+ spec: SPEC,
+ });
+ const record = buildRewriteGradeRecord({
+ skill: TASKS.skillName,
+ spec: SPEC,
+ specHash: "spec-hash-value",
+ selection: selectRewriteCandidate(candidate, candidate, SPEC),
+ heldoutVerdict: SKILL_REWRITE_VERDICT.hold,
+ devScores: candidate,
+ heldoutScores: [],
+ candidateSha256: sha256Hex(CANDIDATE_BODY),
+ });
+ const serialized = JSON.stringify(record);
+ for (const task of TASKS.tasks) {
+ // Task input text, down to a distinguishing fragment, never ships.
+ const fragment = task.input.slice(0, 24);
+ expect(serialized).not.toContain(fragment);
+ }
+ // Transcript step and tool names are never echoed either: only the
+ // check ids, the boolean verdicts and the rates travel.
+ expect(serialized).not.toContain("note_write");
+ expect(serialized).not.toContain("bulk_delete");
+ // The candidate binding is a sha-256, not content: adding the hash to
+ // the payload must not smuggle the candidate body in beside it. A
+ // hold round (this one) stages nothing, but the field rides the same
+ // assembly, so the no-text invariant is pinned over the extended
+ // payload shape.
+ expect(record.candidate_sha256).toBe(sha256Hex(CANDIDATE_BODY));
+ expect(record.candidate_sha256).toMatch(/^[0-9a-f]{64}$/);
+ expect(serialized).not.toContain(CANDIDATE_BODY.slice(0, 24));
+ });
+});
diff --git a/tests/core/brain/sync-lockfile.test.ts b/tests/core/brain/sync-lockfile.test.ts
index a9a0d581..3863ee83 100644
--- a/tests/core/brain/sync-lockfile.test.ts
+++ b/tests/core/brain/sync-lockfile.test.ts
@@ -309,11 +309,11 @@ describe("every module that takes a lock is under a scanned root", () => {
/**
* Declared lock sites, each with the vault-relative root
* {@link lockScanRoots} reaches it through. Verified against the path
- * builders: every entry resolves under `Brain/` except the four that
+ * builders: every entry resolves under `Brain/` except the five that
* live in the derived-store directory - the shared checkpoint substrate
* (both the ingest and the session-import lanes lock through it), the
- * ingest content manifest, the session import ledger, and the session
- * mining ledger.
+ * ingest content manifest, the session import ledger, the session
+ * mining ledger, and the lessons-approval ledger (t_1e952e43).
*/
const DECLARED: ReadonlyMap<string, string> = new Map([
["core/brain/architect/generate.ts", "Brain"],
@@ -325,6 +325,9 @@ describe("every module that takes a lock is under a scanned root", () => {
["core/brain/health/remediation.ts", "Brain"],
["core/brain/idempotency-ledger.ts", "Brain"],
["core/brain/ingest/content-manifest.ts", ".open-second-brain"],
+ // the lessons-approvals ledger read-modify-write (t_1e952e43), the
+ // fifth derived-store lock site
+ ["core/brain/lessons-promotion.ts", ".open-second-brain"],
["core/brain/lineage/ledger.ts", "Brain"],
["core/brain/metrics.ts", "Brain"],
["core/brain/link-graph/hallways.ts", "Brain"],
diff --git a/tests/core/brain/writeback-contract.test.ts b/tests/core/brain/writeback-contract.test.ts
index e145bdbb..f9b40218 100644
--- a/tests/core/brain/writeback-contract.test.ts
+++ b/tests/core/brain/writeback-contract.test.ts
@@ -7,9 +7,11 @@ import {
DEFAULT_BEGIN_MARKER,
DEFAULT_END_MARKER,
} from "../../../src/core/install/managed-block.ts";
+import { RULES_BLOCK_MARKERS } from "../../../src/core/install/rules-block.ts";
import {
AGENT_INSTRUCTION_FILES,
+ CANONICAL_WRITEBACK_BLOCK_BODY,
HOST_INSTRUCTION_PRECEDENCE,
WRITEBACK_CONTRACT_FINDING,
WRITEBACK_CONTRACT_REQUIREMENTS,
@@ -558,3 +560,61 @@ describe("resolveShadowedInstructionContracts", () => {
).toEqual(["claude-code"]);
});
});
+
+describe("CANONICAL_WRITEBACK_BLOCK_BODY", () => {
+ test("satisfies every gate clause, so the installer can never ship a non-conforming block", () => {
+ expect([...missingWritebackGateClauses(CANONICAL_WRITEBACK_BLOCK_BODY)]).toEqual([]);
+ });
+
+ test("merges the cross-project-pointer usage content with the gate clauses", () => {
+ // The four usage surfaces K2 names, in the checker's own vocabulary.
+ expect(CANONICAL_WRITEBACK_BLOCK_BODY).toContain("Brain/active.md");
+ expect(CANONICAL_WRITEBACK_BLOCK_BODY).toContain("brain_feedback");
+ expect(CANONICAL_WRITEBACK_BLOCK_BODY).toContain("brain_apply_evidence");
+ expect(CANONICAL_WRITEBACK_BLOCK_BODY).toContain("dream");
+ });
+
+ test("is static text: no template placeholders, no vault path, no memory content", () => {
+ expect(CANONICAL_WRITEBACK_BLOCK_BODY).not.toMatch(/\{\{?/);
+ expect(CANONICAL_WRITEBACK_BLOCK_BODY).not.toContain("<absolute");
+ expect(CANONICAL_WRITEBACK_BLOCK_BODY).not.toMatch(/\/(home|Users|mnt)\//);
+ });
+
+ test("a file carrying only the lessons pair still grades missing-block", () => {
+ // The audit reads only the settled default markers; a sibling block
+ // with its own spelling is invisible to the contract by design.
+ const lessonsOnly = [
+ RULES_BLOCK_MARKERS.lessons.begin,
+ "- prefer small commits",
+ RULES_BLOCK_MARKERS.lessons.end,
+ ].join("\n");
+ const path = join(tmp, "AGENTS.md");
+ writeFileSync(path, `# W\n\n${lessonsOnly}\n`);
+ expect(auditWritebackContractFile(path).finding).toBe(WRITEBACK_CONTRACT_FINDING.missingBlock);
+ });
+
+ test("a file with both blocks is graded by its own pair alone", () => {
+ const both = [
+ CONFORMING_BLOCK,
+ RULES_BLOCK_MARKERS.lessons.begin,
+ "- prefer small commits",
+ RULES_BLOCK_MARKERS.lessons.end,
+ ].join("\n");
+ const path = join(tmp, "AGENTS.md");
+ writeFileSync(path, `# W\n\n${both}\n`);
+ expect(auditWritebackContractFile(path).finding).toBe(WRITEBACK_CONTRACT_FINDING.conforming);
+ });
+
+ test("the canonical body renders a conforming block through the settled markers", () => {
+ const document = [
+ DEFAULT_BEGIN_MARKER,
+ CANONICAL_WRITEBACK_BLOCK_BODY,
+ DEFAULT_END_MARKER,
+ ].join("\n");
+ const path = join(tmp, "AGENTS.md");
+ writeFileSync(path, `${document}\n`);
+ const audit = auditWritebackContractFile(path);
+ expect(audit.finding).toBe(WRITEBACK_CONTRACT_FINDING.conforming);
+ expect(audit.missing).toEqual([]);
+ });
+});
diff --git a/tests/core/install/adapters/codex-chatgpt-note.test.ts b/tests/core/install/adapters/codex-chatgpt-note.test.ts
new file mode 100644
index 00000000..ca8e3480
--- /dev/null
+++ b/tests/core/install/adapters/codex-chatgpt-note.test.ts
@@ -0,0 +1,212 @@
+/**
+ * The codex adapter names ChatGPT desktop in exactly one place: the
+ * detect note, when the codex binary is absent and the config.toml merge
+ * is the lane that applies.
+ *
+ * ChatGPT desktop has no MCP registration of its own - it reads the same
+ * `$CODEX_HOME/config.toml` the codex target writes. The design settled
+ * on naming it as a reader of that shared config, not on a target of its
+ * own: the target vocabulary is frozen, and a second target for one file
+ * would claim bytes the codex target owns and report them as drift. So
+ * this file pins the whole surface the wave lands - the note and the
+ * docs rows - and refuses the regressions the review gate names: a
+ * detection or status change, and a new install target id.
+ *
+ * The docs assertions at the bottom are content checks over README.md
+ * and install/codex.md, so a docs row that drops the install command or
+ * the shared-config naming fails here rather than drifting silently.
+ */
+
+import { afterEach, beforeEach, describe, expect, test } from "bun:test";
+import { mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from "node:fs";
+import { tmpdir } from "node:os";
+import { join } from "node:path";
+
+import {
+ codexAdapter,
+ resetCodexRunner,
+ setCodexRunner,
+ type CodexRunner,
+} from "../../../../src/core/install/adapters/codex.ts";
+import { OSB_KEY_FULL, OSB_KEY_WRITER } from "../../../../src/core/install/json-merge.ts";
+import { INSTALL_TARGET_ID, INSTALL_TARGET_IDS } from "../../../../src/core/runtime/host-facts.ts";
+import type { InstallEnv } from "../../../../src/core/install/types.ts";
+
+let vault: string;
+let home: string;
+
+beforeEach(() => {
+ vault = mkdtempSync(join(tmpdir(), "osb-codex-note-v-"));
+ home = mkdtempSync(join(tmpdir(), "osb-codex-note-h-"));
+});
+
+afterEach(() => {
+ resetCodexRunner();
+ for (const dir of [vault, home]) {
+ try {
+ rmSync(dir, { recursive: true, force: true });
+ } catch {
+ // temp cleanup is best-effort
+ }
+ }
+});
+
+function env(overrides: Record<string, string> = {}): InstallEnv {
+ return {
+ vault,
+ home,
+ cwd: home,
+ env: { VAULT_AGENT_NAME: "claude-vps", VAULT_TIMEZONE: "UTC", ...overrides },
+ now: new Date("2026-11-02T12:00:00.000Z"),
+ };
+}
+
+/** A runner whose binary does not exist; running it is a test failure. */
+const absentCodex: CodexRunner = {
+ available: () => false,
+ run: () => {
+ throw new Error("the adapter must not spawn codex when it reported the binary absent");
+ },
+};
+
+/** A runner that reports the binary present; detect never spawns it. */
+const presentCodex: CodexRunner = {
+ available: () => true,
+ run: () => {
+ throw new Error("detect must not spawn codex; only apply and verify do");
+ },
+};
+
+/** The file the config merge writes: both Open Second Brain tables declared. */
+function writeConfigWithBothTables(): void {
+ mkdirSync(join(home, ".codex"), { recursive: true });
+ writeFileSync(
+ join(home, ".codex", "config.toml"),
+ [
+ `[mcp_servers.${OSB_KEY_FULL}]`,
+ 'command = "o2b"',
+ 'args = ["mcp"]',
+ "",
+ `[mcp_servers.${OSB_KEY_WRITER}]`,
+ 'command = "o2b"',
+ 'args = ["mcp"]',
+ "",
+ ].join("\n"),
+ );
+}
+
+/** Half an install: one table declared, the other missing. */
+function writeConfigWithOneTable(): void {
+ mkdirSync(join(home, ".codex"), { recursive: true });
+ writeFileSync(
+ join(home, ".codex", "config.toml"),
+ [`[mcp_servers.${OSB_KEY_FULL}]`, 'command = "o2b"', 'args = ["mcp"]', ""].join("\n"),
+ );
+}
+
+// ---------- The detect note ----------
+
+describe("the codex detect note names ChatGPT desktop when the binary is absent", () => {
+ test("with a config.toml present, the note names ChatGPT desktop and the config merge", () => {
+ writeConfigWithBothTables();
+ setCodexRunner(absentCodex);
+ const result = codexAdapter.detect(env());
+ const note = result.notes.join(" ");
+ expect(note).toContain("config.toml merge");
+ expect(note).toContain("ChatGPT desktop");
+ });
+
+ test("with no config yet, the note names ChatGPT desktop all the same", () => {
+ // A ChatGPT-desktop-only operator may not have a config.toml yet;
+ // the merge lane is still the one that would apply, and this note is
+ // the discovery surface that tells them the codex target serves
+ // their app.
+ setCodexRunner(absentCodex);
+ const result = codexAdapter.detect(env());
+ expect(result.status).toBe("not-installed");
+ expect(result.notes.join(" ")).toContain("ChatGPT desktop");
+ });
+
+ test("with the binary present, the note is unchanged", () => {
+ setCodexRunner(presentCodex);
+ const result = codexAdapter.detect(env());
+ expect(result.notes).toEqual(["codex CLI present; registration goes through `codex mcp add`"]);
+ });
+});
+
+// ---------- Statuses are unchanged ----------
+
+describe("detect statuses are unchanged by the ChatGPT naming", () => {
+ const FILE_STATES: ReadonlyArray<{
+ readonly label: string;
+ readonly setup: () => void;
+ readonly expected: "not-installed" | "drift" | "installed";
+ }> = [
+ { label: "no config file", setup: () => undefined, expected: "not-installed" },
+ {
+ label: "one server table declared",
+ setup: () => writeConfigWithOneTable(),
+ expected: "drift",
+ },
+ {
+ label: "both server tables declared",
+ setup: () => writeConfigWithBothTables(),
+ expected: "installed",
+ },
+ ];
+
+ for (const lane of [
+ { name: "binary present", runner: presentCodex },
+ { name: "binary absent", runner: absentCodex },
+ ]) {
+ for (const state of FILE_STATES) {
+ test(`${lane.name} + ${state.label} keeps status ${state.expected}`, () => {
+ setCodexRunner(lane.runner);
+ state.setup();
+ expect(codexAdapter.detect(env()).status).toBe(state.expected);
+ });
+ }
+ }
+});
+
+// ---------- The target vocabulary stays frozen ----------
+
+describe("ChatGPT desktop is a reader of the shared config, not a target", () => {
+ test("no ChatGPT install target id exists and codex keeps its own", () => {
+ expect("chatgptDesktop" in INSTALL_TARGET_ID).toBe(false);
+ expect(Object.values(INSTALL_TARGET_ID).join(" ").toLowerCase()).not.toContain("chatgpt");
+ expect(INSTALL_TARGET_IDS.join(" ").toLowerCase()).not.toContain("chatgpt");
+ expect(codexAdapter.target).toBe("codex");
+ });
+});
+
+// ---------- The docs rows (D2) ----------
+
+describe("the docs name ChatGPT desktop and the codex install command", () => {
+ const repoRoot = join(import.meta.dir, "..", "..", "..", "..");
+
+ test("the README supported-clients row names ChatGPT desktop, the command and the guide", () => {
+ const readme = readFileSync(join(repoRoot, "README.md"), "utf8");
+ const rows = readme.split("\n").filter((line) => line.includes("ChatGPT desktop"));
+ expect(rows.length).toBeGreaterThan(0);
+ expect(
+ rows.some(
+ (line) =>
+ line.includes("o2b install --target codex --apply") && line.includes("install/codex.md"),
+ ),
+ ).toBe(true);
+ });
+
+ test("the codex guide carries a ChatGPT desktop section covering config, install and uninstall", () => {
+ const guide = readFileSync(join(repoRoot, "install", "codex.md"), "utf8");
+ const lines = guide.split("\n");
+ const headingIndex = lines.findIndex((line) => line.trim() === "## ChatGPT desktop");
+ expect(headingIndex).toBeGreaterThanOrEqual(0);
+ const nextHeading = lines.findIndex((line, i) => i > headingIndex && line.startsWith("## "));
+ const end = nextHeading === -1 ? lines.length : nextHeading;
+ const section = lines.slice(headingIndex, end).join("\n");
+ expect(section).toContain("$CODEX_HOME/config.toml");
+ expect(section).toContain("o2b install --target codex --apply");
+ expect(section).toContain("o2b uninstall --target codex");
+ });
+});
diff --git a/tests/core/install/instruction-block.test.ts b/tests/core/install/instruction-block.test.ts
new file mode 100644
index 00000000..21860fba
--- /dev/null
+++ b/tests/core/install/instruction-block.test.ts
@@ -0,0 +1,479 @@
+/**
+ * Tests for the brain-usage block installer step (plan K2, t_ba41a78a).
+ *
+ * The installer maps each install target to the agent-instruction file
+ * its host reads, plans a pure preview (vault-root path, exists, changed,
+ * diff, note), and applies under an approved-preview binding: the apply
+ * re-derives the plan from the live disk and refuses to write anything
+ * else. Every write routes through the shared rules-block writer, and a
+ * successful apply records the ownership lock this module also owns.
+ */
+
+import { afterEach, beforeEach, describe, expect, test } from "bun:test";
+import {
+ existsSync,
+ mkdirSync,
+ mkdtempSync,
+ readFileSync,
+ readdirSync,
+ rmSync,
+ statSync,
+ symlinkSync,
+ writeFileSync,
+} from "node:fs";
+import { tmpdir } from "node:os";
+import { basename, join } from "node:path";
+
+import {
+ auditWritebackContractFile,
+ CANONICAL_WRITEBACK_BLOCK_BODY,
+} from "../../../src/core/brain/writeback-contract.ts";
+import { INSTALL_TARGET_IDS, type InstallTargetId } from "../../../src/core/runtime/host-facts.ts";
+import {
+ DEFAULT_BEGIN_MARKER,
+ DEFAULT_END_MARKER,
+} from "../../../src/core/install/managed-block.ts";
+import {
+ INSTRUCTION_BLOCK_LOCK_FILE,
+ applyInstructionBlock,
+ clearInstructionBlock,
+ instructionBlockLockPath,
+ instructionBlockTargetFor,
+ planInstructionBlock,
+ readInstructionBlockLock,
+ recordInstructionBlock,
+} from "../../../src/core/install/instruction-block.ts";
+import { HOST_INSTRUCTION_PRECEDENCE } from "../../../src/core/brain/writeback-contract.ts";
+import {
+ RULES_BLOCK_ERROR_KIND,
+ RULES_BLOCK_ID,
+ RULES_BLOCK_MARKERS,
+ RulesBlockError,
+ writeRulesBlock,
+} from "../../../src/core/install/rules-block.ts";
+import type { InstallEnv } from "../../../src/core/install/types.ts";
+
+let tmp: string;
+
+beforeEach(() => {
+ tmp = mkdtempSync(join(tmpdir(), "osb-instruction-block-"));
+});
+
+afterEach(() => {
+ rmSync(tmp, { recursive: true, force: true });
+});
+
+const APPLIED_AT_MS = 1_700_000_000_000;
+
+function envFor(vault: string): InstallEnv {
+ return {
+ vault,
+ home: tmp,
+ cwd: tmp,
+ env: {},
+ now: new Date(APPLIED_AT_MS),
+ };
+}
+
+const OPERATOR = "# project notes\n\nHand-written content.\n";
+
+/** The non-conforming body a manual install from the older docs pasted. */
+const DOCS_SNIPPET_BODY = [
+ "## Open Second Brain",
+ "",
+ "This project shares an Obsidian-compatible vault with an active",
+ "observing-memory layer. At session start, read Brain/active.md.",
+].join("\n");
+
+const DOCS_SNIPPET_FILE = [
+ OPERATOR,
+ DEFAULT_BEGIN_MARKER,
+ DOCS_SNIPPET_BODY,
+ DEFAULT_END_MARKER,
+ "",
+].join("\n");
+
+/** Backup siblings of `AGENTS.md` currently in the directory. */
+function backupsOf(name: string): string[] {
+ return readdirSync(tmp)
+ .filter((entry) => entry.startsWith(`${name}.bak.`))
+ .toSorted();
+}
+
+describe("instructionBlockTargetFor", () => {
+ test("maps codex, cursor, opencode and aider to AGENTS.md", () => {
+ expect(instructionBlockTargetFor("codex")).toBe("AGENTS.md");
+ expect(instructionBlockTargetFor("cursor")).toBe("AGENTS.md");
+ expect(instructionBlockTargetFor("opencode")).toBe("AGENTS.md");
+ expect(instructionBlockTargetFor("aider")).toBe("AGENTS.md");
+ });
+
+ test("maps gemini-cli to GEMINI.md", () => {
+ expect(instructionBlockTargetFor("gemini-cli")).toBe("GEMINI.md");
+ });
+
+ test("returns null, as a named skip, for targets with no precedence entry", () => {
+ for (const target of ["copilot-cli", "grok", "kiro", "pi", "generic"] as const) {
+ expect(instructionBlockTargetFor(target)).toBeNull();
+ }
+ });
+
+ test("follows HOST_INSTRUCTION_PRECEDENCE if the table or targets ever grow", () => {
+ const table = HOST_INSTRUCTION_PRECEDENCE as Readonly<Record<string, readonly string[]>>;
+ for (const target of INSTALL_TARGET_IDS as ReadonlyArray<InstallTargetId>) {
+ expect(instructionBlockTargetFor(target)).toBe(table[target]?.[0] ?? null);
+ }
+ });
+});
+
+describe("planInstructionBlock", () => {
+ test("plans a vault-root path for an absent file, with a creation note", () => {
+ const env = envFor(tmp);
+ const plan = planInstructionBlock(env, "codex");
+ expect(plan.path).toBe(join(tmp, "AGENTS.md"));
+ expect(plan.exists).toBe(false);
+ expect(plan.changed).toBe(true);
+ expect(plan.diff).not.toBe("");
+ expect(plan.note).not.toBeNull();
+ expect(plan.note).toContain("AGENTS.md");
+ });
+
+ test("plans an insert into an operator-authored file and renders the diff", () => {
+ writeFileSync(join(tmp, "AGENTS.md"), OPERATOR);
+ const plan = planInstructionBlock(envFor(tmp), "codex");
+ expect(plan.exists).toBe(true);
+ expect(plan.changed).toBe(true);
+ expect(plan.diff).toContain(`--- ${join(tmp, "AGENTS.md")}`);
+ expect(plan.diff).toContain(DEFAULT_BEGIN_MARKER);
+ expect(readFileSync(join(tmp, "AGENTS.md"), "utf8")).toBe(OPERATOR);
+ });
+
+ test("a current block plans no change and no diff", () => {
+ writeRulesBlock(join(tmp, "AGENTS.md"), RULES_BLOCK_ID.usage, CANONICAL_WRITEBACK_BLOCK_BODY);
+ const plan = planInstructionBlock(envFor(tmp), "codex");
+ expect(plan.exists).toBe(true);
+ expect(plan.changed).toBe(false);
+ expect(plan.diff).toBe("");
+ });
+
+ test("a drifted block plans a replacement diff", () => {
+ writeFileSync(join(tmp, "AGENTS.md"), DOCS_SNIPPET_FILE);
+ const plan = planInstructionBlock(envFor(tmp), "codex");
+ expect(plan.exists).toBe(true);
+ expect(plan.changed).toBe(true);
+ expect(plan.diff).toContain(
+ "- observing-memory layer. At session start, read Brain/active.md.",
+ );
+ expect(plan.diff).toContain("+ Memory write gate: apply the marker_writeback guardrail.");
+ });
+
+ test("the gemini-cli file carries the name-implied-reading note", () => {
+ const plan = planInstructionBlock(envFor(tmp), "gemini-cli");
+ expect(plan.path).toBe(join(tmp, "GEMINI.md"));
+ expect(plan.note).toContain("name-implied");
+ });
+
+ test("plans read, never write: a drift-only call leaves the vault untouched", () => {
+ writeFileSync(join(tmp, "AGENTS.md"), OPERATOR);
+ planInstructionBlock(envFor(tmp), "codex");
+ expect(readFileSync(join(tmp, "AGENTS.md"), "utf8")).toBe(OPERATOR);
+ expect(backupsOf("AGENTS.md").length).toBe(0);
+ expect(existsSync(instructionBlockLockPath(tmp))).toBe(false);
+ });
+
+ test("refuses a symbolic link, by name, with the checker's posture", () => {
+ const real = join(tmp, "real-agents.md");
+ writeFileSync(real, OPERATOR);
+ symlinkSync(real, join(tmp, "AGENTS.md"));
+ expect(() => planInstructionBlock(envFor(tmp), "codex")).toThrow(RulesBlockError);
+ });
+
+ test("refuses malformed markers of the block's own spelling, by name", () => {
+ writeFileSync(
+ join(tmp, "AGENTS.md"),
+ `${DEFAULT_BEGIN_MARKER}\nbroken\n${DEFAULT_BEGIN_MARKER}\n`,
+ );
+ let thrown: unknown = null;
+ try {
+ planInstructionBlock(envFor(tmp), "codex");
+ } catch (err) {
+ thrown = err;
+ }
+ expect(thrown).toBeInstanceOf(RulesBlockError);
+ expect((thrown as Error & { kind?: string }).kind).toBe(RULES_BLOCK_ERROR_KIND.markers);
+ });
+});
+
+describe("applyInstructionBlock", () => {
+ test("writes the approved plan, backs up, records the lock, and the audit conforms", () => {
+ writeFileSync(join(tmp, "AGENTS.md"), OPERATOR);
+ const env = envFor(tmp);
+ const approved = planInstructionBlock(env, "codex");
+ const result = applyInstructionBlock(env, { approved });
+ expect(result.backupPath).not.toBeNull();
+ expect(backupsOf("AGENTS.md").length).toBe(1);
+ expect(readFileSync(result.backupPath as string, "utf8")).toBe(OPERATOR);
+ const audit = auditWritebackContractFile(join(tmp, "AGENTS.md"));
+ expect(audit.finding).toBe("conforming");
+ const lock = readInstructionBlockLock(tmp);
+ expect(lock.schema_version).toBe(1);
+ const entry = lock.files["AGENTS.md"];
+ expect(entry).toBeDefined();
+ expect(entry?.block_id).toBe(RULES_BLOCK_ID.usage);
+ expect(entry?.begin_marker).toBe(RULES_BLOCK_MARKERS.usage.begin);
+ // The lock stamps when the write landed: the mtime the gate itself
+ // compares against, not the run-start clock in env.now.
+ expect(Date.parse(entry?.applied_at ?? "")).toBe(
+ Math.trunc(statSync(join(tmp, "AGENTS.md")).mtimeMs),
+ );
+ });
+
+ test("the lock stamps when the write landed, not the run-start clock", () => {
+ // env.now predates the plan render, the consent prompt and the
+ // adapter apply - on an interactive install by more than the writer's
+ // MTIME_SLACK_MS. A run-start stamp then sits behind the written
+ // file's mtime, so the next canonical-body upgrade read our own
+ // write as a later hand edit and refused with user-modified-block
+ // instead of taking the documented rewrite path. The lock records
+ // the written file's mtime, the exact anchor the hand-edit gate
+ // compares against.
+ writeFileSync(join(tmp, "AGENTS.md"), OPERATOR);
+ const env = envFor(tmp);
+ applyInstructionBlock(env, { approved: planInstructionBlock(env, "codex") });
+ const stamped = Date.parse(readInstructionBlockLock(tmp).files["AGENTS.md"]?.applied_at ?? "");
+ expect(stamped).toBe(Math.trunc(statSync(join(tmp, "AGENTS.md")).mtimeMs));
+ expect(stamped).not.toBe(APPLIED_AT_MS);
+ });
+
+ test("a re-plan and re-apply converge: changed false, no new backup", () => {
+ writeFileSync(join(tmp, "AGENTS.md"), OPERATOR);
+ const env = envFor(tmp);
+ applyInstructionBlock(env, { approved: planInstructionBlock(env, "codex") });
+ const once = readFileSync(join(tmp, "AGENTS.md"), "utf8");
+ const second = applyInstructionBlock(env, { approved: planInstructionBlock(env, "codex") });
+ expect(second.backupPath).toBeNull();
+ expect(readFileSync(join(tmp, "AGENTS.md"), "utf8")).toBe(once);
+ expect(backupsOf("AGENTS.md").length).toBe(1);
+ });
+
+ test("refuses preview drift by name and writes nothing", () => {
+ writeFileSync(join(tmp, "AGENTS.md"), OPERATOR);
+ const env = envFor(tmp);
+ const approved = planInstructionBlock(env, "codex");
+ // The operator edits between consent and apply.
+ writeFileSync(join(tmp, "AGENTS.md"), `${OPERATOR}\nMore notes.\n`);
+ let thrown: unknown = null;
+ try {
+ applyInstructionBlock(env, { approved });
+ } catch (err) {
+ thrown = err;
+ }
+ expect(thrown).toBeInstanceOf(RulesBlockError);
+ const err = thrown as Error & { kind?: string };
+ expect(err.kind).toBe(RULES_BLOCK_ERROR_KIND.previewDrift);
+ expect(readFileSync(join(tmp, "AGENTS.md"), "utf8")).toBe(`${OPERATOR}\nMore notes.\n`);
+ expect(backupsOf("AGENTS.md").length).toBe(0);
+ expect(existsSync(instructionBlockLockPath(tmp))).toBe(false);
+ });
+
+ test("refuses a docs-snippet block without force, then upgrades it with force to conforming", () => {
+ writeFileSync(join(tmp, "AGENTS.md"), DOCS_SNIPPET_FILE);
+ const env = envFor(tmp);
+ const approved = planInstructionBlock(env, "codex");
+ // No lock record exists, so the diverged block cannot be proven ours:
+ // the refusal is fail-closed by name.
+ let thrown: unknown = null;
+ try {
+ applyInstructionBlock(env, { approved });
+ } catch (err) {
+ thrown = err;
+ }
+ expect(thrown).toBeInstanceOf(RulesBlockError);
+ expect((thrown as Error & { kind?: string }).kind).toBe(
+ RULES_BLOCK_ERROR_KIND.userModifiedBlock,
+ );
+ expect(readFileSync(join(tmp, "AGENTS.md"), "utf8")).toBe(DOCS_SNIPPET_FILE);
+ // The documented override: force rewrites, the backup holds the prior
+ // bytes, and the real auditor now grades the file conforming.
+ const result = applyInstructionBlock(env, { approved, force: true });
+ expect(result.backupPath).not.toBeNull();
+ expect(readFileSync(result.backupPath as string, "utf8")).toBe(DOCS_SNIPPET_FILE);
+ expect(auditWritebackContractFile(join(tmp, "AGENTS.md")).finding).toBe("conforming");
+ expect(readInstructionBlockLock(tmp).files["AGENTS.md"]).toBeDefined();
+ });
+
+ test("an installedAtMs from the lock excuses a divergence on a stale file", () => {
+ writeFileSync(join(tmp, "AGENTS.md"), OPERATOR);
+ const env = envFor(tmp);
+ applyInstructionBlock(env, { approved: planInstructionBlock(env, "codex") });
+ // The canonical body changed in a newer release; the file mtime is
+ // still at the recorded install time, so the rewrite is ours to make.
+ const second = planInstructionBlock(envFor(tmp), "codex");
+ expect(second.changed).toBe(false);
+ });
+
+ test("dryRun writes nothing: no file change, no backup, no lock", () => {
+ writeFileSync(join(tmp, "AGENTS.md"), OPERATOR);
+ const env = envFor(tmp);
+ const approved = planInstructionBlock(env, "codex");
+ const result = applyInstructionBlock(env, { approved, dryRun: true });
+ expect(result.backupPath).toBeNull();
+ expect(readFileSync(join(tmp, "AGENTS.md"), "utf8")).toBe(OPERATOR);
+ expect(backupsOf("AGENTS.md").length).toBe(0);
+ expect(existsSync(instructionBlockLockPath(tmp))).toBe(false);
+ });
+
+ test("refuses an approved plan that does not name a vault-root agent instruction file", () => {
+ const env = envFor(tmp);
+ const approved = planInstructionBlock(env, "codex");
+ const forged = { ...approved, path: join(tmp, "elsewhere", "AGENTS.md") };
+ let thrown: unknown = null;
+ try {
+ applyInstructionBlock(env, { approved: forged });
+ } catch (err) {
+ thrown = err;
+ }
+ expect(thrown).toBeInstanceOf(RulesBlockError);
+ expect((thrown as Error & { kind?: string }).kind).toBe(RULES_BLOCK_ERROR_KIND.invalidPlan);
+ });
+
+ test("an unchanged approved apply records ownership, so uninstall can find the block", () => {
+ writeRulesBlock(join(tmp, "AGENTS.md"), RULES_BLOCK_ID.usage, CANONICAL_WRITEBACK_BLOCK_BODY);
+ const env = envFor(tmp);
+ const approved = planInstructionBlock(env, "codex");
+ expect(approved.changed).toBe(false);
+ applyInstructionBlock(env, { approved });
+ expect(readInstructionBlockLock(tmp).files["AGENTS.md"]).toBeDefined();
+ });
+
+ test("the apply result names what happened: created, updated, or already current", () => {
+ const env = envFor(tmp);
+ // First apply on a vault with no AGENTS.md: the file is CREATED. The
+ // result must say so - a backupPath-only derivation would report the
+ // creation as "already carries the block".
+ const created = applyInstructionBlock(env, { approved: planInstructionBlock(env, "codex") });
+ expect(created.created).toBe(true);
+ expect(created.changed).toBe(true);
+ expect(created.backupPath).toBeNull();
+ // A re-apply is already current on both fields.
+ const current = applyInstructionBlock(env, { approved: planInstructionBlock(env, "codex") });
+ expect(current.created).toBe(false);
+ expect(current.changed).toBe(false);
+ // A diverged block rewritten under force is an UPDATE of an existing
+ // file, not a creation.
+ writeFileSync(join(tmp, "AGENTS.md"), DOCS_SNIPPET_FILE);
+ const updated = applyInstructionBlock(env, {
+ approved: planInstructionBlock(env, "codex"),
+ force: true,
+ });
+ expect(updated.created).toBe(false);
+ expect(updated.changed).toBe(true);
+ expect(updated.backupPath).not.toBeNull();
+ });
+
+ test("a future-stamped applied_at is untrusted: a diverged block refuses without force", () => {
+ // The lock lives in agent-writable state; an applied_at stamped into
+ // the future would make every operator hand-edit read as a canonical
+ // move under an untouched file. The gate must treat it as no record.
+ writeFileSync(join(tmp, "AGENTS.md"), DOCS_SNIPPET_FILE);
+ recordInstructionBlock(tmp, "AGENTS.md", {
+ block_id: RULES_BLOCK_ID.usage,
+ begin_marker: RULES_BLOCK_MARKERS.usage.begin,
+ applied_at: new Date(Date.now() + 10 * 60_000).toISOString(),
+ });
+ const env = envFor(tmp);
+ const approved = planInstructionBlock(env, "codex");
+ let thrown: unknown = null;
+ try {
+ applyInstructionBlock(env, { approved });
+ } catch (err) {
+ thrown = err;
+ }
+ expect(thrown).toBeInstanceOf(RulesBlockError);
+ const err = thrown as Error & { kind?: string };
+ expect(err.kind).toBe(RULES_BLOCK_ERROR_KIND.userModifiedBlock);
+ expect(err.message).toContain("future");
+ expect(readFileSync(join(tmp, "AGENTS.md"), "utf8")).toBe(DOCS_SNIPPET_FILE);
+ // --force stays the documented override.
+ const forced = applyInstructionBlock(env, { approved, force: true });
+ expect(forced.changed).toBe(true);
+ expect(auditWritebackContractFile(join(tmp, "AGENTS.md")).finding).toBe("conforming");
+ });
+});
+
+describe("instruction-block lock I/O", () => {
+ test("the lock file name and path are the derived-store join", () => {
+ expect(INSTRUCTION_BLOCK_LOCK_FILE).toBe("instruction-block.lock.json");
+ expect(instructionBlockLockPath(tmp)).toBe(
+ join(tmp, ".open-second-brain", "instruction-block.lock.json"),
+ );
+ expect(basename(instructionBlockLockPath(tmp))).toBe("instruction-block.lock.json");
+ });
+
+ test("an absent lock reads as an empty schema-1 document", () => {
+ const lock = readInstructionBlockLock(tmp);
+ expect(lock.schema_version).toBe(1);
+ expect(Object.keys(lock.files).length).toBe(0);
+ });
+
+ test("record and clear round-trip atomically", () => {
+ recordInstructionBlock(tmp, "AGENTS.md", {
+ block_id: RULES_BLOCK_ID.usage,
+ begin_marker: RULES_BLOCK_MARKERS.usage.begin,
+ applied_at: new Date(APPLIED_AT_MS).toISOString(),
+ });
+ recordInstructionBlock(tmp, "GEMINI.md", {
+ block_id: RULES_BLOCK_ID.usage,
+ begin_marker: RULES_BLOCK_MARKERS.usage.begin,
+ applied_at: new Date(APPLIED_AT_MS).toISOString(),
+ });
+ expect(Object.keys(readInstructionBlockLock(tmp).files).toSorted()).toEqual([
+ "AGENTS.md",
+ "GEMINI.md",
+ ]);
+ // Re-recording one file replaces its entry, not the others.
+ recordInstructionBlock(tmp, "AGENTS.md", {
+ block_id: RULES_BLOCK_ID.usage,
+ begin_marker: RULES_BLOCK_MARKERS.usage.begin,
+ applied_at: new Date(APPLIED_AT_MS + 1).toISOString(),
+ });
+ expect(readInstructionBlockLock(tmp).files["AGENTS.md"]?.applied_at).toBe(
+ new Date(APPLIED_AT_MS + 1).toISOString(),
+ );
+ expect(readInstructionBlockLock(tmp).files["GEMINI.md"]).toBeDefined();
+ clearInstructionBlock(tmp, "AGENTS.md");
+ expect(readInstructionBlockLock(tmp).files["AGENTS.md"]).toBeUndefined();
+ clearInstructionBlock(tmp, "CLAUDE.md");
+ expect(Object.keys(readInstructionBlockLock(tmp).files)).toEqual(["GEMINI.md"]);
+ });
+
+ test("corrupted JSON refuses with a named error carrying the path", () => {
+ mkdirSync(join(tmp, ".open-second-brain"), { recursive: true });
+ writeFileSync(instructionBlockLockPath(tmp), "{ not json");
+ expect(() => readInstructionBlockLock(tmp)).toThrow(/instruction-block\.lock\.json/);
+ });
+
+ test("a non-object document refuses with a named error", () => {
+ mkdirSync(join(tmp, ".open-second-brain"), { recursive: true });
+ writeFileSync(instructionBlockLockPath(tmp), "[1, 2]\n");
+ expect(() => readInstructionBlockLock(tmp)).toThrow(/not an object/);
+ });
+
+ test("an unsupported schema_version refuses with a named error", () => {
+ mkdirSync(join(tmp, ".open-second-brain"), { recursive: true });
+ writeFileSync(
+ instructionBlockLockPath(tmp),
+ JSON.stringify({ schema_version: 99, files: {} }) + "\n",
+ );
+ expect(() => readInstructionBlockLock(tmp)).toThrow(/schema_version 99/);
+ });
+
+ test("the lock is never a symlink target: reads refuse links with the writer's posture", () => {
+ // A lock that can be redirected reads state the vault never wrote.
+ mkdirSync(join(tmp, ".open-second-brain"), { recursive: true });
+ const real = join(tmp, "real-lock.json");
+ writeFileSync(real, JSON.stringify({ schema_version: 1, files: {} }));
+ symlinkSync(real, instructionBlockLockPath(tmp));
+ expect(() => readInstructionBlockLock(tmp)).toThrow(RulesBlockError);
+ });
+});
diff --git a/tests/core/install/rules-block.test.ts b/tests/core/install/rules-block.test.ts
new file mode 100644
index 00000000..c906ea71
--- /dev/null
+++ b/tests/core/install/rules-block.test.ts
@@ -0,0 +1,733 @@
+/**
+ * Tests for the shared rules-block writer (plan K1, t_ba41a78a / t_1e952e43).
+ *
+ * One writer owns every byte written into a vault-root agent rules file
+ * through marker fences: the installer writes the `usage` block, the
+ * lessons lane promotes into the `lessons` block. The suite pins the
+ * writer invariants that make the two producers safe to share one file:
+ * operator bytes outside the block are preserved, re-apply is a byte
+ * no-op, line endings survive, the exclusive-create backup is taken once,
+ * hand-edited blocks refuse, and every malformed-marker shape is a named
+ * refusal that wraps the editor's own error.
+ */
+
+import { afterEach, beforeEach, describe, expect, test } from "bun:test";
+import {
+ existsSync,
+ lstatSync,
+ mkdtempSync,
+ readFileSync,
+ readdirSync,
+ rmSync,
+ symlinkSync,
+ utimesSync,
+ writeFileSync,
+} from "node:fs";
+import { tmpdir } from "node:os";
+import { join } from "node:path";
+
+import {
+ DEFAULT_BEGIN_MARKER,
+ DEFAULT_END_MARKER,
+ ManagedBlockError,
+} from "../../../src/core/install/managed-block.ts";
+import { fileMatchesExpected } from "../../../src/core/fs-atomic.ts";
+import {
+ RulesBlockError,
+ RULES_BLOCK_ERROR_KIND,
+ RULES_BLOCK_ID,
+ RULES_BLOCK_MARKERS,
+ RULES_BLOCK_STATE,
+ readRulesBlock,
+ removeRulesBlock,
+ renderRulesBlock,
+ rulesBlockDrift,
+ writeRulesBlock,
+} from "../../../src/core/install/rules-block.ts";
+
+let tmp: string;
+
+beforeEach(() => {
+ tmp = mkdtempSync(join(tmpdir(), "osb-rules-block-"));
+});
+
+afterEach(() => {
+ rmSync(tmp, { recursive: true, force: true });
+});
+
+const OPERATOR = "# my project\n\nSome operator notes that must survive.\n";
+
+const USAGE_BODY = [
+ "## Open Second Brain",
+ "",
+ "Use the marker_writeback guardrail: record memory as atomic facts",
+ "in the same turn they are learned.",
+].join("\n");
+
+const LESSONS_BODY = ["- prefer small commits", "- measure before tuning"].join("\n");
+
+/** Set a file's mtime to an exact millisecond, for the drift refusals. */
+function setMtime(path: string, atMs: number): void {
+ utimesSync(path, new Date(atMs), new Date(atMs));
+}
+
+/** The `.bak.` backup siblings of `name` currently in the directory. */
+function backupsOf(name: string): string[] {
+ return readdirSync(tmp)
+ .filter((entry) => entry.startsWith(`${name}.bak.`))
+ .toSorted();
+}
+
+describe("rules-block markers and renderRulesBlock", () => {
+ test("the usage entry re-exports the settled default marker spellings", () => {
+ expect(RULES_BLOCK_MARKERS.usage.begin).toBe(DEFAULT_BEGIN_MARKER);
+ expect(RULES_BLOCK_MARKERS.usage.end).toBe(DEFAULT_END_MARKER);
+ });
+
+ test("the lessons entry is a distinct HTML-comment pair", () => {
+ expect(RULES_BLOCK_MARKERS.lessons.begin).toBe("<!-- >>> open-second-brain lessons >>> -->");
+ expect(RULES_BLOCK_MARKERS.lessons.end).toBe("<!-- >>> open-second-brain lessons <<< -->");
+ });
+
+ test("renderRulesBlock renders the fenced document for a new file", () => {
+ const usage = renderRulesBlock(RULES_BLOCK_ID.usage, USAGE_BODY);
+ expect(usage.beginMarker).toBe(DEFAULT_BEGIN_MARKER);
+ expect(usage.endMarker).toBe(DEFAULT_END_MARKER);
+ expect(usage.document).toBe(`${DEFAULT_BEGIN_MARKER}\n${USAGE_BODY}\n${DEFAULT_END_MARKER}\n`);
+
+ const lessons = renderRulesBlock(RULES_BLOCK_ID.lessons, LESSONS_BODY);
+ expect(lessons.document).toBe(
+ `${RULES_BLOCK_MARKERS.lessons.begin}\n${LESSONS_BODY}\n${RULES_BLOCK_MARKERS.lessons.end}\n`,
+ );
+ });
+});
+
+describe("writeRulesBlock", () => {
+ test("creates an absent file with just the block", () => {
+ const file = join(tmp, "AGENTS.md");
+ const result = writeRulesBlock(file, RULES_BLOCK_ID.usage, USAGE_BODY);
+ expect(result.changed).toBe(true);
+ expect(result.backupPath).toBeNull();
+ expect(readFileSync(file, "utf8")).toBe(
+ renderRulesBlock(RULES_BLOCK_ID.usage, USAGE_BODY).document,
+ );
+ });
+
+ test("preserves every operator byte outside the block", () => {
+ const file = join(tmp, "AGENTS.md");
+ writeFileSync(file, OPERATOR);
+ writeRulesBlock(file, RULES_BLOCK_ID.usage, USAGE_BODY);
+ const out = readFileSync(file, "utf8");
+ expect(out.startsWith(OPERATOR)).toBe(true);
+ expect(out).toContain(USAGE_BODY);
+ });
+
+ test("a re-apply is a byte no-op reporting changed false", () => {
+ const file = join(tmp, "AGENTS.md");
+ writeFileSync(file, OPERATOR);
+ writeRulesBlock(file, RULES_BLOCK_ID.usage, USAGE_BODY);
+ const once = readFileSync(file, "utf8");
+ const second = writeRulesBlock(file, RULES_BLOCK_ID.usage, USAGE_BODY);
+ expect(second.changed).toBe(false);
+ expect(second.backupPath).toBeNull();
+ expect(readFileSync(file, "utf8")).toBe(once);
+ });
+
+ test("detects and preserves CRLF line endings", () => {
+ const file = join(tmp, "AGENTS.md");
+ writeFileSync(file, "# title\r\noperator line\r\n");
+ writeRulesBlock(file, RULES_BLOCK_ID.usage, USAGE_BODY);
+ const out = readFileSync(file, "utf8");
+ expect(out.includes("\r\n")).toBe(true);
+ expect(out.startsWith("# title\r\noperator line\r\n")).toBe(true);
+ // The markers themselves are CRLF-terminated lines now.
+ expect(out.includes(`${DEFAULT_BEGIN_MARKER}\r\n`)).toBe(true);
+ // A re-apply on the CRLF file is still a byte no-op.
+ const second = writeRulesBlock(file, RULES_BLOCK_ID.usage, USAGE_BODY);
+ expect(second.changed).toBe(false);
+ });
+
+ test("writes both blocks into one file without the pairs fighting", () => {
+ const file = join(tmp, "AGENTS.md");
+ writeFileSync(file, OPERATOR);
+ writeRulesBlock(file, RULES_BLOCK_ID.usage, USAGE_BODY);
+ writeRulesBlock(file, RULES_BLOCK_ID.lessons, LESSONS_BODY);
+ const out = readFileSync(file, "utf8");
+ expect(out).toContain(DEFAULT_BEGIN_MARKER);
+ expect(out).toContain(RULES_BLOCK_MARKERS.lessons.begin);
+ expect(readRulesBlock(file, RULES_BLOCK_ID.usage)).toBe(USAGE_BODY);
+ expect(readRulesBlock(file, RULES_BLOCK_ID.lessons)).toBe(LESSONS_BODY);
+ });
+
+ test("takes exactly one exclusive-create backup before the first write and none on a no-op", () => {
+ const file = join(tmp, "AGENTS.md");
+ writeFileSync(file, OPERATOR);
+ const first = writeRulesBlock(file, RULES_BLOCK_ID.usage, USAGE_BODY);
+ expect(first.backupPath).not.toBeNull();
+ expect(backupsOf("AGENTS.md").length).toBe(1);
+ expect(readFileSync(first.backupPath as string, "utf8")).toBe(OPERATOR);
+ // The backup was created exclusively: a real file, not a leftover temp.
+ expect(lstatSync(first.backupPath as string).isFile()).toBe(true);
+ const second = writeRulesBlock(file, RULES_BLOCK_ID.lessons, LESSONS_BODY);
+ // A different block id still changes the file, so it backs up once more.
+ expect(second.changed).toBe(true);
+ expect(second.backupPath).not.toBeNull();
+ expect(backupsOf("AGENTS.md").length).toBe(2);
+ const third = writeRulesBlock(file, RULES_BLOCK_ID.lessons, LESSONS_BODY);
+ expect(third.changed).toBe(false);
+ expect(third.backupPath).toBeNull();
+ expect(backupsOf("AGENTS.md").length).toBe(2);
+ });
+
+ test("an absent file takes no backup", () => {
+ const file = join(tmp, "AGENTS.md");
+ const result = writeRulesBlock(file, RULES_BLOCK_ID.usage, USAGE_BODY);
+ expect(result.backupPath).toBeNull();
+ expect(backupsOf("AGENTS.md").length).toBe(0);
+ });
+
+ test("refuses a hand-edited block on a file newer than installedAtMs", () => {
+ const file = join(tmp, "AGENTS.md");
+ writeFileSync(file, OPERATOR);
+ const installedAtMs = 1_700_000_000_000;
+ writeRulesBlock(file, RULES_BLOCK_ID.usage, USAGE_BODY, { installedAtMs });
+ // Hand-edit inside the fence, then stamp the file newer than the install.
+ const edited = readFileSync(file, "utf8").replace("atomic facts", "my own wording");
+ writeFileSync(file, edited);
+ setMtime(file, installedAtMs + 60_000);
+ let thrown: unknown = null;
+ try {
+ writeRulesBlock(file, RULES_BLOCK_ID.usage, USAGE_BODY, { installedAtMs });
+ } catch (err) {
+ thrown = err;
+ }
+ expect(thrown).toBeInstanceOf(RulesBlockError);
+ const err = thrown as Error & { kind?: string };
+ expect(err.kind).toBe(RULES_BLOCK_ERROR_KIND.userModifiedBlock);
+ // The refusal is by name: the message names the file and the remedy.
+ expect(err.message).toContain("AGENTS.md");
+ expect(err.message).toContain("--force");
+ // Nothing was written.
+ expect(readFileSync(file, "utf8")).toBe(edited);
+ expect(backupsOf("AGENTS.md").length).toBe(1);
+ });
+
+ test("force rewrites a hand-edited block and the backup holds the prior bytes", () => {
+ const file = join(tmp, "AGENTS.md");
+ writeFileSync(file, OPERATOR);
+ const installedAtMs = 1_700_000_000_000;
+ writeRulesBlock(file, RULES_BLOCK_ID.usage, USAGE_BODY, { installedAtMs });
+ const edited = readFileSync(file, "utf8").replace("atomic facts", "my own wording");
+ writeFileSync(file, edited);
+ setMtime(file, installedAtMs + 60_000);
+ const result = writeRulesBlock(file, RULES_BLOCK_ID.usage, USAGE_BODY, {
+ installedAtMs,
+ force: true,
+ });
+ expect(result.changed).toBe(true);
+ expect(result.backupPath).not.toBeNull();
+ expect(readFileSync(result.backupPath as string, "utf8")).toBe(edited);
+ expect(readRulesBlock(file, RULES_BLOCK_ID.usage)).toBe(USAGE_BODY);
+ });
+
+ test("a diverged block on a file older than installedAtMs is a canonical update, not a refusal", () => {
+ const file = join(tmp, "AGENTS.md");
+ writeFileSync(file, OPERATOR);
+ const installedAtMs = 1_700_000_000_000;
+ writeRulesBlock(file, RULES_BLOCK_ID.usage, USAGE_BODY, { installedAtMs });
+ // The canonical body changed in a newer release; the operator has not
+ // touched the file since, so the stale mtime proves the divergence is
+ // ours to fix, not theirs to authorize.
+ setMtime(file, installedAtMs - 60_000);
+ const stale = readFileSync(file, "utf8").replace("atomic facts", "old canonical wording");
+ writeFileSync(file, stale);
+ setMtime(file, installedAtMs - 60_000);
+ const result = writeRulesBlock(file, RULES_BLOCK_ID.usage, USAGE_BODY, { installedAtMs });
+ expect(result.changed).toBe(true);
+ expect(readRulesBlock(file, RULES_BLOCK_ID.usage)).toBe(USAGE_BODY);
+ });
+
+ test("refuses through a symbolic link, by name", () => {
+ const real = join(tmp, "real-agents.md");
+ writeFileSync(real, OPERATOR);
+ const link = join(tmp, "AGENTS.md");
+ symlinkSync(real, link);
+ let thrown: unknown = null;
+ try {
+ writeRulesBlock(link, RULES_BLOCK_ID.usage, USAGE_BODY);
+ } catch (err) {
+ thrown = err;
+ }
+ expect(thrown).toBeInstanceOf(RulesBlockError);
+ expect((thrown as Error & { kind?: string }).kind).toBe(RULES_BLOCK_ERROR_KIND.symlink);
+ expect(readFileSync(real, "utf8")).toBe(OPERATOR);
+ });
+
+ test("an install anchor stamped into the future is untrusted: the diverged block refuses", () => {
+ // A future-stamped anchor would make every later operator hand-edit
+ // read as a canonical move under an untouched file. It must count as
+ // no record, which refuses every diverged block (fail closed).
+ const file = join(tmp, "AGENTS.md");
+ const futureAnchor = Date.now() + 10 * 60_000; // far past the skew allowance
+ writeRulesBlock(file, RULES_BLOCK_ID.usage, USAGE_BODY, { installedAtMs: futureAnchor });
+ const edited = readFileSync(file, "utf8").replace("atomic facts", "my own wording");
+ writeFileSync(file, edited);
+ // The file is OLDER than the (future) anchor, which is exactly the
+ // shape that used to slip through the gate.
+ setMtime(file, Date.now() - 60_000);
+ let thrown: unknown = null;
+ try {
+ writeRulesBlock(file, RULES_BLOCK_ID.usage, USAGE_BODY, { installedAtMs: futureAnchor });
+ } catch (err) {
+ thrown = err;
+ }
+ expect(thrown).toBeInstanceOf(RulesBlockError);
+ const err = thrown as Error & { kind?: string };
+ expect(err.kind).toBe(RULES_BLOCK_ERROR_KIND.userModifiedBlock);
+ expect(err.message).toContain("future");
+ expect(err.message).toContain("--force");
+ expect(readFileSync(file, "utf8")).toBe(edited);
+ });
+
+ test("a stat failure at the hand-edit gate refuses the write, fail closed", () => {
+ // The gate re-stats the file after the read; a mid-flight move makes
+ // that stat fail. "Not touched" would overwrite a diverged block
+ // without --force, so the failure must refuse instead.
+ const file = join(tmp, "AGENTS.md");
+ const installedAtMs = 1_700_000_000_000;
+ writeRulesBlock(file, RULES_BLOCK_ID.usage, USAGE_BODY, { installedAtMs });
+ const edited = readFileSync(file, "utf8").replace("atomic facts", "my own wording");
+ writeFileSync(file, edited);
+ setMtime(file, installedAtMs - 60_000); // older than the anchor
+ let thrown: unknown = null;
+ try {
+ writeRulesBlock(file, RULES_BLOCK_ID.usage, USAGE_BODY, {
+ installedAtMs,
+ seams: { fileMtimeMs: () => null },
+ });
+ } catch (err) {
+ thrown = err;
+ }
+ expect(thrown).toBeInstanceOf(RulesBlockError);
+ const err = thrown as Error & { kind?: string };
+ expect(err.kind).toBe(RULES_BLOCK_ERROR_KIND.userModifiedBlock);
+ expect(err.message).toContain("--force");
+ // Nothing was written and no backup was taken (the fixture write was
+ // a create, which takes none).
+ expect(readFileSync(file, "utf8")).toBe(edited);
+ expect(backupsOf("AGENTS.md").length).toBe(0);
+ });
+
+ test("current bytes that moved during the write refuse by name, touching nothing", () => {
+ const file = join(tmp, "AGENTS.md");
+ writeFileSync(file, OPERATOR);
+ let thrown: unknown = null;
+ try {
+ writeRulesBlock(file, RULES_BLOCK_ID.usage, USAGE_BODY, {
+ seams: { currentBytesMatch: () => false },
+ });
+ } catch (err) {
+ thrown = err;
+ }
+ expect(thrown).toBeInstanceOf(RulesBlockError);
+ const err = thrown as Error & { kind?: string };
+ expect(err.kind).toBe(RULES_BLOCK_ERROR_KIND.concurrentModification);
+ expect(err.message).toContain("--force");
+ // The refused run left the operator bytes alone and took no backup.
+ expect(readFileSync(file, "utf8")).toBe(OPERATOR);
+ expect(backupsOf("AGENTS.md").length).toBe(0);
+ });
+
+ test("force deliberately writes over the moved bytes", () => {
+ const file = join(tmp, "AGENTS.md");
+ writeFileSync(file, OPERATOR);
+ const result = writeRulesBlock(file, RULES_BLOCK_ID.usage, USAGE_BODY, {
+ force: true,
+ seams: { currentBytesMatch: () => false },
+ });
+ expect(result.changed).toBe(true);
+ expect(readRulesBlock(file, RULES_BLOCK_ID.usage)).toBe(USAGE_BODY);
+ });
+
+ test("bytes that change between the pre-check and the rename refuse through the writer's re-check", () => {
+ // Review MG-2: the seam above models drift the PRE-check sees. This
+ // test stages the other window - the pre-check passes on bytes that
+ // are still current, and the concurrent edit lands while the write is
+ // in flight. Only the writer's own re-check (the `expectBefore`
+ // forwarding into the atomic writer) can refuse it; if that
+ // forwarding regressed, this write would silently clobber the
+ // concurrent edit with the whole suite otherwise green.
+ const file = join(tmp, "AGENTS.md");
+ const concurrent = `${OPERATOR}A line a concurrent editor added while the write ran.\n`;
+ let preChecks = 0;
+ let thrown: unknown = null;
+ try {
+ writeRulesBlock(file, RULES_BLOCK_ID.usage, USAGE_BODY, {
+ seams: {
+ currentBytesMatch: (target, expected) => {
+ preChecks += 1;
+ if (preChecks === 1) {
+ // The pre-check passes - and the edit lands immediately
+ // after it, inside the window the rename-time re-check
+ // covers.
+ writeFileSync(target, concurrent);
+ return true;
+ }
+ return fileMatchesExpected(target, expected);
+ },
+ },
+ });
+ } catch (err) {
+ thrown = err;
+ }
+ expect(preChecks).toBe(1);
+ expect(thrown).toBeInstanceOf(RulesBlockError);
+ const err = thrown as Error & { kind?: string };
+ expect(err.kind).toBe(RULES_BLOCK_ERROR_KIND.concurrentModification);
+ // The concurrent editor's bytes are intact: the refused write did not
+ // clobber them, and an absent-file create takes no backup.
+ expect(readFileSync(file, "utf8")).toBe(concurrent);
+ expect(backupsOf("AGENTS.md").length).toBe(0);
+ });
+
+ test("bytes that change between the pre-check and the rename refuse an UPDATE the same way", () => {
+ // The same window over the update arm of the same call site, where
+ // the writer's expectation is the read bytes rather than absence.
+ // The trusted install anchor keeps the hand-edit gate out of the way
+ // so the drift pre-check is the layer under test.
+ const file = join(tmp, "AGENTS.md");
+ const installedAtMs = 1_700_000_000_000;
+ writeRulesBlock(file, RULES_BLOCK_ID.usage, USAGE_BODY, { installedAtMs });
+ setMtime(file, installedAtMs);
+ const withBlock = readFileSync(file, "utf8");
+ const concurrent = `${withBlock}A concurrent edit landed mid-write.\n`;
+ let preChecks = 0;
+ let thrown: unknown = null;
+ try {
+ writeRulesBlock(file, RULES_BLOCK_ID.usage, `${USAGE_BODY}\nAn updated line.\n`, {
+ installedAtMs,
+ seams: {
+ currentBytesMatch: (target, expected) => {
+ preChecks += 1;
+ if (preChecks === 1) {
+ writeFileSync(target, concurrent);
+ return true;
+ }
+ return fileMatchesExpected(target, expected);
+ },
+ },
+ });
+ } catch (err) {
+ thrown = err;
+ }
+ expect(preChecks).toBe(1);
+ expect(thrown).toBeInstanceOf(RulesBlockError);
+ expect((thrown as Error & { kind?: string }).kind).toBe(
+ RULES_BLOCK_ERROR_KIND.concurrentModification,
+ );
+ expect(readFileSync(file, "utf8")).toBe(concurrent);
+ });
+
+ test("refuses multiple begin markers of the block's own spelling, wrapping ManagedBlockError", () => {
+ const file = join(tmp, "AGENTS.md");
+ writeFileSync(
+ file,
+ `${DEFAULT_BEGIN_MARKER}\nfirst\n${DEFAULT_BEGIN_MARKER}\nsecond\n${DEFAULT_END_MARKER}\n`,
+ );
+ let thrown: unknown = null;
+ try {
+ writeRulesBlock(file, RULES_BLOCK_ID.usage, USAGE_BODY);
+ } catch (err) {
+ thrown = err;
+ }
+ expect(thrown).toBeInstanceOf(RulesBlockError);
+ const err = thrown as Error & { kind?: string; cause?: unknown };
+ expect(err.kind).toBe(RULES_BLOCK_ERROR_KIND.markers);
+ expect(err.cause).toBeInstanceOf(ManagedBlockError);
+ });
+
+ test("refuses a begin marker without an end marker", () => {
+ const file = join(tmp, "AGENTS.md");
+ writeFileSync(file, `${DEFAULT_BEGIN_MARKER}\nnever closed\n`);
+ expect(() => writeRulesBlock(file, RULES_BLOCK_ID.usage, USAGE_BODY)).toThrow(RulesBlockError);
+ });
+
+ test("refuses an end marker without a begin marker", () => {
+ const file = join(tmp, "AGENTS.md");
+ writeFileSync(file, `${DEFAULT_END_MARKER}\n`);
+ expect(() => writeRulesBlock(file, RULES_BLOCK_ID.usage, USAGE_BODY)).toThrow(RulesBlockError);
+ });
+
+ test("refuses a reversed pair", () => {
+ const file = join(tmp, "AGENTS.md");
+ writeFileSync(file, `${DEFAULT_END_MARKER}\nbody\n${DEFAULT_BEGIN_MARKER}\n`);
+ expect(() => writeRulesBlock(file, RULES_BLOCK_ID.usage, USAGE_BODY)).toThrow(RulesBlockError);
+ });
+
+ test("a foreign spelling's stray markers never block a write of this block", () => {
+ // The lessons pair present with a broken shape is not the usage
+ // block's problem: one marker pair per spelling, validated per id.
+ const file = join(tmp, "AGENTS.md");
+ writeFileSync(
+ file,
+ `${RULES_BLOCK_MARKERS.lessons.begin}\n${RULES_BLOCK_MARKERS.lessons.begin}\n`,
+ );
+ const result = writeRulesBlock(file, RULES_BLOCK_ID.usage, USAGE_BODY);
+ expect(result.changed).toBe(true);
+ });
+
+ describe("dryRun writes nothing on every path", () => {
+ test("dryRun on an absent file", () => {
+ const file = join(tmp, "AGENTS.md");
+ const result = writeRulesBlock(file, RULES_BLOCK_ID.usage, USAGE_BODY, { dryRun: true });
+ expect(result.changed).toBe(true);
+ expect(result.backupPath).toBeNull();
+ expect(existsSync(file)).toBe(false);
+ });
+
+ test("dryRun on a file with operator content", () => {
+ const file = join(tmp, "AGENTS.md");
+ writeFileSync(file, OPERATOR);
+ const result = writeRulesBlock(file, RULES_BLOCK_ID.usage, USAGE_BODY, { dryRun: true });
+ expect(result.changed).toBe(true);
+ expect(result.backupPath).toBeNull();
+ expect(readFileSync(file, "utf8")).toBe(OPERATOR);
+ expect(backupsOf("AGENTS.md").length).toBe(0);
+ });
+
+ test("dryRun on a current file reports no change", () => {
+ const file = join(tmp, "AGENTS.md");
+ writeFileSync(file, OPERATOR);
+ writeRulesBlock(file, RULES_BLOCK_ID.usage, USAGE_BODY);
+ const before = readFileSync(file, "utf8");
+ const result = writeRulesBlock(file, RULES_BLOCK_ID.usage, USAGE_BODY, { dryRun: true });
+ expect(result.changed).toBe(false);
+ expect(readFileSync(file, "utf8")).toBe(before);
+ });
+
+ test("dryRun still refuses a hand-edited block", () => {
+ const file = join(tmp, "AGENTS.md");
+ writeFileSync(file, OPERATOR);
+ const installedAtMs = 1_700_000_000_000;
+ writeRulesBlock(file, RULES_BLOCK_ID.usage, USAGE_BODY, { installedAtMs });
+ const edited = readFileSync(file, "utf8").replace("atomic facts", "my own wording");
+ writeFileSync(file, edited);
+ setMtime(file, installedAtMs + 60_000);
+ expect(() =>
+ writeRulesBlock(file, RULES_BLOCK_ID.usage, USAGE_BODY, { installedAtMs, dryRun: true }),
+ ).toThrow(RulesBlockError);
+ expect(readFileSync(file, "utf8")).toBe(edited);
+ });
+ });
+});
+
+describe("readRulesBlock", () => {
+ test("returns the extracted body when the pair exists", () => {
+ const file = join(tmp, "AGENTS.md");
+ writeFileSync(file, OPERATOR);
+ writeRulesBlock(file, RULES_BLOCK_ID.usage, USAGE_BODY);
+ expect(readRulesBlock(file, RULES_BLOCK_ID.usage)).toBe(USAGE_BODY);
+ });
+
+ test("returns null when the file exists but carries no pair of that spelling", () => {
+ const file = join(tmp, "AGENTS.md");
+ writeFileSync(file, OPERATOR);
+ expect(readRulesBlock(file, RULES_BLOCK_ID.usage)).toBeNull();
+ expect(readRulesBlock(file, RULES_BLOCK_ID.lessons)).toBeNull();
+ });
+
+ test("returns null for an absent file", () => {
+ expect(readRulesBlock(join(tmp, "AGENTS.md"), RULES_BLOCK_ID.usage)).toBeNull();
+ });
+
+ test("returns null when only a DIFFERENT block id's pair exists", () => {
+ const file = join(tmp, "AGENTS.md");
+ writeFileSync(file, OPERATOR);
+ writeRulesBlock(file, RULES_BLOCK_ID.lessons, LESSONS_BODY);
+ expect(readRulesBlock(file, RULES_BLOCK_ID.usage)).toBeNull();
+ expect(readRulesBlock(file, RULES_BLOCK_ID.lessons)).toBe(LESSONS_BODY);
+ });
+
+ test("refuses malformed pairs of its own spelling by name", () => {
+ const file = join(tmp, "AGENTS.md");
+ writeFileSync(
+ file,
+ `${DEFAULT_BEGIN_MARKER}\na\n${DEFAULT_BEGIN_MARKER}\nb\n${DEFAULT_END_MARKER}\n`,
+ );
+ let thrown: unknown = null;
+ try {
+ readRulesBlock(file, RULES_BLOCK_ID.usage);
+ } catch (err) {
+ thrown = err;
+ }
+ expect(thrown).toBeInstanceOf(RulesBlockError);
+ expect((thrown as Error & { kind?: string }).kind).toBe(RULES_BLOCK_ERROR_KIND.markers);
+ });
+
+ test("refuses a symbolic link, by name", () => {
+ const real = join(tmp, "real-agents.md");
+ writeFileSync(real, OPERATOR);
+ const link = join(tmp, "AGENTS.md");
+ symlinkSync(real, link);
+ expect(() => readRulesBlock(link, RULES_BLOCK_ID.usage)).toThrow(RulesBlockError);
+ });
+});
+
+describe("rulesBlockDrift", () => {
+ test("absent when the file or the pair is missing", () => {
+ const absent = rulesBlockDrift(join(tmp, "AGENTS.md"), RULES_BLOCK_ID.usage, USAGE_BODY);
+ expect(absent.state).toBe(RULES_BLOCK_STATE.absent);
+ expect(absent.extracted).toBeNull();
+
+ const file = join(tmp, "AGENTS.md");
+ writeFileSync(file, OPERATOR);
+ const noPair = rulesBlockDrift(file, RULES_BLOCK_ID.usage, USAGE_BODY);
+ expect(noPair.state).toBe(RULES_BLOCK_STATE.absent);
+ expect(noPair.extracted).toBeNull();
+ });
+
+ test("current when the extracted body matches the canonical body", () => {
+ const file = join(tmp, "AGENTS.md");
+ writeFileSync(file, OPERATOR);
+ writeRulesBlock(file, RULES_BLOCK_ID.usage, USAGE_BODY);
+ const drift = rulesBlockDrift(file, RULES_BLOCK_ID.usage, USAGE_BODY);
+ expect(drift.state).toBe(RULES_BLOCK_STATE.current);
+ expect(drift.extracted).toBe(USAGE_BODY);
+ });
+
+ test("drifted when the extracted body diverges from the canonical body", () => {
+ const file = join(tmp, "AGENTS.md");
+ writeFileSync(file, OPERATOR);
+ writeRulesBlock(file, RULES_BLOCK_ID.usage, USAGE_BODY);
+ const drift = rulesBlockDrift(file, RULES_BLOCK_ID.usage, `${USAGE_BODY}\nA new clause.\n`);
+ expect(drift.state).toBe(RULES_BLOCK_STATE.drifted);
+ expect(drift.extracted).toBe(USAGE_BODY);
+ });
+
+ test("reads are read-only: drift never writes", () => {
+ const file = join(tmp, "AGENTS.md");
+ writeFileSync(file, OPERATOR);
+ rulesBlockDrift(file, RULES_BLOCK_ID.usage, USAGE_BODY);
+ expect(readFileSync(file, "utf8")).toBe(OPERATOR);
+ expect(backupsOf("AGENTS.md").length).toBe(0);
+ });
+});
+
+describe("removeRulesBlock", () => {
+ test("removes only the pair it owns and preserves the other block and operator bytes", () => {
+ const file = join(tmp, "AGENTS.md");
+ writeFileSync(file, OPERATOR);
+ writeRulesBlock(file, RULES_BLOCK_ID.usage, USAGE_BODY);
+ writeRulesBlock(file, RULES_BLOCK_ID.lessons, LESSONS_BODY);
+ const result = removeRulesBlock(file, RULES_BLOCK_ID.usage);
+ expect(result.removed).toBe(true);
+ const out = readFileSync(file, "utf8");
+ expect(out).not.toContain(DEFAULT_BEGIN_MARKER);
+ expect(out).not.toContain(DEFAULT_END_MARKER);
+ expect(out).not.toContain(USAGE_BODY);
+ expect(out).toContain(LESSONS_BODY);
+ expect(out).toContain(RULES_BLOCK_MARKERS.lessons.begin);
+ expect(out.startsWith(OPERATOR)).toBe(true);
+ // Never an empty fence where the lessons block lives.
+ expect(readRulesBlock(file, RULES_BLOCK_ID.lessons)).toBe(LESSONS_BODY);
+ });
+
+ test("collapses its own padding so cycles do not grow vertical whitespace", () => {
+ const file = join(tmp, "AGENTS.md");
+ writeFileSync(file, OPERATOR);
+ writeRulesBlock(file, RULES_BLOCK_ID.usage, USAGE_BODY);
+ removeRulesBlock(file, RULES_BLOCK_ID.usage);
+ const out = readFileSync(file, "utf8");
+ expect(out).toBe(OPERATOR);
+ });
+
+ test("is a named skip when no pair of that spelling exists", () => {
+ const file = join(tmp, "AGENTS.md");
+ writeFileSync(file, OPERATOR);
+ const result = removeRulesBlock(file, RULES_BLOCK_ID.usage);
+ expect(result.removed).toBe(false);
+ expect(readFileSync(file, "utf8")).toBe(OPERATOR);
+ });
+
+ test("is a named skip on an absent file", () => {
+ const result = removeRulesBlock(join(tmp, "AGENTS.md"), RULES_BLOCK_ID.usage);
+ expect(result.removed).toBe(false);
+ });
+
+ test("dryRun removes nothing", () => {
+ const file = join(tmp, "AGENTS.md");
+ writeFileSync(file, OPERATOR);
+ writeRulesBlock(file, RULES_BLOCK_ID.usage, USAGE_BODY);
+ const before = readFileSync(file, "utf8");
+ const result = removeRulesBlock(file, RULES_BLOCK_ID.usage, { dryRun: true });
+ expect(result.removed).toBe(true);
+ expect(readFileSync(file, "utf8")).toBe(before);
+ });
+
+ test("refuses through a symbolic link, by name", () => {
+ const real = join(tmp, "real-agents.md");
+ writeFileSync(real, OPERATOR);
+ const link = join(tmp, "AGENTS.md");
+ symlinkSync(real, link);
+ expect(() => removeRulesBlock(link, RULES_BLOCK_ID.usage)).toThrow(RulesBlockError);
+ });
+
+ test("current bytes that moved during the removal refuse by name, touching nothing", () => {
+ const file = join(tmp, "AGENTS.md");
+ writeFileSync(file, OPERATOR);
+ writeRulesBlock(file, RULES_BLOCK_ID.usage, USAGE_BODY);
+ let thrown: unknown = null;
+ try {
+ removeRulesBlock(file, RULES_BLOCK_ID.usage, {
+ seams: { currentBytesMatch: () => false },
+ });
+ } catch (err) {
+ thrown = err;
+ }
+ expect(thrown).toBeInstanceOf(RulesBlockError);
+ expect((thrown as Error & { kind?: string }).kind).toBe(
+ RULES_BLOCK_ERROR_KIND.concurrentModification,
+ );
+ // The removal was refused before any rewrite.
+ expect(readRulesBlock(file, RULES_BLOCK_ID.usage)).toBe(USAGE_BODY);
+ });
+
+ test("bytes that change between the pre-check and the rename refuse the removal through the writer's re-check", () => {
+ // The removal twin of the MG-2 pin: the pre-check sees current bytes,
+ // the concurrent edit lands while the rewrite is in flight, and only
+ // the forwarded `expectBefore` re-check stands between the rename and
+ // the concurrent editor's bytes. Removing the forwarding would let
+ // this removal clobber them with every other test still green.
+ const file = join(tmp, "AGENTS.md");
+ writeFileSync(file, OPERATOR);
+ writeRulesBlock(file, RULES_BLOCK_ID.usage, USAGE_BODY);
+ const withBlock = readFileSync(file, "utf8");
+ const concurrent = `${withBlock}A concurrent edit landed mid-removal.\n`;
+ let preChecks = 0;
+ let thrown: unknown = null;
+ try {
+ removeRulesBlock(file, RULES_BLOCK_ID.usage, {
+ seams: {
+ currentBytesMatch: (target, expected) => {
+ preChecks += 1;
+ if (preChecks === 1) {
+ writeFileSync(target, concurrent);
+ return true;
+ }
+ return fileMatchesExpected(target, expected);
+ },
+ },
+ });
+ } catch (err) {
+ thrown = err;
+ }
+ expect(preChecks).toBe(1);
+ expect(thrown).toBeInstanceOf(RulesBlockError);
+ expect((thrown as Error & { kind?: string }).kind).toBe(
+ RULES_BLOCK_ERROR_KIND.concurrentModification,
+ );
+ // The concurrent edit survives and the block was not removed.
+ expect(readFileSync(file, "utf8")).toBe(concurrent);
+ expect(readRulesBlock(file, RULES_BLOCK_ID.usage)).toBe(USAGE_BODY);
+ });
+});
diff --git a/tests/core/install/tool-ceiling.test.ts b/tests/core/install/tool-ceiling.test.ts
index 271ba828..0fe5d3b6 100644
--- a/tests/core/install/tool-ceiling.test.ts
+++ b/tests/core/install/tool-ceiling.test.ts
@@ -347,8 +347,9 @@ describe("the capability report states the ceiling it runs under", () => {
const evaluated = report("cursor");
// 118 registered tools through v1.90.0; the dated-commitments wave
// added brain_pledge and brain_intake_pledges (120); the delivery-trust
- // wave added brain_attestations (121).
- expect(evaluated.available_tool_count).toBe(121);
+ // wave added brain_attestations (121); the agent-presence wave added
+ // brain_skill_rewrite_status (122).
+ expect(evaluated.available_tool_count).toBe(122);
expect(evaluated.advertised_tool_count).toBe(7);
});
});
diff --git a/tests/core/install/uninstall-instruction-step.test.ts b/tests/core/install/uninstall-instruction-step.test.ts
new file mode 100644
index 00000000..92462146
--- /dev/null
+++ b/tests/core/install/uninstall-instruction-step.test.ts
@@ -0,0 +1,161 @@
+/**
+ * `o2b uninstall --target X` reverse instruction step, subprocess-level
+ * tests (t_ba41a78a B3).
+ *
+ * Uninstall removes the LOCK-RECORDED usage block pair and nothing else:
+ * the removal goes through the shared writer (operator bytes preserved,
+ * the file itself never removed), a pair that is already gone is a named
+ * skip, a pair nobody recorded is never touched on a guess, and a
+ * successful removal clears the lock entry so it can never claim a pair
+ * that is gone.
+ */
+
+import { afterEach, beforeEach, describe, expect, setDefaultTimeout, test } from "bun:test";
+import { existsSync, mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from "node:fs";
+import { tmpdir } from "node:os";
+import { join } from "node:path";
+
+import { CLI_SPAWN_BUDGET_MS } from "../../helpers/cli-timeout.ts";
+import { runCli as baseRunCli, type RunCliOptions, type RunResult } from "../../helpers/run-cli.ts";
+import { auditWritebackContractFile } from "../../../src/core/brain/writeback-contract.ts";
+import { DEFAULT_BEGIN_MARKER } from "../../../src/core/install/managed-block.ts";
+import { instructionBlockLockPath } from "../../../src/core/install/instruction-block.ts";
+
+function runCli(args: ReadonlyArray<string>, opts: RunCliOptions = {}): Promise<RunResult> {
+ return baseRunCli(args, { ...opts, subprocess: true });
+}
+
+setDefaultTimeout(CLI_SPAWN_BUDGET_MS);
+
+let vault: string;
+let home: string;
+let configPath: string;
+
+beforeEach(() => {
+ vault = mkdtempSync(join(tmpdir(), "osb-uninst-step-v-"));
+ home = mkdtempSync(join(tmpdir(), "osb-uninst-step-h-"));
+ configPath = join(home, "config.yaml");
+ mkdirSync(vault, { recursive: true });
+ writeFileSync(configPath, `vault: "${vault}"\nagent_name: "claude-vps"\ntimezone: "UTC"\n`);
+});
+
+afterEach(() => {
+ for (const p of [vault, home]) {
+ try {
+ rmSync(p, { recursive: true, force: true });
+ } catch {}
+ }
+});
+
+function envBase(extra: Record<string, string> = {}) {
+ return {
+ HOME: home,
+ OPEN_SECOND_BRAIN_CONFIG: configPath,
+ VAULT_DIR: vault,
+ VAULT_AGENT_NAME: "claude-vps",
+ VAULT_TIMEZONE: "UTC",
+ ...extra,
+ };
+}
+
+const OPERATOR = "# operator notes that must survive uninstall\n";
+
+describe("o2b uninstall --target X --apply: the reverse instruction step", () => {
+ test("removes the lock-recorded pair, keeps operator bytes, and clears the lock", async () => {
+ writeFileSync(join(vault, "AGENTS.md"), OPERATOR);
+ const install = await runCli(["install", "--target", "cursor", "--apply", "--yes"], {
+ env: envBase(),
+ });
+ expect(install.returncode).toBe(0);
+ expect(auditWritebackContractFile(join(vault, "AGENTS.md")).finding).toBe("conforming");
+
+ const r = await runCli(["uninstall", "--target", "cursor", "--apply"], { env: envBase() });
+ expect(r.returncode).toBe(0);
+ expect(r.stdout).toContain("removed instruction block: AGENTS.md");
+ const out = readFileSync(join(vault, "AGENTS.md"), "utf8");
+ expect(out.startsWith(OPERATOR)).toBe(true);
+ expect(out).not.toContain(DEFAULT_BEGIN_MARKER);
+ expect(auditWritebackContractFile(join(vault, "AGENTS.md")).finding).toBe("missing-block");
+ // The lock entry is cleared; the lock file stays as machine state.
+ expect(existsSync(instructionBlockLockPath(vault))).toBe(true);
+ const lock = JSON.parse(readFileSync(instructionBlockLockPath(vault), "utf8")) as {
+ files: Record<string, unknown>;
+ };
+ expect(lock.files["AGENTS.md"]).toBeUndefined();
+ });
+
+ test("is a named skip when the markers are already gone", async () => {
+ writeFileSync(join(vault, "AGENTS.md"), OPERATOR);
+ await runCli(["install", "--target", "cursor", "--apply", "--yes"], { env: envBase() });
+ // The operator removed the whole block by hand; the lock still
+ // claims it.
+ writeFileSync(join(vault, "AGENTS.md"), OPERATOR);
+ const r = await runCli(["uninstall", "--target", "cursor", "--apply"], { env: envBase() });
+ expect(r.returncode).toBe(0);
+ expect(r.stdout).toContain("skipped: instruction block");
+ // The lock never claims a pair that is gone.
+ const lock = JSON.parse(readFileSync(instructionBlockLockPath(vault), "utf8")) as {
+ files: Record<string, unknown>;
+ };
+ expect(lock.files["AGENTS.md"]).toBeUndefined();
+ });
+
+ test("never touches a pair the lock does not record", async () => {
+ await runCli(["install", "--target", "cursor", "--apply", "--yes"], { env: envBase() });
+ // The lock is lost (or the block was adopted by hand): without a
+ // record, the pair on disk is not proven ours, so uninstall leaves
+ // it and says so.
+ rmSync(instructionBlockLockPath(vault));
+ const r = await runCli(["uninstall", "--target", "cursor", "--apply"], { env: envBase() });
+ expect(r.returncode).toBe(0);
+ expect(r.stdout).toContain("no lock-recorded instruction block");
+ expect(readFileSync(join(vault, "AGENTS.md"), "utf8")).toContain(DEFAULT_BEGIN_MARKER);
+ });
+
+ test("dry-run reports the planned removal and changes nothing", async () => {
+ await runCli(["install", "--target", "cursor", "--apply", "--yes"], { env: envBase() });
+ const before = readFileSync(join(vault, "AGENTS.md"), "utf8");
+ const r = await runCli(["uninstall", "--target", "cursor"], { env: envBase() });
+ expect(r.returncode).toBe(0);
+ expect(r.stdout).toContain("dry-run");
+ expect(r.stdout).toContain("AGENTS.md");
+ expect(readFileSync(join(vault, "AGENTS.md"), "utf8")).toBe(before);
+ });
+
+ test("a target with no precedence entry is a named skip with no file touched", async () => {
+ // A hand-written block a copilot-cli operator keeps, installed with
+ // the copilot-cli adapter so ITS uninstall succeeds.
+ writeFileSync(
+ join(vault, "AGENTS.md"),
+ [OPERATOR, DEFAULT_BEGIN_MARKER, "hand-pasted body", ""].join("\n"),
+ );
+ const install = await runCli(["install", "--target", "copilot-cli", "--apply", "--yes"], {
+ env: envBase(),
+ });
+ expect(install.returncode).toBe(0);
+ const r = await runCli(["uninstall", "--target", "copilot-cli", "--apply"], {
+ env: envBase(),
+ });
+ expect(r.returncode).toBe(0);
+ expect(r.stdout).toContain("reads no agent-instruction file");
+ // The block nobody recorded survives uninstall untouched.
+ expect(readFileSync(join(vault, "AGENTS.md"), "utf8")).toContain(DEFAULT_BEGIN_MARKER);
+ });
+
+ test("the JSON payload carries the instruction_block outcome", async () => {
+ await runCli(["install", "--target", "cursor", "--apply", "--yes"], { env: envBase() });
+ const r = await runCli(["uninstall", "--target", "cursor", "--apply", "--json"], {
+ env: envBase(),
+ });
+ expect(r.returncode).toBe(0);
+ // main.ts wraps a --json flag it does not own in its own envelope;
+ // parse through that when present.
+ const outer = JSON.parse(r.stdout) as { stdout?: string } & Record<string, unknown>;
+ const payload = (typeof outer.stdout === "string" ? JSON.parse(outer.stdout) : outer) as {
+ instruction_block: { file: string | null; removed: boolean; skipped_reason: string | null };
+ };
+ expect(payload.instruction_block.file).toBe("AGENTS.md");
+ expect(payload.instruction_block.removed).toBe(true);
+ expect(payload.instruction_block.skipped_reason).toBeNull();
+ });
+});
diff --git a/tests/core/state/surfaces.test.ts b/tests/core/state/surfaces.test.ts
index de57c821..5dfd5566 100644
--- a/tests/core/state/surfaces.test.ts
+++ b/tests/core/state/surfaces.test.ts
@@ -78,6 +78,9 @@ import { sessionMiningLedgerPath } from "../../../src/core/brain/session-mining-
import { sessionMiningSurveysPath } from "../../../src/core/brain/session-mining-surveys.ts";
import { secretsDir } from "../../../src/core/brain/secrets/store.ts";
import { manifestPath as installManifestPath } from "../../../src/core/install/manifest.ts";
+import { instructionBlockLockPath } from "../../../src/core/install/instruction-block.ts";
+import { lessonsApprovalsPath } from "../../../src/core/brain/lessons-promotion.ts";
+import { skillBenchmarkTasksPath } from "../../../src/core/brain/paths.ts";
import { bootstrapReceiptPath } from "../../../src/cli/bootstrap/receipt.ts";
import { receiptsDir } from "../../../src/core/brain/decisions/receipts.ts";
import { anticipatoryCachePath } from "../../../src/core/brain/anticipatory-cache.ts";
@@ -284,6 +287,21 @@ const RESOLVER_BINDINGS: ReadonlyArray<readonly [StateSurfaceId, (vault: string)
["attestations", (v) => attestationsDir(v)],
["attestation_keys", (v) => attestationKeysDir(v)],
["install_manifest", (v) => installManifestPath(v)],
+ ["instruction_block_lock", (v) => instructionBlockLockPath(v)],
+ [
+ "lesson_approvals",
+ // t_1e952e43: the approval ledger lives in the derived store beside
+ // the install manifest; the kernel owns the one path spelling.
+ (v) => lessonsApprovalsPath(v),
+ ],
+ [
+ "skill_benchmarks",
+ // The tasks file is what an operator authors and the receipt
+ // verification reads; the row is the TREE above it (one directory
+ // per skill), so the binding climbs two levels from the core
+ // resolver's file to the directory the row declares.
+ (v) => dirname(dirname(skillBenchmarkTasksPath(v, "example-skill"))),
+ ],
["bootstrap_receipt", (v) => bootstrapReceiptPath(v)],
["hook_audit", (v) => hookAuditDir(v)],
["hook_session_state", (v) => dirname(hookStateFilePath(v, null))],
diff --git a/tests/fixtures/skill-bench/example-skill/spec.json b/tests/fixtures/skill-bench/example-skill/spec.json
new file mode 100644
index 00000000..a6854308
--- /dev/null
+++ b/tests/fixtures/skill-bench/example-skill/spec.json
@@ -0,0 +1,11 @@
+{
+ "schema_version": "o2b.skill-rewrite.v1",
+ "skill_name": "example-skill",
+ "tasks_hash": "a75f5dcc872f6d3366310dfc6c2fca60e0d328795bca39826bad125c3e169d52",
+ "seed": 0,
+ "split_rule": "hash-order-70-30",
+ "dev_task_ids": ["t-03", "t-04", "t-06", "t-07", "t-08", "t-09", "t-10"],
+ "held_out_task_ids": ["t-01", "t-02", "t-05"],
+ "required_margin": 0.1,
+ "min_dev_tasks": 2
+}
diff --git a/tests/fixtures/skill-bench/example-skill/tasks.json b/tests/fixtures/skill-bench/example-skill/tasks.json
new file mode 100644
index 00000000..08243053
--- /dev/null
+++ b/tests/fixtures/skill-bench/example-skill/tasks.json
@@ -0,0 +1,86 @@
+{
+ "skill": "example-skill",
+ "tasks": [
+ {
+ "id": "t-01",
+ "kind": "invocation_transcript",
+ "input": "File the meeting summary from today under Brain/notes/meetings and tag it with the project name.",
+ "expects": [
+ { "check": "tool_used", "tool": "note_write" },
+ { "check": "artifact_created", "path_prefix": "Brain/notes/meetings/" }
+ ]
+ },
+ {
+ "id": "t-02",
+ "kind": "invocation_transcript",
+ "input": "Look up the deployment runbook before touching the release checklist.",
+ "expects": [
+ { "check": "tool_used", "tool": "note_search" },
+ { "check": "step_order", "steps": ["search", "read", "edit"] }
+ ]
+ },
+ {
+ "id": "t-03",
+ "kind": "invocation_transcript",
+ "input": "Archive the retired preference without deleting any adjacent files.",
+ "expects": [
+ { "check": "forbidden_step", "step": "bulk_delete" },
+ { "check": "artifact_created", "path_prefix": "Brain/retired/" }
+ ]
+ },
+ {
+ "id": "t-04",
+ "kind": "invocation_transcript",
+ "input": "Record the benchmark verdict in the vault with a non-empty verdict field.",
+ "expects": [
+ { "check": "output_field", "field": "verdict", "value_class": "non_empty_string" }
+ ]
+ },
+ {
+ "id": "t-05",
+ "kind": "invocation_transcript",
+ "input": "Count how many pending proposals cite the current source and return the number.",
+ "expects": [{ "check": "output_field", "field": "count", "value_class": "number" }]
+ },
+ {
+ "id": "t-06",
+ "kind": "invocation_transcript",
+ "input": "List every skill directory under the configured skills root, one per line.",
+ "expects": [{ "check": "output_field", "field": "entries", "value_class": "non_empty_array" }]
+ },
+ {
+ "id": "t-07",
+ "kind": "invocation_transcript",
+ "input": "Rewrite the stale section of the skill instructions and stage it for review.",
+ "expects": [
+ { "check": "step_order", "steps": ["read", "edit", "stage"] },
+ { "check": "forbidden_step", "step": "direct_publish" }
+ ]
+ },
+ {
+ "id": "t-08",
+ "kind": "invocation_transcript",
+ "input": "Move the finished draft into the accepted folder and report the new path.",
+ "expects": [
+ { "check": "tool_used", "tool": "note_move" },
+ { "check": "artifact_created", "path_prefix": "Brain/skill-proposals/accepted/" }
+ ]
+ },
+ {
+ "id": "t-09",
+ "kind": "invocation_transcript",
+ "input": "Answer whether the flag is enabled, returning a strict boolean.",
+ "expects": [{ "check": "output_field", "field": "enabled", "value_class": "boolean" }]
+ },
+ {
+ "id": "t-10",
+ "kind": "invocation_transcript",
+ "input": "Summarize the invocation evidence for the skill and write it beside the task set.",
+ "expects": [
+ { "check": "tool_used", "tool": "note_write" },
+ { "check": "step_order", "steps": ["read", "summarize", "write"] },
+ { "check": "output_field", "field": "summary", "value_class": "non_empty_string" }
+ ]
+ }
+ ]
+}
diff --git a/tests/helpers/run-cli.ts b/tests/helpers/run-cli.ts
index 5a4014db..009a9687 100644
--- a/tests/helpers/run-cli.ts
+++ b/tests/helpers/run-cli.ts
@@ -73,6 +73,10 @@ const RUNTIME_OVERRIDABLE_ENV = [
// shell that happens to carry it must not turn a locked-store test into
// an unlocked one (or steal the value mid-run).
"OPEN_SECOND_BRAIN_SECRETS_PASSPHRASE",
+ // Lesson-promotion scope selection (t_1e952e43). A developer shell
+ // carrying an enabled scope must not silently flip the promotion gate
+ // in every lessons CLI test.
+ "OPEN_SECOND_BRAIN_LESSONS_PROMOTION_SCOPES",
] as const;
export interface RunCliOptions {
diff --git a/tests/helpers/tool-probe-catalogue.ts b/tests/helpers/tool-probe-catalogue.ts
index 31a98db2..14da21bc 100644
--- a/tests/helpers/tool-probe-catalogue.ts
+++ b/tests/helpers/tool-probe-catalogue.ts
@@ -296,8 +296,11 @@ export const REASONS_REACHING_OWNER_CONTENT: ReadonlySet<string> = new Set([REAS
* `docs/mcp.md` and the release notes. Equalities, not floors - see the
* test that reads them.
*/
-export const PROBE_ENTRY_COUNT = 107;
-export const PROBE_RECIPE_COUNT = 250;
+// 106 -> 107 -> 108, the second hop the agent-presence wave (t_635e3e72):
+// brain_skill_rewrite_status joins driven beside brain_skill_proposals,
+// one ownerless recipe - ids and rates only, nothing owner-tagged to reach.
+export const PROBE_ENTRY_COUNT = 108;
+export const PROBE_RECIPE_COUNT = 251;
export const PROBE_TWO_SIDED_COUNT = 32;
/**
@@ -1064,6 +1067,13 @@ export const NON_CONTENT: ReadonlyArray<ProbeEntry> = [
},
],
},
+ {
+ // Benchmark-gated rewrite status (t_635e3e72): ids and rates over one
+ // skill's lane, the same ownerless discipline as the grade record the
+ // read answers from - no page path, title or body at any reach.
+ name: "brain_skill_rewrite_status",
+ calls: one({ skill_name: "probe-skill" }, REASON.ownerlessLane),
+ },
{ name: "brain_sources", calls: one({}, REASON.signalAuthorship) },
{ name: "brain_stale_scan", calls: one({}, REASON.ownerFiltered) },
{ name: "brain_status", calls: one({}, REASON.aggregateOnly) },
diff --git a/tests/mcp/brain-tools-parity.test.ts b/tests/mcp/brain-tools-parity.test.ts
index f30a6f89..51fb1edd 100644
--- a/tests/mcp/brain-tools-parity.test.ts
+++ b/tests/mcp/brain-tools-parity.test.ts
@@ -177,6 +177,9 @@ const FROZEN_BRAIN_TOOL_NAMES = [
"brain_session_grep",
"brain_session_summary",
"brain_skill_proposals",
+ // benchmark-gated rewrite status (t_635e3e72, agent-presence): read-only
+ // ids-and-rates status beside brain_skill_proposals; never accepts, never scores
+ "brain_skill_rewrite_status",
"brain_sources",
"brain_stale_scan",
"brain_status",
diff --git a/tests/mcp/lessons-status-report.test.ts b/tests/mcp/lessons-status-report.test.ts
new file mode 100644
index 00000000..154364a7
--- /dev/null
+++ b/tests/mcp/lessons-status-report.test.ts
@@ -0,0 +1,166 @@
+/**
+ * Lesson-promotion counts through the EXISTING status plumbing
+ * (t_1e952e43, task C3).
+ *
+ * The MCP surface stays report-only by design: no new tool name is
+ * registered anywhere, and the `second_brain_status` payload carries the
+ * approvals counts because they live in the brain status snapshot that
+ * tool already returns. The frozen tool-name parity set in
+ * `tests/mcp/mcp.test.ts` stays untouched - this file only asserts the
+ * negative (no lessons-shaped tool name appears) so a later lane cannot
+ * add one silently either.
+ */
+
+import { afterEach, beforeEach, describe, expect, test } from "bun:test";
+import { mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from "node:fs";
+import { tmpdir } from "node:os";
+import { dirname, join } from "node:path";
+
+import { bootstrapBrain } from "../../src/core/brain/init.ts";
+import { computeContentHash } from "../../src/core/brain/content-hash.ts";
+import {
+ lessonsApprovalsPath,
+ recordLessonApproval,
+} from "../../src/core/brain/lessons-promotion.ts";
+import { parsePreference, writePreference } from "../../src/core/brain/preference.ts";
+import { preferencePath } from "../../src/core/brain/paths.ts";
+import { resetVaultIdentityPins } from "../../src/core/brain/vault-identity.ts";
+import { RULES_BLOCK_ID } from "../../src/core/install/rules-block.ts";
+import { buildToolTable, findTool } from "../../src/mcp/tools.ts";
+import type { ServerContext } from "../../src/mcp/tool-contract.ts";
+
+const PRINCIPLE = "Always run the full test suite before merging";
+
+let tmp: string;
+let vault: string;
+let ctx: ServerContext;
+
+const statusTool = findTool(buildToolTable(), "second_brain_status");
+
+beforeEach(() => {
+ resetVaultIdentityPins();
+ tmp = mkdtempSync(join(tmpdir(), "o2b-mcp-lessons-"));
+ vault = join(tmp, "vault");
+ mkdirSync(vault, { recursive: true });
+ const configPath = join(tmp, "config.yaml");
+ writeFileSync(configPath, `vault: ${vault}\nagent_name: t\n`);
+ bootstrapBrain(vault, { configPath });
+ ctx = { vault, configPath, repoRoot: null };
+});
+
+afterEach(() => {
+ rmSync(tmp, { recursive: true, force: true });
+});
+
+function seedPreference(slug: string, principle: string = PRINCIPLE): void {
+ writePreference(vault, {
+ slug,
+ topic: slug,
+ principle,
+ scope: "backend",
+ created_at: "2026-05-01T00:00:00Z",
+ confirmed_at: "2026-05-02T00:00:00Z",
+ unconfirmed_until: "2026-05-08T00:00:00Z",
+ status: "confirmed",
+ evidenced_by: ["[[sig-1]]"],
+ applied_count: 2,
+ violated_count: 0,
+ last_evidence_at: "2026-05-10T00:00:00Z",
+ confidence: "high",
+ } as Parameters<typeof writePreference>[1]);
+}
+
+function approve(prefId: string, principle: string = PRINCIPLE): void {
+ // The hash pins the text AS PERSISTED, not the fixture constant: the
+ // writer may normalise the body, and the operator approves the file's
+ // content. Read it back through the same parser the promotion kernel
+ // uses, exactly as the approve verb does.
+ const slug = prefId.replace(/^pref-/, "");
+ const persisted = parsePreference(preferencePath(vault, slug));
+ void principle;
+ recordLessonApproval(vault, {
+ prefId,
+ decision: "approved",
+ decidedAt: "2026-05-15T00:00:00Z",
+ decidedBy: "yes-flag",
+ approvedContentHash: computeContentHash(persisted.principle, persisted.scope),
+ targets: ["AGENTS.md"],
+ blockId: RULES_BLOCK_ID.lessons,
+ lastPromotedAt: null,
+ });
+}
+
+interface LessonsCounts {
+ readonly approved: number;
+ readonly denied: number;
+ readonly stale: number;
+}
+
+async function statusLessonsCounts(): Promise<LessonsCounts> {
+ const payload = (await statusTool.handler(ctx, {})) as Record<string, unknown>;
+ const brain = payload["brain"] as { lessons: LessonsCounts };
+ return brain.lessons;
+}
+
+describe("lesson promotion counts over the status plumbing", () => {
+ test("the counts match the ledger plus derived staleness, with no new tool", async () => {
+ seedPreference("mcp-fresh");
+ approve("pref-mcp-fresh");
+ seedPreference("mcp-stale");
+ approve("pref-mcp-stale");
+ // The operator amends the approved text: the pinned hash goes stale.
+ // The edit replaces the PERSISTED principle bytes, so it cannot be
+ // defeated by the writer's normalisation of the fixture constant,
+ // and it avoids writePreference, which refuses an existing file.
+ const stalePath = preferencePath(vault, "mcp-stale");
+ const stalePref = parsePreference(stalePath);
+ writeFileSync(
+ stalePath,
+ readFileSync(stalePath, "utf8").replace(
+ stalePref.principle,
+ `${stalePref.principle} amended`,
+ ),
+ );
+ seedPreference("mcp-denied");
+ recordLessonApproval(vault, {
+ prefId: "pref-mcp-denied",
+ decision: "denied",
+ decidedAt: "2026-05-16T00:00:00Z",
+ decidedBy: "yes-flag",
+ approvedContentHash: computeContentHash("another principle", "backend"),
+ targets: [],
+ blockId: RULES_BLOCK_ID.lessons,
+ lastPromotedAt: null,
+ });
+
+ expect(await statusLessonsCounts()).toEqual({ approved: 2, denied: 1, stale: 1 });
+ });
+
+ test("a brain with no ledger answers zero counts", async () => {
+ expect(await statusLessonsCounts()).toEqual({ approved: 0, denied: 0, stale: 0 });
+ });
+
+ test("a damaged ledger surfaces a generalized read_error with no machine path", async () => {
+ // The raw error messages embed the ledger's absolute path; the MCP
+ // payload must not. The snapshot names the file and the failure
+ // class; doctor is the surface that names the cause.
+ mkdirSync(dirname(lessonsApprovalsPath(vault)), { recursive: true });
+ writeFileSync(lessonsApprovalsPath(vault), "{ not json at all");
+ const payload = (await statusTool.handler(ctx, {})) as {
+ brain: { lessons: { approved: number; read_error?: string } };
+ };
+ const lessons = payload.brain.lessons;
+ expect(lessons.approved).toBe(0);
+ const readError = lessons.read_error ?? "";
+ expect(readError.length).toBeGreaterThan(0);
+ expect(readError).toContain("lessons-approvals.json");
+ expect(readError.includes(vault)).toBe(false);
+ expect(readError.includes(tmp)).toBe(false);
+ expect(readError.includes("/")).toBe(false);
+ });
+
+ test("no lessons-shaped tool name is registered anywhere", () => {
+ const names = buildToolTable().map((tool) => tool.name);
+ expect(names.some((name) => /lesson/i.test(name))).toBe(false);
+ });
+});
diff --git a/tests/mcp/mcp.test.ts b/tests/mcp/mcp.test.ts
index ca01f0ca..fb799ec3 100644
--- a/tests/mcp/mcp.test.ts
+++ b/tests/mcp/mcp.test.ts
@@ -270,6 +270,9 @@ describe("tool listing", () => {
"brain_session_expand",
// Procedural-learning surfaces (v0.30.0).
"brain_skill_proposals",
+ // Benchmark-gated rewrite status (agent-presence, t_635e3e72):
+ // read-only ids-and-rates status; MCP never accepts or scores.
+ "brain_skill_rewrite_status",
"brain_procedural_memory",
"brain_procedural_graph",
"brain_recurrence",
diff --git a/tests/mcp/skill-rewrite-status.test.ts b/tests/mcp/skill-rewrite-status.test.ts
new file mode 100644
index 00000000..f748949a
--- /dev/null
+++ b/tests/mcp/skill-rewrite-status.test.ts
@@ -0,0 +1,270 @@
+/**
+ * `brain_skill_rewrite_status` - the read-only MCP face of the
+ * benchmark-gated rewrite lane (agent-presence, Lane A, A5).
+ *
+ * MCP NEVER accepts and NEVER scores: the tool reads the frozen receipt
+ * and the grade ledger, and reports what a human accept is being asked to
+ * review. The pinned behaviors: the tool is registered read-only; the
+ * receipt names the take-verification; the grades carry verdicts and
+ * rates with the spec hash (ids and numbers, never task or transcript
+ * text); an unknown skill is a named empty status, not an error; and the
+ * handler writes nothing.
+ */
+
+import { afterEach, beforeEach, describe, expect, setDefaultTimeout, test } from "bun:test";
+import { mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from "node:fs";
+import { tmpdir } from "node:os";
+import { join } from "node:path";
+
+import {
+ listPendingSkillProposals,
+ recordSkillRewriteGrade,
+ stageScoredRewriteProposal,
+} from "../../src/core/brain/skill-proposals.ts";
+import { appendContinuityRecord } from "../../src/core/brain/continuity/store.ts";
+import {
+ buildSkillRewriteSpec,
+ skillRewriteSpecHash,
+ SKILL_REWRITE_VERDICT,
+} from "../../src/core/brain/skill-rewrite-spec.ts";
+import { parseSkillBenchmarkTasks } from "../../src/core/brain/skill-rewrite-tasks.ts";
+import { skillBenchmarkSpecPath, skillBenchmarkTasksPath } from "../../src/core/brain/paths.ts";
+import { PROCEDURE_TOOLS } from "../../src/mcp/brain/procedure-tools.ts";
+import { MCPError, INVALID_PARAMS } from "../../src/mcp/protocol.ts";
+import type { ServerContext } from "../../src/mcp/tool-contract.ts";
+import { CLI_SPAWN_BUDGET_MS } from "../helpers/cli-timeout.ts";
+
+// The wave's explicit per-test budget (test-audit F3): this file drives the
+// MCP server objects directly, and the budget keeps a loaded machine from
+// turning process-start cost into a flaky verdict.
+setDefaultTimeout(CLI_SPAWN_BUDGET_MS);
+
+let vault: string;
+let ctx: ServerContext;
+
+const FIXTURE_DIR = join(import.meta.dir, "..", "fixtures", "skill-bench", "example-skill");
+
+const TASKS = parseSkillBenchmarkTasks(
+ JSON.parse(readFileSync(join(FIXTURE_DIR, "tasks.json"), "utf8")),
+ "tasks.json",
+);
+
+beforeEach(() => {
+ vault = mkdtempSync(join(tmpdir(), "o2b-rewrite-status-"));
+ mkdirSync(join(vault, "Brain"), { recursive: true });
+ ctx = { vault, configPath: join(vault, "brain-config.yaml"), repoRoot: vault } as ServerContext;
+});
+
+afterEach(() => {
+ rmSync(vault, { recursive: true, force: true });
+});
+
+function tool() {
+ return PROCEDURE_TOOLS.find((t) => t.name === "brain_skill_rewrite_status");
+}
+
+describe("brain_skill_rewrite_status", () => {
+ test("is registered as a read tool", () => {
+ const definition = tool();
+ expect(definition).toBeDefined();
+ expect(definition?.kind).toBe("read");
+ });
+
+ test("reports the verified receipt, the grades and the pending rewrite", async () => {
+ seedBenchmark();
+ const spec = buildSkillRewriteSpec("example-skill", TASKS);
+ const specHash = skillRewriteSpecHash(spec);
+ recordSkillRewriteGrade(vault, {
+ payload: {
+ skill: "example-skill",
+ spec_hash: specHash,
+ tasks_hash: spec.tasksHash,
+ metric: "tasks_passed_rate",
+ seed: spec.seed,
+ split_rule: spec.splitRule,
+ verdict: SKILL_REWRITE_VERDICT.hold,
+ baseline_rate: 0.5,
+ candidate_rate: 0.5,
+ dev: [{ task_id: "t-03", passed: false, failed_checks: ["tool_used"] }],
+ held_out: [],
+ },
+ });
+ stageScoredRewriteProposal(vault, {
+ skill: {
+ name: "example-skill",
+ description: "Does a thing, safely.",
+ triggers: ["thing"],
+ body: "Candidate body.",
+ },
+ spec,
+ specHash,
+ baselineScore: 0.5,
+ candidateScore: 0.9,
+ heldoutScore: 1,
+ incumbentVersion: 3,
+ });
+
+ const result = (await tool()?.handler(ctx, { skill_name: "example-skill" })) as {
+ skill: string;
+ receipt: {
+ tasks_hash: string;
+ spec_hash: string;
+ take_verifies: boolean;
+ take_reason: string | null;
+ } | null;
+ grades: ReadonlyArray<{ verdict: string; baseline_rate: number; spec_hash: string }>;
+ pending_rewrite_slug: string | null;
+ };
+
+ expect(result.skill).toBe("example-skill");
+ expect(result.receipt).not.toBeNull();
+ expect(result.receipt?.take_verifies).toBe(true);
+ expect(result.receipt?.spec_hash).toBe(specHash);
+ expect(result.grades.length).toBe(1);
+ expect(result.grades[0]?.verdict).toBe(SKILL_REWRITE_VERDICT.hold);
+ expect(result.grades[0]?.spec_hash).toBe(specHash);
+ const pending = listPendingSkillProposals(vault);
+ expect(result.pending_rewrite_slug).toBe(pending[0]!.slug);
+ // Ids and rates only: no task text, no transcript text anywhere.
+ expect(JSON.stringify(result)).not.toContain("File the meeting summary");
+ });
+
+ test("a corrupt grade row is counted as unreadable, never rendered as a verdict", async () => {
+ // Only external corruption reaches this read: the writer rebuilds
+ // every payload field by field. A row the writer would have refused
+ // must not surface as a plausible `hold` with zeroed rates on the
+ // surface a human consults before accepting a rewrite - it is
+ // dropped from the rows and counted by name.
+ seedBenchmark();
+ const spec = buildSkillRewriteSpec("example-skill", TASKS);
+ const specHash = skillRewriteSpecHash(spec);
+ recordSkillRewriteGrade(vault, {
+ payload: {
+ skill: "example-skill",
+ spec_hash: specHash,
+ tasks_hash: spec.tasksHash,
+ metric: "tasks_passed_rate",
+ seed: spec.seed,
+ split_rule: spec.splitRule,
+ verdict: SKILL_REWRITE_VERDICT.hold,
+ baseline_rate: 0.5,
+ candidate_rate: 0.5,
+ dev: [{ task_id: "t-03", passed: false, failed_checks: ["tool_used"] }],
+ held_out: [],
+ },
+ });
+ appendContinuityRecord(vault, {
+ kind: "skill_rewrite_eval_grade",
+ createdAt: "2026-05-21T09:00:00Z",
+ sourceRefs: [{ id: "src-corrupt" }],
+ payload: {
+ skill: "example-skill",
+ spec_hash: specHash,
+ verdict: "promte",
+ baseline_rate: "not a number",
+ },
+ });
+
+ const result = (await tool()?.handler(ctx, { skill_name: "example-skill" })) as {
+ grades: ReadonlyArray<{ verdict: string; baseline_rate: number; candidate_rate: number }>;
+ unreadable_grades: number;
+ };
+ expect(result.grades.length).toBe(1);
+ expect(result.grades[0]?.verdict).toBe(SKILL_REWRITE_VERDICT.hold);
+ expect(result.grades[0]?.baseline_rate).toBe(0.5);
+ expect(result.unreadable_grades).toBe(1);
+ });
+
+ test("a skill with no benchmark is a named empty status, not an error", async () => {
+ const result = (await tool()?.handler(ctx, { skill_name: "absent-skill" })) as {
+ skill: string;
+ receipt: unknown;
+ grades: ReadonlyArray<unknown>;
+ pending_rewrite_slug: string | null;
+ };
+ expect(result.skill).toBe("absent-skill");
+ expect(result.receipt).toBeNull();
+ expect(result.grades).toEqual([]);
+ expect(result.pending_rewrite_slug).toBeNull();
+ });
+
+ test("the handler writes nothing", async () => {
+ seedBenchmark();
+ const before = listPendingSkillProposals(vault).length;
+ await tool()?.handler(ctx, { skill_name: "example-skill" });
+ expect(listPendingSkillProposals(vault).length).toBe(before);
+ });
+
+ test("a missing skill_name argument is refused", async () => {
+ await expect(tool()?.handler(ctx, {})).rejects.toThrow(/skill_name/);
+ });
+});
+
+describe("the MCP accept boundary", () => {
+ test("accept refuses a scored_rewrite proposal and names the operator's command", async () => {
+ // The design boundary (security M1c): MCP proposes, the operator
+ // accepts. The proposal below is fully gate-valid - benchmark on disk,
+ // matching promote grade record - so the refusal proves the boundary
+ // itself, not a broken gate.
+ seedBenchmark();
+ const spec = buildSkillRewriteSpec("example-skill", TASKS);
+ const specHash = skillRewriteSpecHash(spec);
+ recordSkillRewriteGrade(vault, {
+ payload: {
+ skill: "example-skill",
+ spec_hash: specHash,
+ tasks_hash: spec.tasksHash,
+ metric: "tasks_passed_rate",
+ seed: spec.seed,
+ split_rule: spec.splitRule,
+ verdict: SKILL_REWRITE_VERDICT.promote,
+ baseline_rate: 0.5,
+ candidate_rate: 0.9,
+ dev: [],
+ held_out: [],
+ },
+ });
+ stageScoredRewriteProposal(vault, {
+ skill: {
+ name: "example-skill",
+ description: "Does a thing, safely.",
+ triggers: ["thing"],
+ body: "Candidate body.",
+ },
+ spec,
+ specHash,
+ baselineScore: 0.5,
+ candidateScore: 0.9,
+ heldoutScore: 1,
+ incumbentVersion: 3,
+ });
+ const pending = listPendingSkillProposals(vault);
+ expect(pending.length).toBe(1);
+ const proposalsTool = PROCEDURE_TOOLS.find((t) => t.name === "brain_skill_proposals");
+
+ let thrown: unknown = null;
+ try {
+ await proposalsTool?.handler(ctx, { operation: "accept", slug: pending[0]!.slug });
+ } catch (error) {
+ thrown = error;
+ }
+ expect(thrown).toBeInstanceOf(MCPError);
+ const err = thrown as MCPError;
+ expect(err.code).toBe(INVALID_PARAMS);
+ expect(err.message).toContain("scored_rewrite");
+ expect(err.message).toContain("skill-proposals accept");
+ // Refused, not consumed: the draft is still pending for the operator.
+ expect(listPendingSkillProposals(vault).length).toBe(1);
+ });
+});
+
+function seedBenchmark(): void {
+ const tasksPath = skillBenchmarkTasksPath(vault, "example-skill");
+ mkdirSync(join(tasksPath, ".."), { recursive: true });
+ writeFileSync(tasksPath, readFileSync(join(FIXTURE_DIR, "tasks.json"), "utf8"), "utf8");
+ writeFileSync(
+ skillBenchmarkSpecPath(vault, "example-skill"),
+ readFileSync(join(FIXTURE_DIR, "spec.json"), "utf8"),
+ "utf8",
+ );
+}
diff --git a/uv.lock b/uv.lock
index 8cabe6c8..4eaed70b 100644
--- a/uv.lock
+++ b/uv.lock
@@ -4,5 +4,5 @@ requires-python = ">=3.11"
[[package]]
name = "open-second-brain"
-version = "1.97.0"
+version = "1.98.0"
source = { editable = "." }