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: what earns its keep (v1.51.0) (#177)

Sol Aitken6d3e8b23b2d0
diff --git a/.claude-plugin/plugin.json b/.claude-plugin/plugin.json
index 352072f6..719a9b8b 100644
--- a/.claude-plugin/plugin.json
+++ b/.claude-plugin/plugin.json
@@ -1,6 +1,6 @@
{
"name": "open-second-brain",
- "version": "1.50.3",
+ "version": "1.51.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 a2097d0d..8832d750 100644
--- a/.codex-plugin/plugin.json
+++ b/.codex-plugin/plugin.json
@@ -1,6 +1,6 @@
{
"name": "open-second-brain",
- "version": "1.50.3",
+ "version": "1.51.0",
"description": "Plugin-first second brain package for Codex, Hermes, Claude Code, OpenClaw, and other agent runtimes.",
"skills": "./skills",
"hooks": "./hooks/hooks.json",
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 7983af99..78710a73 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -5,6 +5,29 @@ 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.51.0] - 2026-08-22
+
+Eight tracker cards picked by priority, and reconnaissance against the real source before any design - a pass that corrected three of the eight rather than following them. The salience gate the first card asked for had nothing to stand in front of: the dream pass owns no per-item model lane, only a count-triggered rollup ladder, so the gate governs what enters that fold instead. The architecture diagram the second card wanted could not draw dependencies, because the scanner's own design doc excludes import analysis and its module facts carry no edges - so the diagram draws what the scan truthfully knows, containment, and says so. And the codegraph enrichment the third card described would have required inventing a partner query surface against a constant whose docstring calls its four tokens the entire surface, absolute - so what ships is the honest half, a verdict region that states what the partner index holds without pretending to read symbols it cannot see.
+
+What the eight had in common only became visible against the source: this wave adds three new lanes where a model writes into the vault, and the project already carried three needs-llm-step envelope shapes sharing five field names and no shared type. So the first unit of the wave is the type those six shapes now share, plus a registry for the payload constraints the deliberately shallow shape language cannot express - a design-note payload must carry exactly one recommended alternative, an extraction batch must respect a cap and a confidence floor, and both rules now live in one fail-closed mechanism instead of two ad-hoc ones.
+
+### Added
+
+- **A deterministic salience gate in front of dream synthesis.** `dream.salience_threshold` partitions the rollup fold set by a score built from three signals the system already computes - decayed evidence mass, the Wilson confidence bound, observed reuse - with no model call, no cache, and no second round trip. Every excluded fact is named in the run summary with its score and all three raw signals; unset threshold reproduces the previous behavior byte-for-byte, proven by running the same vault both ways. A `retriage` action on the staged-bundle verbs reports what a changed threshold would admit or exclude without mutating the bundle.
+- **`o2b brain extract-signals` - model-mined session signals that cannot skip the trial lane.** A two-phase batch verb over an already-imported session: phase one emits one envelope carrying the user turns to mine, phase two validates the returned payload against a declared shape plus a per-session cap and per-item confidence floor, then routes survivors through the capture boundary, dedup, the durability denylist, and write-approval staging into `Brain/inbox/` as speculative signals under a new closed-vocabulary `source_type: auto_extract`. Confirmed preferences remain reachable only through the dream pass's own promotion. The live hook path hosts none of this - it runs under a process ceiling that has no room for a model round trip, and the import command's output is now pinned byte-identical to prove it stayed out.
+- **`--delete-linked` - a note delete that can follow provenance, and nothing else.** The cascade adopts the source-cleanup blast-radius rule: only a single-purpose derived file whose structured provenance traces solely to the deleted note joins the deletion set; a page that merely mentions the note in prose, or cites any second source, is reported and preserved. One snapshot covers the whole set, the count guard asserts its exact size, and the dry-run lists deletions and reports separately before any confirm.
+- **Capture notes carry operator guidance, and the operator finally has a capture verb.** `WriteCaptureInput` gains a free-form `guidance` field - part of the capture identity hash, so two captures differing only in guidance are two captures - and `o2b brain capture` becomes the first ingress beside the Telegram bridge: body from argument or stdin, source, sender, timestamp, guidance.
+- **Expiration is now settable, and later changeable, from every writing surface.** `--expires` on the feedback verb and an `expires` parameter on the feedback tool stamp a lifetime at creation; the new `o2b brain expire` / `brain_expire` mutate or explicitly clear it afterwards, addressed by artifact id because the note-path surfaces refuse the `Brain/` root by design. Every path funnels through the one normalizer, clearing is a word rather than an empty string, and an equivalent re-set reports `changed: false` and writes nothing.
+- **Agent Skill drafts mined from the pages that earned them.** A `mature_page` pattern kind in the skill-proposals pipeline: the page-meta trio gates candidates, observed reuse supplies the evidence floor, installed-skill coverage vetoes duplicates with the veto named per page, and each admitted page yields one envelope whose validated draft stages as a pending proposal inside the vault. Accepting it materializes a `SKILL.md` under the configured skills root through the existing write-ahead journal - the only write that may leave the vault, and only on explicit accept.
+- **The architect overview now names its grounding.** A `codegraph` region states the partner graph verdict - `graph-present` with node, file, and edge counts and health findings, or `graph-absent, lexical-only` with the specific state and reason - from the report the partner already publishes, through zero new partner invocations. A `module-map` region renders a deterministic Mermaid containment diagram from the scanner's own facts, and a decisions note lists the repository's mined ADR candidates by the `repo_key` both generators already share, with an explicit empty state when there are none.
+- **`o2b brain design-note` - a one-shot grounded decision artifact.** Given a topic, the verb assembles tension, decision, and truth records matched through the vault's own similarity kernel, reports an empty grounding by name rather than failing on a young vault, and emits one envelope whose payload must carry named alternatives with exactly one recommended - a cardinality the semantic-check registry enforces, since the shape language deliberately cannot. The validated note lands beside the panel outputs under `Brain/decisions/`.
+
+### Notes
+
+- The local transformer embedding provider (the ninth card) is refused rather than shipped. A written invariant stands against bundling a model runtime, the lexical provider already gives a key-less install working recall, and the only runtime-free version - a registered provider name that cannot embed - is a stub wearing a feature's name. The refusal is the explicit choice the card itself asked for; revisit only if the invariant is deliberately lifted.
+- The salience gate is deterministic on purpose. An LLM triage scorer with a verdict cache was designed and rejected: all three inputs already exist as pure functions, recomputation is free, and a gate the kernel can evaluate without a model keeps the pass's no-model property intact.
+- An independent reviewer was given the finished branch with no knowledge of how it was built and returned one blocking finding - a caller-supplied-agent census pinned one wave behind the tools that declare it - and eleven non-blocking ones, all applied: two tools reported absolute host paths where their siblings redact, the cascade's inherited rule read prose mentions as provenance, a corrupted retriage manifest produced a spurious drift note instead of a refusal, the human-readable dream output was the one path that never mentioned the gate, an equivalent expiration re-set logged a change, the envelope builder's stamped status could be overridden by a hostile payload, guidance containing its own heading split at the wrong seam, and a mid-batch write failure reported nothing about the items already landed.
+
## [1.50.3] - 2026-08-22
Reported as [#173](https://github.com/itechmeat/open-second-brain/issues/173): in a Hermes deployment the memory tools were advertised and every call to them was refused, with nothing anywhere naming a cause. The gateway starts its providers with a minimal inherited `PATH`, and Open Second Brain already knew how to work around that for itself - the fallback scan finds an absolute `o2b` that `PATH` cannot see. What it did not do was carry that knowledge into the process it launched, so the wrapper checked its own `PATH` for the Bun runtime, missed, and exited before writing a byte. The transport reported the consequence. The reason was on the child's standard error, which this bridge read and discarded by design.
@@ -7302,6 +7325,7 @@ plugin config (vault field)`, and exits with a clear
- Sandbox vault and plugin manifest fixtures for tests.
- GitHub release workflow for tag-based and manually dispatched releases.
+[1.51.0]: https://github.com/itechmeat/open-second-brain/compare/v1.50.3...v1.51.0
[1.50.3]: https://github.com/itechmeat/open-second-brain/compare/v1.50.2...v1.50.3
[1.50.2]: https://github.com/itechmeat/open-second-brain/compare/v1.50.1...v1.50.2
[1.50.1]: https://github.com/itechmeat/open-second-brain/compare/v1.50.0...v1.50.1
diff --git a/README.md b/README.md
index 9bbb71e4..d4f3b4a7 100644
--- a/README.md
+++ b/README.md
@@ -8,15 +8,15 @@ Open Second Brain plugs into [Hermes Agent](https://github.com/NousResearch/herm
## What is new
-Open Second Brain 1.48.0 is about work you can watch, bound and stop, and about claims that were checked before they were printed. Nine units picked by priority off the tracker, and reconnaissance against the real source before any of them was designed - a pass that corrected six of the nine task bodies rather than following them, because they describe a system with a resident daemon, a chat-model client of its own, and an ingest that locks too often. This one has none of those.
+Open Second Brain 1.51.0 is about which memories earn their keep and how generated artifacts explain what they rest on. Eight tracker cards picked by priority, read against the real source before anything was designed - a pass that corrected three of them, because the lane one wanted to gate did not exist, the dependency diagram another wanted cannot be drawn from a scanner that deliberately collects no edges, and the partner enrichment a third described would have crossed a boundary the code declares absolute. A ninth card was refused outright rather than shipped as a shell: a local transformer embedding provider stands against a written no-ML-runtime invariant, and a registered provider that cannot embed is a stub, not a seam.
-What it had instead was long work that reported nothing. `o2b brain dream` produced its first observable character after it had already finished, so a caller could not tell a slow pass from a hung one. A cancellation contract was fully written and passed by no production call site, which made its error class dead code. A herd of detached reindexes was spawned at startup with their standard error discarded, so every loser of the lock race died where nobody could see it. Now the long passes emit newline-delimited progress on standard error under `--progress`, over stdio to an MCP client that asks for it, and the passes that can observe an interrupt stop at a checkpoint and exit on the shell's own signal convention. The ones that cannot observe one install no handler and say so, because a synchronous function never yields the event loop and a handler that cannot run is worse than none - it swallows the keystroke that used to work.
+What shipped instead: a deterministic salience gate decides which facts enter the dream pass's expensive fold, from three signals the system already computes, and names every exclusion; a batch verb mines memory signals from imported sessions through a validated model lane that can only reach the speculative inbox, never a confirmed preference; a note delete can follow structured provenance - and only structured provenance - under one snapshot and an exact count guard; expiration can finally be set at creation and changed afterwards from every writing surface, through one normalizer; mature vault pages become staged Agent Skill drafts that materialize outside the vault only on explicit accept; the architect overview states its codegraph verdict, draws a containment diagram it can actually prove, and lists the repository's mined decision candidates; and a one-shot design-note verb grounds a topic in tension, decision, and truth records and demands exactly one recommended alternative back.
-The other half is what the tool says about itself. A successful install now states where your brain is, what filesystem backs it, whether the search index is inside that vault, and which outbound services are configured - each measured at the moment it is printed. What cannot be measured is worded as a catalogue rather than a scan, and every row names the verb that created that state and the verb that removes it. The project scanner walks once and stops entering what the repository ignores: 24148 files visited became 2729, and 530.6 ms became 57.5 ms, measured on this repository.
+Under all of it sits one new piece of shared structure: the three divergent needs-llm-step envelope shapes the project had accumulated now share a named type, and the payload rules the deliberately shallow shape language cannot express - cardinality, caps, confidence floors - live in one fail-closed semantic-check registry. An independent reviewer given the finished branch returned one blocking finding and eleven non-blocking ones, all applied; the [CHANGELOG](CHANGELOG.md) names each.
-Then five reviewers were given the finished branch with no knowledge of how it was built, told that a comment is a claim rather than evidence and that a test which cannot fail proves nothing. They returned forty-four reproduced findings, and one of them ran thirty-seven mutations of the production code of which ten went green. The release's own argument caught it six times - three long operations that emitted progress and then simply stopped arriving, a documented deadline four call paths did not have, and, worst, the census the previous release's entire argument rests on turning out to read no source at all. Three findings were then resolved the opposite way to the obvious one, each because a measurement decided it: making a pass async does not deliver a signal either, a shorter lock budget made this branch's own contention test fail, and the proposed semaphore guard cannot see the case that matters. The [CHANGELOG](CHANGELOG.md) has all of it, including what was found and deliberately left open.
+Between this wave and the last feature wave, 1.49.0 through 1.50.3 made a label into a real boundary, taught the installer to see what the machine already has, and fixed a Hermes bridge that discarded the one line of stderr naming why it could not start - the [CHANGELOG](CHANGELOG.md) has the detail.
-One decision is reversed here rather than quietly performed. Release 1.46.0 recorded that there would be no registry of embedding-provider shutdown dates, because a hand-maintained table over an open set of endpoints would rot in place and be believed. The objection was right, and this design answers both halves of it: a surveyed negative expires, a positive carries the date it was reviewed, a model the survey does not know is reported as unsurveyed rather than as having no announced shutdown, and an operator who has read a vendor's announcement can declare it without waiting for a release.
+Previous release, 1.48.0, was about work you can watch, bound and stop: the long passes emit progress and observe interrupts where an interrupt can physically be observed, a successful install states what it measured rather than what it hoped, the project scanner stopped entering what the repository ignores (24148 files visited became 2729), and five independent reviewers returned forty-four reproduced findings against the finished branch, all resolved by measurement rather than argument.
Previous release, 1.47.0, wired what already existed: nine capabilities that were exported, tested and used elsewhere, each with a site that needed them and did not call them - a destructive-operation gate with two call sites against roughly twenty-five destructive operations, and a ranker that read a document's authoring instant nine lines after ranking on the file's modification time.
diff --git a/docs/architecture.md b/docs/architecture.md
index 44bb6b06..1730293e 100644
--- a/docs/architecture.md
+++ b/docs/architecture.md
@@ -379,13 +379,13 @@ disclosure, so `warn`'s observability here is the `owner:` stamp appearing on
new files, not a count in any response.
The enforcement lives in `tests/mcp/agent-scope-matrix.test.ts`, and its shape
-is the point rather than its size. Ninety-six classified tools carry 220 call
+is the point rather than its size. Ninety-nine classified tools carry 226 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 31 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 189 carry a claim of
+stops the closed run from passing vacuously. The other 194 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 arguments that named
diff --git a/docs/brainstorm/salience-lifecycle-enrichment/cli-output/claude.md b/docs/brainstorm/salience-lifecycle-enrichment/cli-output/claude.md
new file mode 100644
index 00000000..46ed478d
--- /dev/null
+++ b/docs/brainstorm/salience-lifecycle-enrichment/cli-output/claude.md
@@ -0,0 +1,36 @@
+### Variant A: Deterministic islands (kernel-lean)
+
+- **Approach**: Build no new shared infrastructure; every unit takes its most deterministic, most descoped option and plugs into existing seams as-is. Unit 1 uses the deterministic scorer (salience mass + Wilson confidence + reuse rates) feeding the rollup fold set; unit 4 emits an honest-template SKILL.md staged inside Brain/skill-proposals/pending/; unit 8 is a standalone diarization-shaped verb with a dedicated cardinality checker beside response-shape.ts (research.ts precedent); unit 2 is the wave's only new envelope, cloned from the diarization shape; unit 5 is deferred with a recorded decision honoring the retrieval-ranking design's no-ML-runtime ruling; units 6 and 7 ship the sentinel-region verdict stamp and containment-only diagram. The only shared piece is a small evidence-scoring module reused by units 1 and 4.
+- **Trade-offs**:
+ - Pro: smallest blast radius; each of the eight units is independently landable and testable, ideal for one PR of atomic TDD units.
+ - Pro: kernel stays strictly model-free on the two units where an LLM lane was optional (1, 4); no verdict ledger, no second round trip.
+ - Con: the envelope count grows from three shapes to four-plus while the named DRY paydown is skipped β€” the debt compounds exactly when it was cheapest to pay.
+ - Con: template-body skill drafts and score-only salience gating cap output quality; a later upgrade to model-authored variants re-opens every one of these files.
+- **Complexity**: small
+- **Risk**: low
+
+### Variant B: Shared envelope spine, additive adoption
+
+- **Approach**: First deliverable of the wave is a named `NeedsLlmStep` envelope core plus a sidecar semantic-checker registry hung beside response-shape.ts (keeping ShapeDescriptors deliberately shallow), and an idempotency-ledger-keyed verdict-ledger helper generalized from rollup discipline. Adoption is additive: the three legacy shapes are re-declared as aliases of the shared type without rewriting write-session, while all new model lanes plug in directly β€” unit 2's auto-capture envelope, unit 8's design-note envelope with an "exactly one Recommended" sidecar checker, unit 1's optional LLM retriage (deterministic scorer ships as default, LLM triage behind the verdict ledger), and unit 4's envelope-drafted SKILL.md body staged through the existing proposal accept path. Units 3, 6, 7 proceed deterministically as in Variant A; unit 5 ships only the EmbeddingIdentity seam and exhaustive-switch registration point, no runtime.
+- **Trade-offs**:
+ - Pro: pays the named DRY debt at the exact moment the wave would otherwise double the envelope population from three to six divergent shapes.
+ - Pro: one home for model-payload validation semantics β€” unit 2's new ShapeDescriptor and unit 8's cardinality checker land in the same registry with the same fail-loud refusal vocabulary.
+ - Pro: additive aliasing avoids touching durable write-session state, so the riskiest legacy surface is read, not rewritten.
+ - Con: sequencing dependency β€” four units block on the spine landing first, weakening unit independence inside the single PR.
+ - Con: the spine must be designed against three existing shapes plus three new consumers at once; a wrong generalization is expensive to unwind after this release.
+- **Complexity**: medium
+- **Risk**: medium
+
+### Variant C: Speculative-artifact pipeline first
+
+- **Approach**: The shared abstraction is the human-approval staging lifecycle, not the envelope: generalize the pending.ts / skill-proposals machinery into a "speculative artifact" surface (source-typed inbox entry, evidence floor, WAL-protected accept, destructive-ladder-guarded reject) that unit 2's auto-extracted signals, unit 4's staged SKILL.md drafts, and unit 1's `retriage` verdicts all flow through. Units 6 and 7 share a sentinel-region writer in architect generate.ts that preserves byte-identity outside stamped regions; unit 8 stays a standalone diarization-shaped verb; unit 3 rides the existing destructive ladder; unit 5 is deferred. Envelopes stay per-unit copies of the diarization shape.
+- **Trade-offs**:
+ - Pro: institutionalizes the house rule that precision beats recall β€” every model-authored durable write in the wave passes one uniform human gate, with one STATE_SURFACES story.
+ - Pro: gives unit 4 its cleanest answer to "skills_dir may be outside the vault": staging lives in the generalized pipeline, materialization on accept is the only out-of-vault write.
+ - Con: skill-proposals.ts is 51KB of working, WAL-protected code; extracting a generic lifecycle from it is the largest and most regression-prone refactor available in this wave.
+ - Con: leaves the envelope DRY debt untouched while adding two more divergent shapes, so the next wave inherits both problems.
+- **Complexity**: large
+- **Risk**: high
+
+### Recommended: Variant B
+**Rationale**: This wave adds model lanes whether or not anything is shared β€” units 2 and 8 are envelopes by specification β€” so Variant A's savings are illusory: it ships the new shapes anyway and merely declines the consolidation the conventions already name as a paydown target. Variant B captures that paydown with additive aliasing rather than a write-session rewrite, keeping risk bounded, and its sidecar-checker registry resolves unit 8's cardinality problem and unit 2's shape validation in one fail-loud mechanism instead of two ad-hoc ones. Variant C's refactor of the 51KB proposal machinery is the wrong risk for a single-PR, eight-unit release, and its benefits (uniform staging) are largely obtainable later on top of B's spine.
diff --git a/docs/brainstorm/salience-lifecycle-enrichment/cli-output/prompt.md b/docs/brainstorm/salience-lifecycle-enrichment/cli-output/prompt.md
new file mode 100644
index 00000000..8aece62a
--- /dev/null
+++ b/docs/brainstorm/salience-lifecycle-enrichment/cli-output/prompt.md
@@ -0,0 +1,70 @@
+You are brainstorming architectural variants for a multi-task release wave. Do not write code. Do not write a final design. Only produce variants and a recommendation.
+
+# Task
+
+One release wave of Open Second Brain (TypeScript, Bun, vault + CLI + MCP server; the kernel deliberately never calls an LLM β€” model work is delegated to the host agent through "needs-llm-step" envelopes). Eight tracker units, already reconnoitered against the real source. The question for you is NOT per-unit implementation detail; it is the wave-level architecture: which shared abstractions to build once, in what order, and where each unit plugs in.
+
+The eight units, with reconnaissance corrections already applied:
+
+1. Salience gate for dream synthesis (t_de8a0b2d). CORRECTION: the dream pass has no per-item model lane; its only model delegation is the rollup ladder, one envelope per count-triggered rung (rollup-ladder.ts, defaults 20 facts -> rollup). A gate can only govern which items enter the rollup fold set. Open choice: deterministic scorer (decayed salience mass in lessons.ts:228, Wilson-bound confidence in confidence.ts:38, reuse rates in observed-use.ts:168 β€” no cache, no second round trip, kernel stays model-free) versus an LLM triage scorer as a second needs-llm-step envelope with a verdict ledger keyed by judging model + prompt version (idempotency-ledger.ts discipline: same key + different hash = explicit payload_mismatch; provider failures never cached, mirroring CodegraphUnanswered vs error). Plus a `retriage` action on the existing dream stage/validate/apply bundle verbs.
+
+2. Auto-capture of memory signals from session streams (t_1dace26d). Must be a separate batch verb (the live hook path runs under a self-terminating process ceiling and cannot host an LLM round trip). Emits one needs-llm-step envelope over imported session turns; returned payload validated by a new ShapeDescriptor in response-shape.ts (MODEL_AUTHORED_SHAPES); extracted signals become speculative inbox entries (new closed-vocabulary source_type member `auto_extract`), staged through the existing write-approval surface (pending.ts), never straight to confirmed preferences. House rule to preserve: precision beats recall β€” a hallucinated fact pollutes memory.
+
+3. Write-time lifecycle (t_5e338af1), three sub-gaps: (a) --delete-linked cascade on note delete β€” the inbound-reference probe already computes the candidate set (notes/lifecycle.ts inboundFiles); the blast-radius rule to adopt is deleteBySource's "only single-purpose derived files tracing SOLELY to this source are deleted, everything else is reported"; full destructive ladder mandatory (dry-run default, count guard, snapshot gate, destructive-sites registry entry). Note: the module header of notes/lifecycle.ts explicitly argues a delete must report, not repair, inbound links β€” the design must argue past it. (b) Per-capture free-form guidance on WriteCaptureInput β€” but no CLI/MCP capture ingress exists (only telegram-capture calls it), so the field needs an ingress decision. (c) Expiration: expiration_date is enforced on read but NO surface can set it at creation and none can mutate it after β€” a double gap; both halves must route through normalizeExpirationDate as the single chokepoint.
+
+4. Agent Skill drafts from mature vault pages (t_abaec26b). A full mine -> verify -> stage -> human-accept pipeline already exists (skill-proposals.ts, 51KB: pending proposals, evidence floor >=3 distinct + 0.55 confidence, WAL-protected accept materialising Brain/procedures/). What is missing: it never reads vault page content (input is continuity telemetry) and never writes SKILL.md. Open choices: extend skill-proposals with a new pattern kind versus a new subsystem; maturity = page-meta trio (tier/lifecycle/confidence frontmatter) gated by observedReuseRates as evidence; where a generated SKILL.md lands (skills_dir may be OUTSIDE the vault; staging inside Brain/skill-proposals/pending/ and materialising on accept splits the problem); draft body: honest template versus needs-llm-step envelope.
+
+5. Local in-process transformer embedding provider (t_916f9953). CONFLICT: docs/brainstorm/retrieval-ranking-quality/design.md declares "NO new npm dependencies and NO ML runtime... the feature is redesigned in the OSB idiom, not the dependency added" β€” phrased release-scoped, justified in absolute terms. The lexical LocalProvider already gives key-less installs working recall. If pursued: distinct EmbeddingIdentity so switching invalidates rather than mixes vector spaces (ensureEmbeddingModel clears on model/dim change); provider registration walks an exhaustive switch (presets.ts) so the type system forces every touch point; house pattern for optional native deps is synchronous require in try/catch with memoized tri-state (cjk-tokenizer.ts), never silent download. Options include: operator-supplied model artifact + operator-installed runtime with loud config-time failure; defer the unit entirely; or ship only the seam.
+
+6. Codegraph-assisted enrichment of brain architect output (t_3a418d07). CORRECTION: the partner report carries counts and health only β€” no symbols, no call edges β€” and partner/codegraph.ts declares its four CLI tokens "the entire surface OSB knows about codegraph... absolute". Honest descope available: a new sentinel region in generated overview stamping the graph verdict ("graph-present, N nodes / M edges, health X" versus "graph-absent, lexical-only") from the existing report, with the five-state CodegraphIndexState vocabulary. Full symbol citation requires inventing a partner query surface β€” a separate decision with its own risks.
+
+7. Deterministic Mermaid module diagram + key-decisions note in brain architect (t_041c571f). CORRECTION: the architect scan carries no module relations (import-graph analysis explicitly out of scope in scan.ts); a deterministic diagram can only show containment (project -> modules, file counts, dominant language). Key-decisions note: repo-scoped ADR candidates already exist (git/decisions.ts mines conventional-commit signals into Brain/decisions/candidates/ with repo_key frontmatter; deriveRepoKey is the join key shared with architect). Regeneration byte-identity guarantee (generate.ts) must be preserved or the exception declared.
+
+8. One-shot design-note generator (t_c87644b4, trimmed). CORRECTION: a stateful multi-turn deliberation surface already exists (o2b brain panel on the write-session kernel, committing to Brain/decisions/panels/). The trimmed unit is: given a topic, ground in tension/decision/truth records (all three have query APIs; truth is an append-only claim ledger with projections), emit exactly one needs-llm-step envelope whose payload is validated to carry named alternatives and exactly one Recommended. Structural template: diarization.ts (read-only report + one envelope + PROSE_MARKER). Open choice: standalone diarization-shaped verb versus a new persona-free panel session kind. The "exactly one Recommended" cardinality cannot be expressed in the deliberately-shallow ShapeDescriptor language β€” either a dedicated checker beside it (as research.ts does for citation set-membership) or extending the descriptor language against its stated design.
+
+# Project context
+
+Open Second Brain, TypeScript on Bun, single-user vault product. v1.50.3.
+Recent commits:
+86544b9b fix(hermes): the bridge child inherits a PATH that can find Bun (v1.50.3)
+ba1a9678 fix(hermes): preserve context-pack recall (v1.50.2)
+4ba335d4 ci: adopt Bun 1.4.0 - pin the toolchain and rebuild the bundle it gates
+1e8792cb fix: a provider the host cannot read is not an unconfigured one (v1.50.1)
+962228ae fix(mcp): the pairing one tool declared and the other only enforced (v1.50.0)
+aa73af4b feat: what the machine already has (v1.50.0)
+b49af81e feat: a label is not a boundary (v1.49.0)
+280469d2 feat: nothing runs unwatched (v1.48.0)
+
+Related files: src/core/brain/{dream-apply,dream-gates,rollup-ladder,response-shape,write-session/,skill-proposals,notes/lifecycle,expiration,capture/capture-note,diarization,decisions/,tensions,truth/,architect/,partner/,sessions/import,signal,pending,idempotency-ledger}.ts, src/core/search/embeddings/, src/mcp/brain-tools.ts, src/mcp/registry-guard.ts.
+
+Conventions:
+- Kernel never calls an LLM; model work is delegated via needs-llm-step envelopes. THREE envelope shapes exist today (write-session durable sessions; diarization plain-data step; rollup envelope) sharing field names but no shared type β€” a named DRY paydown opportunity.
+- Fail loudly, never a misleading fallback: validation that cannot be switched off (response-shape), refusals name the specific reason, partner-absent is a value not an error, partial writes report how far they got.
+- Every model-authored write path validates through response-shape.ts ShapeDescriptors (closed key set, deliberately shallow).
+- New MCP tools: previewBudget mandatory, closed schemas, description on every property, parity test pins the tool-name set. New CLI verbs: dispatch case + help-text + command-manifest, gated by completeness tests.
+- New durable vault state needs a STATE_SURFACES row; destructive operations need a destructive-sites registry entry and the snapshot/count-guard/confirm ladder.
+- bun:test, throwaway vault per test, numbered docblocks stating the claims a suite pins.
+
+Constraints:
+- No new runtime npm dependencies without an explicit policy decision; nothing downloads silently.
+- Public APIs are additive; the MCP tool-name set is frozen per major (additions allowed, renames not).
+- All user-facing strings in English; no language-specific hardcoding.
+- SOLID, KISS, DRY; no stub implementations; errors surface explicitly.
+- One PR, one CHANGELOG version, eight atomic TDD units.
+
+# Required output format
+
+Produce exactly 3 distinct architectural variants FOR THE WAVE AS A WHOLE (how the shared abstractions are shaped and which unit-level options they imply). For each variant:
+
+### Variant N: <short name>
+- **Approach**: 2-3 sentences describing the variant.
+- **Trade-offs**: bullet list of pros and cons.
+- **Complexity**: small | medium | large
+- **Risk**: low | medium | high
+
+After the three variants, add exactly one recommendation:
+
+### Recommended: Variant N
+**Rationale**: 2-3 sentences explaining why this variant over the others, considering the project context and constraints above.
+
+Output nothing outside of these sections.
diff --git a/docs/brainstorm/salience-lifecycle-enrichment/design.md b/docs/brainstorm/salience-lifecycle-enrichment/design.md
new file mode 100644
index 00000000..5ec920d0
--- /dev/null
+++ b/docs/brainstorm/salience-lifecycle-enrichment/design.md
@@ -0,0 +1,64 @@
+# Salience, lifecycle, and enrichment wave - one envelope spine, eight tracker units
+
+**Status:** approved for implementation
+**Author:** claude-dev-agent (via feature-release-playbook)
+**Audience:** implementation
+
+## Problem statement
+
+Eight tracker units touch the same seam from different sides: how model-delegated work enters the vault (needs-llm-step envelopes exist in three divergent shapes with no shared type), which items deserve expensive synthesis, how written memories end their life (no surface can set or change `expiration_date`, no delete can follow links), and how generated artifacts explain what they rest on (architect output names neither its codegraph grounding nor the decisions behind the code). Each unit alone would add one more divergent shape or one more ad-hoc validator; together they justify building the shared pieces once.
+
+## Scope
+
+- **Unit 0 (spine, new):** a named `NeedsLlmStep` envelope core in `src/core/brain/llm-step.ts` shared by every model-delegation lane, adopted additively - the existing diarization and rollup shapes re-declare against it without behavioral change; the durable write-session envelope is documented as the durable superset and is not rewritten. Beside it, a semantic-checker registry (`src/core/brain/response-checks.ts`) for payload constraints the deliberately-shallow `ShapeDescriptor` language cannot express (cardinality, cross-item rules), following the precedent of the research citation set-membership check.
+- **Unit 1 (t_de8a0b2d):** a deterministic salience gate over the rollup ladder's fold set. Scorer combines decayed salience mass (`lessons.ts`), Wilson-bound confidence (`confidence.ts`), and observed reuse (`observed-use.ts`); threshold lives in `BrainDreamConfig`; items below threshold are excluded from rollup envelopes and reported by name in the dream summary (never silently dropped). A `retriage` action on the dream bundle verbs re-runs the gate after a threshold change and reports the delta before apply.
+- **Unit 2 (t_1dace26d):** a new batch verb `o2b brain extract-signals <session>` (CLI + MCP) that reads imported session turns and emits one spine envelope; the returned payload is validated by a new `ShapeDescriptor` plus a semantic check (per-session cap, confidence floor); accepted items are written as speculative inbox signals with new closed-vocabulary `source_type: "auto_extract"`, subject to the durability denylist, staged through `Brain/pending/` whenever write approval is enabled, and never written as confirmed preferences. `import-session` itself stays byte-identical.
+- **Unit 3a (t_5e338af1):** `--delete-linked` on note delete. Blast-radius rule adopted verbatim from `deleteBySource`: only single-purpose derived files whose references trace solely to the deleted note are deleted; every other inbound reference is reported, never repaired. Full destructive ladder: dry-run default, explicit confirm, count guard, snapshot gate, `destructive-sites.ts` entry.
+- **Unit 3b (t_5e338af1):** optional free-form `guidance` on `WriteCaptureInput`, participating in the capture id hash, rendered as a `## Guidance` body section; plus the minimal ingress the field needs to exist: a CLI capture verb (`o2b brain capture`) exposing body, source, sender, and guidance - today `writeCaptureNote` has exactly one caller (telegram) and no operator-facing entry.
+- **Unit 3c (t_5e338af1):** expiration, both halves of the double gap: creation-time `--expires <date>` / `expires` parameter on the feedback surfaces (CLI verb and MCP tool) for signals and preferences, and post-creation mutation via a dedicated lifecycle action that rewrites `expiration_date` - both routed through `normalizeExpirationDate` as the single validation chokepoint. Clearing is explicit (`--expires none`), never an empty-string side effect.
+- **Unit 4 (t_abaec26b):** a new `mature_page` pattern kind in the existing `skill-proposals.ts` pipeline. Maturity gate: the page-meta trio (tier, lifecycle non-stale, confidence) as the cheap filter, observed reuse rates as the evidence floor; skill-usage acts as a negative signal (do not draft what an installed skill already covers). Drafting emits one spine envelope per candidate page; the validated draft is staged as a pending proposal (inside the vault); accepting materializes `SKILL.md` under the configured skills root - the only out-of-vault write, and only on explicit accept through the existing WAL-protected path.
+- **Unit 5 (t_3a418d07, descoped):** a new `codegraph` sentinel region in the architect overview stamping the graph verdict from the existing partner report: `graph-present` with node/edge counts and health, or `graph-absent, lexical-only`, using the five-state `CodegraphIndexState` vocabulary. No new partner queries.
+- **Unit 6 (t_041c571f):** a deterministic Mermaid containment diagram (project to modules, file counts, dominant language; `compareStable` ordering) in a new architect overview region, and a key-decisions note built from repo-scoped ADR candidates (`Brain/decisions/candidates/` filtered by `repo_key`, the join key architect already derives). Both regions are declared exceptions to the unchanged-project byte-identity guarantee, stamped from vault state that can move independently of the repo.
+- **Unit 7 (t_c87644b4, trimmed):** a one-shot `o2b brain design-note <topic>` verb (CLI + MCP), diarization-shaped: read-only grounding pass over tension, decision, and truth records (topic matching reused from `deepSynthesis`), one spine envelope, payload validated to carry named alternatives with exactly one `recommended: true` - the cardinality enforced by a semantic check in the new registry. The note lands beside panel outputs under `Brain/decisions/`.
+- **t_916f9953 (explicit refusal, no code):** the local transformer embedding provider is refused for this wave. Rationale below under Design decisions.
+
+## Out of scope
+
+- An LLM-based salience scorer and its verdict cache. The deterministic gate serves the card's purpose (do not spend synthesis on junk) with zero added round trips and keeps the kernel model-free; if a model scorer is ever wanted it plugs into the same threshold seam.
+- Rewriting the write-session kernel onto the spine type. Adoption is additive; the durable envelope keeps its superset fields.
+- A partner query surface for codegraph (symbols, call edges). `CODEGRAPH_CLI`'s four tokens remain the entire surface; citing real symbols in architect output is a separate decision with its own risks.
+- Import-graph analysis in the architect scanner. The Mermaid diagram shows containment, which is what the scan truthfully knows; the design-doc exclusion in `scan.ts` stands.
+- A transformer/ML runtime in any form, including a registered provider name without a working backend - a name that cannot embed is a stub, and stubs are forbidden here.
+- Generalizing `skill-proposals.ts` into a universal speculative-artifact pipeline (consultant Variant C). The 51KB WAL-protected module is extended with one pattern kind, not refactored.
+
+## Chosen approach
+
+Consultant Variant B, "Shared envelope spine, additive adoption", with two orchestrator amendments. First deliverable is the spine: one named envelope core plus a semantic-checker registry beside `response-shape.ts`, keeping `ShapeDescriptor` deliberately shallow. Every new model lane in the wave (auto-extraction, skill drafting, design notes) plugs into that spine; legacy shapes alias it without rewriting. Deterministic units (salience gate, delete-linked, capture guidance, expiration, codegraph verdict region, Mermaid and decisions regions) proceed independently of the spine. Amendment one: the salience gate ships deterministic-only - the consultant kept an optional LLM retriage lane, which this wave drops as unnecessary complexity. Amendment two: unit 5 in the consultant's numbering (the transformer embedder) is refused rather than shipped as a seam, because a seam without a runtime is a stub.
+
+## Design decisions
+
+- **One envelope grammar, additive adoption.** Three shapes sharing field names without a shared type is the named DRY debt; this wave would otherwise raise the count to six. Aliasing rather than rewriting keeps the riskiest surface (durable write-sessions) read-only.
+- **Semantic checks live beside `ShapeDescriptor`, not inside it.** The descriptor language is shallow by recorded design ("over-constraining an extraction payload degrades recall"); cardinality rules like "exactly one Recommended" get a dedicated fail-closed checker registry, as the research citation contract already does ad hoc.
+- **The salience gate is deterministic.** All three inputs (decayed mass, Wilson-bound confidence, reuse rate) already exist as pure functions; recomputation is free, so no cache, no prompt version, no second envelope. Excluded items are always named in the summary - a gate that drops silently is the misleading fallback this project forbids.
+- **`auto_extract` is a new `source_type` member, not a reuse of `extracted`.** `extracted` means deterministic regex extraction; a model-authored signal must be distinguishable forever, because its trust profile differs. The vocabulary is closed and fail-closed; every consumer switch is updated in the same commit.
+- **Auto-extracted signals obey precision-beats-recall.** Confidence floor and per-session cap are enforced in the semantic check (refusal names the limit); the durability denylist applies; write-approval staging applies when enabled. The inbox trial lane plus dream promotion remains the only path to a confirmed preference.
+- **Delete-linked adopts the solely-derived rule.** The `notes/lifecycle.ts` header commitment (a delete reports inbound links, never repairs them) stands: linked notes that merely reference the target are still reported. Only single-purpose derived files tracing solely to the deleted note join the deletion set, mirroring `deleteBySource`, and the whole set passes the count guard and snapshot gate as one destructive site.
+- **Guidance joins the capture id hash.** Two captures differing only in guidance are different captures; excluding the field would silently collapse them into the `-2` allocator.
+- **Expiration has one chokepoint.** Both the creation flags and the mutation action call `normalizeExpirationDate`; a path that bypasses it would recreate the fail-open corruption the read side deliberately tolerates only because writes were assumed validated.
+- **Skill drafts stage inside the vault, materialize outside on accept.** `skills_dir` may point outside the vault; every automatic write stays in `Brain/skill-proposals/pending/`, and the one out-of-vault write happens on explicit accept through the existing WAL.
+- **Architect regions may be stamped, byte-identity exceptions declared.** The codegraph verdict and decisions regions depend on vault and partner state that moves independently of the repo; each region carries the stamp that explains its provenance (counts, health, candidate set), and the generator docstring names them as declared exceptions.
+- **t_916f9953 is refused.** A written invariant ("no new npm dependencies and NO ML runtime... the feature is redesigned in the OSB idiom, not the dependency added") stands against it; the lexical `LocalProvider` already gives key-less installs a working recall path; and the two honest alternatives - shipping a runtime, or registering a provider that cannot embed - are respectively an invariant break and a stub. The refusal, with this rationale, is the card's requested "explicit refusable choice". Revisit only if the invariant is deliberately lifted.
+
+## File changes
+
+- New: `src/core/brain/llm-step.ts` (spine type + builder), `src/core/brain/response-checks.ts` (semantic-checker registry), `src/core/brain/salience-gate.ts`, `src/core/brain/extract-signals.ts`, `src/core/brain/skill-page-drafts.ts` (mature-page mining, folded into skill-proposals surface), `src/core/brain/design-note.ts`, `src/cli/brain/verbs/{extract-signals,capture,design-note}.ts`, MCP tool modules or extensions for the three new tools, architect region renderers for `codegraph`, `module-map`, decisions note.
+- Modified: `diarization.ts`, `rollup-ladder.ts` (alias spine), `dream.ts` / `dream-apply.ts` / `dream-types.ts` / `dream-gates.ts` / `dream-stage.ts` / `verbs/dream.ts` (gate + retriage), `sessions` types (`source_type`), `signal.ts` / `preference.ts` (expires plumbing), `verbs/feedback.ts` + `feedback-tools.ts` (expires flags), `notes/lifecycle.ts` + `lifecycle-file-tools.ts` + `verbs/note-lifecycle.ts` (delete-linked, expiration action), `capture/capture-note.ts` (guidance), `telegram-capture.ts` (pass-through), `skill-proposals.ts` (+ pattern kind, SKILL.md materializer), `architect/generate.ts` (+ regions), `response-shape.ts` (descriptors), `destructive-sites.ts`, `state/surfaces.ts`, `brain.ts` dispatch, `help-text.ts`, `command-manifest.ts`, `brain-tools.ts`.
+- Docs: README section, CHANGELOG 1.51.0, this brainstorm directory.
+
+## Risks and open questions
+
+- The wave is large (nine implementation units); mitigation is strict TDD per unit, atomic commits, and unit independence outside the spine dependency (units 2, 4, 7 of the numbered scope block on unit 0 only).
+- The spine must generalize three existing shapes and three new consumers at once; a wrong generalization is expensive later. Mitigation: the spine carries only the fields all six share (`status`, `step`, `prompt`, `schema_hints`, `target_path`); everything else stays on the consumer's own type.
+- `source_type` widening changes the on-disk shape of a signal; the parser already fails closed on unknown members, so older readers refuse loudly rather than misread - acceptable and documented in the CHANGELOG.
+- The delete-linked derived-set computation must not confuse "references the note" with "derives solely from the note"; the deleteBySource fold is the tested template and its blast-radius tests are the model.
+- Whether `resolveNoteTarget`'s Brain-root refusal needs a scoped exception for the expiration mutation on signals/preferences - settled during implementation by routing the mutation through the feedback surface instead of the note-lifecycle surface if the refusal is load-bearing.
diff --git a/docs/brainstorm/salience-lifecycle-enrichment/plan.md b/docs/brainstorm/salience-lifecycle-enrichment/plan.md
new file mode 100644
index 00000000..ee147f4d
--- /dev/null
+++ b/docs/brainstorm/salience-lifecycle-enrichment/plan.md
@@ -0,0 +1,60 @@
+# Salience, lifecycle, and enrichment wave - implementation plan
+
+Order is dependency-driven: T1 first (T3, T8, T10 build on it), the rest are independent and land smallest-risk-first. Every task is one atomic conventional commit, TDD (failing test first), formatter and linter green before each commit.
+
+## Tasks
+
+### Task 1: Envelope spine and semantic-checker registry
+- **Files**: new `src/core/brain/llm-step.ts`, new `src/core/brain/response-checks.ts`; modified `src/core/brain/diarization.ts`, `src/core/brain/rollup-ladder.ts` (re-declare their step shapes against the spine type, zero behavioral change); `src/core/brain/response-shape.ts` untouched except exports if needed.
+- **Acceptance**: type-level test pins the spine field set; existing diarization and rollup suites pass unchanged; a semantic check registered for a test surface rejects a violating payload with a named refusal and passes a conforming one.
+- **Depends on**: none.
+
+### Task 2: Deterministic salience gate + retriage (t_de8a0b2d)
+- **Files**: new `src/core/brain/salience-gate.ts`; modified `dream-types.ts`, `dream-apply.ts`, `dream.ts`, `types.ts` (`BrainDreamConfig` threshold), `dream-stage.ts` (retriage action), `src/cli/brain/verbs/dream.ts`, help-text, command-manifest, MCP dream tool schema.
+- **Acceptance**: with threshold set, low-salience facts are excluded from rollup envelopes and listed by name in the dream summary; threshold unset reproduces current behavior byte-for-byte; `retriage` on a staged bundle reports the admitted/excluded delta after a threshold change; refusal paths carry `--json` shapes.
+- **Depends on**: none.
+
+### Task 3: extract-signals verb (t_1dace26d)
+- **Files**: new `src/core/brain/extract-signals.ts`, new `src/cli/brain/verbs/extract-signals.ts`; modified `types.ts` (`BRAIN_SIGNAL_SOURCE_TYPE` + `auto_extract`, all consumers), `response-shape.ts` (descriptor + `MODEL_AUTHORED_SHAPES`), `response-checks.ts` (cap + confidence floor), `signal.ts` if needed, MCP tool module + `brain-tools.ts`, help-text, command-manifest.
+- **Acceptance**: verb emits exactly one envelope over an imported session's turns; submitting a conforming payload writes inbox signals with `source_type: auto_extract` honoring the durability denylist and pending staging when write approval is on; an over-cap or under-floor payload is refused by name; `import-session` output is byte-identical to before.
+- **Depends on**: Task 1.
+
+### Task 4: delete-linked cascade (t_5e338af1 part A)
+- **Files**: modified `src/core/brain/notes/lifecycle.ts` (flag, derived-set fold, ladder), `src/core/brain/destructive-sites.ts`, `src/mcp/brain/lifecycle-file-tools.ts`, `src/cli/brain/verbs/note-lifecycle.ts`, help-text, command-manifest.
+- **Acceptance**: dry-run lists the deletion set (target + solely-derived files) and the report-only inbound references separately; confirm deletes exactly the listed set under one snapshot; a note referenced by any second source is reported, never deleted; destructive-site census test passes.
+- **Depends on**: none.
+
+### Task 5: capture guidance + CLI capture ingress (t_5e338af1 part B)
+- **Files**: modified `src/core/brain/capture/capture-note.ts` (`guidance` in input, hash, frontmatter/body, parser), `src/core/brain/capture/telegram-capture.ts` (pass-through); new `src/cli/brain/verbs/capture.ts`; help-text, command-manifest, `state/surfaces.ts` if the surface row needs updating.
+- **Acceptance**: two captures differing only in guidance produce distinct ids; round-trip parse returns the guidance verbatim; the CLI verb writes a capture note with source, sender, and guidance; existing telegram tests pass unchanged.
+- **Depends on**: none.
+
+### Task 6: expiration creation + mutation (t_5e338af1 part C)
+- **Files**: modified `src/cli/brain/verbs/feedback.ts`, `src/mcp/brain/feedback-tools.ts` (creation `expires`), `signal.ts` / `preference.ts` (mutation helper through `normalizeExpirationDate`), the surface chosen for mutation (feedback verb action or lifecycle action per design note), help-text, command-manifest.
+- **Acceptance**: a signal and a preference created with `expires` carry a normalized `expiration_date` and disappear from default queries after the date; mutation sets, changes, and explicitly clears the date; an unparseable date is refused by name at every surface; nothing bypasses `normalizeExpirationDate`.
+- **Depends on**: none.
+
+### Task 7: skill drafts from mature pages (t_abaec26b)
+- **Files**: modified `src/core/brain/skill-proposals.ts` (new `mature_page` pattern kind, SKILL.md materializer branch), new `src/core/brain/skill-page-drafts.ts` (maturity gate + candidate mining + envelope emission); `response-shape.ts` descriptor; CLI/MCP surface for the drafting action; help-text, command-manifest.
+- **Acceptance**: a page passing the maturity gate (tier/lifecycle/confidence + reuse evidence) yields a pending proposal containing one envelope-drafted SKILL body; a page covered by an installed skill is skipped with the skip named; accept materializes a well-formed SKILL.md under the skills root through the WAL; reject is sticky; nothing writes outside the vault before accept.
+- **Depends on**: Task 1.
+
+### Task 8: codegraph verdict region (t_3a418d07 descoped)
+- **Files**: modified `src/core/brain/architect/generate.ts` (new `codegraph` overview region), reading `partner/codegraph-report.ts` output; region renderer.
+- **Acceptance**: with a healthy partner index the overview carries `graph-present` with node/edge counts and health; with no partner it carries `graph-absent, lexical-only`; all five `CodegraphIndexState` values render distinctly; operator prose outside the region survives byte-for-byte; the declared byte-identity exception is documented in the generator docstring.
+- **Depends on**: none.
+
+### Task 9: Mermaid containment diagram + key-decisions note (t_041c571f)
+- **Files**: modified `src/core/brain/architect/generate.ts` (new `module-map` region, new decisions note kind), reading `architect/scan.ts` facts and `Brain/decisions/candidates/` filtered by `repo_key`.
+- **Acceptance**: the Mermaid block renders containment only (modules, file counts, dominant language), is deterministic under `compareStable`, and regenerates byte-identically for an unchanged project and vault; the decisions note lists ADR candidates for the repo's `repo_key` and updates when candidates change; a repo with no candidates gets an explicit empty-state line, not an absent region.
+- **Depends on**: none.
+
+### Task 10: design-note verb (t_c87644b4 trimmed)
+- **Files**: new `src/core/brain/design-note.ts`, new `src/cli/brain/verbs/design-note.ts`; `response-shape.ts` descriptor; `response-checks.ts` exactly-one-Recommended check; MCP tool + `brain-tools.ts`; help-text, command-manifest.
+- **Acceptance**: the verb grounds a topic in tension, decision, and truth records (empty stores produce a named empty grounding, not a failure), emits one envelope, and a payload with zero or two `recommended` alternatives is refused by the cardinality check while exactly one passes and commits a note under `Brain/decisions/`.
+- **Depends on**: Task 1.
+
+### Task 11: wave docs and version
+- **Files**: `README.md`, `CHANGELOG.md` (`## [1.51.0]` + link reference), `package.json` + `bun run scripts/sync-version.ts` (mirrored manifests), brainstorm directory committed.
+- **Acceptance**: `bun run scripts/sync-version.ts --check` passes; CHANGELOG entry covers all shipped units and the t_916f9953 refusal note.
+- **Depends on**: Tasks 1-10.
diff --git a/docs/brainstorm/salience-lifecycle-enrichment/variants.md b/docs/brainstorm/salience-lifecycle-enrichment/variants.md
new file mode 100644
index 00000000..3bde5795
--- /dev/null
+++ b/docs/brainstorm/salience-lifecycle-enrichment/variants.md
@@ -0,0 +1,46 @@
+# Salience, lifecycle, and enrichment wave - variants audit trail
+
+Consultant: Claude Code (claude -p), primary, one pass. Full verbatim output below, followed by the orchestrator decision.
+
+## Consultant output (verbatim)
+
+### Variant A: Deterministic islands (kernel-lean)
+
+- **Approach**: Build no new shared infrastructure; every unit takes its most deterministic, most descoped option and plugs into existing seams as-is. Unit 1 uses the deterministic scorer (salience mass + Wilson confidence + reuse rates) feeding the rollup fold set; unit 4 emits an honest-template SKILL.md staged inside Brain/skill-proposals/pending/; unit 8 is a standalone diarization-shaped verb with a dedicated cardinality checker beside response-shape.ts (research.ts precedent); unit 2 is the wave's only new envelope, cloned from the diarization shape; unit 5 is deferred with a recorded decision honoring the retrieval-ranking design's no-ML-runtime ruling; units 6 and 7 ship the sentinel-region verdict stamp and containment-only diagram. The only shared piece is a small evidence-scoring module reused by units 1 and 4.
+- **Trade-offs**:
+ - Pro: smallest blast radius; each of the eight units is independently landable and testable, ideal for one PR of atomic TDD units.
+ - Pro: kernel stays strictly model-free on the two units where an LLM lane was optional (1, 4); no verdict ledger, no second round trip.
+ - Con: the envelope count grows from three shapes to four-plus while the named DRY paydown is skipped β€” the debt compounds exactly when it was cheapest to pay.
+ - Con: template-body skill drafts and score-only salience gating cap output quality; a later upgrade to model-authored variants re-opens every one of these files.
+- **Complexity**: small
+- **Risk**: low
+
+### Variant B: Shared envelope spine, additive adoption
+
+- **Approach**: First deliverable of the wave is a named `NeedsLlmStep` envelope core plus a sidecar semantic-checker registry hung beside response-shape.ts (keeping ShapeDescriptors deliberately shallow), and an idempotency-ledger-keyed verdict-ledger helper generalized from rollup discipline. Adoption is additive: the three legacy shapes are re-declared as aliases of the shared type without rewriting write-session, while all new model lanes plug in directly β€” unit 2's auto-capture envelope, unit 8's design-note envelope with an "exactly one Recommended" sidecar checker, unit 1's optional LLM retriage (deterministic scorer ships as default, LLM triage behind the verdict ledger), and unit 4's envelope-drafted SKILL.md body staged through the existing proposal accept path. Units 3, 6, 7 proceed deterministically as in Variant A; unit 5 ships only the EmbeddingIdentity seam and exhaustive-switch registration point, no runtime.
+- **Trade-offs**:
+ - Pro: pays the named DRY debt at the exact moment the wave would otherwise double the envelope population from three to six divergent shapes.
+ - Pro: one home for model-payload validation semantics β€” unit 2's new ShapeDescriptor and unit 8's cardinality checker land in the same registry with the same fail-loud refusal vocabulary.
+ - Pro: additive aliasing avoids touching durable write-session state, so the riskiest legacy surface is read, not rewritten.
+ - Con: sequencing dependency β€” four units block on the spine landing first, weakening unit independence inside the single PR.
+ - Con: the spine must be designed against three existing shapes plus three new consumers at once; a wrong generalization is expensive to unwind after this release.
+- **Complexity**: medium
+- **Risk**: medium
+
+### Variant C: Speculative-artifact pipeline first
+
+- **Approach**: The shared abstraction is the human-approval staging lifecycle, not the envelope: generalize the pending.ts / skill-proposals machinery into a "speculative artifact" surface (source-typed inbox entry, evidence floor, WAL-protected accept, destructive-ladder-guarded reject) that unit 2's auto-extracted signals, unit 4's staged SKILL.md drafts, and unit 1's `retriage` verdicts all flow through. Units 6 and 7 share a sentinel-region writer in architect generate.ts that preserves byte-identity outside stamped regions; unit 8 stays a standalone diarization-shaped verb; unit 3 rides the existing destructive ladder; unit 5 is deferred. Envelopes stay per-unit copies of the diarization shape.
+- **Trade-offs**:
+ - Pro: institutionalizes the house rule that precision beats recall β€” every model-authored durable write in the wave passes one uniform human gate, with one STATE_SURFACES story.
+ - Pro: gives unit 4 its cleanest answer to "skills_dir may be outside the vault": staging lives in the generalized pipeline, materialization on accept is the only out-of-vault write.
+ - Con: skill-proposals.ts is 51KB of working, WAL-protected code; extracting a generic lifecycle from it is the largest and most regression-prone refactor available in this wave.
+ - Con: leaves the envelope DRY debt untouched while adding two more divergent shapes, so the next wave inherits both problems.
+- **Complexity**: large
+- **Risk**: high
+
+### Recommended: Variant B
+**Rationale**: This wave adds model lanes whether or not anything is shared β€” units 2 and 8 are envelopes by specification β€” so Variant A's savings are illusory: it ships the new shapes anyway and merely declines the consolidation the conventions already name as a paydown target. Variant B captures that paydown with additive aliasing rather than a write-session rewrite, keeping risk bounded, and its sidecar-checker registry resolves unit 8's cardinality problem and unit 2's shape validation in one fail-loud mechanism instead of two ad-hoc ones. Variant C's refactor of the 51KB proposal machinery is the wrong risk for a single-PR, eight-unit release, and its benefits (uniform staging) are largely obtainable later on top of B's spine.
+
+## Orchestrator decision
+
+Variant B accepted, with two amendments recorded in design.md: the salience gate ships deterministic-only (the optional LLM retriage lane the consultant kept adds a second envelope and a verdict cache for no benefit the deterministic scorer does not already deliver), and the transformer embedding unit is refused outright rather than shipped as a runtime-less seam, because a registered provider that cannot embed is a stub and stubs are forbidden in this project. Variant A was rejected because units 2 and 8 are envelopes by specification, so its savings are illusory - it ships the new shapes anyway while declining the consolidation. Variant C was rejected because refactoring the 51KB WAL-protected proposal machinery is the wrong risk for a single-PR wave.
diff --git a/docs/cli-reference.md b/docs/cli-reference.md
index 9330876a..78322242 100644
--- a/docs/cli-reference.md
+++ b/docs/cli-reference.md
@@ -637,6 +637,10 @@ o2b brain telegram-capture run | catchup - explicit inbound capture runner (fe
o2b brain inbox-drain [--apply] - walk staged captures, classify each structurally (URL-shaped body -> source reference, explicit obligation marker -> task, otherwise atomic idea), route on apply (source ingest, note in captured/, obligation open), archive processed captures, and report every item with action and reason; dry-run default writes nothing; rerun after apply is a no-op
o2b brain diarize <entity> [--json] - entity profile skeleton plus one needs-llm-step envelope; the stated-vs-evidenced section is computed deterministically (stated claims versus evidence frequency and recency), every line carrying an evidence identity; unknown entity is a typed error
o2b brain repair-lane [--apply --confirm "apply repair"] - propose link-graph edges ordered by identity strength (explicit references, session continuity, same-topic evidence; inferred opt-in) under a confidence threshold and a hard per-run write cap; dry-run default; reruns after apply converge to zero writes. --apply plans first and then runs the paired graph-efficacy holdout harness over every edge that plan proposes, taking anchor and target from the edge itself: it reports graph lift (targets reachable only through the graph) apart from direct recall (targets already a 1-hop neighbour) and refuses the apply, writing nothing, when any target resolves to no durable-memory note or hydrates into no evidence. The refusal names the failing edges with their verdict and resolves its exit through the registered repair-holdout-unresolved diagnostic; --json carries the counts in an additive holdout object beside next_command. Dry-run does not evaluate the gate and its bytes are unchanged - it already names each unresolvable endpoint as a skip-missing-target decision
+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 extract-signals <session-ref> [--payload <json> | --payload-file <path>] [--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, or an item below the confidence floor, refuses the whole payload by name and writes nothing; a session with no imported turns is refused, never reported as empty
o2b brain deep-synthesis --json now also carries findings with causal_context, decomposed confidence (support, opposition, freshness, coverage), and the excluded_findings ledger with excluded_finding_count
```
@@ -1031,7 +1035,8 @@ file under exit `0` can never be read as a machine that recorded nothing.
## Stability and trust (since v1.0.0)
```text
-o2b brain dream [run] [--dry-run] | stage | validate <run-id> | apply <run-id> | discard <run-id> | list - staged lifecycle over a persisted proposal bundle; validate/apply exit 1 on drift
+o2b brain dream [run] [--dry-run] | stage | validate <run-id> | apply <run-id> | retriage <run-id> | discard <run-id> | list - staged lifecycle over a persisted proposal bundle; validate/apply exit 1 on drift
+o2b brain dream retriage R re-run the deterministic salience gate (`dream.salience_threshold`) against staged bundle R and report the delta: which facts would newly enter or leave the rollup ladder's fold set, each named with its current and its staged score. Read-only - the bundle is never rewritten, so re-stage to adopt the new partition. An unknown bundle, or one staged before the gate shipped, exits 2 naming the reason. Mirrors MCP `brain_dream` `action: "retriage"`
o2b brain dream --step S run ONE independently-runnable step instead of the full pass: `scan` (pure read) or `heal-enrich` (asking for it is the opt-in, so the config gate is not consulted). Any other token - including a dream reporting phase - exits 2 with the specific reason that step cannot run alone and the runnable set. Returns a partial result marked `partial: true`, never a run summary. Mirrors MCP `brain_dream` `step`
o2b brain dream --gate N=V override one phase gate for THIS RUN ONLY (`--gate heal_enrich=true|false`); repeatable, never written back to `Brain/_brain.yaml`, so a targeted pass needs no config edit and no revert. An unknown gate or a non-boolean value exits 2 naming the known gates. Mirrors MCP `brain_dream` `gates: {heal_enrich: bool}`
o2b brain doctor gains the removed-tool-reference warning: vault notes, root instruction files, and installed skills naming a tool removed in 1.0.0 are flagged with the replacement
diff --git a/docs/how-it-works.md b/docs/how-it-works.md
index 1dfce54f..26f517d4 100644
--- a/docs/how-it-works.md
+++ b/docs/how-it-works.md
@@ -332,6 +332,14 @@ confirm) -> **heal** (auto-retire stale, optional enrichment) -> **log**
off). The heal phase links exact title/alias mentions across user vault
pages outside the Brain root. Disabled by default so the install stays
byte-identical.
+- **Salience gate** (opt-in via `dream.salience_threshold`, unset by
+ default). The pass's only model delegation is the count-triggered
+ rollup ladder, so the gate governs exactly one thing: which facts are
+ counted into the ladder's fold set. The score is a deterministic
+ weighted sum of the decayed outcome mass, the Wilson-bound confidence
+ and the observed-reuse rate - no model, no cache. Unset, the gate is
+ open, scores nothing, reads nothing, and the run is what it always was;
+ set, every held-back fact is named with its score in the run summary.
### Vault portability + session economy (v0.22.0)
diff --git a/docs/mcp.md b/docs/mcp.md
index 9f11b588..96fc2de3 100644
--- a/docs/mcp.md
+++ b/docs/mcp.md
@@ -172,7 +172,7 @@ Either way a call that has already entered one of them runs it to the end.
## Tool Highlights
-The full server currently advertises 110 tools; the 18 deprecated predecessor
+The full server currently advertises 111 tools; the 18 deprecated predecessor
names were removed in 1.0.0 and now answer a precise INVALID_PARAMS tombstone
(see "Consolidated views and deprecated aliases" below). The table highlights
the operator-facing core,
@@ -1189,3 +1189,46 @@ log line is machine-composed rather than authored.
value is `INVALID_PARAMS` naming the accepted set. Records predating the
field carry no channel and fall into no bucket - see
[`observability.md`](observability.md).
+- Since v1.51.0 `brain_extract_signals` joins the surface (111 total): the
+ batch counterpart to the regex fact extractor. Called with a `session`
+ alone it is read-only and returns that session's imported USER turns plus
+ exactly one needs-llm-step envelope; called with `items` it validates the
+ mined signals - structurally, then against a per-session cap and a
+ per-item confidence floor - and writes the accepted ones into
+ `Brain/inbox/` as `source_type: auto_extract` signals, subject to the
+ durability denylist and to `Brain/pending/` staging when write approval is
+ on. `auto_extract` is a new member of the closed `source_type` vocabulary,
+ distinct from `extracted` (regex) forever, because their trust profiles
+ differ; a reader from an older build refuses a file carrying it rather
+ than misreading it. A payload over the cap or below the floor is refused
+ whole, naming the limit and the offending value - nothing partial lands.
+- Since v1.51.0 `brain_skill_proposals` accepts two further operations and
+ no new tool. `page_candidates` is read-only: it gates the vault's user
+ pages on the page-meta trio (`tier: core`, a non-stale lifecycle,
+ `_confidence: high`) 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 skipped page with the reason and the
+ measured value behind it. `page_draft` validates the returned SKILL.md
+ draft - structurally, then against the rule that its `name` is a legal
+ skill directory name - and STAGES it as a pending proposal under the new
+ `mature_page` pattern kind, inside the vault. Nothing reaches the skills
+ root until `accept`, which materializes a `SKILL.md` there through the
+ same write-ahead journal the procedure branch uses; the journal records
+ the absolute path it is about to write, so a rollback removes exactly
+ that file (and the directory it created for it, only while empty).
+ Sticky rejection applies as it does to every other pattern kind.
+- Since v1.51.0 `brain_design_note` joins the surface (112 total): the
+ one-shot sibling of the panel lane. Called with a `topic` alone it is
+ read-only - it grounds the topic in the vault's tension records, decision
+ records and truth projections using the same deterministic token overlap
+ `brain_decision`'s similar-decision lookup ranks with, and returns one
+ needs-llm-step envelope. A store this vault holds NOTHING in is named in
+ `empty_stores`; a store that holds records and matched none of them is
+ not, because those are different facts and lead to different next moves.
+ An empty vault is a grounded report, never a refusal. Called with a
+ `note` it validates the written note - structurally, then against the
+ rule that EXACTLY ONE alternative sets `recommended: true` - and commits
+ it as `Brain/decisions/design-<date>-<topic>.md`, beside the panel
+ outputs. Zero and two-plus recommendations are both refused and the
+ refusal states the count found; a note for the same topic on the same day
+ is refused rather than overwriting the first.
diff --git a/openclaw.plugin.json b/openclaw.plugin.json
index 35f6189a..f2703c72 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.50.3",
+ "version": "1.51.0",
"activation": { "onStartup": true },
"skills": ["./skills"],
"contracts": {
diff --git a/package.json b/package.json
index 3389a611..dcff22d7 100644
--- a/package.json
+++ b/package.json
@@ -1,6 +1,6 @@
{
"name": "open-second-brain",
- "version": "1.50.3",
+ "version": "1.51.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 6b94736e..2566e86f 100644
--- a/plugin.yaml
+++ b/plugin.yaml
@@ -1,5 +1,5 @@
name: open-second-brain
-version: "1.50.3"
+version: "1.51.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 c20e7a18..a44a7ad9 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.50.3",
+ "version": "1.51.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/hermes/_schemas.py b/plugins/hermes/_schemas.py
index 029a40a6..4c1c180d 100644
--- a/plugins/hermes/_schemas.py
+++ b/plugins/hermes/_schemas.py
@@ -78,7 +78,13 @@ STATIC_TOOL_SCHEMAS: tuple[dict[str, Any], ...] = (
'dedupes retried calls: same '
'key + same payload is a '
'no-op; same key + different '
- 'payload is rejected.'}},
+ 'payload is rejected.'},
+ 'expires': {'type': 'string',
+ 'description': 'Optional YYYY-MM-DD or ISO-8601 '
+ 'lifetime. Past it the signal (and '
+ 'any force-confirmed preference) '
+ 'drops out of default reads; the '
+ 'file is never deleted.'}},
'required': ['topic', 'signal', 'principle'],
'additionalProperties': False}},
{'name': 'brain_apply_evidence',
diff --git a/plugins/hermes/plugin.yaml b/plugins/hermes/plugin.yaml
index 6b94736e..2566e86f 100644
--- a/plugins/hermes/plugin.yaml
+++ b/plugins/hermes/plugin.yaml
@@ -1,5 +1,5 @@
name: open-second-brain
-version: "1.50.3"
+version: "1.51.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 5d7e2583..185cd1f3 100644
--- a/pyproject.toml
+++ b/pyproject.toml
@@ -10,7 +10,7 @@ build-backend = "setuptools.build_meta"
# CLI entry points (those moved to `package.json` `bin`).
[project]
name = "open-second-brain"
-version = "1.50.3"
+version = "1.51.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 2182f56a..4d0f052e 100644
--- a/src/cli/brain.ts
+++ b/src/cli/brain.ts
@@ -108,6 +108,8 @@ import {
cmdBrainTrigger,
cmdBrainDeepSynthesis,
cmdBrainDiarize,
+ cmdBrainExtractSignals,
+ cmdBrainDesignNote,
cmdBrainIdeas,
cmdBrainSessionHook,
cmdBrainImportClaudeMemory,
@@ -131,6 +133,8 @@ import {
cmdBrainToday,
cmdBrainApplyMarkers,
cmdBrainPending,
+ cmdBrainCapture,
+ cmdBrainExpire,
cmdBrainTelegramCapture,
cmdBrainInboxDrain,
cmdBrainRepairLane,
@@ -180,6 +184,8 @@ export async function handleBrainSubcommand(argv: ReadonlyArray<string>): Promis
return await cmdBrainNote(rest);
case "lifecycle":
return await cmdBrainLifecycle(rest);
+ case "expire":
+ return await cmdBrainExpire(rest);
case "note-lifecycle":
return await cmdBrainNoteLifecycle(rest);
case "scaffold-stub":
@@ -356,6 +362,10 @@ export async function handleBrainSubcommand(argv: ReadonlyArray<string>): Promis
return await cmdBrainDeepSynthesis(rest);
case "diarize":
return await cmdBrainDiarize(rest);
+ case "extract-signals":
+ return await cmdBrainExtractSignals(rest);
+ case "design-note":
+ return await cmdBrainDesignNote(rest);
case "ideas":
return await cmdBrainIdeas(rest);
case "entity":
@@ -420,6 +430,8 @@ export async function handleBrainSubcommand(argv: ReadonlyArray<string>): Promis
return await cmdBrainPending(rest);
case "signal":
return await cmdBrainSignal(rest);
+ case "capture":
+ return await cmdBrainCapture(rest);
case "telegram-capture":
return await cmdBrainTelegramCapture(rest);
case "inbox-drain":
diff --git a/src/cli/brain/help-text.ts b/src/cli/brain/help-text.ts
index e694a062..b7b9ddd5 100644
--- a/src/cli/brain/help-text.ts
+++ b/src/cli/brain/help-text.ts
@@ -33,10 +33,11 @@ export const BRAIN_HELP = `usage: o2b brain <verb> [args...]
Brain verbs (observing memory):
init Bootstrap <vault>/Brain/ (idempotent; --force overwrites)
feedback Record a taste signal (--topic, --signal, --principle)
- dream Deterministic dreaming pass; stage/validate/apply staged bundles
+ dream Deterministic dreaming pass; stage/validate/apply/retriage bundles
apply-evidence Log a real-work application of a preference
note Append a one-line narrative milestone to Brain/log/today
lifecycle Tombstone/supersede a memory, resolve chain tips, curator slices
+ expire Set, change or clear a signal's or preference's expiration date
note-lifecycle Note FILES: rename/move/archive/delete one, rewriting inbound links
scaffold-stub Unresolved wikilink targets: list them, or materialise a stub
claims Claim-graph query: current truth, truth-at-T, replaced-by, contested-by
@@ -123,7 +124,7 @@ Brain verbs (observing memory):
recall-telemetry List/summarize opt-in recall telemetry records
knowledge-gaps Rank recurring queries the vault answers poorly (unmet demand)
generation-reports Record/list/summarize opt-in LLM generation traces
- skill-proposals Learn/list/review deterministic skill proposals
+ skill-proposals Learn/list/review skill proposals, from telemetry and from mature vault pages
procedural-memory Reconcile/list procedural memory index and usage
procedural-graph Rebuild/show procedural graph and hint projections
recurrence Inspect and update recurrence/support diagnostics
@@ -134,6 +135,7 @@ Brain verbs (observing memory):
apply-markers Apply @osb set frontmatter write-backs (report by default; --apply writes)
pending Review the write-approval queue: list | apply <id> | reject <id>
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
inbox-drain Classify and route staged captures (dry-run; --apply to route)
repair-lane Propose memory-graph edges (dry-run; --apply --confirm to write, holdout-gated)
@@ -160,6 +162,8 @@ Brain verbs (observing memory):
trigger Proactive trigger queue with anti-nag lifecycle (scan/list/ack/dismiss/act/suppress/unsuppress/history)
deep-synthesis Topic dossier: notes, agreements, contradictions, stale claims, gaps
diarize Subject profile: document set, stated-vs-evidenced gap, needs-llm-step skeleton
+ extract-signals Mine taste signals from an imported session's user turns (two-phase, needs-llm-step)
+ design-note One-shot design note grounded in tensions, decisions and truth records
ideas Ranked next-direction candidates from open loops (--triggers to enqueue)
continuity Export continuity records as ATOF/ATIF trajectories (read-only)
bench Memory quality benchmark over a disposable fixture vault
@@ -195,11 +199,14 @@ export const VERB_HELP: Record<string, string> = {
"Creates a `sig-*.md` in Brain/inbox/. With --force-confirmed also creates a `pref-*.md`.\n",
dream:
"usage: o2b brain dream [run] [--dry-run] | stage | validate <run-id> | apply <run-id> |\n" +
- " discard <run-id> | list [--now <ISO-8601>] [--agent <name>] [--vault <path>] [--json]\n" +
+ " retriage <run-id> | discard <run-id> | list [--now <ISO-8601>] [--agent <name>]\n" +
+ " [--vault <path>] [--json]\n" +
"Runs the deterministic dreaming algorithm (idempotent), or manages the staged\n" +
"lifecycle: stage persists a reviewable proposal bundle under Brain/dream/staged/,\n" +
"validate proves the vault has not drifted, apply re-validates then runs the same\n" +
- "engine live, discard drops the bundle.\n",
+ "engine live, discard drops the bundle. retriage re-runs the salience gate\n" +
+ "(dream.salience_threshold) against the bundle and names the facts that would move\n" +
+ "into or out of the rollup fold set; it changes nothing, so re-stage to adopt it.\n",
"apply-evidence":
"usage: o2b brain apply-evidence --pref <id> --artifact <wikilink> --result applied|violated|outdated\n" +
" [--agent <name>] [--note <text>] [--vault <path>] [--json]\n" +
@@ -220,15 +227,33 @@ export const VERB_HELP: Record<string, string> = {
"[--high-use-min <n>] lists injected-never-used, contradicted, and high-used\n" +
"memories from observed-use verdicts. Tombstoned entries stay on disk for audit\n" +
"but are excluded from recall, inject, and active.md.\n",
+ expire:
+ "usage: o2b brain expire <id> --expires <YYYY-MM-DD|ISO-8601|none>\n" +
+ " [--agent <name>] [--vault <path>] [--json]\n" +
+ "Set, change or clear the expiration_date of one signal or preference,\n" +
+ "addressed by id (sig-<date>-<slug>, pref-<slug> or ret-<slug>). An expired\n" +
+ "memory is FILTERED on read, never deleted or moved - `o2b brain query\n" +
+ "--show-expired` still shows it. --expires none clears the date; it is a word\n" +
+ "rather than an empty string so a broken shell expansion cannot un-expire a\n" +
+ "memory. An unparseable date, or an id naming no artifact, exits 2 by name.\n" +
+ "Create-time expirations come from `o2b brain feedback --expires` instead.\n",
"note-lifecycle":
"usage: o2b brain note-lifecycle <rename|move|archive|delete> <path> [<to>]\n" +
- " [--apply] [--confirm] [--expect <n>] [--strict] [--vault <path>] [--config <path>] [--json]\n" +
+ " [--apply] [--confirm] [--delete-linked] [--expect <n>] [--strict] [--vault <path>]\n" +
+ " [--config <path>] [--json]\n" +
"Note FILES, not memories: rename changes the filename in place, move changes the\n" +
"directory, archive displaces the note under Archive/ mirroring its path, delete\n" +
"removes it. Dry run by default - it walks, counts and writes nothing. --apply\n" +
"performs it; delete additionally requires --confirm, because no archive covers a\n" +
- "note outside Brain/. --expect <n> asserts the inbound-reference count before any\n" +
- "write and --strict refuses a mutation carrying no such guard.\n" +
+ "note outside Brain/. --expect <n> asserts the count before any write and --strict\n" +
+ "refuses a mutation carrying no such guard.\n" +
+ "--delete-linked (delete only) widens the removal to the Brain files that DECLARE\n" +
+ "the note as their provenance and trace SOLELY to it - a per-item summary, signal,\n" +
+ "preference or entity page whose frontmatter names it and whose whole content\n" +
+ "restates it. A page that merely mentions the note in prose is reported and kept,\n" +
+ "as is a page citing a second source, as is every user note; the receipt prints\n" +
+ "the deletion set and the reported set separately, names the scope it scanned,\n" +
+ "and --expect then counts the deletion set.\n" +
"Inbound [[wikilinks]] are rewritten across the vault, minus what vault scope\n" +
"excludes, minus code fences, and minus Brain/log, which is append-only. The\n" +
"receipt names how stale the search index now is and the command that fixes it.\n" +
@@ -671,6 +696,33 @@ export const VERB_HELP: Record<string, string> = {
"One canonical entity per (category, name); aliases resolve to the canonical record.\n" +
"Labels are decoration-stripped and quality-gated on set; prune removes historical\n" +
"malformed nodes and their edges. Denylist: entities.label_denylist config key.",
+ "design-note":
+ "usage: o2b brain design-note <topic> [--vault <vault>] [--agent <name>]\n" +
+ " [--payload <json> | --payload-file <path>] [--json]\n" +
+ "The one-shot sibling of `o2b brain panel`. Without a payload it is\n" +
+ "read-only: it grounds the topic in the vault's tension records, decision\n" +
+ "records and truth projections - naming any store the vault holds nothing\n" +
+ "in, which is not the same as a store that matched nothing - and prints\n" +
+ "the single needs-llm-step envelope the calling agent answers.\n" +
+ "With --payload / --payload-file it validates the written note and commits\n" +
+ "it as Brain/decisions/design-<date>-<topic>.md, beside the panel outputs.\n" +
+ "The note must weigh named alternatives and mark EXACTLY ONE recommended:\n" +
+ "zero and two-plus are both refused, and the refusal states the count.\n" +
+ "A note for the same topic on the same day is refused, never overwritten.\n",
+ "extract-signals":
+ "usage: o2b brain extract-signals <session-ref> [--vault <vault>] [--agent <name>]\n" +
+ " [--payload <json> | --payload-file <path>] [--json]\n" +
+ "Mine durable taste signals out of an ALREADY-IMPORTED session's user\n" +
+ "turns. Without a payload the verb is read-only: it prints the turns it\n" +
+ "would mine and the single needs-llm-step envelope the calling agent\n" +
+ "answers. With --payload / --payload-file it validates that answer and\n" +
+ "writes the accepted items into Brain/inbox/ as speculative signals with\n" +
+ "source_type: auto_extract, subject to the durability denylist and to\n" +
+ "Brain/pending/ staging when write approval is enabled.\n" +
+ "Refusals are named: a payload over the per-session cap, or an item below\n" +
+ "the confidence floor, rejects the whole payload and writes nothing.\n" +
+ "Import the session with `o2b brain import-session --recall` first; a\n" +
+ "session with no imported turns is refused, never reported as empty.\n",
"import-session":
"usage: o2b brain import-session <path> [--vault <vault>]\n" +
" [--format auto|<registered-adapter>]\n" +
@@ -823,14 +875,17 @@ 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> [args]\n" +
- "Deterministic proposal queue lifecycle.\n" +
+ "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" +
" learn [--min-support <n>] [--vault <path>] [--json]\n" +
" list [--vault <path>] [--json]\n" +
" accept <slug> [--note <text>] [--vault <path>] [--json]\n" +
" reject <slug> --note <text> [--vault <path>] [--json]\n" +
" recover [--discard-unreadable] [--vault <path>] [--json]\n" +
" usage [--vault <path>] [--json]\n" +
+ " page-candidates [--vault <path>] [--json]\n" +
+ " page-draft <page> (--payload <json> | --payload-file <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",
"procedural-memory":
"usage: o2b brain procedural-memory <reconcile|list|mark-used> [args]\n" +
@@ -903,6 +958,18 @@ export const VERB_HELP: Record<string, string> = {
"excludes it from the dream pass while it stays readable in Brain/retired/.\n" +
"Retiring a missing, already-retired, or non-signal id exits 2 (never a\n" +
"silent no-op).\n",
+ capture:
+ "usage: o2b brain capture [<body>] [--source <channel>] [--sender <who>]\n" +
+ " [--guidance <text>] [--at <ISO>] [--vault <path>] [--json]\n" +
+ "Stage one capture through the capture-note contract - the same writer the\n" +
+ "Telegram bot uses, so the id, the frontmatter and the staging path are\n" +
+ "identical. The body is the argument, or stdin when no argument is given.\n" +
+ "--source names the channel (default cli) and --sender who is capturing\n" +
+ "(default the configured agent); --at backdates a replayed capture to its\n" +
+ "own instant. --guidance records what should be DONE with the capture as a\n" +
+ "## Guidance body section, kept apart from the captured text and part of\n" +
+ "the id hash, so two captures differing only in guidance stay distinct.\n" +
+ "An empty body or a blank --guidance is refused by name and exits 2.\n",
"telegram-capture":
"usage: o2b brain telegram-capture <run|catchup> [--vault <path>]\n" +
"Inbound Telegram capture bot. run long-polls getUpdates via fetch (needs\n" +
@@ -1094,7 +1161,9 @@ export const VERB_HELP: Record<string, string> = {
architect:
"usage: o2b brain architect <project-path> [--vault V] [--json]\n" +
"Scan a project tree deterministically (stdlib-only, no LLM) and\n" +
- "write architecture notes under Brain/projects/arch/<repo-key>/.\n" +
+ "write architecture notes under Brain/projects/arch/<repo-key>/:\n" +
+ "an overview, a key-decisions note listing this repo's ADR\n" +
+ "candidates, and one note per detected module.\n" +
"Generated content lives in sentinel regions; operator prose\n" +
"outside regions survives every re-scan byte-for-byte.",
git:
diff --git a/src/cli/brain/verbs/architect.ts b/src/cli/brain/verbs/architect.ts
index 97d16bb9..bfa54464 100644
--- a/src/cli/brain/verbs/architect.ts
+++ b/src/cli/brain/verbs/architect.ts
@@ -61,6 +61,7 @@ export async function cmdBrainArchitect(argv: string[]): Promise<number> {
repo_key: res.repoKey,
dir: res.dir,
overview_path: res.overviewPath,
+ decisions_path: res.decisionsPath,
module_paths: res.modulePaths,
created: res.created,
updated: res.updated,
diff --git a/src/cli/brain/verbs/capture.ts b/src/cli/brain/verbs/capture.ts
new file mode 100644
index 00000000..27fbc27d
--- /dev/null
+++ b/src/cli/brain/verbs/capture.ts
@@ -0,0 +1,153 @@
+/**
+ * `o2b brain capture <body>` - stage one inbound capture from a terminal.
+ *
+ * The capture contract shipped with exactly one writer: the inbound
+ * Telegram bot. Everything downstream of it - the staging area, the
+ * inbox drain, the `/catchup` watermark - was therefore reachable only by
+ * an install that had configured a chat channel, and an operator sitting
+ * in front of the vault had no way in at all.
+ *
+ * This verb is that door and nothing more. It builds a
+ * {@link WriteCaptureInput} and hands it to the same
+ * {@link writeCaptureNote} the bot calls, so the id hash, the frontmatter,
+ * the guidance section and the collision ladder are the contract's and
+ * cannot drift into a second set of rules.
+ *
+ * The body may be an argument or arrive on stdin - a captured thought is
+ * as often the output of another command as it is something typed - and
+ * the two paths produce the same page. `--sender` names who is capturing
+ * and defaults to the configured agent, because a capture with no
+ * attributable sender is a record whose provenance nobody can reconstruct.
+ */
+
+import {
+ CaptureContractError,
+ writeCaptureNote,
+ type CaptureNote,
+} from "../../../core/brain/capture/capture-note.ts";
+import { isoSecond } from "../../../core/brain/time.ts";
+import { CliError } from "../../argparse.ts";
+import {
+ brainVerbContext,
+ normalizeFlagString,
+ ok,
+ okJson,
+ parse,
+ parseOptionalIsoDate,
+ resolveBrainAgent,
+} from "../helpers.ts";
+
+const USAGE =
+ "usage: o2b brain capture [<body>] [--source <channel>] [--sender <who>] " +
+ "[--guidance <text>] [--at <ISO>] [--vault <path>] [--json]";
+
+/** Channel recorded when the caller names none: this verb itself. */
+const DEFAULT_SOURCE = "cli";
+
+/**
+ * Refuse a request this verb understood and declined. Exit 2, with the
+ * reason on stderr for a human and inside the payload for a machine - the
+ * `dream` verb's shape, so a caller parsing one parses both.
+ */
+function refuse(message: string, asJson: boolean): number {
+ if (asJson) {
+ okJson({ ok: false, message });
+ return 2;
+ }
+ process.stderr.write(`error: ${message}\n`);
+ return 2;
+}
+
+function renderJson(note: CaptureNote): Record<string, unknown> {
+ return {
+ ok: true,
+ id: note.id,
+ path: note.path,
+ body: note.body,
+ guidance: note.guidance,
+ source: note.provenance.source,
+ sender: note.provenance.sender,
+ captured_at: note.provenance.capturedAt,
+ staged: note.staged,
+ };
+}
+
+export async function cmdBrainCapture(argv: string[]): Promise<number> {
+ const { flags, positional } = parse(argv, {
+ vault: { type: "string" },
+ source: { type: "string" },
+ sender: { type: "string" },
+ guidance: { type: "string" },
+ agent: { type: "string" },
+ at: { type: "string" },
+ json: { type: "boolean" },
+ });
+ const asJson = flags["json"] === true;
+
+ // The argument wins over stdin. Reading both and concatenating would
+ // silently merge two authors' text into one capture; reading stdin when
+ // an argument was given would discard what the caller typed.
+ let body = positional.join(" ").trim();
+ if (body.length === 0) {
+ try {
+ body = (await Bun.stdin.text()).trim();
+ } catch (exc) {
+ return refuse(
+ `capture could not read the body from stdin: ${(exc as Error).message ?? String(exc)}`,
+ asJson,
+ );
+ }
+ }
+ if (body.length === 0) {
+ return refuse(`capture body is empty; pass it as an argument or on stdin. ${USAGE}`, asJson);
+ }
+
+ // An explicit `--at` keeps a backfilled capture on its own instant
+ // rather than the wall clock of the shell that replayed it.
+ const at = parseOptionalIsoDate(flags, "at");
+ if (at.error !== null) return refuse(at.error, asJson);
+ const capturedAt = isoSecond(at.value ?? new Date());
+
+ let context;
+ try {
+ context = brainVerbContext(flags);
+ } catch (exc) {
+ if (exc instanceof CliError) return refuse(exc.message, asJson);
+ throw exc;
+ }
+
+ const guidance = normalizeFlagString(flags["guidance"]);
+ // A `--guidance` that was passed and normalises away is whitespace the
+ // caller meant as an instruction. The contract refuses it by name; this
+ // check exists so the refusal names the FLAG rather than the field.
+ if (flags["guidance"] !== undefined && guidance === null) {
+ return refuse(
+ "capture --guidance was passed with no text; drop the flag or say something",
+ asJson,
+ );
+ }
+
+ try {
+ const note = writeCaptureNote(context.vault, {
+ body,
+ provenance: {
+ source: normalizeFlagString(flags["source"]) ?? DEFAULT_SOURCE,
+ sender: normalizeFlagString(flags["sender"]) ?? resolveBrainAgent(flags, context.config),
+ capturedAt,
+ },
+ ...(guidance === null ? {} : { guidance }),
+ });
+ if (asJson) okJson(renderJson(note));
+ else {
+ ok(`captured: ${note.id}`);
+ ok(` path: ${note.path}`);
+ ok(` source: ${note.provenance.source} / sender: ${note.provenance.sender}`);
+ if (note.guidance !== null) ok(` guidance: ${note.guidance}`);
+ }
+ return 0;
+ } catch (exc) {
+ if (exc instanceof CaptureContractError) return refuse(exc.message, asJson);
+ if (exc instanceof CliError) return refuse(exc.message, asJson);
+ throw exc;
+ }
+}
diff --git a/src/cli/brain/verbs/design-note.ts b/src/cli/brain/verbs/design-note.ts
new file mode 100644
index 00000000..0c31dfe2
--- /dev/null
+++ b/src/cli/brain/verbs/design-note.ts
@@ -0,0 +1,138 @@
+/**
+ * `o2b brain design-note <topic>` (t_c87644b4): the one-shot sibling of
+ * `o2b brain panel`.
+ *
+ * Without a payload the verb is read-only: it grounds the topic in the
+ * vault's tensions, decisions and truth projections and prints the single
+ * needs-llm-step envelope the calling agent answers. With `--payload` /
+ * `--payload-file` it validates that answer - shape, then the
+ * exactly-one-recommended rule - and commits the note under
+ * `Brain/decisions/`. No model is ever called.
+ *
+ * Exit codes: 0 on success, 1 on an operational failure or a refused
+ * payload, 2 on usage errors.
+ */
+
+import { readFileSync } from "node:fs";
+
+import {
+ commitDesignNote,
+ DesignNoteError,
+ planDesignNote,
+} from "../../../core/brain/design-note.ts";
+import { ResponseCheckError } from "../../../core/brain/response-checks.ts";
+import { ResponseShapeError } from "../../../core/brain/response-shape.ts";
+import {
+ brainVerbContext,
+ fail,
+ ok,
+ okJson,
+ parse,
+ resolveBrainAgent,
+ usageError,
+} from "../helpers.ts";
+
+const USAGE =
+ "usage: o2b brain design-note <topic> [--payload <json> | --payload-file <path>] " +
+ "[--agent <name>] [--vault <path>] [--json]";
+
+/** Refusals the caller caused, reported without a stack. */
+const NAMED_REFUSALS = [DesignNoteError, ResponseShapeError, ResponseCheckError] as const;
+
+function isNamedRefusal(err: unknown): err is Error {
+ return NAMED_REFUSALS.some((type) => err instanceof type);
+}
+
+export async function cmdBrainDesignNote(argv: string[]): Promise<number> {
+ const { flags, positional } = parse(argv, {
+ vault: { type: "string" },
+ agent: { type: "string" },
+ payload: { type: "string" },
+ "payload-file": { type: "string" },
+ json: { type: "boolean" },
+ });
+ const topic = positional.join(" ").trim();
+ if (topic === "") return usageError(USAGE);
+ const asJson = flags["json"] === true;
+
+ try {
+ const { config, vault } = brainVerbContext(flags);
+ const rawPayload =
+ typeof flags["payload"] === "string"
+ ? (flags["payload"] as string)
+ : typeof flags["payload-file"] === "string"
+ ? readFileSync(flags["payload-file"] as string, "utf8")
+ : null;
+
+ if (rawPayload === null) {
+ const report = planDesignNote(vault, topic, { now: new Date() });
+ const g = report.grounding;
+ if (asJson) {
+ okJson({
+ ok: true,
+ topic: report.topic,
+ slug: report.slug,
+ generated_at: report.generatedAt,
+ target_path: report.targetPath,
+ grounding: {
+ tensions: g.tensions,
+ decisions: g.decisions,
+ truth_slots: g.truthSlots,
+ conflicts: g.conflicts,
+ counts: g.counts,
+ empty_stores: g.emptyStores,
+ },
+ llm_step: report.llmStep,
+ });
+ return 0;
+ }
+ ok(`design note: ${report.topic}`);
+ ok(
+ `grounding: ${g.counts.tensions} tension(s), ${g.counts.decisions} decision(s), ` +
+ `${g.counts.truthSlots} claim(s), ${g.counts.conflicts} conflict(s)`,
+ );
+ // Named rather than implied: an empty store and a store that matched
+ // nothing are different facts about this vault.
+ if (g.emptyStores.length > 0) ok(`empty stores: ${g.emptyStores.join(", ")}`);
+ ok(`needs-llm-step: ${report.llmStep.step} -> ${report.llmStep.target_path}`);
+ return 0;
+ }
+
+ let payload: unknown;
+ try {
+ payload = JSON.parse(rawPayload);
+ } catch {
+ const message = "payload must be valid JSON";
+ if (!asJson) return fail(message);
+ okJson({ ok: false, message });
+ return 1;
+ }
+ const res = commitDesignNote(vault, topic, payload, {
+ agent: resolveBrainAgent(flags, config),
+ now: new Date(),
+ });
+ if (asJson) {
+ okJson({
+ ok: true,
+ topic: res.topic,
+ slug: res.slug,
+ path: res.path,
+ recommended: res.recommended,
+ alternative_count: res.alternativeCount,
+ });
+ return 0;
+ }
+ ok(`wrote ${res.path}`);
+ ok(`recommended: ${res.recommended} (of ${res.alternativeCount} alternative(s))`);
+ return 0;
+ } catch (err) {
+ const message = isNamedRefusal(err)
+ ? err.message
+ : `design-note failed: ${(err as Error).message ?? String(err)}`;
+ if (asJson) {
+ okJson({ ok: false, message });
+ return 1;
+ }
+ return fail(message);
+ }
+}
diff --git a/src/cli/brain/verbs/dream.ts b/src/cli/brain/verbs/dream.ts
index b68dddce..40593d0f 100644
--- a/src/cli/brain/verbs/dream.ts
+++ b/src/cli/brain/verbs/dream.ts
@@ -1,11 +1,13 @@
/**
* `o2b brain dream [run] [--dry-run] [--step S] [--gate N=V] | stage |
- * validate <run-id> | apply <run-id> | discard <run-id> | list` - the
- * learning pass plus the staged lifecycle (t_ae8a8ec0). `run` (the
- * default, kept positional-free for back-compat) promotes inline;
- * `stage` persists a reviewable proposal bundle; `validate` proves the
- * vault has not drifted; `apply` re-validates and runs the same engine
- * live; `discard` drops the bundle.
+ * validate <run-id> | apply <run-id> | retriage <run-id> | discard
+ * <run-id> | list` - the learning pass plus the staged lifecycle
+ * (t_ae8a8ec0). `run` (the default, kept positional-free for back-compat)
+ * promotes inline; `stage` persists a reviewable proposal bundle;
+ * `validate` proves the vault has not drifted; `apply` re-validates and
+ * runs the same engine live; `retriage` re-runs the salience gate against
+ * the current threshold and reports what would move; `discard` drops the
+ * bundle.
*
* `--step` and `--gate` (no-dead-ends, Unit E - operator surface) are
* the shell reach for the two capabilities that previously existed only
@@ -39,9 +41,12 @@ import {
import {
applyDreamBundle,
discardDreamBundle,
+ DreamRetriageError,
listDreamBundles,
+ retriageDreamBundle,
stageDream,
validateDreamBundle,
+ type DreamRetriageEntry,
} from "../../../core/brain/dream-stage.ts";
import {
createSafeguard,
@@ -67,10 +72,13 @@ import {
const USAGE =
`usage: o2b brain dream [run] [--dry-run] [--step <${DREAM_STEP_RUNNABLE.join("|")}>] ` +
`[--gate <${DREAM_GATE_NAMES.join("|")}>=<true|false>] | ` +
- "stage | validate <run-id> | apply <run-id> | discard <run-id> | list " +
+ "stage | validate <run-id> | apply <run-id> | retriage <run-id> | discard <run-id> | list " +
"[--now ISO] [--agent A] [--vault <path>] [--json]";
-const ACTIONS = new Set(["run", "stage", "validate", "apply", "discard", "list"]);
+const ACTIONS = new Set(["run", "stage", "validate", "apply", "retriage", "discard", "list"]);
+
+/** Staged actions that name one bundle. */
+const RUN_ID_ACTIONS = new Set(["validate", "apply", "retriage", "discard"]);
/**
* Refuse a request this verb understood and declined. Exit 2, with the
@@ -86,6 +94,30 @@ function refuse(message: string, asJson: boolean, payload: Record<string, unknow
return 2;
}
+/** `--json` row for one fact the gate would move. */
+function retriageRow(entry: DreamRetriageEntry): Record<string, unknown> {
+ return {
+ pref_id: entry.pref_id,
+ path: entry.path,
+ score: entry.score,
+ staged_score: entry.staged_score,
+ };
+}
+
+/** An absent threshold reads as a word, never as a number the operator did not set. */
+function describeThreshold(threshold: number | null): string {
+ return threshold === null ? "absent" : String(threshold);
+}
+
+/** Print one side of a retriage delta, naming every fact in it. */
+function printRetriageDelta(label: string, entries: ReadonlyArray<DreamRetriageEntry>): void {
+ ok(`${label}: ${entries.length}`);
+ for (const entry of entries) {
+ const staged = entry.staged_score === null ? "not scored" : String(entry.staged_score);
+ ok(` ${entry.pref_id} ${entry.score} (staged ${staged})`);
+ }
+}
+
/** Render one partial step result as the verb's human line format. */
function printStepResult(result: DreamStepResult): void {
ok(`step: ${result.step}`);
@@ -121,7 +153,7 @@ export async function cmdBrainDream(argv: string[]): Promise<number> {
process.stderr.write(`${USAGE}\n`);
return 2;
}
- const needsRunId = action === "validate" || action === "apply" || action === "discard";
+ const needsRunId = RUN_ID_ACTIONS.has(action);
if (needsRunId ? positional.length !== 2 : positional.length > 1) {
process.stderr.write(`${USAGE}\n`);
return 2;
@@ -364,6 +396,39 @@ export async function cmdBrainDream(argv: string[]): Promise<number> {
return outcome.applied ? 0 : 1;
}
+ if (action === "retriage") {
+ const runId = positional[1]!;
+ const outcome = retriageDreamBundle(vault, runId, {
+ now: now ?? new Date(),
+ safeguard: guard(),
+ ...(agent ? { agentName: agent } : {}),
+ });
+ if (asJson) {
+ okJson({
+ run_id: outcome.runId,
+ staged_threshold: outcome.stagedThreshold,
+ current_threshold: outcome.currentThreshold,
+ changed: outcome.changed,
+ considered: outcome.considered,
+ admitted: outcome.admitted,
+ newly_admitted: outcome.newlyAdmitted.map(retriageRow),
+ newly_excluded: outcome.newlyExcluded.map(retriageRow),
+ notes: [...outcome.notes],
+ });
+ return 0;
+ }
+ ok(
+ `retriage ${runId}: threshold staged=${describeThreshold(outcome.stagedThreshold)} ` +
+ `current=${describeThreshold(outcome.currentThreshold)}`,
+ );
+ ok(`fold set: ${outcome.admitted} of ${outcome.considered} admitted now`);
+ printRetriageDelta("newly admitted", outcome.newlyAdmitted);
+ printRetriageDelta("newly excluded", outcome.newlyExcluded);
+ for (const note of outcome.notes) ok(`note: ${note}`);
+ if (outcome.changed) ok("re-stage the bundle to adopt this partition");
+ return 0;
+ }
+
if (action === "discard") {
const runId = positional[1]!;
const removed = discardDreamBundle(vault, runId);
@@ -398,6 +463,12 @@ export async function cmdBrainDream(argv: string[]): Promise<number> {
return 0;
}
} catch (exc) {
+ // A bundle this verb understood and declined is a refusal, not an
+ // operational failure: exit 2, with the bare reason beside the
+ // sentence so a machine caller can branch on it.
+ if (exc instanceof DreamRetriageError) {
+ return refuse(exc.message, asJson, { action, run_id: exc.runId, reason: exc.reason });
+ }
const timedOut = exc instanceof SafeguardTimeoutError;
if (asJson) {
okJson({
@@ -485,6 +556,17 @@ export async function cmdBrainDream(argv: string[]): Promise<number> {
}
ok(`run_id: ${summary.run_id}`);
ok(`changed: ${summary.changed}`);
+ // Only when a threshold is configured: with the gate open every fact is
+ // admitted, and a line saying so on every run would be noise. With it
+ // closed the exclusions are otherwise invisible on this stream - the
+ // ladder just folds fewer facts and says nothing about why.
+ const gate = summary.salience_gate;
+ if (gate.threshold !== null) {
+ ok(
+ `salience_gate: ${gate.admitted} of ${gate.considered} fact(s) admitted ` +
+ `(threshold ${gate.threshold})`,
+ );
+ }
if (summary.new_unconfirmed.length > 0)
ok(`new_unconfirmed: ${summary.new_unconfirmed.join(", ")}`);
if (summary.confirmed.length > 0) ok(`confirmed: ${summary.confirmed.join(", ")}`);
diff --git a/src/cli/brain/verbs/expire.ts b/src/cli/brain/verbs/expire.ts
new file mode 100644
index 00000000..f5d23321
--- /dev/null
+++ b/src/cli/brain/verbs/expire.ts
@@ -0,0 +1,118 @@
+/**
+ * `o2b brain expire <id> --expires <date|none>` - set, change or clear a
+ * memory's expiration after it was written.
+ *
+ * The sibling half of `o2b brain feedback --expires`, which can only
+ * declare a lifetime at creation. This verb is the one that changes one:
+ * a migration that slipped, a rule that turned out to be permanent, a
+ * date that was simply wrong.
+ *
+ * One verb for both artifact kinds, addressed by id, because "how long
+ * does this memory hold" is one question whether the memory is a signal
+ * or a preference. Every value goes through the core's
+ * `normalizeExpirationDate`; clearing is the explicit word `none`, never
+ * an empty string a broken shell expansion could produce.
+ *
+ * Deliberately NOT part of `o2b brain note-lifecycle`: that surface runs
+ * every path through `resolveNoteTarget`, which refuses the `Brain/`
+ * machinery root, and that refusal is what keeps a note-editing verb from
+ * rewriting a preference.
+ */
+
+import {
+ EXPIRATION_CLEAR,
+ ExpirationTargetNotFoundError,
+ ExpirationValueError,
+ InvalidExpirationTargetError,
+ setExpiration,
+ type SetExpirationResult,
+} from "../../../core/brain/expiration-set.ts";
+import { CliError } from "../../argparse.ts";
+import {
+ brainVerbContext,
+ normalizeFlagString,
+ ok,
+ okJson,
+ parse,
+ resolveBrainAgent,
+} from "../helpers.ts";
+
+const USAGE =
+ `usage: o2b brain expire <id> --expires <YYYY-MM-DD|ISO-8601|${EXPIRATION_CLEAR}> ` +
+ "[--agent <name>] [--vault <path>] [--json]";
+
+/** Refuse by name, exit 2, on whichever stream the caller is reading. */
+function refuse(message: string, asJson: boolean): number {
+ if (asJson) {
+ okJson({ ok: false, message });
+ return 2;
+ }
+ process.stderr.write(`error: ${message}\n`);
+ return 2;
+}
+
+function renderJson(res: SetExpirationResult): Record<string, unknown> {
+ return {
+ ok: true,
+ id: res.id,
+ kind: res.kind,
+ path: res.path,
+ expiration: res.expiration,
+ previous: res.previous,
+ changed: res.changed,
+ };
+}
+
+export async function cmdBrainExpire(argv: string[]): Promise<number> {
+ const { flags, positional } = parse(argv, {
+ vault: { type: "string" },
+ expires: { type: "string" },
+ agent: { type: "string" },
+ json: { type: "boolean" },
+ });
+ const asJson = flags["json"] === true;
+
+ const id = positional[0];
+ if (id === undefined || id.trim().length === 0) {
+ return refuse(`brain expire requires a signal or preference id. ${USAGE}`, asJson);
+ }
+ // Required rather than defaulted. There is no sensible default lifetime,
+ // and a missing flag reading as "clear it" would be the destructive
+ // reading of an omission.
+ const expires = normalizeFlagString(flags["expires"]);
+ if (expires === null) {
+ return refuse(`brain expire requires --expires. ${USAGE}`, asJson);
+ }
+
+ let context;
+ try {
+ context = brainVerbContext(flags);
+ } catch (exc) {
+ if (exc instanceof CliError) return refuse(exc.message, asJson);
+ throw exc;
+ }
+
+ try {
+ const res = setExpiration(context.vault, id, expires, {
+ agent: resolveBrainAgent(flags, context.config),
+ });
+ if (asJson) okJson(renderJson(res));
+ else {
+ const what = res.expiration === null ? "cleared" : `expires ${res.expiration}`;
+ ok(`${res.id}: ${what}${res.changed ? "" : " (unchanged)"}`);
+ ok(` path: ${res.path}`);
+ ok(` previous: ${res.previous ?? EXPIRATION_CLEAR}`);
+ }
+ return 0;
+ } catch (exc) {
+ if (
+ exc instanceof ExpirationValueError ||
+ exc instanceof ExpirationTargetNotFoundError ||
+ exc instanceof InvalidExpirationTargetError
+ ) {
+ return refuse((exc as Error).message, asJson);
+ }
+ if (exc instanceof CliError) return refuse(exc.message, asJson);
+ throw exc;
+ }
+}
diff --git a/src/cli/brain/verbs/extract-signals.ts b/src/cli/brain/verbs/extract-signals.ts
new file mode 100644
index 00000000..d07c9c01
--- /dev/null
+++ b/src/cli/brain/verbs/extract-signals.ts
@@ -0,0 +1,134 @@
+/**
+ * `o2b brain extract-signals <session-ref>` (t_1dace26d): mine durable
+ * taste signals out of an already-imported session's user turns.
+ *
+ * Two phases through one verb. Without a payload the verb is read-only and
+ * prints the mining plan plus the single needs-llm-step envelope the
+ * calling agent answers. With `--payload` / `--payload-file` it validates
+ * that answer and writes the accepted items as speculative inbox signals.
+ * OSB runs no model on either path.
+ *
+ * Exit codes: 0 on success, 1 on an operational failure or a refused
+ * payload, 2 on usage errors.
+ */
+
+import { readFileSync } from "node:fs";
+
+import {
+ commitExtractedSignals,
+ ExtractSignalsError,
+ planExtractSignals,
+} from "../../../core/brain/extract-signals.ts";
+import { ResponseCheckError } from "../../../core/brain/response-checks.ts";
+import { ResponseShapeError } from "../../../core/brain/response-shape.ts";
+import {
+ brainVerbContext,
+ fail,
+ ok,
+ okJson,
+ parse,
+ resolveBrainAgent,
+ usageError,
+} from "../helpers.ts";
+
+const USAGE =
+ "usage: o2b brain extract-signals <session-ref> [--payload <json> | --payload-file <path>] " +
+ "[--agent <name>] [--vault <path>] [--json]";
+
+/** Refusals the operator caused, reported without a stack. */
+const NAMED_REFUSALS = [ExtractSignalsError, ResponseShapeError, ResponseCheckError] as const;
+
+function isNamedRefusal(err: unknown): err is Error {
+ return NAMED_REFUSALS.some((type) => err instanceof type);
+}
+
+export async function cmdBrainExtractSignals(argv: string[]): Promise<number> {
+ const { flags, positional } = parse(argv, {
+ vault: { type: "string" },
+ agent: { type: "string" },
+ payload: { type: "string" },
+ "payload-file": { type: "string" },
+ json: { type: "boolean" },
+ });
+ const sessionRef = positional[0];
+ if (!sessionRef || sessionRef.trim() === "") return usageError(USAGE);
+ const asJson = flags["json"] === true;
+
+ try {
+ const { config, vault } = brainVerbContext(flags);
+ const rawPayload =
+ typeof flags["payload"] === "string"
+ ? (flags["payload"] as string)
+ : typeof flags["payload-file"] === "string"
+ ? readFileSync(flags["payload-file"] as string, "utf8")
+ : null;
+
+ if (rawPayload === null) {
+ const plan = planExtractSignals(vault, sessionRef, { now: new Date() });
+ if (asJson) {
+ okJson({
+ ok: true,
+ session_id: plan.sessionId,
+ generated_at: plan.generatedAt,
+ boundary_decision: plan.boundaryDecision,
+ turns_scanned: plan.turnsScanned,
+ turns_mined: plan.turnsMined.map((t) => ({ turn_id: t.turnId, text: t.text })),
+ cap: plan.cap,
+ confidence_floor: plan.confidenceFloor,
+ llm_step: plan.llmStep,
+ });
+ return 0;
+ }
+ ok(`session: ${plan.sessionId} (${plan.turnsScanned} imported turn(s))`);
+ ok(`mining ${plan.turnsMined.length} user turn(s)`);
+ ok(`limits: at most ${plan.cap} items, confidence >= ${plan.confidenceFloor}`);
+ ok(`needs-llm-step: ${plan.llmStep.step} -> ${plan.llmStep.target_path}`);
+ return 0;
+ }
+
+ let payload: unknown;
+ try {
+ payload = JSON.parse(rawPayload);
+ } catch {
+ // Reported here rather than by the ingress: at this point the mistake
+ // is the JSON the operator typed, and a path inside a payload the CLI
+ // never parsed would not tell them what to fix.
+ const message = "payload must be valid JSON";
+ if (!asJson) return fail(message);
+ okJson({ ok: false, message });
+ return 1;
+ }
+ const res = commitExtractedSignals(vault, sessionRef, payload, {
+ agent: resolveBrainAgent(flags, config),
+ now: new Date(),
+ });
+ if (asJson) {
+ okJson({
+ ok: true,
+ session_id: res.sessionId,
+ written: res.written.map((w) => ({ id: w.id, path: w.path, topic: w.topic })),
+ staged: res.staged,
+ deduped: res.deduped,
+ durability_rejected: res.durabilityRejected,
+ rejected: res.rejected.map((r) => ({ topic: r.topic, reason: r.reason })),
+ });
+ return 0;
+ }
+ ok(
+ `wrote ${res.written.length} signal(s)` +
+ (res.staged > 0 ? ` (staged for approval)` : "") +
+ `, deduped ${res.deduped}, durability-rejected ${res.durabilityRejected}`,
+ );
+ for (const r of res.rejected) ok(`rejected: ${r.topic} (${r.reason})`);
+ return 0;
+ } catch (err) {
+ const message = isNamedRefusal(err)
+ ? err.message
+ : `extract-signals failed: ${(err as Error).message ?? String(err)}`;
+ if (asJson) {
+ okJson({ ok: false, message });
+ return 1;
+ }
+ return fail(message);
+ }
+}
diff --git a/src/cli/brain/verbs/feedback.ts b/src/cli/brain/verbs/feedback.ts
index 9eaea0cd..87c5d4a6 100644
--- a/src/cli/brain/verbs/feedback.ts
+++ b/src/cli/brain/verbs/feedback.ts
@@ -14,6 +14,7 @@ import { emitNextStep, type AdvisoryStream } from "../../advisory-rail.ts";
import { loadFeedbackDefaultScopeSafe } from "../../../core/brain/policy.ts";
import { appendLogEvent } from "../../../core/brain/log.ts";
import { writePreference } from "../../../core/brain/preference.ts";
+import { normalizeExpirationDate } from "../../../core/brain/expiration.ts";
import { isoDate, isoSecond } from "../../../core/brain/time.ts";
import {
BRAIN_LOG_EVENT_KIND,
@@ -37,6 +38,7 @@ export async function cmdBrainFeedback(argv: string[]): Promise<number> {
"force-confirmed": { type: "boolean" },
date: { type: "string" },
slug: { type: "string" },
+ expires: { type: "string" },
json: { type: "boolean" },
});
@@ -74,6 +76,21 @@ export async function cmdBrainFeedback(argv: string[]): Promise<number> {
raw = String(flags["raw"]);
}
+ // Creation-time expiration (unit 3c). Validated HERE, before the
+ // signal write, so an unparseable date refuses the whole call by name
+ // instead of landing a signal and then failing on the preference.
+ // `normalizeExpirationDate` is the one door: the writers call it too,
+ // and this pre-check exists so the refusal reaches the operator as a
+ // usage error rather than as a write failure halfway through.
+ let expires: string | undefined;
+ if (flags["expires"] !== undefined) {
+ try {
+ expires = normalizeExpirationDate(String(flags["expires"]));
+ } catch (exc) {
+ return fail(`brain feedback --expires: ${(exc as Error).message ?? exc}`);
+ }
+ }
+
const now = new Date();
const date = (flags["date"] as string | undefined) ?? isoDate(now);
const slug = (flags["slug"] as string | undefined) ?? String(flags["topic"]);
@@ -89,6 +106,7 @@ export async function cmdBrainFeedback(argv: string[]): Promise<number> {
...(flags["scope"] ? { scope: String(flags["scope"]) } : {}),
...(flags["source"] ? { source: flags["source"] as string[] } : {}),
...(raw !== undefined ? { raw } : {}),
+ ...(expires !== undefined ? { expiration_date: expires } : {}),
};
let sigResult;
try {
@@ -162,6 +180,9 @@ export async function cmdBrainFeedback(argv: string[]): Promise<number> {
// preferences. This writer now matches it.
confidence_value: 0,
...(effectiveScope !== undefined ? { scope: effectiveScope } : {}),
+ // The same lifetime the signal carries: a rule confirmed from
+ // an observation that expires on a date does not outlive it.
+ ...(expires !== undefined ? { expiration_date: expires } : {}),
},
// Ownership is resolved by the writer from the CLI's own config,
// never echoed from `--agent`: the flag is caller-supplied, and a
diff --git a/src/cli/brain/verbs/index.ts b/src/cli/brain/verbs/index.ts
index 6fa8ce04..971bc079 100644
--- a/src/cli/brain/verbs/index.ts
+++ b/src/cli/brain/verbs/index.ts
@@ -91,6 +91,8 @@ export { cmdBrainPanel } from "./panel.ts";
export { cmdBrainTrigger } from "./trigger.ts";
export { cmdBrainDeepSynthesis } from "./deep-synthesis.ts";
export { cmdBrainDiarize } from "./diarize.ts";
+export { cmdBrainExtractSignals } from "./extract-signals.ts";
+export { cmdBrainDesignNote } from "./design-note.ts";
export { cmdBrainIdeas } from "./ideas.ts";
export { cmdBrainEntity } from "./entity.ts";
export { cmdBrainSessionHook } from "./session-hook.ts";
@@ -116,6 +118,8 @@ export { cmdBrainAgenda } from "./agenda.ts";
export { cmdBrainToday } from "./today.ts";
export { cmdBrainApplyMarkers } from "./apply-markers.ts";
export { cmdBrainPending } from "./pending.ts";
+export { cmdBrainCapture } from "./capture.ts";
+export { cmdBrainExpire } from "./expire.ts";
export { cmdBrainTelegramCapture } from "./telegram-capture.ts";
export { cmdBrainInboxDrain } from "./inbox-drain.ts";
export { cmdBrainRepairLane } from "./repair-lane.ts";
diff --git a/src/cli/brain/verbs/note-lifecycle.ts b/src/cli/brain/verbs/note-lifecycle.ts
index b0192bdf..be6ef914 100644
--- a/src/cli/brain/verbs/note-lifecycle.ts
+++ b/src/cli/brain/verbs/note-lifecycle.ts
@@ -13,8 +13,15 @@
*
* Dry run is the default here as it is in the core. `--apply` performs
* the operation, `--confirm` is additionally required by `delete`, and
- * `--expect N` / `--strict` assert the inbound-reference count before
- * anything is written.
+ * `--expect N` / `--strict` assert the count before anything is written -
+ * the deletion set under `--delete-linked`, the inbound references
+ * otherwise.
+ *
+ * `--delete-linked` widens a delete to the Brain files that declare the
+ * note as their provenance and derive solely from it; a page that only
+ * mentions it in prose is reported, never deleted. The receipt then
+ * prints two lists rather than a count: what will go, and what is
+ * reported and stays.
*/
import { defaultConfigPath } from "../../../core/config.ts";
@@ -62,6 +69,14 @@ function renderJson(res: NoteLifecycleResult): Record<string, unknown> {
next_command: res.references.index.nextCommand,
},
},
+ cascade:
+ res.cascade === null
+ ? null
+ : {
+ deletion_set: [...res.cascade.deletionSet],
+ reported_files: [...res.cascade.reportedFiles],
+ scanned_scope: res.cascade.scannedScope,
+ },
};
}
@@ -83,10 +98,24 @@ function renderText(res: NoteLifecycleResult): string {
? ""
: ` NOT rewritten (still naming ${res.from}):\n` +
refs.rewriteFailures.map((f) => ` ${f.path}: ${f.reason}\n`).join("");
+ // The cascade's two lists are printed IN FULL and separately, not
+ // counted. An operator authorising a multi-file delete has to be able
+ // to read every path that will go and every path that will not, and a
+ // count is precisely the summary that hides the one wrong entry.
+ const cascade =
+ res.cascade === null
+ ? ""
+ : ` deletion set (${res.cascade.deletionSet.length}, scope ${res.cascade.scannedScope}):\n` +
+ res.cascade.deletionSet.map((p) => ` ${p}\n`).join("") +
+ ` reported, not deleted (${res.cascade.reportedFiles.length}):\n` +
+ (res.cascade.reportedFiles.length === 0
+ ? " (none)\n"
+ : res.cascade.reportedFiles.map((p) => ` ${p}\n`).join(""));
return (
`${mode}: ${where}\n` +
` inbound references: ${refs.inboundFiles.length} file(s) of ${refs.filesScanned} scanned, ` +
`${refs.filesRewritten} rewritten (basename: ${refs.basename})\n` +
+ cascade +
split +
` recoverability: ${res.recoverability.state}` +
(res.recoverability.blockers.length > 0 ? ` (${res.recoverability.blockers.join(", ")})` : "") +
@@ -103,6 +132,7 @@ export async function cmdBrainNoteLifecycle(argv: string[]): Promise<number> {
config: { type: "string" },
apply: { type: "boolean" },
confirm: { type: "boolean" },
+ "delete-linked": { type: "boolean" },
expect: { type: "string" },
strict: { type: "boolean" },
json: { type: "boolean" },
@@ -136,6 +166,7 @@ export async function cmdBrainNoteLifecycle(argv: string[]): Promise<number> {
...(to !== undefined ? { to } : {}),
apply: flags["apply"] === true,
confirm: flags["confirm"] === true,
+ deleteLinked: flags["delete-linked"] === true,
expect: expectCount,
strict: flags["strict"] === true,
});
diff --git a/src/cli/brain/verbs/skill-proposals.ts b/src/cli/brain/verbs/skill-proposals.ts
index 0e369f41..391b9ad9 100644
--- a/src/cli/brain/verbs/skill-proposals.ts
+++ b/src/cli/brain/verbs/skill-proposals.ts
@@ -1,3 +1,10 @@
+import { readFileSync } from "node:fs";
+
+import { resolveSkillsDir } from "../../../core/config.ts";
+import {
+ commitSkillPageDraft,
+ planSkillPageDrafts,
+} from "../../../core/brain/skill-page-drafts.ts";
import {
acceptSkillProposal,
discardUnreadableSkillAcceptJournals,
@@ -18,9 +25,115 @@ export async function cmdBrainSkillProposals(argv: string[]): Promise<number> {
if (sub === "reject") return reject(rest);
if (sub === "recover") return recover(rest);
if (sub === "usage") return usage(rest);
+ if (sub === "page-candidates") return pageCandidates(rest);
+ if (sub === "page-draft") return pageDraft(rest);
throw new CliError(
- "brain skill-proposals: expected learn, list, accept, reject, recover, or usage",
+ "brain skill-proposals: expected learn, list, accept, reject, recover, usage, " +
+ "page-candidates, or page-draft",
+ );
+}
+
+/**
+ * Which mature vault pages deserve a skill, and the envelope for each.
+ *
+ * Read-only. Every page the walk turned down is listed with the reason -
+ * a report that showed only the winners could not be told apart from a
+ * vault nobody has tagged.
+ */
+function pageCandidates(argv: string[]): number {
+ const { flags } = parse(argv, {
+ vault: { type: "string" },
+ json: { type: "boolean" },
+ });
+ const { config, vault } = brainVerbContext(flags);
+ const skillsDir = resolveSkillsDir(config);
+ const report = planSkillPageDrafts(vault, {
+ now: new Date(),
+ ...(skillsDir !== null ? { skillsDir } : {}),
+ });
+
+ if (flags["json"]) {
+ process.stdout.write(
+ JSON.stringify(
+ {
+ generated_at: report.generatedAt,
+ pages_scanned: report.pagesScanned,
+ admitted: report.admitted.map((c) => ({
+ path: c.path,
+ title: c.title,
+ tier: c.tier,
+ lifecycle: c.lifecycle,
+ confidence: c.confidence,
+ reuse_score: c.reuseScore,
+ reuse_observations: c.reuseObservations,
+ llm_step: c.llmStep,
+ })),
+ skipped: report.skipped.map((s) => ({
+ path: s.path,
+ title: s.title,
+ reason: s.reason,
+ detail: s.detail,
+ })),
+ },
+ null,
+ 2,
+ ) + "\n",
+ );
+ return 0;
+ }
+
+ process.stdout.write(
+ `skill-proposals page-candidates: scanned=${report.pagesScanned} ` +
+ `admitted=${report.admitted.length} skipped=${report.skipped.length}\n`,
+ );
+ for (const c of report.admitted) {
+ process.stdout.write(` admit ${c.path} needs-llm-step: ${c.llmStep.step}\n`);
+ }
+ for (const s of report.skipped) {
+ process.stdout.write(` skip ${s.path} ${s.reason}: ${s.detail}\n`);
+ }
+ return 0;
+}
+
+/**
+ * Stage one returned draft as a pending proposal. Writes inside the vault
+ * only - the SKILL.md is materialized by `accept`, never here.
+ */
+function pageDraft(argv: string[]): number {
+ const { flags, positional } = parse(argv, {
+ vault: { type: "string" },
+ json: { type: "boolean" },
+ payload: { type: "string" },
+ "payload-file": { type: "string" },
+ });
+ const page = trim(positional[0]);
+ if (!page) throw new CliError("brain skill-proposals page-draft: page path is required");
+ const raw =
+ typeof flags["payload"] === "string"
+ ? (flags["payload"] as string)
+ : typeof flags["payload-file"] === "string"
+ ? readFileSync(flags["payload-file"] as string, "utf8")
+ : null;
+ if (raw === null) {
+ throw new CliError("brain skill-proposals page-draft: --payload or --payload-file is required");
+ }
+ let payload: unknown;
+ try {
+ payload = JSON.parse(raw);
+ } catch {
+ throw new CliError("brain skill-proposals page-draft: payload must be valid JSON");
+ }
+ const vault = brainVerbContext(flags).vault;
+ const result = commitSkillPageDraft(vault, page, payload, { now: new Date() });
+
+ if (flags["json"]) {
+ process.stdout.write(JSON.stringify(result, null, 2) + "\n");
+ return 0;
+ }
+ process.stdout.write(
+ `${result.outcome} ${result.id}` + ("reason" in result ? ` (${result.reason})` : "") + `\n`,
);
+ return 0;
}
/**
@@ -151,11 +264,16 @@ function accept(argv: string[]): number {
});
const slug = trim(positional[0]);
if (!slug) throw new CliError("brain skill-proposals accept: slug is required");
- const vault = brainVerbContext(flags).vault;
+ const { config, vault } = brainVerbContext(flags);
const note = trim(flags["note"]);
- const result = note
- ? acceptSkillProposal(vault, slug, { note })
- : acceptSkillProposal(vault, slug);
+ // 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.
+ const skillsRoot = resolveSkillsDir(config);
+ const result = acceptSkillProposal(vault, slug, {
+ ...(note ? { note } : {}),
+ ...(skillsRoot !== null ? { skillsRoot } : {}),
+ });
if (flags["json"]) {
process.stdout.write(JSON.stringify(result, null, 2) + "\n");
diff --git a/src/cli/command-manifest.ts b/src/cli/command-manifest.ts
index 88096950..99cf604c 100644
--- a/src/cli/command-manifest.ts
+++ b/src/cli/command-manifest.ts
@@ -135,10 +135,25 @@ export const CLI_COMMAND_MANIFEST: CliRootManifest = Object.freeze({
[],
[
command("init", "Bootstrap Brain skeleton"),
- command("feedback", "Record a taste signal"),
+ command("feedback", "Record a taste signal", [
+ flag("vault", "string"),
+ flag("topic", "string"),
+ flag("signal", "string"),
+ flag("principle", "string"),
+ flag("scope", "string"),
+ flag("source", "string-array"),
+ flag("agent", "string"),
+ flag("raw", "string"),
+ flag("raw-file", "string"),
+ flag("force-confirmed", "boolean"),
+ flag("date", "string"),
+ flag("slug", "string"),
+ flag("expires", "string"),
+ ]),
command(
"dream",
- "Run deterministic consolidation; staged lifecycle via stage/validate/apply; " +
+ "Run deterministic consolidation; staged lifecycle via stage/validate/apply, " +
+ "retriage re-runs the salience gate over a staged bundle; " +
"--step runs one independently-runnable step, --gate overrides a phase gate for one run",
[flag("step", "string"), flag("gate", "string-array")],
),
@@ -363,6 +378,11 @@ export const CLI_COMMAND_MANIFEST: CliRootManifest = Object.freeze({
"lifecycle",
"Tombstone or supersede a memory, resolve chain tips, list curator slices",
),
+ command("expire", "Set, change or clear a signal's or preference's expiration date", [
+ flag("vault", "string"),
+ flag("expires", "string"),
+ flag("agent", "string"),
+ ]),
command(
"note-lifecycle",
"Note FILES: rename, move, archive or delete one, rewriting inbound wikilinks",
@@ -371,6 +391,7 @@ export const CLI_COMMAND_MANIFEST: CliRootManifest = Object.freeze({
flag("config", "string"),
flag("apply", "boolean"),
flag("confirm", "boolean"),
+ flag("delete-linked", "boolean"),
flag("expect", "string"),
flag("strict", "boolean"),
],
@@ -432,6 +453,26 @@ export const CLI_COMMAND_MANIFEST: CliRootManifest = Object.freeze({
"diarize",
"Subject profile: document set, stated-versus-evidenced gap, needs-LLM skeleton",
),
+ command(
+ "design-note",
+ "One-shot design note grounded in tension, decision, and truth records",
+ [
+ flag("vault", "string"),
+ flag("agent", "string"),
+ flag("payload", "string"),
+ flag("payload-file", "string"),
+ ],
+ ),
+ command(
+ "extract-signals",
+ "Mine taste signals from an imported session's user turns (two-phase, needs-LLM)",
+ [
+ flag("vault", "string"),
+ flag("agent", "string"),
+ flag("payload", "string"),
+ flag("payload-file", "string"),
+ ],
+ ),
command("okf-export", "Write a portable Open Knowledge Format bundle"),
command(
"okf-import",
@@ -458,7 +499,8 @@ 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 deterministic skill proposals",
+ "Learn, list, review, and recover skill proposals, including drafts from mature pages",
+ [flag("vault", "string"), flag("payload", "string"), flag("payload-file", "string")],
),
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"),
@@ -485,6 +527,14 @@ export const CLI_COMMAND_MANIFEST: CliRootManifest = Object.freeze({
],
),
command("signal", "Fact signal lifecycle: retire a signal with a reason"),
+ command("capture", "Stage one capture from the terminal: body, source, sender, guidance", [
+ flag("vault", "string"),
+ flag("source", "string"),
+ flag("sender", "string"),
+ flag("guidance", "string"),
+ flag("agent", "string"),
+ flag("at", "string"),
+ ]),
command("telegram-capture", "Inbound Telegram capture bot: long-poll run or catchup"),
command("inbox-drain", "Classify and route staged captures (dry-run by default)"),
command(
diff --git a/src/core/brain/architect/decisions.ts b/src/core/brain/architect/decisions.ts
new file mode 100644
index 00000000..58b78190
--- /dev/null
+++ b/src/core/brain/architect/decisions.ts
@@ -0,0 +1,94 @@
+/**
+ * Repo-scoped ADR candidate reader for the architecture notes
+ * (salience-lifecycle-enrichment, unit 6 / t_041c571f).
+ *
+ * `Brain/decisions/candidates/` is a VAULT-GLOBAL store: the commit miner
+ * (`git/decisions.ts`) writes one candidate per decision-shaped commit of
+ * every repository the vault has ingested, and stamps each one with the
+ * `repo_key` it came from. The architect derives the same key from the
+ * project it is scanning, so the join is exact - and it is the only thing
+ * that keeps one repository's key-decisions note from listing another
+ * repository's drafts.
+ *
+ * Read-only and deterministic: candidates are ordered by filename in
+ * codepoint order, never by directory order (which no filesystem
+ * promises) and never by a locale collator. A candidate whose frontmatter
+ * is missing a field is REPORTED with that field named as unrecorded, not
+ * skipped - a hand-edited draft that lost its sha is exactly the note an
+ * operator needs to see in the list.
+ */
+
+import { existsSync, readdirSync } from "node:fs";
+import { join } from "node:path";
+
+import { parseFrontmatter } from "../../vault.ts";
+import { compareStable } from "./scan.ts";
+
+/** Where the commit miner puts its drafts, relative to the vault root. */
+export const DECISION_CANDIDATES_DIR = ["Brain", "decisions", "candidates"] as const;
+
+/** One ADR candidate, as the key-decisions note needs it. */
+export interface DecisionCandidateFact {
+ /** Absolute path of the candidate note. */
+ readonly path: string;
+ /** Vault-relative, extension-less path - the wikilink target. */
+ readonly link: string;
+ /** The candidate's own heading, or its filename when it has none. */
+ readonly title: string;
+ /** The commit sha the candidate is identified by, when it records one. */
+ readonly sha: string | null;
+ /** Deterministic signal ids that made the commit decision-shaped. */
+ readonly signals: ReadonlyArray<string>;
+}
+
+/** The first ATX heading of a candidate body, without its marker. */
+function headingOf(body: string): string | null {
+ for (const line of body.split("\n")) {
+ if (line.startsWith("# ")) return line.slice(2).trim();
+ }
+ return null;
+}
+
+/** A frontmatter value read as a non-empty string, or null. */
+function stringField(value: unknown): string | null {
+ return typeof value === "string" && value.trim() !== "" ? value.trim() : null;
+}
+
+/** A frontmatter value read as a string list. */
+function listField(value: unknown): ReadonlyArray<string> {
+ if (Array.isArray(value)) return value.filter((item): item is string => typeof item === "string");
+ const single = stringField(value);
+ return single === null ? [] : [single];
+}
+
+/**
+ * Every ADR candidate in the vault whose `repo_key` is `repoKey`, in a
+ * stable order. A vault with no candidate directory yields an empty list;
+ * that is an ordinary state, not a failure.
+ */
+export function listRepoDecisionCandidates(
+ vault: string,
+ repoKey: string,
+): ReadonlyArray<DecisionCandidateFact> {
+ const dir = join(vault, ...DECISION_CANDIDATES_DIR);
+ if (!existsSync(dir)) return Object.freeze([]);
+
+ const facts: DecisionCandidateFact[] = [];
+ for (const name of readdirSync(dir).toSorted(compareStable)) {
+ if (!name.endsWith(".md")) continue;
+ const path = join(dir, name);
+ const [metadata, body] = parseFrontmatter(path);
+ if (stringField(metadata["repo_key"]) !== repoKey) continue;
+ const stem = name.slice(0, -".md".length);
+ facts.push(
+ Object.freeze({
+ path,
+ link: `${DECISION_CANDIDATES_DIR.join("/")}/${stem}`,
+ title: headingOf(body) ?? stem,
+ sha: stringField(metadata["sha"]),
+ signals: Object.freeze(listField(metadata["signals"])),
+ }),
+ );
+ }
+ return Object.freeze(facts);
+}
diff --git a/src/core/brain/architect/generate.ts b/src/core/brain/architect/generate.ts
index a52ecf2c..8b2b8d62 100644
--- a/src/core/brain/architect/generate.ts
+++ b/src/core/brain/architect/generate.ts
@@ -2,12 +2,33 @@
* Architecture docs generator (Project History Suite, t_929da8a2).
*
* Renders scanProject facts into vault notes under
- * `Brain/projects/arch/<repo-key>/`: one overview plus one note per
- * detected module, all generated content inside sentinel regions.
- * Regeneration goes through mergeRegions, so operator prose outside
- * regions survives byte-for-byte, and an unchanged project regenerates
- * byte-identically (the scanner is deterministic and the renderer adds
- * no timestamps).
+ * `Brain/projects/arch/<repo-key>/`: one overview, one key-decisions
+ * note, and one note per detected module, all generated content inside
+ * sentinel regions. Regeneration goes through mergeRegions, so operator
+ * prose outside regions survives byte-for-byte, and an unchanged project
+ * regenerates byte-identically (the scanner is deterministic and the
+ * renderer adds no timestamps).
+ *
+ * DECLARED EXCEPTIONS to that byte-identity guarantee - two of them, and
+ * no others. Both are scoped to their own region: every other region, and
+ * every byte of operator prose, still regenerates identically, and each
+ * exception carries the whole provenance of what it was stamped from, so
+ * a stale stamp describes its own reading rather than passing for a
+ * current one.
+ *
+ * - the overview's `codegraph` region states the codegraph partner's
+ * verdict, which is a fact about the machine and the partner index,
+ * not about the project tree; an index built, deleted, or gone stale
+ * moves those bytes while the repository stands still. Stamped with
+ * state, counts and health;
+ * - the key-decisions note lists the repo's ADR candidates, which the
+ * commit miner writes into the VAULT; mining new commits moves those
+ * bytes with no change to the repository at all. Stamped with each
+ * candidate's sha and matched signals.
+ *
+ * The overview's `module-map` diagram is NOT an exception: it renders the
+ * same scanned facts as every other region and moves only when the tree
+ * does.
*
* Frontmatter is written ONCE at file creation and never rewritten -
* it carries static identity (kind, repo key, path), while every fact
@@ -40,6 +61,9 @@ import { existsSync, mkdirSync, readFileSync } from "node:fs";
import { join } from "node:path";
import { atomicWriteFileSync } from "../../fs-atomic.ts";
+import { summarizeGraphHealth } from "../../partner/codegraph-health.ts";
+import { buildCodegraphReport } from "../../partner/codegraph-report.ts";
+import type { CodegraphReport, CodegraphReportOptions } from "../../partner/codegraph-report.ts";
import { repoKey as deriveRepoKey } from "../git/identity.ts";
import { OPERATION, progressCounter, progressReasonForError } from "../progress.ts";
import type { ProgressCounter, ProgressSink } from "../progress.ts";
@@ -47,7 +71,9 @@ import { buildRegionDocument, mergeRegions } from "../regions.ts";
import type { Region } from "../regions.ts";
import type { Safeguard } from "../safeguard.ts";
import { acquireLockSyncWithRetry, LOCK_WAIT_INTERACTIVE_MS } from "../sync-lockfile.ts";
-import { ARCHITECT_STAGE, scanProject } from "./scan.ts";
+import { listRepoDecisionCandidates } from "./decisions.ts";
+import type { DecisionCandidateFact } from "./decisions.ts";
+import { ARCHITECT_STAGE, compareStable, scanProject } from "./scan.ts";
import type { ModuleFact, ProjectFacts } from "./scan.ts";
import { assertVaultIdentityForWrite } from "../vault-identity.ts";
@@ -59,17 +85,30 @@ export interface GenerateArchDocsOptions {
* per note while planning - never between two writes.
*/
readonly safeguard?: Safeguard;
+ /**
+ * How the run learns the codegraph partner's verdict. Defaults to the
+ * real {@link buildCodegraphReport}.
+ *
+ * A seam rather than a setting: nothing in the product produces a
+ * different reader, but the verdict is the one input to this module
+ * that is neither the project tree nor the vault, so a test of the
+ * region cannot construct it by arranging files.
+ */
+ readonly codegraphReport?: (options: CodegraphReportOptions) => CodegraphReport;
}
export interface GenerateArchDocsResult {
readonly repoKey: string;
readonly dir: string;
readonly overviewPath: string;
+ /** The key-decisions note, one per repo, beside the overview. */
+ readonly decisionsPath: string;
readonly modulePaths: ReadonlyArray<string>;
/**
* What this run did to the notes: how many it wrote for the first time,
* how many it rewrote, and how many it found already correct. They sum
- * to `1 + modulePaths.length` and go out on the CLI's JSON envelope.
+ * to `2 + modulePaths.length` - the overview, the key-decisions note,
+ * and one per module - and go out on the CLI's JSON envelope.
*
* Each one is the verdict of a READ - `planNote` compares what is on
* disk against what the facts say - so the three are only true of the
@@ -97,28 +136,152 @@ export interface GenerateArchDocsResult {
}
/**
- * Codepoint order, not `localeCompare`: ICU collation varies with the
- * runtime locale, so a collator-based tie-break renders different bytes
- * for the same tree on two hosts - and byte-identical regeneration is
- * this module's whole contract. Every other ordering in the scanner
- * already uses plain `toSorted()`; this is the one that did not.
+ * Extensions by descending file count, ties broken in codepoint order.
+ * One definition: the summary line and the diagram's dominant-language
+ * label must agree about which language leads a module.
*/
-function compareStable(a: string, b: string): number {
- return a < b ? -1 : a > b ? 1 : 0;
+function sortedLanguages(
+ languages: Readonly<Record<string, number>>,
+): ReadonlyArray<readonly [string, number]> {
+ return Object.entries(languages).toSorted(
+ (a, b) => b[1] - a[1] || compareStable(a[0], b[0]),
+ ) as ReadonlyArray<readonly [string, number]>;
}
function languagesLine(languages: Readonly<Record<string, number>>): string {
- const entries = Object.entries(languages).toSorted(
- (a, b) => b[1] - a[1] || compareStable(a[0], b[0]),
- );
+ const entries = sortedLanguages(languages);
if (entries.length === 0) return "none detected";
return entries
- .slice(0, 8)
+ .slice(0, LANGUAGES_LINE_CAP)
.map(([ext, count]) => `${ext} (${count})`)
.join(", ");
}
-function overviewRegions(facts: ProjectFacts, key: string): ReadonlyArray<Region> {
+/** How many extensions the summary line names before it stops. */
+const LANGUAGES_LINE_CAP = 8;
+
+/**
+ * The two verdicts the codegraph region can state, in the words an
+ * operator reads. `graph-present` means a structural index exists for
+ * this tree; `graph-absent, lexical-only` means everything in these notes
+ * came from the deterministic file scan and nothing from a code graph.
+ * Both are values, never errors - the partner report already settled that
+ * (`partner/codegraph-report.ts`).
+ */
+const GRAPH_VERDICT = Object.freeze({
+ present: "graph-present",
+ absent: "graph-absent, lexical-only",
+} as const);
+
+/** How the region names a partner CLI that is not on PATH. */
+const NO_PARTNER_CLI = "not on PATH";
+
+/**
+ * The codegraph verdict, as the region body an operator reads.
+ *
+ * Every one of the five {@link CodegraphReport} index states renders
+ * distinctly. The four non-`indexed` states share the `graph-absent`
+ * verdict but keep their own name and their own reason, because their
+ * remediations differ and one of them is actively wrong for the others:
+ * `not_indexed` asks for `codegraph init`, which is the last thing to run
+ * at a partner that timed out (`error`).
+ *
+ * The body is also the provenance stamp for the declared byte-identity
+ * exception in this module's docblock - state, counts and health are all
+ * in it, so a region left behind by an index that has since changed
+ * describes the reading it was made from.
+ */
+function codegraphRegionBody(report: CodegraphReport): string {
+ const index = report.index;
+ const head = [
+ `Project: ${report.project ?? "none in scope"}`,
+ `Partner CLI: ${report.cli.path ?? NO_PARTNER_CLI}`,
+ ];
+ if (index.state !== "indexed") {
+ return [
+ `${GRAPH_VERDICT.absent}: this overview rests on the file scan alone`,
+ `State: ${index.state}`,
+ ...head,
+ `Reason: ${index.reason ?? "none reported"}`,
+ ].join("\n");
+ }
+ const health = index.health;
+ return [
+ `${GRAPH_VERDICT.present}: codegraph holds an index for this project`,
+ `State: ${index.state}`,
+ ...head,
+ `Nodes: ${index.node_count ?? 0}`,
+ `Files: ${index.file_count ?? 0}`,
+ `Edges: ${index.edge_count ?? 0}`,
+ `Health: ${health === undefined ? "not assessed" : summarizeGraphHealth(health)}`,
+ ...(health?.warnings ?? []).map((warning) => `- ${warning.code}: ${warning.message}`),
+ ].join("\n");
+}
+
+/**
+ * Escape a name that came from a DIRECTORY for a quoted Mermaid label.
+ *
+ * Mermaid's own escape mechanism is the `#nnn;`/`#name;` entity, so `#`
+ * is rewritten FIRST - doing it last would rewrite the escapes this
+ * function just produced. `<` and `>` matter because flowchart labels
+ * render as HTML by default, so an unescaped angle bracket in a directory
+ * name is markup, and `"` would end the label early.
+ *
+ * Line breaks are folded to a space rather than escaped: a directory name
+ * may legally contain one, and `<br/>` is the label's own field
+ * separator here.
+ */
+function mermaidLabel(text: string): string {
+ return text
+ .replaceAll("#", "#35;")
+ .replaceAll('"', "#quot;")
+ .replaceAll("<", "#lt;")
+ .replaceAll(">", "#gt;")
+ .replaceAll(/[\r\n]+/g, " ");
+}
+
+/** What a module node says when nothing in it carries an extension. */
+const NO_LANGUAGE = "no language detected";
+
+/**
+ * The module containment diagram, as a Mermaid flowchart.
+ *
+ * CONTAINMENT ONLY, and the region says so in prose above the block. The
+ * scanner records no import graph at all (`scan.ts`: "Import-graph
+ * analysis is explicitly out of scope"), so every edge here runs from the
+ * project root to a module it contains; a module-to-module edge would be
+ * a relation nothing measured.
+ *
+ * Node ids are positional (`mod0`, `mod1`, ...), never derived from the
+ * module name. A directory name is arbitrary bytes and a Mermaid node id
+ * is an identifier, so deriving one from the other needs a mangling that
+ * must also stay collision-free - an index needs neither.
+ */
+function moduleMapBody(facts: ProjectFacts): string {
+ const modules = facts.modules.toSorted((a, b) => compareStable(a.name, b.name));
+ const lines = [
+ "Containment only: the scan records no import edges, so this diagram claims none.",
+ "",
+ "```mermaid",
+ "graph TD",
+ ` root["${mermaidLabel(facts.name)}<br/>${modules.length} module(s)"]`,
+ ];
+ for (const [index, module] of modules.entries()) {
+ const language = sortedLanguages(module.languages)[0]?.[0] ?? NO_LANGUAGE;
+ lines.push(
+ ` root --> mod${index}["${mermaidLabel(module.name)}<br/>` +
+ `${module.files} file(s)<br/>${mermaidLabel(language)}"]`,
+ );
+ }
+ lines.push("```");
+ return lines.join("\n");
+}
+
+function overviewRegions(
+ facts: ProjectFacts,
+ key: string,
+ codegraph: CodegraphReport,
+): ReadonlyArray<Region> {
const summary = [
`Project: ${facts.name}`,
...(facts.manifest?.version != null ? [`Version: ${facts.manifest.version}`] : []),
@@ -149,11 +312,56 @@ function overviewRegions(facts: ProjectFacts, key: string): ReadonlyArray<Region
return [
{ id: "summary", body: summary },
{ id: "modules", body: modules },
+ { id: "module-map", body: moduleMapBody(facts) },
{ id: "entry-points", body: entryPoints },
{ id: "dependencies", body: dependencies },
+ { id: "codegraph", body: codegraphRegionBody(codegraph) },
];
}
+/** What the key-decisions note says when the repo has no candidates. */
+const NO_DECISION_CANDIDATES = "No decision candidates recorded for this repository.";
+
+/** What one entry says instead of a sha the candidate never recorded. */
+const NO_CANDIDATE_SHA = "sha unrecorded";
+
+/** What one entry says instead of the signals a candidate never recorded. */
+const NO_CANDIDATE_SIGNALS = "no signals recorded";
+
+/**
+ * Keep a wikilink's display text from ending the link early.
+ *
+ * The text is a commit subject by way of the candidate's heading, so it
+ * can hold anything a committer typed. `|` would open a second alias
+ * field and `]]` would close the link mid-title; both are folded to
+ * characters that read the same way in prose and mean nothing here.
+ */
+function wikilinkText(text: string): string {
+ return text.replaceAll("|", "/").replaceAll("]", ")");
+}
+
+/**
+ * The repo's ADR candidates, one entry each: title, sha, matched signals.
+ *
+ * The empty case is an explicit sentence rather than an empty region. A
+ * blank region is indistinguishable from a generator that failed to run,
+ * and "this repository has no mined decisions yet" is a real answer that
+ * points at `o2b brain git mine`.
+ */
+function decisionsRegionBody(candidates: ReadonlyArray<DecisionCandidateFact>): string {
+ if (candidates.length === 0) return NO_DECISION_CANDIDATES;
+ return candidates
+ .map((candidate) => {
+ const signals =
+ candidate.signals.length === 0
+ ? NO_CANDIDATE_SIGNALS
+ : `signals: ${candidate.signals.join(", ")}`;
+ const sha = candidate.sha === null ? NO_CANDIDATE_SHA : `sha \`${candidate.sha}\``;
+ return `- [[${candidate.link}|${wikilinkText(candidate.title)}]] (${sha}, ${signals})`;
+ })
+ .join("\n");
+}
+
function moduleRegions(module: ModuleFact): ReadonlyArray<Region> {
const facts = [
`Path: ${module.path}`,
@@ -265,6 +473,11 @@ function modulePath(dir: string, module: ModuleFact): string {
return join(dir, "modules", `${module.name}.md`);
}
+/** Where the key-decisions note lives. Beside the overview, one per repo. */
+function decisionsPath(dir: string): string {
+ return join(dir, "decisions.md");
+}
+
/**
* Plan every note, then write them - in that order, and never
* interleaved.
@@ -282,6 +495,8 @@ function renderNotes(
dir: string,
key: string,
facts: ProjectFacts,
+ codegraph: CodegraphReport,
+ candidates: ReadonlyArray<DecisionCandidateFact>,
opts: GenerateArchDocsOptions,
progress: ProgressCounter,
): ReadonlyArray<PlannedNote> {
@@ -291,9 +506,15 @@ function renderNotes(
planNote(
join(dir, "overview.md"),
frontmatter("arch-overview", key, [`repo_path: ${facts.root}`]),
- overviewRegions(facts, key),
+ overviewRegions(facts, key, codegraph),
),
);
+ opts.safeguard?.checkpoint();
+ plans.push(
+ planNote(decisionsPath(dir), frontmatter("arch-decisions", key, [`repo_path: ${facts.root}`]), [
+ { id: "decisions", body: decisionsRegionBody(candidates) },
+ ]),
+ );
for (const module of facts.modules) {
opts.safeguard?.checkpoint();
plans.push(
@@ -393,6 +614,20 @@ function generateRun(
...(opts.safeguard === undefined ? {} : { safeguard: opts.safeguard }),
});
const key = deriveRepoKey(facts.root);
+
+ // The partner verdict, read BEFORE the lock: it touches neither the
+ // vault nor this repo's notes, so holding the critical section across
+ // it would only lengthen the window another architect run waits on.
+ //
+ // `limit: 1` scopes the question to the project this overview is about.
+ // `findCodeProjects` otherwise widens to the vault parent's siblings and
+ // would answer about whichever of them it reached first - a verdict for
+ // a different repository, stamped into this repository's overview. A
+ // project root that is not a code project (no `.git`, no manifest) is
+ // then reported as `no_project`, which is exactly true of it.
+ const readReport = opts.codegraphReport ?? buildCodegraphReport;
+ const codegraph = readReport({ cwd: facts.root, vault, limit: 1 });
+
const dir = join(vault, "Brain", "projects", "arch", key);
mkdirSync(join(dir, "modules"), { recursive: true });
@@ -402,10 +637,15 @@ function generateRun(
const overviewPath = join(dir, "overview.md");
const modulePaths = facts.modules.map((module) => modulePath(dir, module));
- // The note count is known only now, and it is known exactly: one
- // overview plus one note per detected module. Unlike the walk, this
- // stage has a denominator.
- progress.start(ARCHITECT_STAGE.render, 1 + facts.modules.length);
+ // The repo's slice of the vault-global candidate store, read outside
+ // the lock for the same reason the partner verdict is: it is a read of
+ // `Brain/decisions/`, which this run never writes.
+ const candidates = listRepoDecisionCandidates(vault, key);
+
+ // The note count is known only now, and it is known exactly: the
+ // overview, the key-decisions note, and one note per detected module.
+ // Unlike the walk, this stage has a denominator.
+ progress.start(ARCHITECT_STAGE.render, 2 + facts.modules.length);
// One critical section over every note, held across the reads AND the
// writes. Atomicity is not exclusivity: a whole file is renamed into
@@ -437,7 +677,7 @@ function generateRun(
const handle = acquireLockSyncWithRetry(dir, LOCK_WAIT_INTERACTIVE_MS);
let plans: ReadonlyArray<PlannedNote>;
try {
- plans = renderNotes(dir, key, facts, opts, progress);
+ plans = renderNotes(dir, key, facts, codegraph, candidates, opts, progress);
} finally {
handle.release();
}
@@ -447,6 +687,7 @@ function generateRun(
repoKey: key,
dir,
overviewPath,
+ decisionsPath: decisionsPath(dir),
modulePaths: Object.freeze(modulePaths),
created: countOf(plans, NOTE_DISPOSITION.created),
updated: countOf(plans, NOTE_DISPOSITION.updated),
diff --git a/src/core/brain/architect/scan.ts b/src/core/brain/architect/scan.ts
index f99b0be3..81fdcd4e 100644
--- a/src/core/brain/architect/scan.ts
+++ b/src/core/brain/architect/scan.ts
@@ -159,6 +159,22 @@ interface WalkStats {
dirs: string[];
}
+/**
+ * Codepoint order, not `localeCompare`: ICU collation varies with the
+ * runtime locale, so a collator-based tie-break renders different bytes
+ * for the same tree on two hosts - and byte-identical regeneration is the
+ * generator's whole contract. Plain `toSorted()` on strings already does
+ * this; the comparator exists for the orderings that need a tie-break
+ * (language counts) or sort objects rather than strings.
+ *
+ * It lives here, in the leaf of the scan/render pair, because both the
+ * renderer and the decision-candidate reader order their output with it
+ * and neither may import the other.
+ */
+export function compareStable(a: string, b: string): number {
+ return a < b ? -1 : a > b ? 1 : 0;
+}
+
/** Count one file's extension, the single place the mapping is defined. */
function tallyExtension(languages: Record<string, number>, path: string): void {
const ext = extname(path).toLowerCase();
diff --git a/src/core/brain/capture/capture-note.ts b/src/core/brain/capture/capture-note.ts
index 48fe7432..da0b5bdf 100644
--- a/src/core/brain/capture/capture-note.ts
+++ b/src/core/brain/capture/capture-note.ts
@@ -15,6 +15,17 @@
* routes it. The captures subtree is deliberately separate from the signal
* inbox so the dream pass and signal machinery stay byte-identical for vaults
* that never capture.
+ *
+ * ## Guidance, and why it is not part of the body
+ *
+ * A capture may carry an optional `guidance` string: what the capturer
+ * says should be DONE with the text, as opposed to the text itself. It
+ * lands in a `## Guidance` body section under a frontmatter marker, and
+ * it joins the id hash - two captures differing only in guidance are two
+ * captures, and hashing the body alone would collapse them onto one stem
+ * and hand the second to the `-2` allocator. Both additions are
+ * conditional on the field being present, so a capture without guidance
+ * is byte-identical to one written before the field existed.
*/
import { existsSync, mkdirSync, readdirSync, readFileSync, renameSync, rmSync } from "node:fs";
@@ -61,8 +72,16 @@ export interface CaptureNote {
readonly id: string;
/** Vault-relative path (POSIX separators). */
readonly path: string;
- /** The captured text body. */
+ /** The captured text body, with any guidance section split back off. */
readonly body: string;
+ /**
+ * What the capturer said should be DONE with this capture, verbatim, or
+ * `null` when they said nothing. Never merged into {@link body}: the two
+ * are written by the same person in one breath and mean different
+ * things, and a drain that cannot tell them apart would route on an
+ * instruction as though it were content.
+ */
+ readonly guidance: string | null;
readonly provenance: CaptureProvenance;
/** `true` in the staging area, `false` once archived. */
readonly staged: boolean;
@@ -71,6 +90,12 @@ export interface CaptureNote {
export interface WriteCaptureInput {
readonly body: string;
readonly provenance: CaptureProvenance;
+ /**
+ * Optional per-capture handling note, rendered as a `## Guidance` body
+ * section and read back verbatim. Present-but-blank is refused rather
+ * than stored as an empty section; omit the field to say nothing.
+ */
+ readonly guidance?: string;
}
/** Typed failure raised by every contract refusal - never a silent skip. */
@@ -98,17 +123,86 @@ function requireNonEmpty(value: string, label: string): string {
function captureBaseId(
body: string,
provenance: CaptureProvenance,
+ guidance: string | null,
): { prefix: string; slug: string } {
const stamp = provenance.capturedAt.trim();
const date = stamp.slice(0, 10);
const time = stamp.slice(11, 19).replace(/:/g, "");
+ // Guidance joins the hash because two captures differing only in it are
+ // two captures - "read this" and "act on this" over the same text are
+ // not the same message - and hashing only the body would collapse them
+ // onto one stem and hand the second to the `-2` allocator, where the id
+ // stops describing the content.
+ //
+ // The segment is CONDITIONAL, and that is the difference between an
+ // additive field and a re-keying: with no guidance the hash input is
+ // the historical three-part string byte for byte, so every capture the
+ // Telegram bot writes today keeps the id it would have had.
const hash = createHash("sha256")
- .update(`${provenance.source}\0${provenance.sender}\0${body}`, "utf8")
+ .update(
+ `${provenance.source}\0${provenance.sender}\0${body}` +
+ (guidance === null ? "" : `\0${guidance}`),
+ "utf8",
+ )
.digest("hex")
.slice(0, CAPTURE_HASH_LEN);
return { prefix: `${CAPTURE_ID_PREFIX}-${date}`, slug: `${time}-${hash}` };
}
+/** Heading of the body section carrying {@link WriteCaptureInput.guidance}. */
+const GUIDANCE_HEADING = "## Guidance";
+
+/**
+ * Frontmatter marker saying the body carries a {@link GUIDANCE_HEADING}
+ * section that this contract wrote.
+ *
+ * The marker is what makes the split unambiguous, and without it the
+ * feature would be a misreading waiting to happen: a captured message may
+ * itself end in a `## Guidance` heading - people quote documents - and a
+ * parser that went looking for the heading would hand that quotation back
+ * as an instruction. The writer sets the marker, so only a capture this
+ * contract gave guidance to is ever split.
+ */
+const GUIDANCE_MARKER_FIELD = "capture_guidance";
+
+/**
+ * Read the marker. Both spellings, because the frontmatter reader hands
+ * back the scalar as written and a YAML `true` arrives here as the string
+ * `"true"` - the same two-form check `truth/contamination.ts:31` and
+ * `trust/untrusted-provenance.ts:79` already make.
+ */
+function guidanceMarked(meta: FrontmatterMap): boolean {
+ const value = meta[GUIDANCE_MARKER_FIELD];
+ return value === true || value === "true";
+}
+
+/** Compose the on-disk body: the capture, then the guidance section. */
+function renderCaptureBody(body: string, guidance: string | null): string {
+ return guidance === null ? body : `${body}\n\n${GUIDANCE_HEADING}\n\n${guidance}`;
+}
+
+/**
+ * Split a marked body back into its two halves.
+ *
+ * The leading `[\s\S]*` is greedy, so it takes as much of the body as it
+ * can and the separator matches at its LAST occurrence - which is the one
+ * {@link renderCaptureBody} appended, whatever the captured text itself
+ * quotes. A marked body with
+ * no such section is a corrupted page rather than a guidance-less one, and
+ * it is refused: reporting `guidance: null` there would silently return
+ * the marker's own text as part of the capture.
+ */
+function splitGuidance(body: string, id: string): { body: string; guidance: string } {
+ const match = new RegExp(String.raw`^([\s\S]*)\n\n${GUIDANCE_HEADING}\n\n([\s\S]*)$`).exec(body);
+ if (match === null) {
+ throw new CaptureContractError(
+ `capture ${id} declares ${GUIDANCE_MARKER_FIELD} but its body carries no ` +
+ `'${GUIDANCE_HEADING}' section`,
+ );
+ }
+ return { body: match[1]!.trim(), guidance: match[2]!.trim() };
+}
+
/** Write one capture note into the staging area through the contract. */
export function writeCaptureNote(vault: string, input: WriteCaptureInput): CaptureNote {
// Vault-identity write guard (context-integrity-gates, Unit J).
@@ -117,10 +211,14 @@ export function writeCaptureNote(vault: string, input: WriteCaptureInput): Captu
const source = requireNonEmpty(input.provenance.source, "source");
const sender = requireNonEmpty(input.provenance.sender, "sender");
const capturedAt = requireNonEmpty(input.provenance.capturedAt, "captured_at");
+ // Absent says nothing; present-but-blank is a caller that meant to say
+ // something and sent whitespace, which is the shape a silent drop hides.
+ const guidance =
+ input.guidance === undefined ? null : requireNonEmpty(input.guidance, "guidance");
const dir = capturesDir(vault);
mkdirSync(dir, { recursive: true });
- const { prefix, slug } = captureBaseId(body, { source, sender, capturedAt });
+ const { prefix, slug } = captureBaseId(body, { source, sender, capturedAt }, guidance);
const provenance: CaptureProvenance = { source, sender, capturedAt };
// Allocation and creation are one step: two captures that hash to the
@@ -136,11 +234,16 @@ export function writeCaptureNote(vault: string, input: WriteCaptureInput): Captu
// pass: without them a collision here reported a raw errno naming
// an absolute path, which leaks the operator's home directory into
// CLI output and MCP envelopes and never says what collided.
- writeFrontmatterAtomic(allocation.path, captureFrontmatter(captureId, provenance), body, {
- overwrite: false,
- existsErrorKind: "capture",
- vaultForRelativePath: vault,
- });
+ writeFrontmatterAtomic(
+ allocation.path,
+ captureFrontmatter(captureId, provenance, guidance),
+ renderCaptureBody(body, guidance),
+ {
+ overwrite: false,
+ existsErrorKind: "capture",
+ vaultForRelativePath: vault,
+ },
+ );
return captureId;
},
);
@@ -148,18 +251,26 @@ export function writeCaptureNote(vault: string, input: WriteCaptureInput): Captu
id,
path: vaultRelative(allocated.path, vault),
body,
+ guidance,
provenance,
staged: true,
});
}
-function captureFrontmatter(id: string, provenance: CaptureProvenance): FrontmatterMap {
+function captureFrontmatter(
+ id: string,
+ provenance: CaptureProvenance,
+ guidance: string | null,
+): FrontmatterMap {
return {
kind: BRAIN_CAPTURE_KIND,
id,
capture_source: provenance.source,
capture_sender: provenance.sender,
captured_at: provenance.capturedAt,
+ // Emitted only when there IS guidance, so a capture without it is
+ // byte-identical to one written before this field existed.
+ ...(guidance === null ? {} : { [GUIDANCE_MARKER_FIELD]: true }),
tags: ["brain", "brain/capture"],
};
}
@@ -178,10 +289,14 @@ function parseCaptureFile(absPath: string, relPath: string, staged: boolean): Ca
const source = typeof meta["capture_source"] === "string" ? meta["capture_source"] : "";
const sender = typeof meta["capture_sender"] === "string" ? meta["capture_sender"] : "";
const capturedAt = typeof meta["captured_at"] === "string" ? meta["captured_at"] : "";
+ const split = guidanceMarked(meta)
+ ? splitGuidance(body.trim(), id)
+ : { body: body.trim(), guidance: null };
return Object.freeze({
id,
path: relPath,
- body: body.trim(),
+ body: split.body,
+ guidance: split.guidance,
provenance: Object.freeze({ source, sender, capturedAt }),
staged,
});
diff --git a/src/core/brain/capture/telegram-capture.ts b/src/core/brain/capture/telegram-capture.ts
index 82c69ab5..691eb148 100644
--- a/src/core/brain/capture/telegram-capture.ts
+++ b/src/core/brain/capture/telegram-capture.ts
@@ -287,6 +287,12 @@ export function handleCaptureUpdate(
});
}
+ // No `guidance` here, and that is a reading of the payload rather than
+ // an omission: a Telegram update carries a chat id and one text body,
+ // and nothing in it distinguishes what was captured from what should be
+ // done with it. Splitting a message on a convention this bot invented
+ // would put words in the sender's mouth. Guidance reaches the contract
+ // from surfaces that have a field for it - see `o2b brain capture`.
const note = writeCaptureNote(vault, {
body: trimmed,
provenance: { source, sender: chatId, capturedAt: at },
diff --git a/src/core/brain/config-template.ts b/src/core/brain/config-template.ts
index d7d8bcb7..d37cbfa6 100644
--- a/src/core/brain/config-template.ts
+++ b/src/core/brain/config-template.ts
@@ -187,6 +187,13 @@ export const BRAIN_CONFIG_TEMPLATE: ReadonlyArray<BrainTemplateBlock> = Object.f
"Opt-in heal-phase enrichment. Left off, the heal phase is a",
"checkpoint-only no-op.",
]),
+ example("salience_threshold", 0.2, [
+ "Unset by default, which leaves the salience gate open: every fact",
+ "enters the rollup ladder's fold set. Set a number in [0, 1] to fold",
+ "only facts whose combined salience score (decayed outcome mass,",
+ "Wilson-bound confidence, observed reuse) reaches it. Excluded facts",
+ "are always named in the dream summary, never silently dropped.",
+ ]),
],
},
{
diff --git a/src/core/brain/design-note.ts b/src/core/brain/design-note.ts
new file mode 100644
index 00000000..b592e778
--- /dev/null
+++ b/src/core/brain/design-note.ts
@@ -0,0 +1,532 @@
+/**
+ * One-shot design notes (salience-lifecycle-enrichment, unit 7,
+ * t_c87644b4).
+ *
+ * `o2b brain panel` already deliberates: it opens a durable write session,
+ * walks personas over several turns, and commits under
+ * `Brain/decisions/panels/`. That is the right shape when a decision is
+ * worth several rounds, and the wrong one when somebody wants a design note
+ * now. This module is the one-shot sibling, built like `diarization.ts`:
+ * read-only grounding, no session, no model, and exactly one
+ * needs-llm-step envelope handed back to the caller.
+ *
+ * What "grounded" means here is the whole point. A design note written from
+ * nothing is prose; this one is written from three vault stores that
+ * already know what the project has argued about, decided, and asserted:
+ *
+ * - TENSIONS - the contradictions the vault has materialized and, in
+ * particular, the ones nobody has resolved.
+ * - DECISIONS - what was chosen before on a similar question, and how it
+ * turned out.
+ * - TRUTH - the claim-ledger projection: what is currently asserted about
+ * the entities in play, and which of those slots are contested.
+ *
+ * Matching is the vault's own deterministic token overlap - `tokenise` and
+ * `jaccard` from `similarity.ts`, the same pair `findSimilarDecisions`
+ * ranks with - so a topic reaches the same records from every surface and
+ * no model is consulted to decide relevance.
+ *
+ * An EMPTY store is not a failure and not an absence: it is named. A vault
+ * with no decisions yet and a vault whose decisions all missed the topic
+ * are different answers to "what grounds this note", and a report that
+ * rendered both as an empty list would be the misleading silence this
+ * project forbids.
+ *
+ * The payload contract is one recommendation. A design note listing three
+ * alternatives and recommending none has not been written yet, and one
+ * recommending two has not been decided; both are refused by the semantic
+ * check, which states the count it found.
+ */
+
+import { mkdirSync } from "node:fs";
+import { join, posix } from "node:path";
+
+import { slugify, writeFrontmatterAtomic } from "../vault.ts";
+import {
+ DECISION_SIMILARITY_THRESHOLD,
+ findSimilarDecisions,
+ listDecisions,
+} from "./decisions/record.ts";
+import { buildNeedsLlmStep, type NeedsLlmStep } from "./llm-step.ts";
+import { decisionsDir } from "./paths.ts";
+import {
+ assertResponseCheck,
+ registerResponseCheck,
+ SEMANTIC_VIOLATION_CODES,
+ semanticViolation,
+ type SemanticViolation,
+} from "./response-checks.ts";
+import {
+ assertResponseShape,
+ DESIGN_NOTE_SHAPE,
+ DESIGN_NOTE_SURFACE,
+ SHAPE_ROOT_PATH,
+} from "./response-shape.ts";
+import { jaccard, tokenise } from "./similarity.ts";
+import { isoDate } from "./time.ts";
+import { listTensions, TENSION_UNRESOLVED_STATUSES, type TensionRecord } from "./tensions.ts";
+import { readTruthState } from "./truth/store.ts";
+import type { ClaimSlot, TruthConflict } from "./truth/types.ts";
+import { assertVaultIdentityForWrite } from "./vault-identity.ts";
+
+/** Vault-relative directory a committed design note lands in. */
+export const DESIGN_NOTE_DIR_REL = "Brain/decisions";
+
+/** The needs-llm-step step name for the deferred design note. */
+export const DESIGN_NOTE_STEP = "design-note";
+
+/** Frontmatter discriminator of a committed design note. */
+export const DESIGN_NOTE_KIND = "brain-design-note";
+
+/**
+ * Token-overlap floor a record must clear to ground the note. The decision
+ * store's own floor is reused for all three stores rather than three
+ * numbers being picked: a topic that reaches a decision should reach the
+ * tension arguing about the same words, and a second threshold would make
+ * "related" mean two things in one report.
+ */
+export const DESIGN_NOTE_MATCH_THRESHOLD = DECISION_SIMILARITY_THRESHOLD;
+
+/** Most records per store the grounding carries into one prompt. */
+export const DESIGN_NOTE_PER_STORE_LIMIT = 10;
+
+/**
+ * The three grounding stores, named so an empty one can be reported as
+ * itself. "The decision store is empty" and "no decision matched" are
+ * different facts about the vault and lead to different next moves.
+ */
+export const DESIGN_NOTE_STORE = Object.freeze({
+ tensions: "tensions",
+ decisions: "decisions",
+ truth: "truth",
+} as const);
+
+export type DesignNoteStore = (typeof DESIGN_NOTE_STORE)[keyof typeof DESIGN_NOTE_STORE];
+
+/** A design note could not be produced, and the reason is in the message. */
+export class DesignNoteError extends Error {
+ constructor(message: string) {
+ super(message);
+ this.name = "DesignNoteError";
+ }
+}
+
+/** One tension the topic reaches. */
+export interface GroundedTension {
+ readonly id: string;
+ readonly slug: string;
+ readonly subject: string;
+ readonly status: string;
+ /** True while the tension is open or confirmed - nobody has settled it. */
+ readonly unresolved: boolean;
+ readonly jaccard: number;
+}
+
+/** One prior decision the topic reaches, with how it turned out. */
+export interface GroundedDecision {
+ readonly id: string;
+ readonly slug: string;
+ readonly title: string;
+ readonly chosen: string;
+ /** Hindsight outcome; empty until a backfill records one. */
+ readonly outcome: string;
+ readonly jaccard: number;
+}
+
+/** One claim slot the topic reaches. */
+export interface GroundedClaim {
+ readonly entity: string;
+ readonly aspect: string;
+ readonly value: string;
+ /** True when an unresolved conflict involves this slot. */
+ readonly contested: boolean;
+ readonly jaccard: number;
+}
+
+/** One materialized contradiction in the claim ledger. */
+export interface GroundedConflict {
+ readonly entity: string;
+ readonly aspect: string;
+ readonly values: ReadonlyArray<string>;
+}
+
+export interface DesignNoteGrounding {
+ readonly topic: string;
+ readonly tensions: ReadonlyArray<GroundedTension>;
+ readonly decisions: ReadonlyArray<GroundedDecision>;
+ readonly truthSlots: ReadonlyArray<GroundedClaim>;
+ readonly conflicts: ReadonlyArray<GroundedConflict>;
+ readonly counts: {
+ readonly tensions: number;
+ readonly decisions: number;
+ readonly truthSlots: number;
+ readonly conflicts: number;
+ };
+ /**
+ * Stores that hold NOTHING AT ALL in this vault, named. A store absent
+ * from this list held records and simply matched none of them.
+ */
+ readonly emptyStores: ReadonlyArray<DesignNoteStore>;
+}
+
+export interface DesignNoteReport {
+ readonly topic: string;
+ readonly slug: string;
+ readonly generatedAt: string;
+ readonly grounding: DesignNoteGrounding;
+ /** Vault-relative path the committed note will occupy. */
+ readonly targetPath: string;
+ readonly llmStep: NeedsLlmStep;
+}
+
+export interface PlanDesignNoteOptions {
+ readonly now: Date;
+}
+
+export interface CommitDesignNoteOptions {
+ readonly agent: string;
+ readonly now: Date;
+}
+
+/** One alternative the note weighs. */
+export interface DesignNoteAlternative {
+ readonly name: string;
+ readonly approach: string;
+ readonly tradeoffs: string;
+ readonly recommended: boolean;
+}
+
+export interface CommitDesignNoteResult {
+ readonly topic: string;
+ readonly slug: string;
+ /** Absolute path of the committed note. */
+ readonly path: string;
+ /** Name of the single recommended alternative. */
+ readonly recommended: string;
+ readonly alternativeCount: number;
+}
+
+// ----- The cardinality rule the descriptor language cannot express ----------
+
+/**
+ * Exactly one alternative may carry `recommended: true`.
+ *
+ * This is the canonical case for the semantic registry: the rule reads
+ * every element of an array at once, so no per-value descriptor can state
+ * it, and the refusal has to carry the COUNT - "zero" and "three" are
+ * different mistakes with different fixes.
+ */
+registerResponseCheck(DESIGN_NOTE_SURFACE, (payload) => {
+ const violations: SemanticViolation[] = [];
+ if (typeof payload !== "object" || payload === null) return violations;
+ const alternatives = (payload as { alternatives?: unknown }).alternatives;
+ if (!Array.isArray(alternatives)) return violations;
+ const recommended = alternatives.filter(
+ (item) =>
+ typeof item === "object" &&
+ item !== null &&
+ (item as { recommended?: unknown }).recommended === true,
+ );
+ if (recommended.length !== 1) {
+ violations.push(
+ semanticViolation(
+ SEMANTIC_VIOLATION_CODES.cardinality,
+ `${SHAPE_ROOT_PATH}.alternatives`,
+ `exactly one alternative must set recommended: true; found ${recommended.length} of ${alternatives.length}`,
+ ),
+ );
+ }
+ return violations;
+});
+
+// ----- Grounding ------------------------------------------------------------
+
+/**
+ * Read the three stores and keep what the topic reaches. Pure read; writes
+ * nothing, calls no model, and never fails on an empty vault.
+ */
+export function designNoteGrounding(vault: string, topic: string): DesignNoteGrounding {
+ const trimmed = requireTopic(topic);
+ const queryTokens = tokenise(trimmed);
+ const emptyStores: DesignNoteStore[] = [];
+
+ const allTensions = listTensions(vault);
+ if (allTensions.length === 0) emptyStores.push(DESIGN_NOTE_STORE.tensions);
+ const tensions = allTensions
+ .map((record) => ({ record, score: tensionScore(queryTokens, record) }))
+ .filter((row) => row.score >= DESIGN_NOTE_MATCH_THRESHOLD)
+ .toSorted((a, b) => b.score - a.score || a.record.slug.localeCompare(b.record.slug))
+ .slice(0, DESIGN_NOTE_PER_STORE_LIMIT)
+ .map(({ record, score }) =>
+ Object.freeze({
+ id: record.id,
+ slug: record.slug,
+ subject: record.subject,
+ status: record.status,
+ unresolved: TENSION_UNRESOLVED_STATUSES.has(record.status),
+ jaccard: score,
+ }),
+ );
+
+ // The decision store owns its own matcher; reusing it keeps one ranking
+ // rule for "a decision like this one" across every surface that asks.
+ if (listDecisions(vault).length === 0) emptyStores.push(DESIGN_NOTE_STORE.decisions);
+ const decisions = findSimilarDecisions(
+ vault,
+ { title: trimmed },
+ { threshold: DESIGN_NOTE_MATCH_THRESHOLD, limit: DESIGN_NOTE_PER_STORE_LIMIT },
+ ).map((match) =>
+ Object.freeze({
+ id: match.id,
+ slug: match.slug,
+ title: match.title,
+ chosen: match.chosen,
+ outcome: match.outcome,
+ jaccard: match.jaccard,
+ }),
+ );
+
+ const truth = readTruthState(vault);
+ // A truth state that is absent and one that is unreadable are the same
+ // fact for this report - there is no projection to ground anything in -
+ // and `readTruthState` already collapses them to null by design.
+ if (truth === null || truth.slots.length === 0) emptyStores.push(DESIGN_NOTE_STORE.truth);
+ const truthSlots = (truth?.slots ?? [])
+ .map((slot) => ({ slot, score: claimScore(queryTokens, slot) }))
+ .filter((row) => row.score >= DESIGN_NOTE_MATCH_THRESHOLD)
+ .toSorted(
+ (a, b) =>
+ b.score - a.score ||
+ `${a.slot.entity}/${a.slot.aspect}`.localeCompare(`${b.slot.entity}/${b.slot.aspect}`),
+ )
+ .slice(0, DESIGN_NOTE_PER_STORE_LIMIT)
+ .map(({ slot, score }) =>
+ Object.freeze({
+ entity: slot.entity,
+ aspect: slot.aspect,
+ value: slot.current.value,
+ contested: slot.contested,
+ jaccard: score,
+ }),
+ );
+ const conflicts = (truth?.conflicts ?? [])
+ .filter((conflict) => conflictScore(queryTokens, conflict) >= DESIGN_NOTE_MATCH_THRESHOLD)
+ .slice(0, DESIGN_NOTE_PER_STORE_LIMIT)
+ .map((conflict) =>
+ Object.freeze({
+ entity: conflict.entity,
+ aspect: conflict.aspect,
+ values: Object.freeze(conflict.values.map((v) => v.value)),
+ }),
+ );
+
+ return Object.freeze({
+ topic: trimmed,
+ tensions: Object.freeze(tensions),
+ decisions: Object.freeze(decisions),
+ truthSlots: Object.freeze(truthSlots),
+ conflicts: Object.freeze(conflicts),
+ counts: Object.freeze({
+ tensions: tensions.length,
+ decisions: decisions.length,
+ truthSlots: truthSlots.length,
+ conflicts: conflicts.length,
+ }),
+ emptyStores: Object.freeze(emptyStores),
+ });
+}
+
+// ----- Phase one: the request -----------------------------------------------
+
+/**
+ * Ground a topic and return the one envelope that asks for the note.
+ * Read-only. An empty vault yields a report, not a refusal: the caller can
+ * still write a design note, and the report says exactly how little it
+ * rests on.
+ */
+export function planDesignNote(
+ vault: string,
+ topic: string,
+ opts: PlanDesignNoteOptions,
+): DesignNoteReport {
+ const trimmed = requireTopic(topic);
+ const grounding = designNoteGrounding(vault, trimmed);
+ const slug = slugify(trimmed);
+ const targetPath = posix.join(DESIGN_NOTE_DIR_REL, noteBasename(slug, opts.now));
+ return Object.freeze({
+ topic: trimmed,
+ slug,
+ generatedAt: opts.now.toISOString(),
+ grounding,
+ targetPath,
+ llmStep: buildNeedsLlmStep({
+ step: DESIGN_NOTE_STEP,
+ prompt:
+ `Write a design note on '${trimmed}'. Weigh at least two NAMED alternatives, each with ` +
+ "its approach and its tradeoffs, and mark EXACTLY ONE of them recommended - a note that " +
+ "recommends none has not been written and one that recommends two has not been decided. " +
+ "Ground every claim in the records below; where they say nothing, say so rather than " +
+ "filling the gap.\n\n" +
+ renderGrounding(grounding),
+ schema_hints: [
+ 'payload: { "title", "summary"?, "alternatives": [ { "name", "approach", "tradeoffs", "recommended" } ] }',
+ "alternatives: at least two, each field non-empty",
+ "recommended: boolean; exactly one alternative may set it true",
+ ],
+ target_path: targetPath,
+ }),
+ });
+}
+
+// ----- Phase two: the note --------------------------------------------------
+
+/**
+ * Validate the returned note and commit it beside the panel outputs.
+ *
+ * The write is exclusive. A second note for the same topic on the same day
+ * is refused by name rather than overwriting the first: two design notes
+ * that disagree are a fact worth keeping, and silently replacing one is
+ * how the disagreement disappears.
+ */
+export function commitDesignNote(
+ vault: string,
+ topic: string,
+ payload: unknown,
+ opts: CommitDesignNoteOptions,
+): CommitDesignNoteResult {
+ // Vault-identity write guard (context-integrity-gates, Unit J): this is
+ // the module's only write, and `tests/core/brain/vault-guard-census.test.ts`
+ // counts every write-capable module in this tree.
+ assertVaultIdentityForWrite(vault);
+ const trimmed = requireTopic(topic);
+ // Structure first, then the cardinality rule. Nothing is written until
+ // both pass.
+ assertResponseShape(DESIGN_NOTE_SURFACE, DESIGN_NOTE_SHAPE, payload);
+ assertResponseCheck(DESIGN_NOTE_SURFACE, payload);
+
+ const note = payload as {
+ title: string;
+ summary?: string;
+ alternatives: ReadonlyArray<DesignNoteAlternative>;
+ };
+ const recommended = note.alternatives.find((a) => a.recommended)!;
+ const slug = slugify(trimmed);
+ const dir = decisionsDir(vault);
+ mkdirSync(dir, { recursive: true });
+ const path = join(dir, noteBasename(slug, opts.now));
+
+ writeFrontmatterAtomic(
+ path,
+ {
+ schema_version: 1,
+ kind: DESIGN_NOTE_KIND,
+ slug,
+ topic: trimmed,
+ title: note.title.trim(),
+ recommended: recommended.name.trim(),
+ alternative_count: String(note.alternatives.length),
+ agent: opts.agent,
+ created_at: opts.now.toISOString(),
+ },
+ renderNote(trimmed, note),
+ {
+ overwrite: false,
+ existsErrorKind: "design note",
+ vaultForRelativePath: vault,
+ },
+ );
+
+ return Object.freeze({
+ topic: trimmed,
+ slug,
+ path,
+ recommended: recommended.name.trim(),
+ alternativeCount: note.alternatives.length,
+ });
+}
+
+// ----- Internals ------------------------------------------------------------
+
+function requireTopic(topic: string): string {
+ const trimmed = topic.trim();
+ if (trimmed.length === 0) throw new DesignNoteError("a design note needs a topic");
+ return trimmed;
+}
+
+/** `design-<date>-<topic>.md`, the panel outputs' shape one directory up. */
+function noteBasename(slug: string, now: Date): string {
+ return `design-${isoDate(now)}-${slug}.md`;
+}
+
+function tensionScore(queryTokens: ReadonlySet<string>, record: TensionRecord): number {
+ return jaccard(queryTokens, tokenise(`${record.subject} ${record.quoteA} ${record.quoteB}`));
+}
+
+function claimScore(queryTokens: ReadonlySet<string>, slot: ClaimSlot): number {
+ return jaccard(queryTokens, tokenise(`${slot.entity} ${slot.aspect} ${slot.current.value}`));
+}
+
+function conflictScore(queryTokens: ReadonlySet<string>, conflict: TruthConflict): number {
+ return jaccard(queryTokens, tokenise(`${conflict.entity} ${conflict.aspect}`));
+}
+
+/** The grounding set as the prompt shows it - identities, not prose. */
+function renderGrounding(grounding: DesignNoteGrounding): string {
+ const out: string[] = [];
+ const section = (heading: string, lines: ReadonlyArray<string>, store: DesignNoteStore): void => {
+ out.push(`## ${heading}`);
+ if (grounding.emptyStores.includes(store)) {
+ out.push(`(this vault holds no ${store} at all)`);
+ } else if (lines.length === 0) {
+ out.push(`(the ${store} store holds records, but none match this topic)`);
+ } else {
+ out.push(...lines);
+ }
+ out.push("");
+ };
+
+ section(
+ "Unresolved and past tensions",
+ grounding.tensions.map(
+ (t) => `- ${t.id} [${t.status}${t.unresolved ? ", unresolved" : ""}] ${t.subject}`,
+ ),
+ DESIGN_NOTE_STORE.tensions,
+ );
+ section(
+ "Prior decisions",
+ grounding.decisions.map(
+ (d) =>
+ `- ${d.id} chose "${d.chosen}"${d.outcome ? ` -> ${d.outcome}` : " (no outcome recorded)"}`,
+ ),
+ DESIGN_NOTE_STORE.decisions,
+ );
+ const truthLines = [
+ ...grounding.truthSlots.map(
+ (s) => `- ${s.entity}/${s.aspect} = ${s.value}${s.contested ? " (contested)" : ""}`,
+ ),
+ ...grounding.conflicts.map(
+ (c) => `- CONFLICT ${c.entity}/${c.aspect}: ${c.values.join(" vs ")}`,
+ ),
+ ];
+ section("Current claims", truthLines, DESIGN_NOTE_STORE.truth);
+ return out.join("\n");
+}
+
+function renderNote(
+ topic: string,
+ note: {
+ title: string;
+ summary?: string;
+ alternatives: ReadonlyArray<DesignNoteAlternative>;
+ },
+): string {
+ const out: string[] = [`# ${note.title.trim()}`, "", `Topic: ${topic}`, ""];
+ if (note.summary?.trim()) out.push("## Summary", "", note.summary.trim(), "");
+ out.push("## Alternatives", "");
+ for (const alt of note.alternatives) {
+ out.push(`### ${alt.name.trim()}${alt.recommended ? " (recommended)" : ""}`, "");
+ out.push(alt.approach.trim(), "");
+ out.push(`Tradeoffs: ${alt.tradeoffs.trim()}`, "");
+ }
+ return out.join("\n");
+}
diff --git a/src/core/brain/destructive-sites.ts b/src/core/brain/destructive-sites.ts
index 976d32c1..1e140efb 100644
--- a/src/core/brain/destructive-sites.ts
+++ b/src/core/brain/destructive-sites.ts
@@ -355,13 +355,16 @@ export const DESTRUCTIVE_SITES: Readonly<Record<string, DestructiveSiteDeclarati
// --- Two-phase accept with a journalled rollback ---------------------
"src/core/brain/skill-proposals.ts": {
- calls: ["rmSync", "unlinkSync"],
+ calls: ["rmSync", "rmdirSync", "unlinkSync"],
recovery: UNARCHIVED_BRAIN,
reason:
"unlinks the pending proposal only after the accepted copy landed through " +
"`writeFrontmatterAtomic` and the journal recorded the commit phase; the " +
- "`rmSync` arm is the rollback, and it removes the accepted copy and its " +
- "procedure only when the journal recorded that neither existed beforehand.",
+ "`rmSync` arm is the rollback, and it removes the accepted copy and the " +
+ "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.",
},
// --- Repair under an explicit apply ----------------------------------
@@ -401,7 +404,9 @@ export const DESTRUCTIVE_SITES: Readonly<Record<string, DestructiveSiteDeclarati
"every other. The case-only rename cannot use that order - unlinking the source would " +
"remove the destination with it - so it stages a third private name for the same inode " +
"first. A note lives outside `Brain/` by construction, which is why no archive covers " +
- "it and why the DELETE arm of the same module is behind the gate instead.",
+ "it and why the DELETE arm of the same module is behind the gate instead - including " +
+ "the `--delete-linked` cascade, whose extra unlinks all sit inside that one gate call " +
+ "and whose Brain-resident half the archive therefore does hold.",
},
// --- Outside the vault entirely --------------------------------------
diff --git a/src/core/brain/diarization.ts b/src/core/brain/diarization.ts
index 0055daa3..a1876b85 100644
--- a/src/core/brain/diarization.ts
+++ b/src/core/brain/diarization.ts
@@ -27,6 +27,7 @@ import { hasEvidenceIdentity, type EvidenceIdentity } from "./deep-synthesis.ts"
import { getEntity } from "./entities/registry.ts";
import type { EntityRef } from "./entities/types.ts";
import { getIngestedSource, listIngestedSources } from "./ingest/sources-registry.ts";
+import { buildNeedsLlmStep, type NeedsLlmStep } from "./llm-step.ts";
/** Vault-relative directory a fleshed profile note lands in. */
export const PROFILE_DIR_REL = "Brain/profiles";
@@ -74,18 +75,11 @@ export interface DiarizationGapLine {
}
/**
- * The single deferred generation step. Shape mirrors the write-session
- * `needs-llm-step` envelope grammar (status, step, prompt, schema hints,
- * target path) but stays plain data: diarization is read-only and opens
- * no durable session.
+ * The single deferred generation step: the shared envelope spine, exactly.
+ * It stays plain data - diarization is read-only and opens no durable
+ * session - so it carries the spine and nothing beyond it.
*/
-export interface DiarizationLlmStep {
- readonly status: "needs-llm-step";
- readonly step: string;
- readonly prompt: string;
- readonly schema_hints: ReadonlyArray<string>;
- readonly target_path: string;
-}
+export type DiarizationLlmStep = NeedsLlmStep;
export interface DiarizationReport {
readonly entityId: string;
@@ -233,17 +227,16 @@ export function diarize(
lines,
documentSet,
});
- const llmStep: DiarizationLlmStep = Object.freeze({
- status: "needs-llm-step" as const,
+ const llmStep: DiarizationLlmStep = buildNeedsLlmStep({
step: PROFILE_PROSE_STEP,
prompt:
`Write the summary prose for the profile of ${entity.name} (${entity.id}). ` +
"Ground every statement in the stated-vs-evidenced section and the document set below; " +
`replace the ${PROSE_MARKER} marker with the prose and submit the full note.`,
- schema_hints: Object.freeze([
+ schema_hints: [
"frontmatter: preserve the skeleton block verbatim",
"body: replace only the prose marker; keep the structured sections intact",
- ]),
+ ],
target_path: targetPath,
});
diff --git a/src/core/brain/dream-stage.ts b/src/core/brain/dream-stage.ts
index afba5ac1..8d4886a1 100644
--- a/src/core/brain/dream-stage.ts
+++ b/src/core/brain/dream-stage.ts
@@ -22,6 +22,10 @@
* with, then executes `dream()` live; determinism guarantees the
* live run performs exactly the staged plan. Drift at any point
* aborts before a single write.
+ * - `retriageDreamBundle` re-runs the salience gate against the
+ * CURRENT threshold and reports the admitted/excluded delta against
+ * the partition the bundle recorded. It mutates nothing: re-staging
+ * to adopt the new partition stays the operator's decision.
*
* The projection deliberately drops run ids, timestamps, and any
* field that legitimately varies with the wall clock without changing
@@ -37,6 +41,15 @@ import { sha256Hex } from "../integrity/digest.ts";
import { appendMetric } from "./metrics.ts";
import { brainDirs } from "./paths.ts";
import { dream, type DreamOptions, type DreamRunSummary } from "./dream.ts";
+import { scanBrain } from "./dream-scan.ts";
+import { loadBrainConfig } from "./policy.ts";
+import {
+ collectSalienceFoldSet,
+ gateFoldSet,
+ openSalienceGate,
+ resolveSalienceThreshold,
+ type SalienceGateVerdict,
+} from "./salience-gate.ts";
import { isoSecond } from "./time.ts";
import { assertVaultIdentityForWrite } from "./vault-identity.ts";
@@ -58,6 +71,37 @@ export interface DreamStagePlan {
readonly gated_retires: ReadonlyArray<{ pref_id: string; attempted_reason: string }>;
}
+/**
+ * The salience partition the bundle was staged with (salience-lifecycle-
+ * enrichment, unit 1).
+ *
+ * Deliberately NOT part of {@link DreamStagePlan}: the plan projection is
+ * what `validate` diffs to prove the vault has not drifted, and it covers
+ * what the pass WRITES. The gate changes which facts the rollup ladder
+ * folds, and the ladder's envelopes are not in the projection either, so
+ * folding this in would report drift for something the projection does
+ * not otherwise model. It rides beside the plan in the manifest, and
+ * {@link retriageDreamBundle} is what reads it back.
+ */
+export interface DreamStageSalience {
+ readonly threshold: number | null;
+ readonly considered: number;
+ readonly admitted: number;
+ readonly excluded: ReadonlyArray<{ readonly pref_id: string; readonly score: number }>;
+}
+
+/** The manifest-side projection of one gate verdict. */
+export function projectSalienceGate(verdict: SalienceGateVerdict): DreamStageSalience {
+ return Object.freeze({
+ threshold: verdict.threshold,
+ considered: verdict.considered,
+ admitted: verdict.admitted,
+ excluded: Object.freeze(
+ verdict.excluded.map((e) => Object.freeze({ pref_id: e.pref_id, score: e.score })),
+ ),
+ });
+}
+
export interface DreamStageSource {
readonly path: string;
readonly sha256: string;
@@ -208,7 +252,12 @@ function planToProposals(plan: DreamStagePlan): Array<Record<string, unknown>> {
const section = (title: string, lines: ReadonlyArray<string>): string[] =>
lines.length === 0 ? [] : [`## ${title}`, "", ...lines.map((l) => `- ${l}`), ""];
-function renderReport(runId: string, stagedAt: string, plan: DreamStagePlan): string {
+function renderReport(
+ runId: string,
+ stagedAt: string,
+ plan: DreamStagePlan,
+ salience: DreamStageSalience,
+): string {
return [
`# Dream stage ${runId}`,
"",
@@ -217,6 +266,14 @@ function renderReport(runId: string, stagedAt: string, plan: DreamStagePlan): st
"",
`Staged at: ${stagedAt}`,
`Planned changes: ${plan.changed ? "yes" : "none"}`,
+ // Silent when no gate is configured, so an un-opted-in vault's report
+ // is byte-identical to the one it has always rendered.
+ ...(salience.threshold === null
+ ? []
+ : [
+ `Salience threshold: ${salience.threshold} ` +
+ `(${salience.admitted} of ${salience.considered} facts folded)`,
+ ]),
"",
...section("Would create (unconfirmed)", plan.new_unconfirmed),
...section("Would confirm", plan.confirmed),
@@ -235,6 +292,10 @@ function renderReport(runId: string, stagedAt: string, plan: DreamStagePlan): st
plan.gated_retires.map((g) => `${g.pref_id} (${g.attempted_reason})`),
),
...section("Open contradictions", plan.contradictions),
+ ...section(
+ "Held out of the rollup fold set",
+ salience.excluded.map((e) => `${e.pref_id} (salience ${e.score})`),
+ ),
].join("\n");
}
@@ -253,6 +314,7 @@ export function stageDream(vault: string, opts: DreamStageOptions): DreamStageBu
...(opts.agentName !== undefined ? { agentName: opts.agentName } : {}),
});
const plan = projectDreamPlan(summary);
+ const salience = projectSalienceGate(summary.salience_gate);
const sources = scanSources(vault);
const stagedAt = isoSecond(opts.now);
// Second-resolution ids can collide (same --now, same second): take
@@ -272,7 +334,7 @@ export function stageDream(vault: string, opts: DreamStageOptions): DreamStageBu
atomicWriteFileSync(join(dir, "proposals.jsonl"), proposalsBody);
atomicWriteFileSync(join(dir, "sources.jsonl"), sourcesBody);
- atomicWriteFileSync(join(dir, "REPORT.md"), renderReport(runId, stagedAt, plan) + "\n");
+ atomicWriteFileSync(join(dir, "REPORT.md"), renderReport(runId, stagedAt, plan, salience) + "\n");
atomicWriteFileSync(
join(dir, "manifest.json"),
JSON.stringify(
@@ -285,6 +347,7 @@ export function stageDream(vault: string, opts: DreamStageOptions): DreamStageBu
plan,
plan_hash: sha256Hex(JSON.stringify(plan)),
sources_hash: sha256Hex(sourcesBody),
+ salience,
},
null,
2,
@@ -440,6 +503,219 @@ export function applyDreamBundle(
return Object.freeze({ applied: true, validation, summary });
}
+// ----- retriage ------------------------------------------------------------
+
+/**
+ * Raised when a bundle cannot be retriaged. Carries the id and the bare
+ * reason so a caller reading only the error knows whether to re-stage,
+ * fix the id, or look somewhere else.
+ */
+export class DreamRetriageError extends Error {
+ readonly runId: string;
+ /** The reason alone, without the sentence wrapped around it. */
+ readonly reason: string;
+
+ constructor(runId: string, reason: string) {
+ super(`dream bundle ${runId} cannot be retriaged: ${reason}`);
+ this.name = "DreamRetriageError";
+ this.runId = runId;
+ this.reason = reason;
+ }
+}
+
+/** One fact that crosses the gate differently than the bundle recorded. */
+export interface DreamRetriageEntry {
+ readonly pref_id: string;
+ readonly path: string;
+ /** Score under the current scoring pass. */
+ readonly score: number;
+ /**
+ * Score the bundle recorded, or `null` when it recorded none - the
+ * bundle only stores scores for the facts it EXCLUDED, and an open
+ * gate scores nothing at all.
+ */
+ readonly staged_score: number | null;
+}
+
+export interface DreamRetriageOutcome {
+ readonly runId: string;
+ readonly stagedThreshold: number | null;
+ readonly currentThreshold: number | null;
+ /** True when the threshold moved or either delta is non-empty. */
+ readonly changed: boolean;
+ /** Fold-set size now. */
+ readonly considered: number;
+ /** Facts the current threshold would fold. */
+ readonly admitted: number;
+ /** Excluded when staged, admitted now. */
+ readonly newlyAdmitted: ReadonlyArray<DreamRetriageEntry>;
+ /** Admitted when staged, excluded now. */
+ readonly newlyExcluded: ReadonlyArray<DreamRetriageEntry>;
+ /** Named observations the two deltas alone cannot carry. */
+ readonly notes: ReadonlyArray<string>;
+}
+
+/** Read the manifest's salience block, refusing anything it cannot trust. */
+function readStagedSalience(runId: string, raw: unknown): DreamStageSalience {
+ if (raw === null || typeof raw !== "object" || Array.isArray(raw)) {
+ throw new DreamRetriageError(
+ runId,
+ "it records no salience partition - it was staged before the gate shipped, so re-stage it " +
+ "to get a partition worth comparing",
+ );
+ }
+ const block = raw as Record<string, unknown>;
+ const threshold = block["threshold"];
+ if (threshold !== null && typeof threshold !== "number") {
+ throw new DreamRetriageError(runId, "its recorded salience threshold is not a number or null");
+ }
+ const excludedRaw = block["excluded"];
+ if (!Array.isArray(excludedRaw)) {
+ throw new DreamRetriageError(runId, "its recorded salience exclusions are not a list");
+ }
+ const excluded = excludedRaw.map((entry) => {
+ const row = entry as Record<string, unknown>;
+ if (typeof row?.["pref_id"] !== "string" || typeof row["score"] !== "number") {
+ throw new DreamRetriageError(
+ runId,
+ "one recorded salience exclusion carries no pref_id and score pair",
+ );
+ }
+ return Object.freeze({ pref_id: row["pref_id"], score: row["score"] });
+ });
+ return Object.freeze({
+ threshold,
+ considered: readStagedCount(runId, block, "considered", excluded.length),
+ admitted: readStagedCount(runId, block, "admitted", 0),
+ excluded: Object.freeze(excluded),
+ });
+}
+
+/**
+ * One recorded count, or the fallback for a bundle staged before the
+ * field existed.
+ *
+ * Validated like the threshold and the exclusion list above rather than
+ * coerced: `Number("many")` is NaN, NaN equals nothing, and the retriage
+ * would then report "the fold set changed size" on every run over the
+ * same corrupted manifest - a note naming a delta that never happened,
+ * instead of the refusal a corrupted bundle deserves.
+ */
+function readStagedCount(
+ runId: string,
+ block: Record<string, unknown>,
+ key: string,
+ fallback: number,
+): number {
+ const raw = block[key];
+ if (raw === undefined || raw === null) return fallback;
+ if (typeof raw !== "number" || !Number.isFinite(raw)) {
+ throw new DreamRetriageError(runId, `its recorded salience '${key}' count is not a number`);
+ }
+ return raw;
+}
+
+/**
+ * Re-run the gate against the CURRENT threshold and report what would
+ * move. Read-only in both directions: the bundle is never rewritten and
+ * the vault is never touched, so an operator who wants the new partition
+ * re-stages deliberately.
+ *
+ * Unlike a pass, this always scores the fold set - even with the gate
+ * open - because the delta has to name a score for every fact it moves,
+ * and "the gate is open so nothing was measured" is an answer that
+ * cannot be compared against the bundle.
+ */
+export function retriageDreamBundle(
+ vault: string,
+ runId: string,
+ opts: DreamStageOptions,
+): DreamRetriageOutcome {
+ if (!isValidRunId(runId)) {
+ throw new DreamRetriageError(runId, "that is not an id this staging surface issues");
+ }
+ const manifest = readManifest(join(stagedRoot(vault), runId));
+ if (manifest === null) {
+ throw new DreamRetriageError(
+ runId,
+ "there is no staged bundle by that name, or its manifest is unreadable",
+ );
+ }
+ const staged = readStagedSalience(runId, manifest["salience"]);
+
+ const cfg = loadBrainConfig(vault);
+ const currentThreshold = resolveSalienceThreshold(cfg);
+ const items = collectSalienceFoldSet({
+ vault,
+ preferences: scanBrain(vault).preferences,
+ cfg,
+ now: opts.now,
+ });
+ const verdict =
+ currentThreshold === null
+ ? openSalienceGate(items.length)
+ : gateFoldSet(items, currentThreshold);
+
+ const stagedScores = new Map(staged.excluded.map((e) => [e.pref_id, e.score]));
+ const currentExcluded = new Set(verdict.excluded.map((e) => e.pref_id));
+ const scoreById = new Map(items.map((i) => [i.pref_id, i]));
+
+ const newlyExcluded: DreamRetriageEntry[] = [];
+ for (const entry of verdict.excluded) {
+ if (stagedScores.has(entry.pref_id)) continue;
+ newlyExcluded.push(
+ Object.freeze({
+ pref_id: entry.pref_id,
+ path: entry.path,
+ score: entry.score,
+ staged_score: null,
+ }),
+ );
+ }
+
+ const newlyAdmitted: DreamRetriageEntry[] = [];
+ const notes: string[] = [];
+ for (const [prefId, stagedScore] of [...stagedScores].toSorted((a, b) =>
+ a[0] < b[0] ? -1 : a[0] > b[0] ? 1 : 0,
+ )) {
+ if (currentExcluded.has(prefId)) continue;
+ const item = scoreById.get(prefId);
+ if (item === undefined) {
+ // Gone from the fold set entirely: reporting it as "newly
+ // admitted" would claim the ladder will now fold a fact that no
+ // longer exists.
+ notes.push(`${prefId} was excluded at stage time and is no longer in the fold set`);
+ continue;
+ }
+ newlyAdmitted.push(
+ Object.freeze({
+ pref_id: prefId,
+ path: item.path,
+ score: item.score.score,
+ staged_score: stagedScore,
+ }),
+ );
+ }
+ if (staged.considered !== verdict.considered) {
+ notes.push(
+ `the fold set changed size: ${staged.considered} fact(s) at stage time, ${verdict.considered} now`,
+ );
+ }
+
+ return Object.freeze({
+ runId,
+ stagedThreshold: staged.threshold,
+ currentThreshold,
+ changed:
+ staged.threshold !== currentThreshold || newlyAdmitted.length > 0 || newlyExcluded.length > 0,
+ considered: verdict.considered,
+ admitted: verdict.admitted,
+ newlyAdmitted: Object.freeze(newlyAdmitted),
+ newlyExcluded: Object.freeze(newlyExcluded),
+ notes: Object.freeze(notes),
+ });
+}
+
/** Remove one staged bundle. True when it existed. */
export function discardDreamBundle(vault: string, runId: string): boolean {
// Vault-identity write guard (context-integrity-gates, Unit J).
diff --git a/src/core/brain/dream-summary.ts b/src/core/brain/dream-summary.ts
index e066e77f..fcff0dda 100644
--- a/src/core/brain/dream-summary.ts
+++ b/src/core/brain/dream-summary.ts
@@ -29,6 +29,7 @@ import type {
import type { BrainIntentReviewEntry } from "./intent-review.ts";
import type { ReconcileOutcomes } from "./reconcile-outcomes.ts";
import type { RollupLadderEntry, RollupLadderPlan } from "./rollup-ladder.ts";
+import type { SalienceGateVerdict } from "./salience-gate.ts";
/** Empty, frozen views for the fields a no-op run cannot populate. */
const NO_UNCERTAIN = Object.freeze([] as ReadonlyArray<DreamUncertainEntry>);
@@ -44,6 +45,8 @@ export interface DreamNoOpSummaryInput {
readonly reconcile: ReconcileOutcomes;
readonly intentReviews: ReadonlyArray<BrainIntentReviewEntry>;
readonly warnings: ReadonlyArray<DreamWarning>;
+ /** The gate's verdict over the fold set the ladder would have counted. */
+ readonly salienceGate: SalienceGateVerdict;
}
export function buildNoOpSummary(input: DreamNoOpSummaryInput): DreamRunSummary {
@@ -65,6 +68,7 @@ export function buildNoOpSummary(input: DreamNoOpSummaryInput): DreamRunSummary
outcome_regressions: Object.freeze([...refresh.outcomeRegressions]),
phases: NO_PHASES,
rollups: NO_ROLLUPS,
+ salience_gate: input.salienceGate,
open_questions: Object.freeze([...reconcile.openQuestions]),
...(input.dryRun ? { dry_run: true } : {}),
} satisfies DreamRunSummary);
@@ -85,6 +89,8 @@ export interface DreamChangedSummaryInput {
readonly refresh: RefreshResult;
readonly reconcile: ReconcileOutcomes;
readonly rollupPlan: RollupLadderPlan;
+ /** The gate's verdict over the fold set `rollupPlan` counted. */
+ readonly salienceGate: SalienceGateVerdict;
readonly intentReviews: ReadonlyArray<BrainIntentReviewEntry>;
readonly warnings: ReadonlyArray<DreamWarning>;
readonly gatedRetires: ReadonlyArray<DreamGatedRetireEntry>;
@@ -103,6 +109,7 @@ export function buildChangedSummary(input: DreamChangedSummaryInput): DreamRunSu
changed: true,
phases: buildPhaseSummaries(input),
rollups: Object.freeze([...input.rollupPlan.entries]),
+ salience_gate: input.salienceGate,
open_questions: Object.freeze([...reconcile.openQuestions]),
new_unconfirmed: plan.newUnconfirmed.map((p) => `pref-${p.slug}`),
confirmed: Array.from(refresh.confirmed.values()).map((s) => `pref-${s}`),
diff --git a/src/core/brain/dream-types.ts b/src/core/brain/dream-types.ts
index 8ee75fcc..a1243afd 100644
--- a/src/core/brain/dream-types.ts
+++ b/src/core/brain/dream-types.ts
@@ -15,6 +15,7 @@ import type { DreamQuarantinedEntry } from "./dream-plan.ts";
import type { DreamOutcomeRegression } from "./dream-refresh.ts";
import type { BrainIntentReviewEntry } from "./intent-review.ts";
import type { RollupLadderEntry } from "./rollup-ladder.ts";
+import type { SalienceGateVerdict } from "./salience-gate.ts";
import type { BrainRetiredReason, DreamOpenQuestion } from "./types.ts";
/**
@@ -141,6 +142,15 @@ export interface DreamRunSummary {
* crossed its threshold, keeping a below-threshold run byte-identical.
*/
readonly rollups: ReadonlyArray<RollupLadderEntry>;
+ /**
+ * Deterministic salience gate over the fold set the rollup ladder
+ * counts (salience-lifecycle-enrichment, unit 1). Always present:
+ * `threshold: null` says the gate was ABSENT, which a missing field
+ * could not distinguish from a gate that excluded nothing. Every
+ * excluded fact is named here with its score - the gate never drops
+ * anything silently.
+ */
+ readonly salience_gate: SalienceGateVerdict;
/**
* Reconcile-phase domain classification (Brain lifecycle suite,
* Feature 3). Contradictions that stayed unresolved, each tagged with
diff --git a/src/core/brain/dream.ts b/src/core/brain/dream.ts
index f4f88233..ddfe2735 100644
--- a/src/core/brain/dream.ts
+++ b/src/core/brain/dream.ts
@@ -84,6 +84,7 @@ import {
resolveRollupThresholds,
type RollupLadderPlan,
} from "./rollup-ladder.ts";
+import { applySalienceGate } from "./salience-gate.ts";
import { withDestructiveSnapshot } from "./snapshot-gate.ts";
import { compactRunStamp, isoDate } from "./time.ts";
import { BRAIN_SNAPSHOT_REASON } from "./types.ts";
@@ -262,13 +263,21 @@ function dreamRun(
// the `reconcile` log events below are emitted only on a changed run.
const reconcile = buildReconcileOutcomes(scan, plan, cfg, now);
+ // Deterministic salience gate over the ladder's fold set
+ // (salience-lifecycle-enrichment, unit 1). The ladder counts facts and
+ // nothing else, so this is the only seam where a salience judgement can
+ // change what the pass asks a model to fold. With
+ // `dream.salience_threshold` unset the gate is open and reads nothing,
+ // which is why an un-opted-in vault pays no I/O here.
+ const salienceGate = applySalienceGate({ vault, preferences: scan.preferences, cfg, now });
+
// Count-triggered fact rollup ladder (S3): pure counters over the
- // current fact artifacts (preferences) against the persisted per-tier
+ // ADMITTED fact artifacts (preferences) against the persisted per-tier
// baselines. Computed before the `changed` gate so a run whose ONLY
// effect is a rollup still counts as changed; below threshold it fires
// nothing and the ledger is never written, so the run stays
// byte-identical.
- let rollupPlan = buildRollupPlan(vault, cfg, scan.preferences.length, runId);
+ let rollupPlan = buildRollupPlan(vault, cfg, salienceGate.admitted, runId);
if (!hasStateChange(plan, refresh, scan.corrupted.length, rollupPlan)) {
if (!dryRun) {
@@ -288,6 +297,7 @@ function dreamRun(
reconcile,
intentReviews: intentReview.reviews,
warnings,
+ salienceGate,
});
}
@@ -328,7 +338,7 @@ function dreamRun(
// the pre-collision runId; if the ladder corrected it, rebuild the
// plan so every target_path embeds the final run_id.
if (rollupPlan.fired && runId !== baseRunId) {
- rollupPlan = buildRollupPlan(vault, cfg, scan.preferences.length, runId);
+ rollupPlan = buildRollupPlan(vault, cfg, salienceGate.admitted, runId);
}
opts.safeguard?.checkpoint();
const handle = openWorkrun(vault, runId);
@@ -444,6 +454,7 @@ function dreamRun(
refresh,
reconcile,
rollupPlan,
+ salienceGate,
intentReviews: intentReview.reviews,
warnings,
gatedRetires: exec.gatedRetires,
diff --git a/src/core/brain/expiration-set.ts b/src/core/brain/expiration-set.ts
new file mode 100644
index 00000000..d6eb0240
--- /dev/null
+++ b/src/core/brain/expiration-set.ts
@@ -0,0 +1,289 @@
+/**
+ * Post-creation expiration mutation for signals and preferences
+ * (unit 3c / t_5e338af1).
+ *
+ * `expiration.ts` has had a validator, a read filter and a writer
+ * parameter on both artifact kinds since C5, and nothing has ever been
+ * able to CHANGE the field once written. The gap is the whole of this
+ * module: an operator who set "until 2026-07-15" and then extended the
+ * migration had no way to say so, and one who set nothing had no way to
+ * add a lifetime to a rule that turned out to be temporary.
+ *
+ * ## Why the mutation lives here and not on the note surfaces
+ *
+ * `brain_update_note` and `note_lifecycle` both run every path through
+ * `resolveNoteTarget`, which refuses the `Brain/` machinery root for
+ * every note path it is given. That refusal is load-bearing - it is what
+ * keeps a note-editing surface from rewriting a preference - so reaching
+ * signals and preferences from there would mean carving an exception
+ * into the one guard that makes those surfaces safe. This module
+ * addresses the artifacts by ID instead, exactly as `retireSignal` does,
+ * and never accepts a path at all.
+ *
+ * ## One chokepoint
+ *
+ * Every value written here goes through
+ * {@link normalizeExpirationDate}, which is also the only door
+ * `writeSignal` and `writePreference` use. That matters more than it
+ * looks: the READ side deliberately fails open on an unparseable date so
+ * a corrupted value surfaces rather than silently hiding a memory, and
+ * that tolerance is only safe while every write is validated. A second
+ * writer skipping the validator would turn a documented fail-open into a
+ * memory that never expires and nobody notices.
+ *
+ * Clearing is explicit, and it REMOVES the key rather than writing an
+ * empty one. An empty `expiration_date` parses to nothing, fails open on
+ * read, and reads on disk as a lifetime somebody meant to set.
+ */
+
+import { existsSync } from "node:fs";
+import { join } from "node:path";
+
+import type { FrontmatterMap } from "../types.ts";
+import { parseFrontmatter, writeFrontmatterAtomic } from "../vault.ts";
+import { EXPIRATION_DATE_FIELD, normalizeExpirationDate } from "./expiration.ts";
+import { appendLogEvent } from "./log.ts";
+import { brainDirsForWrite, ensureInsideVault } from "./paths.ts";
+import { isoSecond } from "./time.ts";
+import { BRAIN_LOG_EVENT_KIND } from "./types.ts";
+import { assertVaultIdentityForWrite } from "./vault-identity.ts";
+
+/**
+ * The value that CLEARS an expiration.
+ *
+ * A word rather than an empty string, and that is the point: `--expires
+ * ""` is what a shell produces when a variable did not expand, so
+ * accepting it would let a broken script silently un-expire a memory.
+ * Clearing has to be something a caller can only type on purpose.
+ */
+export const EXPIRATION_CLEAR = "none";
+
+/** The artifact kinds this surface can address. */
+export const EXPIRATION_TARGET_KIND = Object.freeze({
+ signal: "signal",
+ preference: "preference",
+} as const);
+
+/** Closed union over {@link EXPIRATION_TARGET_KIND}. */
+export type ExpirationTargetKind =
+ (typeof EXPIRATION_TARGET_KIND)[keyof typeof EXPIRATION_TARGET_KIND];
+
+/**
+ * An id shape that could never name an artifact, so no filesystem path is
+ * formed from it. The regexes also close path traversal: no separator
+ * survives either of them.
+ */
+const SIGNAL_ID_RE = /^sig-\d{4}-\d{2}-\d{2}-[A-Za-z0-9][A-Za-z0-9._-]*$/;
+const PREFERENCE_ID_RE = /^(?:pref|ret)-[A-Za-z0-9][A-Za-z0-9._-]*$/;
+
+/** The caller named something this surface cannot address. */
+export class InvalidExpirationTargetError extends Error {
+ readonly id: string;
+ constructor(id: string) {
+ super(
+ `invalid expiration target ${JSON.stringify(id)} - expected sig-<date>-<slug>, ` +
+ "pref-<slug> or ret-<slug>",
+ );
+ this.name = "InvalidExpirationTargetError";
+ this.id = id;
+ }
+}
+
+/** The id is well-formed and no file carries it. Never a silent no-op. */
+export class ExpirationTargetNotFoundError extends Error {
+ readonly id: string;
+ readonly searched: ReadonlyArray<string>;
+ constructor(id: string, searched: ReadonlyArray<string>) {
+ super(`no signal or preference with id ${JSON.stringify(id)}; searched ${searched.join(", ")}`);
+ this.name = "ExpirationTargetNotFoundError";
+ this.id = id;
+ this.searched = Object.freeze([...searched]);
+ }
+}
+
+/**
+ * The value is not a date this project can compare against a clock.
+ *
+ * A typed wrapper around {@link normalizeExpirationDate}'s message rather
+ * than a second validator: the surfaces branch on the class, and the
+ * sentence a caller reads is still the chokepoint's own.
+ */
+export class ExpirationValueError extends Error {
+ readonly value: string;
+ constructor(value: string, reason: string) {
+ super(reason);
+ this.name = "ExpirationValueError";
+ this.value = value;
+ }
+}
+
+export interface SetExpirationResult {
+ readonly id: string;
+ readonly kind: ExpirationTargetKind;
+ /** Vault-relative path of the artifact that was rewritten. */
+ readonly path: string;
+ /** The normalised value now on the artifact; `null` once cleared. */
+ readonly expiration: string | null;
+ /** What the artifact carried before this call; `null` when it carried none. */
+ readonly previous: string | null;
+ /** False when the artifact already said exactly this - no bytes were written. */
+ readonly changed: boolean;
+}
+
+export interface SetExpirationOptions {
+ /** Agent stamped on the audit event; defaults to the surface's own name. */
+ readonly agent?: string;
+ /** Injected clock, so a run stays reproducible. */
+ readonly now?: Date;
+}
+
+/** Agent recorded when the caller names none. */
+const DEFAULT_AGENT = "set_expiration";
+
+/**
+ * Sentinel for a stored value the validator cannot parse. It is equal to
+ * nothing, so the rewrite that repairs a corrupted date always happens -
+ * a `null` there would collide with the clear-what-is-already-clear case
+ * and leave the junk on disk.
+ */
+const UNPARSEABLE_EXPIRATION = Symbol("unparseable-expiration");
+
+/**
+ * The stored value in the form the new one is compared against.
+ *
+ * Both sides have to come through {@link normalizeExpirationDate} for
+ * "already says exactly this" to be a statement about the LIFETIME rather
+ * than about the spelling: `2026-07-15` and `2026-07-15T00:00:00Z` are
+ * one date, and re-setting one over the other used to rewrite the file
+ * and append an audit event describing no change at all.
+ */
+function comparableExpiration(previous: string | null): string | null | symbol {
+ if (previous === null) return null;
+ try {
+ return normalizeExpirationDate(previous);
+ } catch {
+ return UNPARSEABLE_EXPIRATION;
+ }
+}
+
+/** Where an id of each shape can live, in search order. */
+function candidatePaths(vault: string, id: string): { kind: ExpirationTargetKind; dirs: string[] } {
+ const dirs = brainDirsForWrite(vault);
+ if (SIGNAL_ID_RE.test(id)) {
+ // A signal outlives the inbox: the dream pass moves consumed signals
+ // to `inbox/processed/` and `retireSignal` moves retired ones to
+ // `Brain/retired/`. All three are still readable memories, so all
+ // three can carry a lifetime.
+ return {
+ kind: EXPIRATION_TARGET_KIND.signal,
+ dirs: [dirs.inbox, dirs.processed, dirs.retired],
+ };
+ }
+ if (PREFERENCE_ID_RE.test(id)) {
+ return {
+ kind: EXPIRATION_TARGET_KIND.preference,
+ dirs: [dirs.preferences, dirs.retired],
+ };
+ }
+ throw new InvalidExpirationTargetError(id);
+}
+
+/**
+ * Set, change, or clear the `expiration_date` of one signal or
+ * preference, addressed by id.
+ *
+ * `expires` is a date-only `YYYY-MM-DD`, a full ISO-8601 timestamp, or
+ * {@link EXPIRATION_CLEAR}. Every other value is refused before any file
+ * is opened.
+ */
+export function setExpiration(
+ vault: string,
+ id: string,
+ expires: string,
+ opts: SetExpirationOptions = {},
+): SetExpirationResult {
+ // Vault-identity write guard (context-integrity-gates, Unit J).
+ assertVaultIdentityForWrite(vault);
+ const trimmed = id.trim();
+ const { kind, dirs } = candidatePaths(vault, trimmed);
+
+ // Validate BEFORE the walk, so a junk date cannot depend on whether the
+ // artifact happened to exist for whether it is reported as junk.
+ const clearing = expires.trim() === EXPIRATION_CLEAR;
+ let normalized: string | null = null;
+ if (!clearing) {
+ try {
+ normalized = normalizeExpirationDate(expires);
+ } catch (err) {
+ throw new ExpirationValueError(expires, (err as Error).message);
+ }
+ }
+
+ const searched: string[] = [];
+ let abs: string | null = null;
+ for (const dir of dirs) {
+ const candidate = ensureInsideVault(join(dir, `${trimmed}.md`), vault);
+ searched.push(
+ candidate
+ .slice(vault.length + 1)
+ .split("\\")
+ .join("/"),
+ );
+ if (existsSync(candidate)) {
+ abs = candidate;
+ break;
+ }
+ }
+ if (abs === null) throw new ExpirationTargetNotFoundError(trimmed, searched);
+ const relPath = abs
+ .slice(vault.length + 1)
+ .split("\\")
+ .join("/");
+
+ const [meta, body] = parseFrontmatter(abs);
+ const priorRaw = meta[EXPIRATION_DATE_FIELD];
+ const previous = typeof priorRaw === "string" && priorRaw.length > 0 ? priorRaw : null;
+ if (comparableExpiration(previous) === normalized) {
+ // Byte-identical no-op, including the clear-what-is-already-clear
+ // case. Reporting `changed: false` rather than rewriting keeps a
+ // re-run out of the audit log and off the disk.
+ return Object.freeze({
+ id: trimmed,
+ kind,
+ path: relPath,
+ expiration: normalized,
+ previous,
+ changed: false,
+ });
+ }
+
+ const nextMeta: FrontmatterMap = { ...meta };
+ if (normalized === null) delete nextMeta[EXPIRATION_DATE_FIELD];
+ else nextMeta[EXPIRATION_DATE_FIELD] = normalized;
+ writeFrontmatterAtomic(abs, nextMeta, body, { overwrite: true });
+
+ const at = isoSecond(opts.now ?? new Date());
+ appendLogEvent(vault, {
+ timestamp: at,
+ eventType: BRAIN_LOG_EVENT_KIND.expirationSet,
+ body: {
+ target: `[[${trimmed}]]`,
+ kind,
+ // Both sides of the change, because "cleared" and "set to X" are
+ // different events and the log is where an operator reconstructs
+ // which one happened.
+ expiration: normalized ?? EXPIRATION_CLEAR,
+ previous: previous ?? EXPIRATION_CLEAR,
+ agent: opts.agent?.trim() ? opts.agent.trim() : DEFAULT_AGENT,
+ },
+ });
+
+ return Object.freeze({
+ id: trimmed,
+ kind,
+ path: relPath,
+ expiration: normalized,
+ previous,
+ changed: true,
+ });
+}
diff --git a/src/core/brain/extract-signals.ts b/src/core/brain/extract-signals.ts
new file mode 100644
index 00000000..e4023ed7
--- /dev/null
+++ b/src/core/brain/extract-signals.ts
@@ -0,0 +1,471 @@
+/**
+ * Model-mined session signals (salience-lifecycle-enrichment, unit 2,
+ * t_1dace26d).
+ *
+ * `fact-extract.ts` mines a session turn with regexes, which is why it can
+ * run inside the live capture hook: it costs nothing and knows no language.
+ * The price is that it only ever recognises structure - a URL, an address,
+ * a unit-bound number - so every stated preference in a transcript is
+ * invisible to it. This module is the batch counterpart: it hands the
+ * calling agent the user turns of an ALREADY-IMPORTED session and asks for
+ * the taste signals in them. OSB still calls no model; it owns the turns it
+ * offers, the limits the answer must satisfy, and the write.
+ *
+ * Two phases, diarization-shaped:
+ *
+ * 1. {@link planExtractSignals} - read-only. Resolves the session's
+ * imported turns, keeps the USER ones (the import path's rule at
+ * `sessions/import.ts`: bare assistant output is never auto-extracted),
+ * and returns a report carrying exactly one needs-llm-step envelope.
+ * 2. {@link commitExtractedSignals} - validates the returned payload
+ * structurally ({@link EXTRACTED_SIGNALS_SHAPE}) and semantically (the
+ * per-session cap and the per-item confidence floor, registered on the
+ * semantic-check registry because neither is expressible in a
+ * descriptor), then routes the accepted items through the same helper
+ * chain the deterministic extractor uses.
+ *
+ * Everything written here is SPECULATIVE. The items land in `Brain/inbox/`
+ * as `source_type: auto_extract` signals - a member of its own so a
+ * model-authored signal is distinguishable from a regex-authored one
+ * forever - and the inbox trial lane plus the dream pass remains the only
+ * route to a confirmed preference. Nothing here writes a preference.
+ *
+ * Precision beats recall, as it does in `fact-extract.ts`: the cap and the
+ * floor are refusals, not filters. A payload over either limit is rejected
+ * whole and named, because an over-eager mine that silently kept its best
+ * twelve would teach the caller nothing about what it asked for.
+ */
+
+import { posix } from "node:path";
+
+import { buildCaptureBoundary, type SessionCaptureDecision } from "./capture-boundary.ts";
+import { buildDedupIndex, computeDedupHash, type DedupIndexEntry } from "./dedup-hash.ts";
+import { classifyDurability, resolveDurabilityDenylist } from "./gates/durability.ts";
+import { buildNeedsLlmStep, type NeedsLlmStep } from "./llm-step.ts";
+import { brainDirsForWrite } from "./paths.ts";
+import { resolveWriteApprovalEnabled } from "./pending.ts";
+import {
+ assertResponseCheck,
+ registerResponseCheck,
+ SEMANTIC_VIOLATION_CODES,
+ semanticViolation,
+ type SemanticViolation,
+} from "./response-checks.ts";
+import {
+ assertResponseShape,
+ EXTRACTED_SIGNALS_SHAPE,
+ EXTRACTED_SIGNALS_SURFACE,
+ SHAPE_ROOT_PATH,
+} from "./response-shape.ts";
+import { listSessionRawTurns } from "./session-recall.ts";
+import { writeSignal } from "./signal.ts";
+import { isoDate, isoSecond } from "./time.ts";
+import { BRAIN_SIGNAL_SOURCE_TYPE, type BrainSignalSign } from "./types.ts";
+
+/** Vault-relative directory an accepted auto-extracted signal lands in. */
+export const AUTO_EXTRACT_TARGET_DIR_REL = "Brain/inbox";
+
+/** The needs-llm-step step name for the deferred signal mining. */
+export const EXTRACT_SIGNALS_STEP = "extract-signals";
+
+/**
+ * Most signals one session may yield. A transcript that genuinely states
+ * more than this many durable preferences is a transcript worth reading by
+ * hand; past the cap the mine is guessing, and guesses at inbox scale cost
+ * more to retire than they ever pay back.
+ */
+export const AUTO_EXTRACT_PER_SESSION_CAP = 12;
+
+/**
+ * Lowest confidence an item may carry. The floor sits above a coin flip on
+ * purpose: an item the caller is not clearly sure of is exactly the item
+ * whose retirement will cost an operator a review.
+ */
+export const AUTO_EXTRACT_CONFIDENCE_FLOOR = 0.6;
+
+/** The role whose turns are mining material - the import path's rule. */
+const MINED_TURN_ROLE = "user";
+
+/** Per-turn text budget in the prompt, so one huge turn cannot crowd out the rest. */
+const PROMPT_TURN_TEXT_MAX = 2000;
+
+/** A signal extraction could not proceed, and the reason is in the message. */
+export class ExtractSignalsError extends Error {
+ constructor(message: string) {
+ super(message);
+ this.name = "ExtractSignalsError";
+ }
+}
+
+/**
+ * A write failed PART WAY through the accepted items.
+ *
+ * The commit writes one file per item, so a failure on the fourth leaves
+ * three signals on disk. The house precedent for that state is
+ * `ArchWriteError` (`architect/generate.ts`): a partial write reports how
+ * far it got rather than throwing a bare cause and leaving the caller to
+ * guess. This is that error for this lane - the ids already written are
+ * ON it, so an operator can find them, and re-running the same payload is
+ * safe because the dedup index recognises every one of them.
+ *
+ * Not an {@link ExtractSignalsError}: that class is the caller's fault
+ * and the surfaces report it as such. A filesystem that refused a write
+ * is not.
+ */
+export class ExtractSignalsWriteError extends Error {
+ /** The item whose write failed. */
+ readonly topic: string;
+ /** Signals whose bytes are already on disk, in write order. */
+ readonly written: ReadonlyArray<ExtractedSignalWrite>;
+ /** Payload items this call never reached, the failing one included. */
+ readonly remaining: number;
+
+ constructor(
+ topic: string,
+ written: ReadonlyArray<ExtractedSignalWrite>,
+ remaining: number,
+ cause: unknown,
+ ) {
+ super(
+ `failed to write extracted signal ${JSON.stringify(topic)}: ` +
+ `${cause instanceof Error ? cause.message : String(cause)} - ` +
+ `${written.length} signal(s) are already on disk ` +
+ `(${written.length === 0 ? "none" : written.map((w) => w.id).join(", ")}) and ` +
+ `${remaining} payload item(s) were not reached; fix the cause and re-run the ` +
+ "same payload, which dedups what is already there",
+ { cause },
+ );
+ this.name = "ExtractSignalsWriteError";
+ this.topic = topic;
+ this.written = Object.freeze([...written]);
+ this.remaining = remaining;
+ }
+}
+
+/** One user turn offered to the caller as mining material. */
+export interface MinedTurn {
+ readonly turnId: string;
+ readonly text: string;
+}
+
+/** Phase-one report: what will be mined, and the one envelope that mines it. */
+export interface SignalExtractionPlan {
+ readonly sessionId: string;
+ readonly generatedAt: string;
+ /** Capture-boundary verdict for the session; always `capture` here. */
+ readonly boundaryDecision: SessionCaptureDecision;
+ /** Imported turns of every role, before the user filter. */
+ readonly turnsScanned: number;
+ /** The user turns the prompt embeds, in record order. */
+ readonly turnsMined: ReadonlyArray<MinedTurn>;
+ /** The limits the payload will be held to, echoed so the caller can read them. */
+ readonly cap: number;
+ readonly confidenceFloor: number;
+ readonly llmStep: NeedsLlmStep;
+}
+
+/** One mined taste signal, as the calling agent returns it. */
+export interface ExtractedSignalItem {
+ readonly topic: string;
+ readonly signal: BrainSignalSign;
+ readonly principle: string;
+ readonly confidence: number;
+ readonly scope?: string;
+}
+
+/** One item the durability gate refused, named rather than dropped. */
+export interface ExtractedSignalRejection {
+ readonly topic: string;
+ readonly reason: string;
+}
+
+/** One item that reached disk, with the coordinates it landed at. */
+export interface ExtractedSignalWrite {
+ readonly id: string;
+ readonly path: string;
+ readonly topic: string;
+}
+
+export interface CommitExtractedSignalsResult {
+ readonly sessionId: string;
+ readonly written: ReadonlyArray<ExtractedSignalWrite>;
+ /**
+ * How many of {@link written} were STAGED into `Brain/pending/` rather
+ * than written straight to the inbox. Zero when write approval is off.
+ */
+ readonly staged: number;
+ readonly deduped: number;
+ /** Items the durability gate refused; each is named in {@link rejected}. */
+ readonly durabilityRejected: number;
+ readonly rejected: ReadonlyArray<ExtractedSignalRejection>;
+}
+
+export interface PlanExtractSignalsOptions {
+ readonly now: Date;
+}
+
+export interface CommitExtractedSignalsOptions {
+ readonly agent: string;
+ readonly now: Date;
+ /**
+ * Pre-compiled durability denylist. When omitted it is resolved from the
+ * plugin config, mirroring `routeExtractedFacts`; tests inject it so the
+ * gate is exercised without the default config path.
+ */
+ readonly durabilityDenylist?: ReadonlyArray<RegExp>;
+ /** Write-approval toggle; resolved from config when omitted. */
+ readonly writeApprovalEnabled?: boolean;
+ /** Shared dedup index; built from the vault when omitted. */
+ readonly dedup?: Map<string, DedupIndexEntry>;
+}
+
+// ----- Semantic rules the descriptor language cannot express ---------------
+
+/**
+ * Cap and floor, registered once at module scope. Both read across the
+ * payload rather than one value at a time - the cap counts the whole list,
+ * and the floor compares a number to a limit the descriptor cannot name -
+ * so they belong here rather than in {@link EXTRACTED_SIGNALS_SHAPE}.
+ *
+ * Registration is a module side effect on purpose: the registry is
+ * fail-closed, so a lane that forgot to register refuses its own writes
+ * instead of performing them unchecked.
+ */
+registerResponseCheck(EXTRACTED_SIGNALS_SURFACE, (payload) => {
+ const violations: SemanticViolation[] = [];
+ const items = readItems(payload);
+ if (items === null) return violations;
+ if (items.length > AUTO_EXTRACT_PER_SESSION_CAP) {
+ violations.push(
+ semanticViolation(
+ SEMANTIC_VIOLATION_CODES.threshold,
+ `${SHAPE_ROOT_PATH}.items`,
+ `at most ${AUTO_EXTRACT_PER_SESSION_CAP} signals may be mined from one session; got ${items.length}`,
+ ),
+ );
+ }
+ items.forEach((item, index) => {
+ const confidence = (item as { confidence?: unknown }).confidence;
+ if (typeof confidence !== "number") return;
+ if (confidence < AUTO_EXTRACT_CONFIDENCE_FLOOR) {
+ violations.push(
+ semanticViolation(
+ SEMANTIC_VIOLATION_CODES.threshold,
+ `${SHAPE_ROOT_PATH}.items[${index}].confidence`,
+ `confidence must be at least ${AUTO_EXTRACT_CONFIDENCE_FLOOR}; got ${confidence}`,
+ ),
+ );
+ }
+ });
+ return violations;
+});
+
+/**
+ * The item list, or null when the payload is not shaped like one. The
+ * shape layer has already refused that case by the time the check runs;
+ * returning null keeps the check pure and total rather than throwing from
+ * inside a validator whose contract says it never throws.
+ */
+function readItems(payload: unknown): ReadonlyArray<unknown> | null {
+ if (typeof payload !== "object" || payload === null) return null;
+ const items = (payload as { items?: unknown }).items;
+ return Array.isArray(items) ? items : null;
+}
+
+// ----- Phase one: what to mine ---------------------------------------------
+
+/**
+ * Assemble the mining plan for one imported session. Read-only; writes
+ * nothing and calls no model.
+ *
+ * Three conditions are refusals rather than empty reports, because each
+ * one means the caller asked for something this vault cannot answer:
+ * a session the capture boundary ignores, a session with no imported turns
+ * at all, and a session whose turns are all non-user. Reporting any of them
+ * as "mined nothing" would read as a clean run over a barren transcript.
+ */
+export function planExtractSignals(
+ vault: string,
+ sessionId: string,
+ opts: PlanExtractSignalsOptions,
+): SignalExtractionPlan {
+ const trimmed = sessionId.trim();
+ if (trimmed.length === 0) {
+ throw new ExtractSignalsError("extract-signals needs a session reference");
+ }
+ const boundary = buildCaptureBoundary(vault);
+ const boundaryDecision = boundary.sessionDecision(trimmed);
+ if (boundaryDecision !== "capture") {
+ throw new ExtractSignalsError(
+ `session ${trimmed} is classified '${boundaryDecision}' by the capture boundary; it may not produce signals`,
+ );
+ }
+ const turns = listSessionRawTurns(vault, trimmed);
+ if (turns.length === 0) {
+ throw new ExtractSignalsError(
+ `session ${trimmed} has no imported turns; import it first with 'o2b brain import-session --recall'`,
+ );
+ }
+ const mined: MinedTurn[] = [];
+ for (const turn of turns) {
+ if (turn.role !== MINED_TURN_ROLE) continue;
+ // Message-level boundary, mirroring the import path: suppressed text
+ // never reaches extraction, so it never reaches the prompt either.
+ if (boundary.suppressMessage(turn.text)) continue;
+ const text = turn.text.trim();
+ if (text.length === 0) continue;
+ mined.push(Object.freeze({ turnId: turn.turn_id, text }));
+ }
+ if (mined.length === 0) {
+ throw new ExtractSignalsError(
+ `session ${trimmed} has ${turns.length} imported turn(s) but none authored by the user; there is nothing to mine`,
+ );
+ }
+ return Object.freeze({
+ sessionId: trimmed,
+ generatedAt: opts.now.toISOString(),
+ boundaryDecision,
+ turnsScanned: turns.length,
+ turnsMined: Object.freeze(mined),
+ cap: AUTO_EXTRACT_PER_SESSION_CAP,
+ confidenceFloor: AUTO_EXTRACT_CONFIDENCE_FLOOR,
+ llmStep: buildMiningStep(trimmed, mined),
+ });
+}
+
+/**
+ * The one envelope. The turns ride inside the prompt rather than beside it
+ * because the receiving agent is answering a question about exactly these
+ * turns and nothing else; a prompt that named a session id would invite the
+ * caller to go and read more of it.
+ */
+function buildMiningStep(sessionId: string, mined: ReadonlyArray<MinedTurn>): NeedsLlmStep {
+ const transcript = mined
+ .map((turn) => `[${turn.turnId}] ${turn.text.slice(0, PROMPT_TURN_TEXT_MAX)}`)
+ .join("\n");
+ return buildNeedsLlmStep({
+ step: EXTRACT_SIGNALS_STEP,
+ prompt:
+ `Mine durable taste signals from the ${mined.length} user turn(s) of session ${sessionId} below. ` +
+ "A taste signal is a rule the operator stated about how work should be done - a preference, a " +
+ "correction, a prohibition - not a fact, a task, or a one-off instruction about this session. " +
+ `Return at most ${AUTO_EXTRACT_PER_SESSION_CAP} items, each with a confidence of at least ` +
+ `${AUTO_EXTRACT_CONFIDENCE_FLOOR}; omit anything you are less sure of rather than lowering the ` +
+ "number, because an item below the floor refuses the whole payload.\n\n" +
+ transcript,
+ schema_hints: [
+ 'payload: { "items": [ { "topic", "signal", "principle", "confidence", "scope"? } ] }',
+ "topic: stable kebab-slug naming the rule",
+ "signal: 'positive' when the principle is the rule to follow, 'negative' when it is what to avoid",
+ "principle: one imperative line, in the language the operator used",
+ `confidence: number in [${AUTO_EXTRACT_CONFIDENCE_FLOOR}, 1]`,
+ `items: at most ${AUTO_EXTRACT_PER_SESSION_CAP} entries`,
+ ],
+ target_path: posix.normalize(AUTO_EXTRACT_TARGET_DIR_REL),
+ });
+}
+
+// ----- Phase two: what the caller mined ------------------------------------
+
+/**
+ * Validate the returned payload and write the accepted items.
+ *
+ * Order is the deterministic extractor's, kept deliberately identical so
+ * the two lanes cannot diverge on what reaches the inbox: capture boundary,
+ * then per item dedup, then the durability gate, then staging, then the
+ * write. A deduped item never reaches the durability gate, and a
+ * durability-rejected item is counted and NAMED in
+ * {@link CommitExtractedSignalsResult.rejected} - never a silent drop.
+ */
+export function commitExtractedSignals(
+ vault: string,
+ sessionId: string,
+ payload: unknown,
+ opts: CommitExtractedSignalsOptions,
+): CommitExtractedSignalsResult {
+ const trimmed = sessionId.trim();
+ if (trimmed.length === 0) {
+ throw new ExtractSignalsError("extract-signals needs a session reference");
+ }
+ const boundaryDecision = buildCaptureBoundary(vault).sessionDecision(trimmed);
+ if (boundaryDecision !== "capture") {
+ throw new ExtractSignalsError(
+ `session ${trimmed} is classified '${boundaryDecision}' by the capture boundary; it may not produce signals`,
+ );
+ }
+ // Structure first, then the cross-item rules. Nothing is written until
+ // both gates pass, so a payload with one bad item lands nothing.
+ assertResponseShape(EXTRACTED_SIGNALS_SURFACE, EXTRACTED_SIGNALS_SHAPE, payload);
+ assertResponseCheck(EXTRACTED_SIGNALS_SURFACE, payload);
+
+ const items = (payload as { items: ReadonlyArray<ExtractedSignalItem> }).items;
+ const dedup = opts.dedup ?? buildDedupIndex(vault);
+ const denylist = opts.durabilityDenylist ?? resolveDurabilityDenylist();
+ const writeApprovalEnabled = opts.writeApprovalEnabled ?? resolveWriteApprovalEnabled();
+ const targetDir = writeApprovalEnabled ? brainDirsForWrite(vault).pending : undefined;
+
+ const written: ExtractedSignalWrite[] = [];
+ const rejected: ExtractedSignalRejection[] = [];
+ let deduped = 0;
+
+ for (const [index, item] of items.entries()) {
+ const scope = item.scope?.trim();
+ const hash = computeDedupHash({
+ topic: item.topic,
+ signal: item.signal,
+ principle: item.principle,
+ ...(scope ? { scope } : {}),
+ });
+ if (dedup.has(hash)) {
+ deduped++;
+ continue;
+ }
+ const verdict = classifyDurability(item.principle, { denylist });
+ if (!verdict.durable) {
+ rejected.push(Object.freeze({ topic: item.topic, reason: verdict.reason! }));
+ continue;
+ }
+ // Per-item writes, so a failure here is a PARTIAL write: everything
+ // before this item is on disk and stays there. It is reported as such
+ // rather than propagating a bare cause with no accounting - the same
+ // choice `ArchWriteError` makes for the architect tree.
+ let res;
+ try {
+ res = writeSignal(
+ vault,
+ {
+ topic: item.topic,
+ signal: item.signal,
+ agent: opts.agent,
+ principle: item.principle,
+ created_at: isoSecond(opts.now),
+ date: isoDate(opts.now),
+ slug: item.topic,
+ ...(scope ? { scope } : {}),
+ source: [`[[${trimmed}]]`],
+ source_type: BRAIN_SIGNAL_SOURCE_TYPE.autoExtract,
+ dedup_hash: hash,
+ session_ref: trimmed,
+ // The confidence the caller claimed rides onto the file: it is the
+ // one thing separating two auto-extracted signals whose text reads
+ // equally plausible, and the dream pass has no other way to see it.
+ raw: `confidence: ${item.confidence}`,
+ },
+ targetDir !== undefined ? { targetDir } : {},
+ );
+ } catch (err) {
+ throw new ExtractSignalsWriteError(item.topic, written, items.length - index, err);
+ }
+ dedup.set(hash, { id: res.id, path: res.path });
+ written.push(Object.freeze({ id: res.id, path: res.path, topic: item.topic }));
+ }
+
+ return Object.freeze({
+ sessionId: trimmed,
+ written: Object.freeze(written),
+ staged: writeApprovalEnabled ? written.length : 0,
+ deduped,
+ durabilityRejected: rejected.length,
+ rejected: Object.freeze(rejected),
+ });
+}
diff --git a/src/core/brain/fact-extract.ts b/src/core/brain/fact-extract.ts
index 8d263ced..fab2dcfe 100644
--- a/src/core/brain/fact-extract.ts
+++ b/src/core/brain/fact-extract.ts
@@ -138,8 +138,9 @@ function collapse(span: string): string {
}
/**
- * Extract every fact the seven families recognise, in (line, family
- * table) order. Deterministic: same input, same output.
+ * Extract every fact the {@link FAMILY_PATTERNS} families recognise -
+ * url, email, quantity - in (line, family table) order. Deterministic:
+ * same input, same output.
*/
export function extractFacts(text: string): ExtractedFact[] {
if (!text || text.trim().length === 0) return [];
diff --git a/src/core/brain/llm-step.ts b/src/core/brain/llm-step.ts
new file mode 100644
index 00000000..f98043dc
--- /dev/null
+++ b/src/core/brain/llm-step.ts
@@ -0,0 +1,110 @@
+/**
+ * The needs-llm-step envelope spine (salience-lifecycle-enrichment, unit 0).
+ *
+ * OSB never calls an LLM. Every lane that needs generated text hands the
+ * calling agent one envelope describing exactly what to write and where it
+ * lands, and OSB owns the sequencing, the validation, and the commit. Three
+ * lanes already spoke that grammar with three independent declarations of
+ * it - the durable write-session envelope, the diarization profile step,
+ * the rollup ladder envelope - and a fourth divergence was one new lane
+ * away. This module is the one declaration they share.
+ *
+ * The spine carries ONLY what all three carry: `status`, `step`, `prompt`,
+ * `schema_hints`, `target_path`. A field two of them happen to share is not
+ * spine - `tier`, `session_id`, `expires_at` and the rest stay on the
+ * consumer's own type, which extends this one. Generalizing further would
+ * make the spine a union of everybody's needs rather than the contract the
+ * receiving agent can rely on.
+ *
+ * Adoption is additive and type-level. `WriteSessionEnvelope` is the
+ * DURABLE superset: it is the only one of the three backed by a session
+ * record, and its `status` widens to the whole session-status union, so it
+ * shares {@link LlmStepFields} rather than {@link NeedsLlmStep}. It is not
+ * rewritten - the session kernel's behavior is untouched by this module.
+ */
+
+/** The one status literal this grammar is named for. */
+export const NEEDS_LLM_STEP = "needs-llm-step";
+
+/**
+ * What the receiving agent needs in order to generate: which step it is
+ * answering, the instruction, the constraints the artifact must satisfy,
+ * and the vault-relative path the result is destined for.
+ */
+export interface LlmStepFields {
+ /** Step name the caller is answering, e.g. `profile-prose`, `rollup:fact`. */
+ readonly step: string;
+ /** Generation instruction for this step. */
+ readonly prompt: string;
+ /** Constraints on the artifact; empty when the step has none to declare. */
+ readonly schema_hints: ReadonlyArray<string>;
+ /** Vault-relative path the generated artifact is destined for. */
+ readonly target_path: string;
+}
+
+/** One deferred generation step, awaiting the calling agent's text. */
+export interface NeedsLlmStep extends LlmStepFields {
+ readonly status: typeof NEEDS_LLM_STEP;
+}
+
+/**
+ * The spine's key set, in the order {@link buildNeedsLlmStep} emits it.
+ * Exported so a consumer can assert over the whole envelope at once rather
+ * than field by field.
+ */
+export const NEEDS_LLM_STEP_KEYS: ReadonlyArray<keyof NeedsLlmStep> = Object.freeze([
+ "status",
+ "step",
+ "prompt",
+ "schema_hints",
+ "target_path",
+] as const);
+
+/** An envelope was built with a field that tells the caller nothing. */
+export class LlmStepError extends Error {
+ constructor(message: string) {
+ super(message);
+ this.name = "LlmStepError";
+ }
+}
+
+/**
+ * Build one envelope. The status literal is stamped here, never by the
+ * caller, and the hint list is copied so the envelope cannot change under a
+ * reference the caller kept. Extra fields a lane declares on its own type
+ * (the rollup's `tier` and `produces`) pass through and keep the position
+ * they were written in - these envelopes are serialized across the CLI and
+ * MCP boundaries, so their key order is observable.
+ *
+ * A blank `step`, `prompt`, or `target_path` throws {@link LlmStepError}:
+ * an envelope missing any of the three cannot be answered, and it is worth
+ * more to the caller as a refusal at the construction site than as an
+ * unanswerable request downstream. An empty `schema_hints` is legal - a
+ * step can genuinely have no constraint to declare.
+ */
+export function buildNeedsLlmStep<T extends LlmStepFields>(fields: T): NeedsLlmStep & T {
+ requireContent("step", fields.step);
+ requireContent("prompt", fields.prompt);
+ requireContent("target_path", fields.target_path);
+ // A spread would not honour the sentence above: `LlmStepFields` declares
+ // no `status`, so the type system never sees one coming, and a runtime
+ // key of that name would land AFTER the literal and replace it. It is
+ // dropped rather than re-positioned last, because the serialized key
+ // order is part of this contract (see NEEDS_LLM_STEP_KEYS).
+ const envelope: Record<string, unknown> = { status: NEEDS_LLM_STEP };
+ for (const [key, value] of Object.entries(fields)) {
+ if (key === "status") continue;
+ envelope[key] = value;
+ }
+ envelope["schema_hints"] = Object.freeze([...fields.schema_hints]);
+ // The loop above copies every field of `T` and the line before it
+ // stamps the status, so the result satisfies `NeedsLlmStep & T` - a
+ // fact the compiler cannot derive from a keyed record.
+ return Object.freeze(envelope) as unknown as NeedsLlmStep & T;
+}
+
+function requireContent(field: keyof LlmStepFields, value: string): void {
+ if (value.trim().length === 0) {
+ throw new LlmStepError(`needs-llm-step envelope: ${field} must be a non-empty string`);
+ }
+}
diff --git a/src/core/brain/notes/lifecycle.ts b/src/core/brain/notes/lifecycle.ts
index 68bfb4fa..9afe6332 100644
--- a/src/core/brain/notes/lifecycle.ts
+++ b/src/core/brain/notes/lifecycle.ts
@@ -49,7 +49,10 @@
* command that makes it agree with the vault again.
* - a delete rewrites NOTHING and reports the inbound references it is
* about to strand, because a delete that silently repaired its own
- * inbound links would be erasing the evidence that it happened.
+ * inbound links would be erasing the evidence that it happened. This
+ * holds under `--delete-linked` too, and the flag is narrower than
+ * its name suggests for exactly that reason - see "What
+ * --delete-linked may remove" below.
* - a rewrite that could not be written is NAMED. The operation is not
* rolled back, and the result says where it split - see
* {@link noteLifecycle} for why one half-state is preferable to the
@@ -77,6 +80,40 @@
* note by path holds an ordinary reference, and it dangles exactly like a
* user note's would.
*
+ * ## What `--delete-linked` may remove, and what it may not
+ *
+ * The commitment above - a delete repairs nothing and reports what it
+ * strands - is not weakened by the cascade, because the cascade never
+ * REPAIRS anything either. It removes a second class of file: the
+ * single-purpose derived artifact whose entire content is a restatement
+ * of the note, and which therefore has no meaning once the note is gone.
+ * The rule deciding membership is not this module's; it is
+ * `source-cleanup.ts`'s, called through {@link traceNoteDerivations}, so
+ * "derived solely from" means one thing in this project rather than two.
+ *
+ * Membership additionally requires DECLARED provenance, and only on this
+ * path: the page's own frontmatter has to name the note as what it was
+ * derived from. See {@link planCascade} for why the shared rule is not
+ * sufficient here.
+ *
+ * Four consequences follow and each is on the response:
+ *
+ * - a page that only MENTIONS the note - a `[[Note]]` in prose, with no
+ * `source:` array naming it - is reported and left alone, however
+ * derived-looking the page's directory is;
+ * - a page citing a SECOND source - a signal naming another note, a
+ * preference folded from a foreign signal - is reported and left
+ * alone, exactly as it is by `deleteBySource`;
+ * - everything the inbound probe found that is not in the deletion set
+ * is reported and left alone, including every user note. The two
+ * lists are disjoint and both are returned, so a caller never has to
+ * subtract one from the other to find out what survives;
+ * - the fold walks {@link DERIVED_SET_SCOPE} and the response says so.
+ * A user note is outside it by construction and no scan widening
+ * would change that - nothing outside `Brain/` is a derivation this
+ * project generated - but an empty derived set must be legible as a
+ * measurement rather than as an unstated scope limit.
+ *
* ## Where an archived note goes, and why
*
* `NOTE_ARCHIVE_ROOT` - a top-level `Archive/` directory mirroring the
@@ -110,11 +147,13 @@ import {
unlinkSync,
type Stats,
} from "node:fs";
-import { dirname, posix } from "node:path";
+import { dirname, join, posix } from "node:path";
import { isFileAlreadyExists } from "../../fs-atomic.ts";
+import { ensureInsideVault } from "../../path-safety.ts";
import { pathCovers } from "../../vault-scope/defaults.ts";
import { assertExpectedCount } from "../count-guard.ts";
+import { DERIVATION_SCAN_SCOPE, traceNoteDerivations } from "../source-cleanup.ts";
import { BRAIN_LOG_REL, BRAIN_ROOT_REL } from "../path-constants.ts";
import { requireNextStep } from "../next-step.ts";
import { SEARCH_INDEX_MISSING_CODE } from "../diagnostics.ts";
@@ -297,6 +336,48 @@ export interface NoteReferenceReport {
readonly index: IndexEvidence;
}
+/**
+ * The subtree {@link NoteLifecycleInput.deleteLinked}'s fold walks.
+ *
+ * Re-exported from the module that owns the fold rather than spelled
+ * again here: the response promises a caller which scope was scanned, and
+ * a second copy of that string is a promise that can go stale.
+ */
+export const DERIVED_SET_SCOPE = DERIVATION_SCAN_SCOPE;
+
+/**
+ * What a `--delete-linked` run found, split into the two lists that
+ * matter: what it will remove, and what it will leave standing.
+ *
+ * Both are returned on the dry run and on the confirmed run, and they are
+ * disjoint. A caller reading only one of them still gets a complete
+ * answer to the question it asked; a caller reading both never has to
+ * compute the difference itself, which is where a report and a deletion
+ * come to disagree.
+ */
+export interface NoteDeleteCascade {
+ /**
+ * Exactly what a confirmed run removes: the note first, then the
+ * solely-derived files, sorted. This is also the list the count guard
+ * asserts over, so `--expect` counts the same things the response
+ * printed.
+ */
+ readonly deletionSet: ReadonlyArray<string>;
+ /**
+ * Everything else that references the note: inbound wikilinks from
+ * anywhere in the vault, plus the Brain pages the fold classified as
+ * shared rather than derived. Reported, never deleted, never rewritten.
+ */
+ readonly reportedFiles: ReadonlyArray<string>;
+ /**
+ * The subtree the derived-set fold walked, always
+ * {@link DERIVED_SET_SCOPE}. On the response because an empty
+ * `deletionSet` tail has two readings and only one of them is a
+ * measurement.
+ */
+ readonly scannedScope: string;
+}
+
/** Machine-readable reason a {@link noteLifecycle} call was refused. */
export type NoteLifecycleErrorCode =
/** The source note does not exist. */
@@ -313,7 +394,9 @@ export type NoteLifecycleErrorCode =
/** A delete reached the mutating path without an explicit confirmation. */
| "not_confirmed"
/** The subject already sits under the archive root. */
- | "already_archived";
+ | "already_archived"
+ /** `deleteLinked` was passed to an action that removes nothing. */
+ | "cascade_forbidden";
export class NoteLifecycleError extends Error {
readonly code: NoteLifecycleErrorCode;
@@ -334,6 +417,12 @@ export interface NoteLifecycleInput {
readonly apply?: boolean;
/** Required by `delete` before it will remove anything. */
readonly confirm?: boolean;
+ /**
+ * `--delete-linked`: extend a `delete` to the single-purpose derived
+ * files that trace SOLELY to this note. Refused on every other action.
+ * Absent (the default) leaves the delete byte-identical to before.
+ */
+ readonly deleteLinked?: boolean;
/** `--expect N`: assert the inbound-reference count before any write. */
readonly expect?: number | null;
/** `--strict`: refuse a mutation carrying no `--expect` guard. */
@@ -356,6 +445,14 @@ export interface NoteLifecycleResult {
readonly snapshot: { readonly runId: string; readonly path: string } | null;
/** What happened to inbound references, and on what evidence. */
readonly references: NoteReferenceReport;
+ /**
+ * What `--delete-linked` computed, or `null` when the flag was absent.
+ *
+ * `null` and an empty {@link NoteDeleteCascade.deletionSet} are
+ * different answers: the first says no cascade was asked for, the
+ * second says one was and it found nothing beyond the note.
+ */
+ readonly cascade: NoteDeleteCascade | null;
}
/**
@@ -772,6 +869,16 @@ export async function noteLifecycle(
`destination already exists: ${destination.relPath}`,
);
}
+ const deleteLinked = input.deleteLinked === true;
+ if (deleteLinked && action !== NOTE_LIFECYCLE_ACTION.delete) {
+ // Refused rather than ignored. A relocation has no deletion set to
+ // extend, so honouring the flag silently would tell a caller that
+ // asked for a cascade that it got one.
+ throw new NoteLifecycleError(
+ "cascade_forbidden",
+ `delete-linked extends a delete's blast radius; ${action} removes nothing`,
+ );
+ }
if (action === NOTE_LIFECYCLE_ACTION.delete && input.confirm !== true && apply) {
throw new NoteLifecycleError(
"not_confirmed",
@@ -797,12 +904,23 @@ export async function noteLifecycle(
? probe.matched.filter((rel) => rel !== source.relPath)
: probe.matched;
+ const cascade = deleteLinked ? planCascade(vault, source.relPath, inboundFiles) : null;
+
+ // The guard asserts what the operation will REMOVE. Without a cascade
+ // that is one file and the number worth guarding is the collateral -
+ // how many inbound references the delete will strand - which is what
+ // `--expect` has meant here since it shipped. With a cascade the set
+ // itself is variable, so the guard moves onto it: `--expect` counts the
+ // paths the response just listed as the deletion set, and a stale plan
+ // aborts before the first unlink instead of removing a file the
+ // operator never saw.
+ const guarded = cascade === null ? inboundFiles : cascade.deletionSet;
assertExpectedCount({
- matched: inboundFiles.length,
+ matched: guarded.length,
expect: input.expect ?? null,
strict: input.strict === true,
willMutate: apply,
- matchList: inboundFiles,
+ matchList: guarded,
});
const basename =
@@ -827,14 +945,36 @@ export async function noteLifecycle(
// point: the previous shape of this problem returned a snapshot
// path with nothing beside it, which every caller reads as "this is
// reversible".
+ //
+ // ONE gate over the WHOLE set, not one per file: the set is a
+ // single decision the operator authorised and a per-file recovery
+ // point would leave them choosing which of five archives to roll
+ // back to. The derived half lives under `Brain/` and IS in the
+ // archive, so a cascade's verdict is `partial` where a bare
+ // delete's is `unproven` - the note is still uncovered, and the
+ // blockers say so.
+ const derivedFiles = cascade === null ? [] : cascade.deletionSet.slice(1);
const gated = withDestructiveSnapshot(
vault,
BRAIN_SNAPSHOT_REASON.noteDelete,
() => {
+ // The note goes FIRST, and the order is the choice between two
+ // half-states. A derived file whose note is already gone is a
+ // dangling derivation - the exact state every delete before
+ // this flag left behind, and one the operator can re-run into.
+ // The reverse - derivations removed while the note they restate
+ // survives - destroys the only copies of material nothing will
+ // regenerate.
unlinkSync(source.abs);
+ for (const rel of derivedFiles) {
+ unlinkSync(ensureInsideVault(join(vault, rel), vault));
+ }
},
{
- blastRadius: { outsideBrainRoot: true },
+ blastRadius: {
+ outsideBrainRoot: true,
+ ...(derivedFiles.length > 0 ? { brainTopLevel: true } : {}),
+ },
...(input.now !== undefined ? { now: input.now } : {}),
},
);
@@ -853,6 +993,7 @@ export async function noteLifecycle(
[],
basename,
await readIndexEvidence(vault, true),
+ cascade,
);
}
relocateBytes(source, destination!, sameEntry);
@@ -918,9 +1059,64 @@ export async function noteLifecycle(
rewriteFailures,
basename,
await readIndexEvidence(vault, apply),
+ cascade,
);
}
+/**
+ * Split everything that references the note into the two lists
+ * {@link NoteDeleteCascade} promises.
+ *
+ * The classification is `source-cleanup.ts`'s: {@link traceNoteDerivations}
+ * runs it - a single-purpose derived page in a derivation directory,
+ * citing no second source, folded from no foreign signal - and this
+ * function sorts the verdict into the two lists and unions the mentions
+ * with the vault-wide inbound probe.
+ *
+ * One condition is added on top of it, and only on this path. That rule
+ * was written for an IMPORTED source, where "cites no second source" is
+ * decisive because the pages in range are ones the import generated. A
+ * note is different: any Brain page may write `[[Note]]` in prose, and
+ * such a page carries no `source:` array to contradict - so the
+ * solely-derived test passes vacuously and somebody's paragraph enters a
+ * deletion set. The cascade therefore requires explicit structured
+ * provenance (`structuredProvenance`) as well: a page is deletable only
+ * when its frontmatter NAMES the note as what it was derived from. A
+ * prose mention is always reported and never deleted. `deleteBySource`
+ * is untouched - its subject brings index artifacts of its own and its
+ * rule is long-settled.
+ *
+ * Two populations meet here and the union is the point. The probe reads
+ * `[[...]]` spellings anywhere in the vault, which is where user notes
+ * live; the fold reads Brain frontmatter provenance, which the probe
+ * cannot see because `source_path: Imports/Note.md` is not a wikilink.
+ * Reporting only one of them would silently drop the other's findings.
+ */
+function planCascade(
+ vault: string,
+ sourceRel: string,
+ inboundFiles: ReadonlyArray<string>,
+): NoteDeleteCascade {
+ const traced = traceNoteDerivations(vault, sourceRel);
+ const derived = traced
+ .filter((entry) => entry.deletable && entry.structuredProvenance)
+ .map((entry) => entry.path)
+ // The note itself is never a Brain page, but a fold that ever
+ // returned it would otherwise put it in the set twice.
+ .filter((rel) => rel !== sourceRel)
+ .toSorted();
+ const deletionSet = Object.freeze([sourceRel, ...derived]);
+ const deleting = new Set(deletionSet);
+ const reported = new Set<string>();
+ for (const rel of inboundFiles) if (!deleting.has(rel)) reported.add(rel);
+ for (const entry of traced) if (!deleting.has(entry.path)) reported.add(entry.path);
+ return Object.freeze({
+ deletionSet,
+ reportedFiles: Object.freeze([...reported].toSorted()),
+ scannedScope: DERIVED_SET_SCOPE,
+ });
+}
+
/**
* The spellings this relocation will actually rewrite. The bare basename
* is included only when {@link decideBasename} cleared it, so the
@@ -957,6 +1153,7 @@ function finish(
rewriteFailures: ReadonlyArray<{ readonly path: string; readonly reason: string }>,
basename: BasenameRewrite,
index: IndexEvidence,
+ cascade: NoteDeleteCascade | null,
): NoteLifecycleResult {
return Object.freeze({
action,
@@ -965,6 +1162,7 @@ function finish(
applied,
recoverability,
snapshot,
+ cascade,
references: Object.freeze({
filesScanned,
inboundFiles: Object.freeze([...inboundFiles]),
diff --git a/src/core/brain/policy/blocks/lifecycle.ts b/src/core/brain/policy/blocks/lifecycle.ts
index eda069b2..ef28e17b 100644
--- a/src/core/brain/policy/blocks/lifecycle.ts
+++ b/src/core/brain/policy/blocks/lifecycle.ts
@@ -31,6 +31,9 @@ import { DEFAULT_BRAIN_CONFIG } from "../defaults.ts";
*/
const RETIRE_OPTIONAL_KEYS = ["confirmed_evidence_min_threshold"] as const;
+/** Optional `dream:` sub-key with no default, for the same reason. */
+const DREAM_OPTIONAL_KEYS = ["salience_threshold"] as const;
+
/**
* Merge one lifecycle block onto its slice of {@link DEFAULT_BRAIN_CONFIG}.
* The cast is the one `mergeBlock` already documents: the merged values
@@ -54,7 +57,7 @@ function merge(
}
export function parseDreamBlock(ctx: BlockParseContext): BrainDreamConfig {
- const dream = merge(ctx, "dream", DEFAULT_BRAIN_CONFIG.dream);
+ const dream = merge(ctx, "dream", DEFAULT_BRAIN_CONFIG.dream, DREAM_OPTIONAL_KEYS);
requirePositiveInteger("dream.candidate_threshold", dream.candidate_threshold, ctx.source);
requirePositiveInteger(
"dream.unconfirmed_window_days",
@@ -66,6 +69,12 @@ export function parseDreamBlock(ctx: BlockParseContext): BrainDreamConfig {
dream.contradiction_window_days,
ctx.source,
);
+ // Optional salience gate over the rollup fold set (unit 1). Out of
+ // range is a hard error rather than a silently ignored knob - the same
+ // rule the destructive-from-confirmed gate below follows.
+ if (dream.salience_threshold !== undefined) {
+ requireUnitInterval("dream.salience_threshold", dream.salience_threshold, ctx.source);
+ }
return {
candidate_threshold: dream.candidate_threshold as number,
unconfirmed_window_days: dream.unconfirmed_window_days as number,
@@ -74,6 +83,13 @@ export function parseDreamBlock(ctx: BlockParseContext): BrainDreamConfig {
// or non-boolean coerces to false so the default install stays
// byte-identical (the heal phase becomes a checkpoint-only no-op).
heal_enrich_enabled: dream.heal_enrich_enabled === true,
+ // Absent stays absent: `undefined` is the documented open-gate
+ // state `salience-gate.ts` branches on, so spreading the key in
+ // unconditionally would change `dream` from omitting it to carrying
+ // an explicit undefined.
+ ...(dream.salience_threshold !== undefined
+ ? { salience_threshold: dream.salience_threshold as number }
+ : {}),
};
}
diff --git a/src/core/brain/preference.ts b/src/core/brain/preference.ts
index c75b86f7..847fe8b8 100644
--- a/src/core/brain/preference.ts
+++ b/src/core/brain/preference.ts
@@ -81,7 +81,7 @@ import { readCommitmentTier, validateCommitmentTier } from "./commitment.ts";
import type { PageLifecycle } from "./page-meta/lifecycle.ts";
import type { PageTier } from "./page-meta/tier.ts";
import { computeContentHash } from "./content-hash.ts";
-import { normalizeExpirationDate } from "./expiration.ts";
+import { EXPIRATION_DATE_FIELD, normalizeExpirationDate } from "./expiration.ts";
import {
computePayloadHash,
IdempotencyPayloadMismatchError,
@@ -773,7 +773,7 @@ function preferenceFrontmatter(input: WritePreferenceInput, id: string): Frontma
// supplied so legacy callers stay byte-identical. Reader-side support
// is via parsePreference's optional-scalar read + the expiration filter.
if (input.expiration_date?.trim()) {
- metadata["expiration_date"] = normalizeExpirationDate(input.expiration_date);
+ metadata[EXPIRATION_DATE_FIELD] = normalizeExpirationDate(input.expiration_date);
}
// Freshness trend (t_ee09a6ce): stamped by the dream refresh pass;
// emitted only when supplied so legacy callers stay byte-identical.
diff --git a/src/core/brain/response-checks.ts b/src/core/brain/response-checks.ts
new file mode 100644
index 00000000..e1a68fe1
--- /dev/null
+++ b/src/core/brain/response-checks.ts
@@ -0,0 +1,178 @@
+/**
+ * Semantic checks for model-authored payloads
+ * (salience-lifecycle-enrichment, unit 0).
+ *
+ * `response-shape.ts` validates one value at a time against a descriptor
+ * that is deliberately shallow, because over-constraining an extraction
+ * payload degrades recall. That flatness has a cost: a constraint reading
+ * more than one value at once - "exactly one alternative is recommended",
+ * "every finding cites a consulted source", "at most N items per session" -
+ * is not expressible there, and deepening the descriptor language to fit it
+ * would trade the property the shape layer exists to keep.
+ *
+ * Those constraints live here instead, beside it rather than inside it,
+ * following the precedent the research report already set: its citation
+ * contract is a set-membership check written next to its descriptor
+ * (see `research/research.ts`), not a descriptor key. This module is that
+ * pattern given a registry, so every lane in the wave writes its cross-item
+ * rule the same way and every refusal reaches the caller named.
+ *
+ * Two properties are load-bearing:
+ *
+ * - The gate is FAIL-CLOSED. Asserting a surface nobody registered throws.
+ * A registry that answered "no check, therefore fine" would turn a
+ * forgotten registration into a silently unvalidated write path, which
+ * is the failure this layer exists to prevent.
+ * - Every violation is NAMED from a frozen vocabulary. A check returning a
+ * code outside it is itself refused, so no caller ever has to parse
+ * prose to learn what went wrong.
+ *
+ * The path vocabulary is the shape layer's, so a caller rendering both kinds
+ * of violation is reading one language.
+ */
+
+import { SHAPE_ROOT_PATH } from "./response-shape.ts";
+
+/**
+ * Stable codes a semantic violation is classified under. The set is closed
+ * on purpose: a check names the KIND of rule it broke here and the specifics
+ * in the message, so callers route on the code.
+ */
+export const SEMANTIC_VIOLATION_CODES = Object.freeze({
+ /** Wrong number of items satisfying a rule (exactly one, at least one, ...). */
+ cardinality: "semantic_cardinality",
+ /** An item contradicts another item of the same payload. */
+ crossItem: "semantic_cross_item",
+ /** A value a payload references is absent from the set it must come from. */
+ setMembership: "semantic_set_membership",
+ /** A count, size, or score outside the limit the surface declares. */
+ threshold: "semantic_threshold",
+ /** No check is registered for the asserted surface (fail-closed). */
+ unregistered: "semantic_check_unregistered",
+} as const);
+
+export type SemanticViolationCode =
+ (typeof SEMANTIC_VIOLATION_CODES)[keyof typeof SEMANTIC_VIOLATION_CODES];
+
+const SEMANTIC_VIOLATION_CODE_SET: ReadonlySet<string> = new Set(
+ Object.values(SEMANTIC_VIOLATION_CODES),
+);
+
+/** One semantic defect, located by path and classified by code. */
+export interface SemanticViolation {
+ readonly code: SemanticViolationCode;
+ /** JSON-path-ish location, in the shape layer's vocabulary. */
+ readonly path: string;
+ /** The defect, without the path - callers render `<path>: <message>`. */
+ readonly message: string;
+}
+
+/**
+ * One surface's semantic rules. Pure by contract: it reads the payload and
+ * returns every violation it finds, an empty array meaning the payload
+ * conforms. It never throws and never writes - {@link assertResponseCheck}
+ * owns the refusal.
+ */
+export type ResponseCheck = (payload: unknown) => ReadonlyArray<SemanticViolation>;
+
+/** Build one violation, frozen, so a check cannot hand back a mutable verdict. */
+export function semanticViolation(
+ code: SemanticViolationCode,
+ path: string,
+ message: string,
+): SemanticViolation {
+ return Object.freeze({ code, path, message });
+}
+
+/** Render one violation as the single line a caller prints or joins. */
+export function formatSemanticViolation(violation: SemanticViolation): string {
+ return `${violation.path}: ${violation.message}`;
+}
+
+/**
+ * An agent-authored payload broke a rule its write path declares. Carries
+ * the defect structurally - `code`, `path`, and the full violation list - so
+ * a caller routes on fields rather than parsing the message. Nothing has
+ * been written when this is thrown.
+ */
+export class ResponseCheckError extends Error {
+ /** Code of the first violation; the full set is on {@link violations}. */
+ readonly code: SemanticViolationCode;
+ /** Path of the first violation. */
+ readonly path: string;
+ /** The write path whose checks were run, e.g. `design_note`. */
+ readonly surface: string;
+ readonly violations: ReadonlyArray<SemanticViolation>;
+
+ constructor(surface: string, violations: ReadonlyArray<SemanticViolation>) {
+ const first = violations[0];
+ if (first === undefined) {
+ throw new TypeError("ResponseCheckError requires at least one violation");
+ }
+ super(
+ `${surface} response checks violated: ${violations.map(formatSemanticViolation).join("; ")}`,
+ );
+ this.name = "ResponseCheckError";
+ this.code = first.code;
+ this.path = first.path;
+ this.surface = surface;
+ this.violations = Object.freeze([...violations]);
+ }
+}
+
+const REGISTRY = new Map<string, ResponseCheck>();
+
+/**
+ * Declare the semantic rules of one surface. A surface may be registered
+ * once: a second registration throws rather than replacing the first, so a
+ * duplicated name surfaces as a startup failure instead of one lane quietly
+ * validating another lane's payload.
+ */
+export function registerResponseCheck(surface: string, check: ResponseCheck): void {
+ if (surface.trim().length === 0) {
+ throw new TypeError("a response check needs a non-empty surface name");
+ }
+ if (REGISTRY.has(surface)) {
+ throw new TypeError(`a response check is already registered for surface '${surface}'`);
+ }
+ REGISTRY.set(surface, check);
+}
+
+/** The check declared for `surface`, or undefined when none is. */
+export function getResponseCheck(surface: string): ResponseCheck | undefined {
+ return REGISTRY.get(surface);
+}
+
+/** Every registered surface, sorted, so the listing is stable to read. */
+export function listResponseCheckSurfaces(): ReadonlyArray<string> {
+ return Object.freeze([...REGISTRY.keys()].toSorted());
+}
+
+/**
+ * Fail-closed gate: return silently when the payload satisfies the surface's
+ * semantic rules, throw {@link ResponseCheckError} otherwise. Asserting a
+ * surface with no registered check is itself a violation - an unchecked
+ * payload is never reported as a checked one.
+ */
+export function assertResponseCheck(surface: string, payload: unknown): void {
+ const check = REGISTRY.get(surface);
+ if (check === undefined) {
+ throw new ResponseCheckError(surface, [
+ semanticViolation(
+ SEMANTIC_VIOLATION_CODES.unregistered,
+ SHAPE_ROOT_PATH,
+ "no semantic check is registered for this surface",
+ ),
+ ]);
+ }
+ const violations = check(payload);
+ if (violations.length === 0) return;
+ for (const violation of violations) {
+ if (!SEMANTIC_VIOLATION_CODE_SET.has(violation.code)) {
+ throw new TypeError(
+ `response check for surface '${surface}' returned an unnamed violation code: ${violation.code}`,
+ );
+ }
+ }
+ throw new ResponseCheckError(surface, violations);
+}
diff --git a/src/core/brain/response-shape.ts b/src/core/brain/response-shape.ts
index b3fd042d..2bf6a223 100644
--- a/src/core/brain/response-shape.ts
+++ b/src/core/brain/response-shape.ts
@@ -253,6 +253,12 @@ export const DISTILL_CLAIMS_SURFACE = "distill_claims";
export const DERIVED_FACT_SURFACE = "derived_fact";
/** Surface label of the research-report synthesis payload. */
export const RESEARCH_REPORT_SURFACE = "research_report";
+/** Surface label of the model-mined session-signal payload. */
+export const EXTRACTED_SIGNALS_SURFACE = "extracted_signals";
+/** Surface label of the skill draft written from a mature vault page. */
+export const SKILL_PAGE_DRAFT_SURFACE = "skill_page_draft";
+/** Surface label of the one-shot design note. */
+export const DESIGN_NOTE_SURFACE = "design_note";
const STRING_SHAPE: ShapeDescriptor = { type: "string" };
const STRING_LIST_SHAPE: ShapeDescriptor = { type: "array", items: STRING_SHAPE };
@@ -320,6 +326,88 @@ export const RESEARCH_REPORT_SHAPE: ShapeDescriptor = freezeDescriptor({
},
});
+/**
+ * Taste signals a model mined from one imported session's user turns.
+ *
+ * Structure only. The two rules that actually protect the inbox - at most
+ * N items per session, and a floor under each item's confidence - read the
+ * whole list or compare a number against a limit, so they live in the
+ * semantic-check registry beside this descriptor rather than inside it.
+ * `sign` is checked against the two-member sign vocabulary here because a
+ * third value is a structural defect, not a judgement call.
+ */
+export const EXTRACTED_SIGNALS_SHAPE: ShapeDescriptor = freezeDescriptor({
+ type: "object",
+ required: ["items"],
+ properties: {
+ items: {
+ type: "array",
+ items: {
+ type: "object",
+ required: ["topic", "signal", "principle", "confidence"],
+ properties: {
+ topic: FILLED_STRING_SHAPE,
+ signal: { enum: ["positive", "negative"] },
+ principle: FILLED_STRING_SHAPE,
+ confidence: { type: "number" },
+ scope: STRING_SHAPE,
+ },
+ },
+ },
+ },
+});
+
+/**
+ * A SKILL.md draft written from one mature vault page.
+ *
+ * Every field must carry content: a skill with a blank description is a
+ * skill no lexical matcher can ever surface, and a blank body is an
+ * installed file that teaches nothing. What is NOT here is the charset
+ * rule on `name` - the descriptor language has no pattern key, and the
+ * name becomes a DIRECTORY under the skills root, so the constraint is a
+ * semantic check beside this descriptor rather than a widening of it.
+ */
+export const SKILL_PAGE_DRAFT_SHAPE: ShapeDescriptor = freezeDescriptor({
+ type: "object",
+ required: ["name", "description", "triggers", "body"],
+ properties: {
+ name: FILLED_STRING_SHAPE,
+ description: FILLED_STRING_SHAPE,
+ triggers: FILLED_STRING_LIST_SHAPE,
+ body: FILLED_STRING_SHAPE,
+ },
+});
+
+/**
+ * A design note: named alternatives, one of them recommended.
+ *
+ * `recommended` is checked here only as a BOOLEAN. The rule that matters -
+ * exactly one alternative carries `true` - reads the whole array at once,
+ * which the descriptor language cannot express and is not being widened
+ * to; it lives in the semantic-check registry beside this descriptor.
+ */
+export const DESIGN_NOTE_SHAPE: ShapeDescriptor = freezeDescriptor({
+ type: "object",
+ required: ["title", "alternatives"],
+ properties: {
+ title: FILLED_STRING_SHAPE,
+ summary: FILLED_STRING_SHAPE,
+ alternatives: {
+ type: "array",
+ items: {
+ type: "object",
+ required: ["name", "approach", "tradeoffs", "recommended"],
+ properties: {
+ name: FILLED_STRING_SHAPE,
+ approach: FILLED_STRING_SHAPE,
+ tradeoffs: FILLED_STRING_SHAPE,
+ recommended: { type: "boolean" },
+ },
+ },
+ },
+ },
+});
+
/**
* Every declared descriptor, by surface. The registry exists so the shallow-
* and-expressible discipline can be asserted over the whole set at once
@@ -329,6 +417,9 @@ export const MODEL_AUTHORED_SHAPES: Readonly<Record<string, ShapeDescriptor>> =
[DISTILL_CLAIMS_SURFACE]: DISTILL_CLAIMS_SHAPE,
[DERIVED_FACT_SURFACE]: DERIVED_FACT_SHAPE,
[RESEARCH_REPORT_SURFACE]: RESEARCH_REPORT_SHAPE,
+ [EXTRACTED_SIGNALS_SURFACE]: EXTRACTED_SIGNALS_SHAPE,
+ [SKILL_PAGE_DRAFT_SURFACE]: SKILL_PAGE_DRAFT_SHAPE,
+ [DESIGN_NOTE_SURFACE]: DESIGN_NOTE_SHAPE,
});
// ----- Internals ----------------------------------------------------------
diff --git a/src/core/brain/rollup-ladder.ts b/src/core/brain/rollup-ladder.ts
index 42cb82e2..c285e6c0 100644
--- a/src/core/brain/rollup-ladder.ts
+++ b/src/core/brain/rollup-ladder.ts
@@ -22,6 +22,7 @@
import { existsSync, readFileSync } from "node:fs";
import { atomicWriteFileSync } from "../fs-atomic.ts";
+import { buildNeedsLlmStep, type NeedsLlmStep } from "./llm-step.ts";
import type { BrainConfig } from "./types.ts";
import { rollupLedgerPath } from "./paths.ts";
import { assertVaultIdentityForWrite } from "./vault-identity.ts";
@@ -60,15 +61,14 @@ export interface RollupLedger {
readonly produced: Readonly<Record<string, number>>;
}
-/** The needs-llm-step envelope emitted for one fired rung. */
-export interface RollupEnvelope {
- readonly status: "needs-llm-step";
- readonly step: string;
+/**
+ * The needs-llm-step envelope emitted for one fired rung: the shared
+ * envelope spine plus the two fields only a ladder rung has - which rung
+ * fired and which tier its summary note becomes.
+ */
+export interface RollupEnvelope extends NeedsLlmStep {
readonly tier: string;
readonly produces: string;
- readonly prompt: string;
- readonly schema_hints: ReadonlyArray<string>;
- readonly target_path: string;
}
/** One fired rung: the counter reset plus its emitted envelope. */
@@ -192,18 +192,17 @@ export function planRollupLadder(input: RollupLadderInput): RollupLadderPlan {
function buildEnvelope(rung: Rung, newSinceLast: number, runId: string): RollupEnvelope {
const targetPath = `Brain/rollups/rollup-${rung.produces}-${runId}.md`;
- return Object.freeze({
- status: "needs-llm-step" as const,
+ return buildNeedsLlmStep({
step: `rollup:${rung.tier}`,
tier: rung.tier,
produces: rung.produces,
prompt:
`Consolidate the ${newSinceLast} new ${rung.tier} items since the last rollup into one ` +
`${rung.produces}-tier summary note. Cite the items you fold in; submit the full note.`,
- schema_hints: Object.freeze([
+ schema_hints: [
"frontmatter: required YAML block with at least a `kind` key",
`tier: ${rung.produces} (the rollup's tier weight)`,
- ]),
+ ],
target_path: targetPath,
});
}
diff --git a/src/core/brain/salience-gate.ts b/src/core/brain/salience-gate.ts
new file mode 100644
index 00000000..c3168314
--- /dev/null
+++ b/src/core/brain/salience-gate.ts
@@ -0,0 +1,332 @@
+/**
+ * Deterministic salience gate over the rollup ladder's fold set
+ * (salience-lifecycle-enrichment, unit 1, t_de8a0b2d).
+ *
+ * ## What it governs, and what it does not
+ *
+ * The dream pass has no per-item model lane. Its entire model delegation
+ * is the count-triggered rollup ladder (`rollup-ladder.ts`), which reads
+ * one number - how many facts exist - and emits one envelope per fired
+ * rung. So there is exactly one place a salience judgement can change
+ * anything: WHICH facts are counted into that fold set. This module
+ * decides that and nothing else. It never suppresses a preference, never
+ * touches a retire, and never changes what the pass writes about a fact
+ * it excluded.
+ *
+ * ## The formula
+ *
+ * Three signals already exist as pure functions elsewhere and are reused
+ * verbatim - there is no second copy of their math here:
+ *
+ * - `mass` β€” the dominant decayed outcome mass from `lessons.ts`,
+ * `max(positiveMass, negativeMass)`. Unbounded and >= 0. Contested
+ * evidence is loud, not cancelled: a fact people keep violating is
+ * as worth folding as one they keep applying.
+ * - `confidence` β€” the Wilson lower bound times freshness decay from
+ * `confidence.ts`, already in [0, 1].
+ * - `reuse` β€” the observed-reuse rate from `observed-use.ts`, already
+ * in [0, 1]: `(used - contradicted) / total`, clamped.
+ *
+ * `mass` is the only unbounded one, so it is mapped into [0, 1) by the
+ * hyperbolic saturation `mass / (mass + HALF)`, which is monotone, zero
+ * at zero, and exactly 0.5 at {@link SALIENCE_MASS_HALF_SATURATION}. The
+ * combined score is then the weighted sum
+ *
+ * score = W_mass * (mass / (mass + HALF))
+ * + W_confidence * confidence
+ * + W_reuse * reuse
+ *
+ * whose weights sum to 1, so the score is bounded to [0, 1] and each
+ * weight reads directly as "how much of the score this signal can buy".
+ * Mass leads because it is the only signal that grows with repeated
+ * evidence; confidence is the corroboration term; reuse is the smallest
+ * because it is the sparsest store in a young vault.
+ *
+ * No model, no cache, no prompt version. Recomputation is free, and a
+ * cached verdict would be a second source of truth about a number three
+ * pure functions already answer.
+ *
+ * ## Absent threshold is the documented default, not a fallback
+ *
+ * With `dream.salience_threshold` unset the gate is OPEN: nothing is
+ * scored (so neither the log nor the continuity store is read), every
+ * fact is admitted, and the verdict reports `threshold: null` so the
+ * summary can say the gate was absent rather than omit the subject. A
+ * malformed threshold is refused by name - the same doctrine
+ * `dream-gates.ts` states for a malformed gate override, and for the
+ * same reason: a knob that silently reverted is indistinguishable from
+ * one the operator never set.
+ */
+
+import { computeConfidence } from "./confidence.ts";
+import { computeLessons } from "./lessons.ts";
+import { observedReuseRates } from "./observed-use.ts";
+import { describe as describeValue } from "./policy/field-checks.ts";
+import { vaultRelative } from "../path-safety.ts";
+import type { BrainConfig, BrainPreference } from "./types.ts";
+
+/** Share of the score the decayed outcome mass can buy. */
+export const SALIENCE_MASS_WEIGHT = 0.5;
+/** Share of the score the Wilson-bound confidence can buy. */
+export const SALIENCE_CONFIDENCE_WEIGHT = 0.3;
+/** Share of the score the observed-reuse rate can buy. */
+export const SALIENCE_REUSE_WEIGHT = 0.2;
+/**
+ * Decayed mass that maps to exactly half the mass component's range.
+ * Two full-weight outcomes is the anchor: one event is an anecdote, two
+ * is the smallest pattern the corroboration tier in `lessons.ts` also
+ * recognises.
+ */
+export const SALIENCE_MASS_HALF_SATURATION = 2;
+/** Decimal places every reported salience number is rounded to. */
+const SALIENCE_PRECISION = 4;
+/** The configuration key this gate reads, spelled as an operator writes it. */
+export const SALIENCE_THRESHOLD_FIELD = "dream.salience_threshold";
+
+/**
+ * Raised when a salience input cannot be honoured exactly as given.
+ * Carries the field and the offending value so a caller reading only the
+ * error knows which signal to fix.
+ */
+export class SalienceGateError extends Error {
+ /** `mass`, `confidence`, `reuse`, or the config key. */
+ readonly field: string;
+ /** The value as supplied. */
+ readonly value: unknown;
+
+ constructor(field: string, value: unknown, requirement: string) {
+ super(`salience gate: ${field} ${requirement}; got ${describeValue(value)}`);
+ this.name = "SalienceGateError";
+ this.field = field;
+ this.value = value;
+ }
+}
+
+/** The three raw signals for one fact, as their source modules report them. */
+export interface SalienceComponents {
+ /** Dominant decayed outcome mass; unbounded, >= 0. */
+ readonly mass: number;
+ /** Wilson lower bound x freshness, in [0, 1]. */
+ readonly confidence: number;
+ /** Observed-reuse rate, in [0, 1]. */
+ readonly reuse: number;
+}
+
+/** One fact's components plus the derived numbers the gate compares. */
+export interface SalienceScore extends SalienceComponents {
+ /** `mass` mapped into [0, 1) by the hyperbolic saturation. */
+ readonly mass_component: number;
+ /** Weighted sum of the three components, in [0, 1]. */
+ readonly score: number;
+}
+
+/** A preference offered to the gate, as `scanBrain` already holds it. */
+export interface SalienceCandidate {
+ /** Absolute path of the preference file. */
+ readonly path: string;
+ readonly pref: BrainPreference;
+}
+
+/** One scored member of the fold set. */
+export interface SalienceFoldItem {
+ readonly pref_id: string;
+ /** Vault-relative path, so the verdict survives a synced vault. */
+ readonly path: string;
+ readonly score: SalienceScore;
+}
+
+/** A fact the gate kept out of the fold set, with the reason in numbers. */
+export interface SalienceExclusion extends SalienceComponents {
+ readonly pref_id: string;
+ readonly path: string;
+ readonly score: number;
+}
+
+/**
+ * What the gate decided for one pass.
+ *
+ * `threshold: null` is the OPEN gate: nothing was scored, `admitted`
+ * equals `considered`, and `excluded` is empty. The field is always
+ * present - a summary that omitted it could not tell an absent gate from
+ * a gate that excluded nothing.
+ */
+export interface SalienceGateVerdict {
+ readonly threshold: number | null;
+ /** Facts offered to the gate. */
+ readonly considered: number;
+ /** Facts the rollup ladder counts. */
+ readonly admitted: number;
+ /** Every excluded fact, by name. Never truncated, never summarised. */
+ readonly excluded: ReadonlyArray<SalienceExclusion>;
+}
+
+export interface SalienceFoldSetInput {
+ readonly vault: string;
+ readonly preferences: ReadonlyArray<SalienceCandidate>;
+ readonly cfg: BrainConfig;
+ readonly now: Date;
+}
+
+function round(n: number): number {
+ const factor = 10 ** SALIENCE_PRECISION;
+ return Math.round(n * factor) / factor;
+}
+
+/** Refuse a component outside its domain rather than clamping it. */
+function requireUnitComponent(field: string, value: number): void {
+ if (!Number.isFinite(value) || value < 0 || value > 1) {
+ throw new SalienceGateError(field, value, "must be a number in [0, 1]");
+ }
+}
+
+/**
+ * Combine the three signals into one score. Pure, total, and monotone in
+ * every component.
+ */
+export function scoreSalience(components: SalienceComponents): SalienceScore {
+ const { mass, confidence, reuse } = components;
+ if (!Number.isFinite(mass) || mass < 0) {
+ throw new SalienceGateError("mass", mass, "must be a finite number >= 0");
+ }
+ requireUnitComponent("confidence", confidence);
+ requireUnitComponent("reuse", reuse);
+ const massComponent = round(mass / (mass + SALIENCE_MASS_HALF_SATURATION));
+ return Object.freeze({
+ mass,
+ confidence,
+ reuse,
+ mass_component: massComponent,
+ score: round(
+ SALIENCE_MASS_WEIGHT * massComponent +
+ SALIENCE_CONFIDENCE_WEIGHT * confidence +
+ SALIENCE_REUSE_WEIGHT * reuse,
+ ),
+ });
+}
+
+/** Codepoint order, so the reported partition is machine-stable. */
+function byPrefId(a: { pref_id: string }, b: { pref_id: string }): number {
+ return a.pref_id < b.pref_id ? -1 : a.pref_id > b.pref_id ? 1 : 0;
+}
+
+/** The verdict for a vault with no configured threshold. Nothing is scored. */
+export function openSalienceGate(considered: number): SalienceGateVerdict {
+ return Object.freeze({
+ threshold: null,
+ considered,
+ admitted: considered,
+ excluded: Object.freeze([] as ReadonlyArray<SalienceExclusion>),
+ });
+}
+
+/**
+ * Partition a scored fold set at `threshold`. A fact scoring exactly the
+ * threshold is admitted: the operator asked for "at least this salient".
+ */
+export function gateFoldSet(
+ items: ReadonlyArray<SalienceFoldItem>,
+ threshold: number,
+): SalienceGateVerdict {
+ requireUnitComponent(SALIENCE_THRESHOLD_FIELD, threshold);
+ const excluded: SalienceExclusion[] = [];
+ let admitted = 0;
+ for (const entry of items) {
+ if (entry.score.score >= threshold) {
+ admitted++;
+ continue;
+ }
+ excluded.push(
+ Object.freeze({
+ pref_id: entry.pref_id,
+ path: entry.path,
+ score: entry.score.score,
+ mass: entry.score.mass,
+ confidence: entry.score.confidence,
+ reuse: entry.score.reuse,
+ }),
+ );
+ }
+ return Object.freeze({
+ threshold,
+ considered: items.length,
+ admitted,
+ excluded: Object.freeze(excluded.toSorted(byPrefId)),
+ });
+}
+
+/**
+ * Read the configured threshold, or `null` when the operator set none.
+ * A present-but-malformed value is refused by name; it is never treated
+ * as absent, because that would report an applied setting the pass did
+ * not apply.
+ */
+export function resolveSalienceThreshold(cfg: BrainConfig): number | null {
+ const raw: unknown = cfg.dream.salience_threshold;
+ if (raw === undefined || raw === null) return null;
+ if (typeof raw !== "number" || !Number.isFinite(raw) || raw < 0 || raw > 1) {
+ throw new SalienceGateError(SALIENCE_THRESHOLD_FIELD, raw, "must be a number in [0, 1]");
+ }
+ return raw;
+}
+
+/**
+ * Score every candidate against the three signal stores. Reads the log
+ * (through `computeLessons`) and the continuity store (through
+ * `observedReuseRates`) once for the whole set, never once per fact.
+ */
+export function collectSalienceFoldSet(
+ input: SalienceFoldSetInput,
+): ReadonlyArray<SalienceFoldItem> {
+ const { vault, preferences, cfg, now } = input;
+ if (preferences.length === 0) return Object.freeze([]);
+
+ const lessons = computeLessons(
+ vault,
+ preferences.map((c) => c.pref),
+ [],
+ // The default limit is a rendering budget for `Brain/lessons.md`; a
+ // gate that saw only the top twenty would score the rest as silent.
+ { now, limit: preferences.length },
+ );
+ const massById = new Map<string, number>();
+ for (const lesson of lessons) {
+ massById.set(lesson.id, Math.max(lesson.positiveMass, lesson.negativeMass));
+ }
+ const reuseByKey = observedReuseRates(vault);
+
+ return Object.freeze(
+ preferences.map((candidate) => {
+ const relative = vaultRelative(candidate.path, vault);
+ // Observed use is keyed by path when the emitter knew one, else by
+ // id; the id is tried first so a record carrying both resolves the
+ // same way every run.
+ const reuse = reuseByKey.get(candidate.pref.id) ?? reuseByKey.get(relative);
+ return Object.freeze({
+ pref_id: candidate.pref.id,
+ path: relative,
+ score: scoreSalience({
+ mass: massById.get(candidate.pref.id) ?? 0,
+ confidence: computeConfidence(
+ candidate.pref.applied_count,
+ candidate.pref.violated_count,
+ candidate.pref.last_evidence_at,
+ cfg,
+ now,
+ ).value,
+ reuse: reuse?.score ?? 0,
+ }),
+ });
+ }),
+ );
+}
+
+/**
+ * Resolve the threshold and partition the fold set. With no threshold
+ * configured this reads nothing at all, so a vault that never opted in
+ * pays no I/O and behaves exactly as it did before the gate existed.
+ */
+export function applySalienceGate(input: SalienceFoldSetInput): SalienceGateVerdict {
+ const threshold = resolveSalienceThreshold(input.cfg);
+ if (threshold === null) return openSalienceGate(input.preferences.length);
+ return gateFoldSet(collectSalienceFoldSet(input), threshold);
+}
diff --git a/src/core/brain/session-recall.ts b/src/core/brain/session-recall.ts
index fbbbb79a..e6fd9239 100644
--- a/src/core/brain/session-recall.ts
+++ b/src/core/brain/session-recall.ts
@@ -307,6 +307,27 @@ function lineageDescription(
return { lineage_root: rootId, segments: Object.freeze(segments) };
}
+/**
+ * Every raw turn one imported session holds, in record order.
+ *
+ * `describeSessionRecall` counts them and `expandSessionRecall` pages
+ * them from one node outward; neither hands a caller the turns of a
+ * session as a list, which is what a batch lane reading an
+ * already-imported transcript needs. An unknown session id returns an
+ * empty array - "this session has no imported turns" is a fact about the
+ * vault, and the caller decides whether it is a refusal.
+ */
+export function listSessionRawTurns(
+ vault: string,
+ sessionId: string,
+): ReadonlyArray<ExpandedRawTurn> {
+ return Object.freeze(
+ sessionRecallRecords(vault, sessionId)
+ .filter((record) => record.kind === "session_turn")
+ .map(expandedRawTurn),
+ );
+}
+
export function expandSessionRecall(
vault: string,
input: ExpandSessionRecallInput,
diff --git a/src/core/brain/signal.ts b/src/core/brain/signal.ts
index ecb8e7e8..a73f0946 100644
--- a/src/core/brain/signal.ts
+++ b/src/core/brain/signal.ts
@@ -35,7 +35,7 @@ import {
rememberKey,
} from "./idempotency-ledger.ts";
import { sanitisePrinciple } from "./text/sanitize-principle.ts";
-import { normalizeExpirationDate } from "./expiration.ts";
+import { EXPIRATION_DATE_FIELD, normalizeExpirationDate } from "./expiration.ts";
import { writeFrontmatterAtomic, parseFrontmatter } from "../vault.ts";
import { compress, expand, CODEC_VERSION } from "./portability/codec.ts";
import { allocateAndCreate, brainDirsForWrite, validateIsoDate } from "./paths.ts";
@@ -47,12 +47,22 @@ import {
import {
BRAIN_SIGNAL_SIGN,
BRAIN_SIGNAL_SOURCE_TYPE,
+ BRAIN_SIGNAL_SOURCE_TYPES,
isBrainSignalSourceType,
type BrainSignal,
type BrainSignalSign,
type BrainSignalSourceType,
} from "./types.ts";
+/**
+ * The legal `source_type` values, rendered for a refusal message. Derived
+ * from the vocabulary rather than restated, so a new member cannot leave a
+ * refusal naming a set the guard no longer enforces.
+ */
+function renderSourceTypes(): string {
+ return BRAIN_SIGNAL_SOURCE_TYPES.map((v) => `'${v}'`).join(", ");
+}
+
/** Filename prefix without the trailing dash, e.g. `sig-2026-05-14`. */
function signalPrefix(date: string): string {
return `sig-${validateIsoDate(date)}`;
@@ -270,7 +280,7 @@ export function writeSignal(
}
if (sanitised.source_type !== undefined && !isBrainSignalSourceType(sanitised.source_type)) {
throw new Error(
- `signal field 'source_type' must be 'live', 'inline', or 'session'; got ${JSON.stringify(sanitised.source_type)}`,
+ `signal field 'source_type' must be one of ${renderSourceTypes()}; got ${JSON.stringify(sanitised.source_type)}`,
);
}
@@ -421,7 +431,7 @@ function renderSignalDocument(
// supplied so legacy / live writes stay byte-identical. Reader-side
// support is via parseSignal's optional read + the expiration filter.
if (sanitised.expiration_date && sanitised.expiration_date.trim()) {
- metadata["expiration_date"] = normalizeExpirationDate(sanitised.expiration_date);
+ metadata[EXPIRATION_DATE_FIELD] = normalizeExpirationDate(sanitised.expiration_date);
}
// Opt-in codec (v0.22.0): store the raw body compressed and stamp a
@@ -577,7 +587,7 @@ export function parseSignal(path: string, options: ParseSignalOptions = {}): Bra
if (trimmed) {
if (!isBrainSignalSourceType(trimmed)) {
throw new Error(
- `signal field 'source_type' must be 'live', 'inline', or 'session'; got ${JSON.stringify(trimmed)} (${path})`,
+ `signal field 'source_type' must be one of ${renderSourceTypes()}; got ${JSON.stringify(trimmed)} (${path})`,
);
}
source_type = trimmed;
diff --git a/src/core/brain/skill-accept-journal.ts b/src/core/brain/skill-accept-journal.ts
index c644ef38..d066c7a0 100644
--- a/src/core/brain/skill-accept-journal.ts
+++ b/src/core/brain/skill-accept-journal.ts
@@ -21,8 +21,20 @@
* - `materialize` - about to write the procedure
* - `commit` - about to remove the pending copy, then reproject
*
- * `acceptedExisted` / `procedureExisted` are captured before the sequence
- * starts so a rollback never deletes a file the sequence did not create.
+ * `acceptedExisted` / `materializedExisted` are captured before the
+ * sequence starts so a rollback never deletes a file the sequence did not
+ * create.
+ *
+ * The materialize step writes ONE artifact, but not always the same kind
+ * of one: a mined or declared proposal materializes a procedure inside the
+ * vault, and a `mature_page` proposal materializes a `SKILL.md` under the
+ * configured skills root, which may sit OUTSIDE the vault. So the journal
+ * records the absolute path the step is about to write
+ * ({@link SkillAcceptJournalEntry.materializedPath}) rather than leaving
+ * the resolver to re-derive it from the slug - a rollback that guessed the
+ * wrong tree would leave the real artifact behind and claim it had not.
+ * The field is optional: a marker written before it existed names the
+ * procedure path implicitly, and the resolver falls back to that.
*
* 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
@@ -56,8 +68,14 @@ export interface SkillAcceptJournalEntry {
readonly startedAt: string;
/** The accepted archive was already on disk before the sequence started. */
readonly acceptedExisted: boolean;
- /** The procedure file was already on disk before the sequence started. */
- readonly procedureExisted: boolean;
+ /** The materialize target was already on disk before the sequence started. */
+ readonly materializedExisted: boolean;
+ /**
+ * Absolute path the materialize step writes. Absent on a marker written
+ * before this field existed, where the target is the procedure path the
+ * slug derives.
+ */
+ readonly materializedPath?: string;
}
const JOURNAL_SCHEMA_VERSION = 1;
@@ -77,7 +95,10 @@ export function writeSkillAcceptJournal(vault: string, entry: SkillAcceptJournal
phase: entry.phase,
started_at: entry.startedAt,
accepted_existed: entry.acceptedExisted,
- procedure_existed: entry.procedureExisted,
+ // Written under the historical key so a marker this build leaves behind
+ // is still readable by the build that shipped the key.
+ procedure_existed: entry.materializedExisted,
+ ...(entry.materializedPath !== undefined ? { materialized_path: entry.materializedPath } : {}),
};
atomicWriteFileSync(path, `${JSON.stringify(payload, null, 2)}\n`);
}
@@ -207,12 +228,16 @@ 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"];
return Object.freeze({
slug,
id,
phase: phase as SkillAcceptPhase,
startedAt,
acceptedExisted: raw["accepted_existed"] === true,
- procedureExisted: raw["procedure_existed"] === true,
+ materializedExisted: raw["procedure_existed"] === true,
+ ...(typeof materializedPath === "string" && materializedPath.length > 0
+ ? { materializedPath }
+ : {}),
});
}
diff --git a/src/core/brain/skill-page-drafts.ts b/src/core/brain/skill-page-drafts.ts
new file mode 100644
index 00000000..e7720306
--- /dev/null
+++ b/src/core/brain/skill-page-drafts.ts
@@ -0,0 +1,439 @@
+/**
+ * Skill drafts from mature vault pages
+ * (salience-lifecycle-enrichment, unit 4, t_abaec26b).
+ *
+ * `skill-proposals.ts` mines continuity TELEMETRY: what the agent did,
+ * repeatedly, in a shape a detector recognises. It has never read a vault
+ * page. So the material an operator has already written down, verified and
+ * reused - the pages that are the most obvious skill candidates in the
+ * vault - was the one input the proposal queue could not see.
+ *
+ * This module is that input, gated three ways before a model is ever
+ * asked for anything:
+ *
+ * 1. The CHEAP filter is the page-meta trio, the only three fields that
+ * apply to arbitrary user pages: `tier` must be `core` (operator
+ * intent), the lifecycle must not be stale (freshness), and
+ * `_confidence` must be `high`. Each is a separate dimension and each
+ * rejection is reported by name - a gate that answered "no candidates"
+ * would be indistinguishable from a vault nobody has tagged.
+ * 2. The EVIDENCE floor is observed reuse. A page can be tagged core,
+ * fresh and high-confidence and still be something nobody has ever
+ * pulled back out; `observedReuseRates` is the only signal that says
+ * the material was actually USED, so it is the one that decides.
+ * 3. The NEGATIVE signal is skill coverage. A page an installed skill
+ * already covers must not be drafted again: the second copy would
+ * shadow or be shadowed by the first, and `discoverSkills` would
+ * report a collision an operator never asked for.
+ *
+ * Drafting itself is envelope-mediated, and each ADMITTED page gets its
+ * own: one page, one skill, one prompt carrying that page's content. The
+ * returned draft is validated structurally ({@link SKILL_PAGE_DRAFT_SHAPE})
+ * and semantically (the name has to be a legal directory name, which no
+ * descriptor can say) and then STAGED as a pending proposal inside the
+ * vault. Nothing reaches the skills root until a human accepts.
+ */
+
+import { existsSync, readFileSync } from "node:fs";
+import { posix, relative } from "node:path";
+
+import { resolveSkillsDir } from "../config.ts";
+import { ensureInsideVault } from "../path-safety.ts";
+import { discoverSkills, skillRoots } from "../surface/skills.ts";
+import { EXCLUDED_DIRS, listVaultPages, slugify } from "../vault.ts";
+import { buildNeedsLlmStep, type NeedsLlmStep } from "./llm-step.ts";
+import { observedReuseRates } from "./observed-use.ts";
+import {
+ ageDaysFromIso,
+ isStale,
+ readLifecycle,
+ type PageLifecycle,
+} from "./page-meta/lifecycle.ts";
+import { readConfidence, type PageConfidence } from "./page-meta/confidence.ts";
+import { PAGE_TIER, readTier, type PageTier } from "./page-meta/tier.ts";
+import { BRAIN_ROOT_REL } from "./paths.ts";
+import {
+ assertResponseCheck,
+ registerResponseCheck,
+ SEMANTIC_VIOLATION_CODES,
+ semanticViolation,
+ type SemanticViolation,
+} from "./response-checks.ts";
+import {
+ assertResponseShape,
+ SHAPE_ROOT_PATH,
+ SKILL_PAGE_DRAFT_SHAPE,
+ SKILL_PAGE_DRAFT_SURFACE,
+} from "./response-shape.ts";
+import {
+ draftMaturePageSkillProposal,
+ SKILL_NAME_RE,
+ type DeclaredSkillProposalResult,
+} from "./skill-proposals.ts";
+import { BRAIN_CONFIDENCE } from "./types.ts";
+
+/** Lowest tier a page may carry and still be a skill candidate. */
+export const MATURE_PAGE_TIER: PageTier = PAGE_TIER.core;
+
+/** Lowest confidence a page may carry and still be a skill candidate. */
+export const MATURE_PAGE_CONFIDENCE: PageConfidence = BRAIN_CONFIDENCE.high;
+
+/**
+ * Age past which a `stable` or `draft` page counts as stale. The page-meta
+ * default is reused rather than re-picked: a page this module calls stale
+ * and `o2b brain stale` calls fresh would be two answers to one question.
+ */
+export const MATURE_PAGE_STALE_DAYS = 180;
+
+/**
+ * Lowest observed-reuse score a page may carry. `observedReuseRates`
+ * scores `(used - contradicted) / total` in [0, 1], so this floor demands
+ * that a clear majority of the times the page was surfaced, it was used.
+ */
+export const MATURE_PAGE_REUSE_FLOOR = 0.5;
+
+/** The needs-llm-step step name for a deferred skill draft. */
+export const SKILL_PAGE_DRAFT_STEP = "skill-page-draft";
+
+/** Per-page content budget in the prompt, so one long page cannot dominate. */
+const PROMPT_PAGE_TEXT_MAX = 8000;
+
+/**
+ * Why a page is not a candidate. Closed, and one reason per page: the
+ * FIRST gate that rejected it, in the order the gates run, so a reader
+ * fixes the cheapest problem first.
+ */
+export const SKILL_PAGE_SKIP_REASON = Object.freeze({
+ /** `tier` is below `core`. */
+ tier: "tier_below_core",
+ /** The lifecycle is stale for the page's age. */
+ lifecycle: "lifecycle_stale",
+ /** `_confidence` is below `high`. */
+ confidence: "confidence_below_high",
+ /** Nothing has reused the page often enough to evidence it. */
+ reuse: "reuse_below_floor",
+ /** An installed skill already covers the page. */
+ covered: "covered_by_installed_skill",
+} as const);
+
+export type SkillPageSkipReason =
+ (typeof SKILL_PAGE_SKIP_REASON)[keyof typeof SKILL_PAGE_SKIP_REASON];
+
+/** A skill-page draft could not proceed, and the reason is in the message. */
+export class SkillPageDraftError extends Error {
+ constructor(message: string) {
+ super(message);
+ this.name = "SkillPageDraftError";
+ }
+}
+
+/** One page admitted for drafting, with the evidence that admitted it. */
+export interface SkillPageCandidate {
+ /** Vault-relative POSIX path - the identity every surface here uses. */
+ readonly path: string;
+ readonly title: string;
+ readonly tier: PageTier;
+ readonly lifecycle: PageLifecycle;
+ readonly confidence: PageConfidence;
+ /** Observed-reuse score in [0, 1]; at or above {@link MATURE_PAGE_REUSE_FLOOR}. */
+ readonly reuseScore: number;
+ /** How many observed-use verdicts the score was folded from. */
+ readonly reuseObservations: number;
+ readonly llmStep: NeedsLlmStep;
+}
+
+/** One page the gate turned down, named. */
+export interface SkillPageSkip {
+ readonly path: string;
+ readonly title: string;
+ readonly reason: SkillPageSkipReason;
+ /** The measured value behind the reason, so the report is actionable. */
+ readonly detail: string;
+}
+
+export interface SkillPageDraftPlan {
+ readonly generatedAt: string;
+ /** User pages walked, before any gate. */
+ readonly pagesScanned: number;
+ readonly admitted: ReadonlyArray<SkillPageCandidate>;
+ readonly skipped: ReadonlyArray<SkillPageSkip>;
+}
+
+export interface PlanSkillPageDraftsOptions {
+ readonly now: Date;
+ /** Repo skills root, when the caller has one; used for coverage only. */
+ readonly repoRoot?: string | null;
+ /** Skills directory override; defaults to the configured `skills_dir`. */
+ readonly skillsDir?: string | null;
+}
+
+export interface CommitSkillPageDraftOptions {
+ readonly now: Date;
+}
+
+// ----- The semantic rule the descriptor language cannot express -------------
+//
+// The descriptor language has no pattern key and deliberately stays that
+// way, so the `name` charset rule is a semantic check. The pattern itself
+// is `SKILL_NAME_RE`, declared in `skill-proposals.ts` and imported here:
+// the accept path re-applies it at materialize time, and one pattern in
+// two spellings would let the two ends disagree about what a skill
+// directory may be called.
+
+/** Longest legal skill name; a directory name, not a sentence. */
+const SKILL_NAME_MAX_LEN = 64;
+
+registerResponseCheck(SKILL_PAGE_DRAFT_SURFACE, (payload) => {
+ const violations: SemanticViolation[] = [];
+ if (typeof payload !== "object" || payload === null) return violations;
+ const name = (payload as { name?: unknown }).name;
+ if (typeof name !== "string") return violations;
+ const path = `${SHAPE_ROOT_PATH}.name`;
+ if (!SKILL_NAME_RE.test(name)) {
+ violations.push(
+ semanticViolation(
+ SEMANTIC_VIOLATION_CODES.crossItem,
+ path,
+ `must be a skill directory name - lowercase letters, digits and single hyphens; got ${JSON.stringify(name)}`,
+ ),
+ );
+ }
+ if (name.length > SKILL_NAME_MAX_LEN) {
+ violations.push(
+ semanticViolation(
+ SEMANTIC_VIOLATION_CODES.threshold,
+ path,
+ `must be at most ${SKILL_NAME_MAX_LEN} characters; got ${name.length}`,
+ ),
+ );
+ }
+ return violations;
+});
+
+// ----- Phase one: which pages deserve a draft -------------------------------
+
+/**
+ * Walk the vault's user pages and decide which of them a skill should be
+ * drafted from. Read-only; writes nothing and calls no model.
+ *
+ * The `Brain/` tree is excluded for the same reason `heal-run.ts` excludes
+ * it: it is agent-owned bookkeeping, not the operator's knowledge, and the
+ * page-meta trio is a statement about the latter.
+ */
+export function planSkillPageDrafts(
+ vault: string,
+ opts: PlanSkillPageDraftsOptions,
+): SkillPageDraftPlan {
+ const brainDir = BRAIN_ROOT_REL.split("/")[0] ?? "Brain";
+ const pages = listVaultPages(vault, { skipDirs: [...EXCLUDED_DIRS, brainDir] });
+ const reuse = observedReuseRates(vault);
+ const covered = installedSkillNames(vault, opts);
+
+ const admitted: SkillPageCandidate[] = [];
+ const skipped: SkillPageSkip[] = [];
+
+ for (const page of pages) {
+ const rel = toPosixRel(vault, page.path);
+ const title = page.title;
+ const skip = (reason: SkillPageSkipReason, detail: string): void => {
+ skipped.push(Object.freeze({ path: rel, title, reason, detail }));
+ };
+
+ const tier = readTier(page.metadata);
+ if (tier !== MATURE_PAGE_TIER) {
+ skip(SKILL_PAGE_SKIP_REASON.tier, `tier is '${tier}', not '${MATURE_PAGE_TIER}'`);
+ continue;
+ }
+ const lifecycle = readLifecycle(page.metadata);
+ const ageDays = ageDaysFromIso(pageInstant(page.metadata), opts.now);
+ if (isStale(lifecycle, ageDays, MATURE_PAGE_STALE_DAYS)) {
+ skip(
+ SKILL_PAGE_SKIP_REASON.lifecycle,
+ `lifecycle '${lifecycle}' is stale at ${Math.floor(ageDays)} day(s), past ${MATURE_PAGE_STALE_DAYS}`,
+ );
+ continue;
+ }
+ const confidence = readConfidence(page.metadata);
+ if (confidence !== MATURE_PAGE_CONFIDENCE) {
+ skip(
+ SKILL_PAGE_SKIP_REASON.confidence,
+ `confidence is '${confidence}', not '${MATURE_PAGE_CONFIDENCE}'`,
+ );
+ continue;
+ }
+ // The reuse ledger keys artifacts by whatever path the recorder had, so
+ // both forms are consulted rather than assuming one.
+ const observed = reuse.get(rel) ?? reuse.get(page.path);
+ const score = observed?.score ?? 0;
+ if (score < MATURE_PAGE_REUSE_FLOOR) {
+ skip(
+ SKILL_PAGE_SKIP_REASON.reuse,
+ `observed reuse ${score.toFixed(2)} is below ${MATURE_PAGE_REUSE_FLOOR}` +
+ ` over ${observed?.total ?? 0} observation(s)`,
+ );
+ continue;
+ }
+ const name = slugify(title);
+ if (covered.has(name)) {
+ skip(
+ SKILL_PAGE_SKIP_REASON.covered,
+ `an installed skill named '${name}' already covers this page`,
+ );
+ continue;
+ }
+ admitted.push(
+ Object.freeze({
+ path: rel,
+ title,
+ tier,
+ lifecycle,
+ confidence,
+ reuseScore: score,
+ reuseObservations: observed?.total ?? 0,
+ llmStep: buildDraftStep(rel, title, name, readPageBody(page.path)),
+ }),
+ );
+ }
+
+ return Object.freeze({
+ generatedAt: opts.now.toISOString(),
+ pagesScanned: pages.length,
+ admitted: Object.freeze(admitted),
+ skipped: Object.freeze(skipped),
+ });
+}
+
+/**
+ * The envelope for one admitted page. The page's own content rides in the
+ * prompt: the caller is writing a skill FROM this page, and a prompt that
+ * merely named the file would invite it to write from memory instead.
+ */
+function buildDraftStep(
+ rel: string,
+ title: string,
+ suggestedName: string,
+ body: string,
+): NeedsLlmStep {
+ return buildNeedsLlmStep({
+ step: SKILL_PAGE_DRAFT_STEP,
+ prompt:
+ `Write an Agent Skill from the vault page '${title}' (${rel}). The skill must teach an ` +
+ "agent to do what the page describes, in imperative steps, without restating the page's " +
+ `background. Suggested name: '${suggestedName}'.\n\n` +
+ body.slice(0, PROMPT_PAGE_TEXT_MAX),
+ schema_hints: [
+ 'payload: { "name", "description", "triggers": [...], "body" }',
+ "name: skill directory name - lowercase letters, digits and single hyphens",
+ "description: one line naming when an agent should reach for this skill",
+ "triggers: keywords a matcher scores the skill on; at least one, each non-empty",
+ "body: the SKILL.md body, imperative and self-contained",
+ ],
+ target_path: `${BRAIN_ROOT_REL}/skill-proposals/pending`,
+ });
+}
+
+// ----- Phase two: what the caller drafted -----------------------------------
+
+/**
+ * Validate a returned draft and STAGE it as a pending proposal.
+ *
+ * The page path is validated against the vault before anything else -
+ * confined to it, then required to exist: a draft citing a page that is
+ * not there has no provenance, one citing a path outside the vault has
+ * provenance this surface cannot vouch for, and a proposal whose only
+ * evidence is a broken wikilink is worse than no proposal.
+ */
+export function commitSkillPageDraft(
+ vault: string,
+ pagePath: string,
+ payload: unknown,
+ opts: CommitSkillPageDraftOptions,
+): DeclaredSkillProposalResult {
+ const rel = pagePath.trim();
+ if (rel.length === 0) {
+ throw new SkillPageDraftError("a skill page draft needs the page it was drafted from");
+ }
+ // Confinement before existence: `rel` is caller-supplied, and a path
+ // climbing out of the vault with `..` (or through a symlinked directory
+ // inside it) could otherwise be confirmed to exist and then cited as
+ // this proposal's provenance. The refusal is by name, like every other
+ // one on this surface.
+ let abs: string;
+ try {
+ abs = ensureInsideVault(posix.join(vault, rel), vault);
+ } catch (err) {
+ throw new SkillPageDraftError(
+ `page path is not inside the vault: ${rel} (${(err as Error).message})`,
+ );
+ }
+ if (!existsSync(abs)) {
+ throw new SkillPageDraftError(`no such vault page: ${rel}`);
+ }
+ // Structure first, then the rules a descriptor cannot state. Nothing is
+ // staged until both pass.
+ assertResponseShape(SKILL_PAGE_DRAFT_SURFACE, SKILL_PAGE_DRAFT_SHAPE, payload);
+ assertResponseCheck(SKILL_PAGE_DRAFT_SURFACE, payload);
+
+ const draft = payload as {
+ name: string;
+ description: string;
+ triggers: ReadonlyArray<string>;
+ body: string;
+ };
+ return draftMaturePageSkillProposal(vault, {
+ name: draft.name,
+ description: draft.description,
+ triggers: draft.triggers,
+ body: draft.body,
+ sourceRefs: [`[[${rel}]]`],
+ now: opts.now,
+ });
+}
+
+// ----- Internals ------------------------------------------------------------
+
+/** Names of every skill installed on any root this vault can see. */
+function installedSkillNames(vault: string, opts: PlanSkillPageDraftsOptions): ReadonlySet<string> {
+ const skillsDir = opts.skillsDir ?? resolveSkillsDir();
+ const roots = skillRoots({
+ vault,
+ ...(opts.repoRoot ? { repoRoot: opts.repoRoot } : {}),
+ ...(skillsDir ? { skillsDir } : {}),
+ });
+ return new Set(discoverSkills(roots).map((skill) => slugify(skill.name)));
+}
+
+/**
+ * The instant a page's age is measured from. `last_evidence_at` wins when
+ * present - a page re-evidenced last week is not stale because it was
+ * created two years ago - and `created_at` is the fallback.
+ */
+function pageInstant(meta: Readonly<Record<string, unknown>>): string | null {
+ for (const key of ["last_evidence_at", "created_at"]) {
+ const value = meta[key];
+ if (typeof value === "string" && value.trim().length > 0) return value.trim();
+ }
+ return null;
+}
+
+/** Page body without its frontmatter block, for the prompt. */
+function readPageBody(abs: string): string {
+ let text: string;
+ try {
+ text = readFileSync(abs, "utf8");
+ } catch (err) {
+ // A page the walk listed and the read cannot open is a real fault, not
+ // an empty page: drafting from silence would produce a plausible skill
+ // grounded in nothing.
+ throw new SkillPageDraftError(
+ `could not read candidate page ${abs}: ${(err as Error).message ?? String(err)}`,
+ );
+ }
+ if (!text.startsWith("---\n")) return text.trim();
+ const end = text.indexOf("\n---", 4);
+ return end < 0 ? text.trim() : text.slice(end + "\n---".length).trim();
+}
+
+function toPosixRel(vault: string, abs: string): string {
+ return relative(vault, abs).split(/[\\/]/).join(posix.sep);
+}
diff --git a/src/core/brain/skill-proposals.ts b/src/core/brain/skill-proposals.ts
index a39979d1..a1fbe172 100644
--- a/src/core/brain/skill-proposals.ts
+++ b/src/core/brain/skill-proposals.ts
@@ -5,12 +5,15 @@ import {
mkdirSync,
readdirSync,
readFileSync,
+ rmdirSync,
rmSync,
unlinkSync,
} from "node:fs";
import { basename, dirname, join, relative } 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 { verifySkillProposalCandidate } from "./skill-proposal-verifier.ts";
@@ -62,12 +65,34 @@ import { listContinuityRecords, type ContinuityRecord } from "./continuity/store
*/
export const DECLARED_MARKER_PATTERN_KIND = "declared_marker";
+/**
+ * Pattern kind stamped on a proposal drafted from a MATURE VAULT PAGE
+ * (salience-lifecycle-enrichment, unit 4) rather than from continuity
+ * telemetry or an author's marker.
+ *
+ * It sits outside the mining verifier for the same reason
+ * {@link DECLARED_MARKER_PATTERN_KIND} does, and for one more of its own.
+ * The verifier scores a candidate against the continuity records that
+ * produced it; a page candidate has no such records - its evidence is the
+ * page-meta trio plus the observed reuse of the page itself, gated in
+ * `skill-page-drafts.ts` before a draft is ever requested. Running a
+ * record-counting gate over it would reject every page and make the
+ * feature a silent no-op.
+ *
+ * This is also the one pattern kind whose acceptance writes OUTSIDE the
+ * vault: it materializes a `SKILL.md` under the configured skills root
+ * instead of a procedure page. Everything before accept stays in
+ * `Brain/skill-proposals/pending/`.
+ */
+export const MATURE_PAGE_PATTERN_KIND = "mature_page";
+
export type SkillProposalPatternKind =
| "repeated_action"
| "structural_similarity"
| "co_occurrence"
| "temporal_routine"
- | typeof DECLARED_MARKER_PATTERN_KIND;
+ | typeof DECLARED_MARKER_PATTERN_KIND
+ | typeof MATURE_PAGE_PATTERN_KIND;
/** The three phases a proposal file can live in, most terminal first. */
const PROPOSAL_PHASES = ["accepted", "rejected", "pending"] as const;
@@ -96,7 +121,16 @@ export interface SkillProposalReviewResult {
readonly slug: string;
readonly status: "accepted" | "rejected";
readonly proposalPath: string;
+ /** Set when acceptance materialized a procedure inside the vault. */
readonly procedurePath?: string;
+ /**
+ * Set when acceptance materialized a `SKILL.md` under the skills root -
+ * the one artifact this module writes outside the vault, and only on an
+ * explicit accept. The two keys are separate rather than one
+ * `materializedPath` so a caller reads WHICH kind of artifact landed
+ * without re-deriving it from the proposal's pattern kind.
+ */
+ readonly skillPath?: string;
}
/**
@@ -115,6 +149,13 @@ export interface SkillProposalAcceptOptions {
readonly now?: Date;
readonly note?: string;
readonly contract?: SkillContractInput;
+ /**
+ * Where a `mature_page` proposal materializes its `SKILL.md`. Absent
+ * resolves the configured `skills_dir`, falling back to the vault's own
+ * `Brain/skills`. Every other pattern kind ignores it - they materialize
+ * a procedure INSIDE the vault and never touch this tree.
+ */
+ readonly skillsRoot?: string;
}
/** Contract field name -> frontmatter key, in the order they are written. */
@@ -498,6 +539,108 @@ export function draftDeclaredSkillProposal(
return { id: plan.id, slug: plan.slug, path: plan.path, outcome: "created" };
}
+/**
+ * Frontmatter keys carrying the SKILL.md contract a `mature_page`
+ * proposal will materialize on accept. Declared here because the writer
+ * below and the materializer in {@link acceptSkillProposal} are the only
+ * two readers, and a second spelling of any of them would produce a
+ * SKILL.md missing the field a reviewer approved.
+ */
+const SKILL_DRAFT_NAME_KEY = "skill_name";
+const SKILL_DRAFT_DESCRIPTION_KEY = "skill_description";
+const SKILL_DRAFT_TRIGGERS_KEY = "skill_triggers";
+
+/**
+ * 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
+ * `skill-page-drafts.ts` because BOTH ends need it and this module is the
+ * one they can share: the draft-time semantic check imports it from here,
+ * and {@link readSkillDraft} re-applies it at materialize time.
+ */
+export const SKILL_NAME_RE = /^[a-z0-9]+(?:-[a-z0-9]+)*$/;
+
+/** One drafted skill, as the calling agent returned it for a mature page. */
+export interface MaturePageSkillProposalInput {
+ /** Skill directory name; validated as such before it reaches here. */
+ 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 SKILL.md body. */
+ readonly body: string;
+ /** Where the draft came from, as wikilinks - the mature page itself. */
+ readonly sourceRefs: ReadonlyArray<string>;
+ readonly now?: Date;
+}
+
+/**
+ * Stage a PENDING proposal drafted from a mature vault page.
+ *
+ * The write lands in `pending` and nowhere else. That is the whole point
+ * of the two-step: the skills root may sit OUTSIDE the vault, and nothing
+ * automatic may write there - only {@link acceptSkillProposal}, on an
+ * explicit human accept, through the write-ahead journal.
+ *
+ * Identity, dedup and sticky rejection are the declared path's, unchanged:
+ * one name, one proposal, and a name a human already rejected is
+ * suppressed rather than resurfaced.
+ */
+export function draftMaturePageSkillProposal(
+ vault: string,
+ input: MaturePageSkillProposalInput,
+): DeclaredSkillProposalResult {
+ // Vault-identity write guard (context-integrity-gates, Unit J).
+ assertVaultIdentityForWrite(vault);
+ const planned = planDeclaredSkillProposal(
+ vault,
+ { name: input.name, body: input.body, sourceRefs: input.sourceRefs },
+ MATURE_PAGE_PATTERN_KIND,
+ );
+ if ("declined" in planned) return planned.declined;
+ const plan = planned.plan;
+
+ const now = (input.now ?? new Date()).toISOString();
+ const sourceRefs = [...input.sourceRefs];
+ const triggers = input.triggers.map((t) => t.trim()).filter((t) => t.length > 0);
+
+ writeFrontmatterAtomic(
+ plan.path,
+ {
+ schema_version: 1,
+ kind: "brain-skill-proposal",
+ id: plan.id,
+ slug: plan.slug,
+ status: "pending",
+ pattern_kind: MATURE_PAGE_PATTERN_KIND,
+ name_key: plan.nameKey,
+ version: SKILL_PROPOSAL_INITIAL_VERSION,
+ payload_hash: plan.payloadHash,
+ created_at: now,
+ updated_at: now,
+ evidence_count: String(sourceRefs.length),
+ [SKILL_DRAFT_NAME_KEY]: plan.name,
+ [SKILL_DRAFT_DESCRIPTION_KEY]: input.description.trim(),
+ [SKILL_DRAFT_TRIGGERS_KEY]: triggers,
+ source_refs: sourceRefs,
+ },
+ renderProposalDocument({
+ title: plan.name,
+ patternKind: MATURE_PAGE_PATTERN_KIND,
+ key: plan.key,
+ suggestedBody: plan.body.split("\n"),
+ evidence: sourceRefs.map((ref) => `- drafted from ${ref}`),
+ }),
+ {
+ overwrite: false,
+ existsErrorKind: "skill proposal",
+ vaultForRelativePath: vault,
+ },
+ );
+
+ return { id: plan.id, slug: plan.slug, path: plan.path, outcome: "created" };
+}
+
/**
* What {@link draftDeclaredSkillProposal} would do, without writing.
*
@@ -540,6 +683,7 @@ interface DeclaredSkillProposalPlan {
function planDeclaredSkillProposal(
vault: string,
input: DeclaredSkillProposalInput,
+ patternKind: SkillProposalPatternKind = DECLARED_MARKER_PATTERN_KIND,
):
| { readonly plan: DeclaredSkillProposalPlan }
| { readonly declined: DeclaredSkillProposalResult } {
@@ -549,7 +693,7 @@ function planDeclaredSkillProposal(
if (!body) throw new DeclaredSkillProposalError(`declared skill proposal '${name}' has no body`);
const key = slugify(name);
- const nameKey = nameKeyFor(DECLARED_MARKER_PATTERN_KIND, key);
+ const nameKey = nameKeyFor(patternKind, key);
for (const phase of PROPOSAL_PHASES) {
const existing = findProposalByNameKey(vault, phase, nameKey);
if (existing === null) continue;
@@ -567,9 +711,9 @@ function planDeclaredSkillProposal(
}
const payloadHash = createHash("sha256")
- .update(JSON.stringify({ patternKind: DECLARED_MARKER_PATTERN_KIND, key, body }), "utf8")
+ .update(JSON.stringify({ patternKind, key, body }), "utf8")
.digest("hex");
- const slug = composeProposalSlug(DECLARED_MARKER_PATTERN_KIND, key, payloadHash);
+ const slug = composeProposalSlug(patternKind, key, payloadHash);
const id = `prop-${slug}`;
for (const phase of PROPOSAL_PHASES) {
@@ -646,7 +790,14 @@ export function acceptSkillProposal(
const id = typeof fm["id"] === "string" ? fm["id"] : `prop-${slug}`;
const version = parseVersion(fm["version"]);
const acceptedPath = skillProposalAcceptedPath(vault, slug);
- const procPath = procedurePath(vault, slug);
+ // Which tree the materialize step writes into is decided by the
+ // proposal's pattern kind, once, here - so the journal, the write and
+ // the returned result all name the same file.
+ const skillDraft = readSkillDraft(fm);
+ const materializedPath =
+ skillDraft === null
+ ? procedurePath(vault, slug)
+ : join(resolveSkillsRoot(vault, opts.skillsRoot), skillDraft.name, SKILL_FILE_NAME);
let journal: SkillAcceptJournalEntry = {
slug,
@@ -656,7 +807,8 @@ export function acceptSkillProposal(
// Captured up front so a rollback never deletes a file this
// sequence did not create.
acceptedExisted: existsSync(acceptedPath),
- procedureExisted: existsSync(procPath),
+ materializedExisted: existsSync(materializedPath),
+ materializedPath,
};
writeSkillAcceptJournal(vault, journal);
@@ -682,27 +834,52 @@ export function acceptSkillProposal(
journal = { ...journal, phase: "materialize" };
writeSkillAcceptJournal(vault, journal);
- writeFrontmatterAtomic(
- procPath,
- {
- schema_version: 1,
- kind: "brain-procedure",
- id: `proc-${slug}`,
- slug,
- source_proposal: id,
- version,
- created_at: now,
- updated_at: now,
- status: "active",
- ...contract,
- },
- renderAcceptedProcedureBody(id, body),
- {
- overwrite: false,
- existsErrorKind: "procedure",
- vaultForRelativePath: vault,
- },
- );
+ if (skillDraft === null) {
+ writeFrontmatterAtomic(
+ materializedPath,
+ {
+ schema_version: 1,
+ kind: "brain-procedure",
+ id: `proc-${slug}`,
+ slug,
+ source_proposal: id,
+ version,
+ created_at: now,
+ updated_at: now,
+ status: "active",
+ ...contract,
+ },
+ renderAcceptedProcedureBody(id, body),
+ {
+ overwrite: false,
+ existsErrorKind: "procedure",
+ vaultForRelativePath: vault,
+ },
+ );
+ } else {
+ // The skills root may live outside the vault, so this write passes
+ // no `vaultForRelativePath` - the confinement check that key drives
+ // would refuse the very path the operator configured. The path is
+ // 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.
+ mkdirSync(dirname(materializedPath), { recursive: true });
+ writeFrontmatterAtomic(
+ materializedPath,
+ {
+ name: skillDraft.name,
+ description: skillDraft.description,
+ ...(skillDraft.triggers.length > 0 ? { triggers: skillDraft.triggers } : {}),
+ source_proposal: id,
+ version,
+ created_at: now,
+ updated_at: now,
+ ...contract,
+ },
+ renderAcceptedSkillBody(id, skillDraft.name, body),
+ { overwrite: false, existsErrorKind: "skill" },
+ );
+ }
journal = { ...journal, phase: "commit" };
writeSkillAcceptJournal(vault, journal);
@@ -718,7 +895,9 @@ export function acceptSkillProposal(
slug,
status: "accepted",
proposalPath: acceptedPath,
- procedurePath: procPath,
+ ...(skillDraft === null
+ ? { procedurePath: materializedPath }
+ : { skillPath: materializedPath }),
};
} finally {
lock.release();
@@ -858,8 +1037,22 @@ function resolveSkillAccept(
if (!journal.acceptedExisted) {
rmSync(skillProposalAcceptedPath(vault, journal.slug), { force: true });
}
- if (!journal.procedureExisted) {
- rmSync(procedurePath(vault, journal.slug), { force: true });
+ if (!journal.materializedExisted) {
+ // The recorded path, never a re-derived one: a `mature_page` accept
+ // materializes under the skills root, which the slug does not name.
+ const target = journal.materializedPath ?? procedurePath(vault, journal.slug);
+ rmSync(target, { force: true });
+ // A skill directory this sequence created is now empty; leaving it
+ // would make `discoverSkills` report a root with a nameless hole in
+ // it. `rmdirSync` refuses a non-empty directory, which is exactly the
+ // guard wanted - a pre-existing sibling file keeps the directory.
+ if (target !== procedurePath(vault, journal.slug)) {
+ try {
+ rmdirSync(dirname(target));
+ } catch {
+ // Non-empty or already gone; either way nothing more to undo.
+ }
+ }
}
clearSkillAcceptJournal(vault, journal.slug);
return "rolled_back";
@@ -1453,6 +1646,75 @@ function candidateHash(candidate: ProposalCandidate): string {
.digest("hex");
}
+/**
+ * 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 name's charset is re-checked here even though the draft path
+ * 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
+ * other write leans on is absent, and the only thing standing between a
+ * hand-edited `skill_name` in a pending proposal's frontmatter and a
+ * `join()` into an arbitrary directory is this test.
+ */
+function readSkillDraft(
+ fm: Readonly<Record<string, unknown>>,
+): { name: string; description: string; triggers: string[] } | null {
+ if (fm["pattern_kind"] !== MATURE_PAGE_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) {
+ throw new Error(`skill proposal is missing '${SKILL_DRAFT_NAME_KEY}'`);
+ }
+ if (typeof description !== "string" || description.trim().length === 0) {
+ throw new Error(`skill proposal is missing '${SKILL_DRAFT_DESCRIPTION_KEY}'`);
+ }
+ const trimmedName = name.trim();
+ if (!SKILL_NAME_RE.test(trimmedName)) {
+ throw new Error(
+ `skill proposal '${SKILL_DRAFT_NAME_KEY}' is not a skill directory name ` +
+ `(lowercase letters, digits and single hyphens): ${JSON.stringify(trimmedName)}`,
+ );
+ }
+ const raw = fm[SKILL_DRAFT_TRIGGERS_KEY];
+ const triggers = Array.isArray(raw)
+ ? raw.filter((t): t is string => typeof t === "string" && t.trim().length > 0)
+ : typeof raw === "string" && raw.trim().length > 0
+ ? [raw.trim()]
+ : [];
+ return { name: trimmedName, description: description.trim(), triggers };
+}
+
+/**
+ * Where an accepted `mature_page` skill is materialized: the caller's
+ * override, else the configured `skills_dir`, else the vault's own
+ * `Brain/skills`. `skillRoots()` is not used here because it filters to
+ * roots that already EXIST, and the first accepted skill is exactly the
+ * case where the root does not.
+ */
+function resolveSkillsRoot(vault: string, override: string | undefined): string {
+ const explicit = override?.trim();
+ if (explicit) return explicit;
+ return resolveSkillsDir() ?? join(vault, "Brain", "skills");
+}
+
+function renderAcceptedSkillBody(proposalId: string, name: string, proposalBody: string): string {
+ const idx = proposalBody.indexOf(SUGGESTED_BODY_HEADING);
+ const suggested =
+ idx >= 0 ? proposalBody.slice(idx + SUGGESTED_BODY_HEADING.length).trim() : proposalBody.trim();
+ return [
+ `# ${name}`,
+ "",
+ `Accepted from proposal: [[${proposalId}]]`,
+ "",
+ suggested || "No suggested body was captured.",
+ ].join("\n");
+}
+
function renderAcceptedProcedureBody(proposalId: string, proposalBody: string): string {
const idx = proposalBody.indexOf(SUGGESTED_BODY_HEADING);
const suggested =
diff --git a/src/core/brain/source-cleanup.ts b/src/core/brain/source-cleanup.ts
index 79044c9a..30d68d01 100644
--- a/src/core/brain/source-cleanup.ts
+++ b/src/core/brain/source-cleanup.ts
@@ -8,7 +8,7 @@
* content-manifest entry) β€” without re-mining the vault or hand-chasing
* summary pages.
*
- * Two surfaces, one shared tracer:
+ * Three surfaces, one shared tracer:
* - {@link searchBySourceFile} β€” read-only. Every Brain page that traces
* to the exact source.
* - {@link deleteBySource} β€” DRY-RUN BY DEFAULT. Reports the blast radius
@@ -16,6 +16,11 @@
* the index artifacts; original user notes are removed ONLY with an
* explicit `includeOriginals`. Every confirmed cleanup writes a
* `source_invalidation` continuity record (auditable).
+ * - {@link traceNoteDerivations} β€” read-only. The same classification
+ * run for a NOTE path rather than an imported source, so
+ * `noteLifecycle`'s `--delete-linked` cascade decides "derived solely
+ * from this" with this module's rule instead of a second one of its
+ * own. It removes nothing; the caller owns the ladder.
*
* Provenance a page can carry back to a source:
* - frontmatter `source_path` (the ingest summary page, kind
@@ -98,6 +103,31 @@ export interface SourceCleanupEntry {
readonly deletable: boolean;
}
+/**
+ * A traced entry plus the one thing a NOTE delete needs and a source
+ * delete does not.
+ *
+ * The extra field is on this type rather than on
+ * {@link SourceCleanupEntry} deliberately: `deleteBySource`'s payload is
+ * pinned byte-for-byte by
+ * `tests/core/brain/gates/recoverability.test.ts`, and its rule is
+ * long-settled. Only {@link traceNoteDerivations} reports it.
+ */
+export interface NoteDerivationEntry extends SourceCleanupEntry {
+ /**
+ * True when the page names the subject in STRUCTURED provenance - a
+ * `source_path`, a `session_ref`, a `source:` link, or the
+ * `evidenced_by` fold - rather than only mentioning it in prose.
+ *
+ * {@link tracesSolelyToSource} is vacuously true for a page carrying no
+ * `source:` array at all, so `deletable` alone cannot tell a derivation
+ * from a paragraph that happens to write `[[Note]]`. The
+ * `--delete-linked` cascade requires this as well before it will put a
+ * Brain page in a deletion set.
+ */
+ readonly structuredProvenance: boolean;
+}
+
export interface SourceCleanupPlan {
/** Canonical form of the queried source. */
readonly source: string;
@@ -154,6 +184,70 @@ export interface DeleteBySourceOptions {
readonly agent?: string;
}
+/**
+ * The spellings that name ONE subject, and the canonical form they all
+ * reduce to.
+ *
+ * `deleteBySource` has exactly one spelling - the canonical path of the
+ * imported file, which is how the ingest pipeline stamps `source_path`
+ * and how its provenance wikilinks are written. A NOTE is the same
+ * subject reached from the other side and Obsidian writes it two ways,
+ * `[[Projects/Note.md]]` and `[[Projects/Note]]`, so a tracer that knew
+ * only the first would leave a solely-derived signal unmatched and report
+ * it as a protected mention - a safe answer, but the wrong one.
+ *
+ * The bare `[[Note]]` spelling is deliberately NOT a member of any
+ * identity built here. It resolves to one note only when exactly one note
+ * in the vault carries the basename (`store/links.ts:66-69`), so
+ * attributing it would let a page derived from a DIFFERENT note of the
+ * same name into a deletion set. The caller still reports it: the
+ * note-delete surface's own inbound probe reads all three spellings.
+ */
+interface SourceIdentity {
+ /** Canonical form of the subject's own path. */
+ readonly canonical: string;
+ /** The subject as the caller spelled it, for `session_ref` equality. */
+ readonly sourceFile: string;
+ /** Every wikilink / `source_path` spelling that names the subject. */
+ readonly canonicalSpellings: ReadonlySet<string>;
+ /** The same spellings in match order, for the wikilink probes. */
+ readonly spellings: ReadonlyArray<string>;
+}
+
+/** One canonical path, spelled one way: `deleteBySource`'s subject. */
+function exactSourceIdentity(sourceFile: string): SourceIdentity {
+ const canonical = canonicalNotePath(sourceFile);
+ return Object.freeze({
+ canonical,
+ sourceFile,
+ canonicalSpellings: new Set([canonical]),
+ spellings: Object.freeze([canonical]),
+ });
+}
+
+/** The `.md` suffix, matched case-insensitively as the note surfaces do. */
+const MARKDOWN_SUFFIX = ".md";
+
+/** One note path, spelled with and without its `.md` suffix. */
+function noteIdentity(notePath: string): SourceIdentity {
+ const canonical = canonicalNotePath(notePath);
+ const bare = canonical.toLowerCase().endsWith(MARKDOWN_SUFFIX)
+ ? canonical.slice(0, -MARKDOWN_SUFFIX.length)
+ : canonical;
+ const spellings = bare === canonical ? [canonical] : [canonical, bare];
+ return Object.freeze({
+ canonical,
+ sourceFile: notePath,
+ canonicalSpellings: new Set(spellings),
+ spellings: Object.freeze(spellings),
+ });
+}
+
+/** Does `target` - any spelling - name this subject? */
+function namesSubject(identity: SourceIdentity, target: string): boolean {
+ return identity.canonicalSpellings.has(canonicalNotePath(target));
+}
+
/** Directories whose pages are per-item, single-source derived artifacts. */
const DERIVATION_DIRS: ReadonlyArray<string> = Object.freeze([
BRAIN_SOURCES_REL,
@@ -250,12 +344,7 @@ interface RawMatch {
* transitive `evidenced_by` fold is resolved in a second pass once the set
* of directly-derived signals is known.
*/
-function directMatch(
- vault: string,
- absPath: string,
- canonical: string,
- sourceFile: string,
-): RawMatch | null {
+function directMatch(vault: string, absPath: string, identity: SourceIdentity): RawMatch | null {
let text: string;
try {
text = readFileSync(absPath, "utf8");
@@ -289,7 +378,7 @@ function directMatch(
};
const sourcePath = stringField(meta, "source_path");
- if (sourcePath !== null && canonicalNotePath(sourcePath) === canonical) {
+ if (sourcePath !== null && namesSubject(identity, sourcePath)) {
return {
...base,
match: "source_path",
@@ -298,11 +387,14 @@ function directMatch(
}
const sessionRef = stringField(meta, "session_ref");
- if (sessionRef !== null && (sessionRef === canonical || sessionRef === sourceFile)) {
+ if (
+ sessionRef !== null &&
+ (sessionRef === identity.canonical || sessionRef === identity.sourceFile)
+ ) {
return { ...base, match: "session_ref", isIndexArtifact: false };
}
- if (wikilinkRegExp(canonical).test(text)) {
+ if (identity.spellings.some((spelling) => wikilinkRegExp(spelling).test(text))) {
return { ...base, match: "wikilink", isIndexArtifact: false };
}
@@ -314,16 +406,40 @@ function directMatch(
* OTHER structured source link. A signal whose `source` array names a
* second source is a shared observation β€” reported, never auto-deleted.
*/
-function tracesSolelyToSource(raw: RawMatch, canonical: string): boolean {
+function tracesSolelyToSource(raw: RawMatch, identity: SourceIdentity): boolean {
for (const link of raw.sourceLinks) {
- if (canonicalNotePath(wikilinkTarget(link)) !== canonical) return false;
+ if (!namesSubject(identity, wikilinkTarget(link))) return false;
}
return true;
}
+/**
+ * Does the page declare the subject as its PROVENANCE, or does it merely
+ * mention it?
+ *
+ * Every match except `wikilink` is structured by construction: a
+ * `source_path`, a `session_ref` and the `evidenced_by` fold are all
+ * frontmatter this project writes. A wikilink match is structured only
+ * when one of the page's own `source:` links names the subject - the same
+ * spelling in a paragraph of prose is a reference, not a derivation, and
+ * {@link tracesSolelyToSource} cannot tell the two apart because a page
+ * with no `source:` array satisfies it vacuously.
+ */
+function hasStructuredProvenance(raw: RawMatch, identity: SourceIdentity): boolean {
+ if (raw.match !== "wikilink") return true;
+ return raw.sourceLinks.some((link) => namesSubject(identity, wikilinkTarget(link)));
+}
+
interface Traced {
readonly derived: ReadonlyArray<SourceCleanupEntry>;
readonly mentions: ReadonlyArray<SourceCleanupEntry>;
+ /**
+ * Vault-relative paths of the pages that named the subject in
+ * structured provenance. Carried beside the two lists rather than on
+ * the entries so `deleteBySource`'s payload keeps the exact shape it
+ * shipped with; {@link traceNoteDerivations} is the one reader.
+ */
+ readonly structured: ReadonlySet<string>;
}
/**
@@ -331,13 +447,12 @@ interface Traced {
* deletable-derived set and the reported-only mentions set. Deterministic:
* both lists are sorted by vault-relative path.
*/
-function traceReferences(vault: string, sourceFile: string): Traced {
- const canonical = canonicalNotePath(sourceFile);
+function traceReferences(vault: string, identity: SourceIdentity): Traced {
const root = brainDirs(vault).brain;
const rawMatches: RawMatch[] = [];
if (existsSync(root)) {
for (const absPath of walkBrainMarkdown(root)) {
- const m = directMatch(vault, absPath, canonical, sourceFile);
+ const m = directMatch(vault, absPath, identity);
if (m !== null) rawMatches.push(m);
}
}
@@ -376,8 +491,9 @@ function traceReferences(vault: string, sourceFile: string): Traced {
const derived: SourceCleanupEntry[] = [];
const mentions: SourceCleanupEntry[] = [];
+ const structured = new Set<string>();
for (const raw of rawMatches) {
- const deletable = computeDeletable(vault, raw, canonical, derivedSignalIds);
+ const deletable = computeDeletable(vault, raw, identity, derivedSignalIds);
const entry: SourceCleanupEntry = {
path: raw.path,
id: raw.id,
@@ -386,9 +502,14 @@ function traceReferences(vault: string, sourceFile: string): Traced {
isIndexArtifact: raw.isIndexArtifact,
deletable,
};
+ if (hasStructuredProvenance(raw, identity)) structured.add(entry.path);
(deletable ? derived : mentions).push(entry);
}
- return { derived: derived.toSorted(byPath), mentions: mentions.toSorted(byPath) };
+ return {
+ derived: derived.toSorted(byPath),
+ mentions: mentions.toSorted(byPath),
+ structured,
+ };
}
function byPath(a: SourceCleanupEntry, b: SourceCleanupEntry): number {
@@ -398,7 +519,7 @@ function byPath(a: SourceCleanupEntry, b: SourceCleanupEntry): number {
function computeDeletable(
vault: string,
raw: RawMatch,
- canonical: string,
+ identity: SourceIdentity,
derivedSignalIds: ReadonlySet<string>,
): boolean {
// The ingest summary page is always an index artifact to purge.
@@ -406,7 +527,7 @@ function computeDeletable(
// Only per-item derivation pages are ever auto-deleted.
if (!inDerivationDir(vault, raw.absPath)) return false;
// A signal citing a second source is a shared observation β€” report it.
- if (!tracesSolelyToSource(raw, canonical)) return false;
+ if (!tracesSolelyToSource(raw, identity)) return false;
// A preference folded from any foreign signal is a shared fold β€” report it.
// This holds however the preference was first matched: a second-pass
// `evidenced_by` fold OR a first-pass `[[source]]` wikilink match that also
@@ -456,10 +577,55 @@ export function searchBySourceFile(
vault: string,
sourceFile: string,
): ReadonlyArray<SourceCleanupEntry> {
- const { derived, mentions } = traceReferences(vault, sourceFile);
+ const { derived, mentions } = traceReferences(vault, exactSourceIdentity(sourceFile));
return Object.freeze([...derived, ...mentions].toSorted(byPath));
}
+/**
+ * The vault-relative root the derived-set fold walks, and the whole of
+ * it: `Brain/`.
+ *
+ * Named rather than implied because a caller reporting an empty derived
+ * set has to be able to say whether that is a measurement or a scope
+ * boundary. Only `Brain/` holds per-item derivation pages, so a user note
+ * outside it is never a candidate for auto-deletion however tightly it
+ * references the subject - it is somebody's prose, and this fold does not
+ * reach it.
+ */
+export const DERIVATION_SCAN_SCOPE = "Brain/";
+
+/**
+ * Every Brain page tracing back to one NOTE path, classified by the same
+ * blast-radius rule {@link deleteBySource} applies to an imported source:
+ * `deletable` marks a single-purpose derived file tracing SOLELY to the
+ * note, everything else is a reported mention.
+ *
+ * Read-only. The caller decides what to do with the two lists; this
+ * function's whole contribution is that the rule deciding which list a
+ * page lands in is the SAME function in both cases, so a note delete and
+ * a source delete cannot come to disagree about what "derived solely
+ * from" means.
+ *
+ * Each entry additionally carries
+ * {@link NoteDerivationEntry.structuredProvenance}, which the shared rule
+ * does not read: a note, unlike an imported source, is something ordinary
+ * prose links to, and the cascade needs to tell a declared derivation
+ * from a sentence.
+ */
+export function traceNoteDerivations(
+ vault: string,
+ notePath: string,
+): ReadonlyArray<NoteDerivationEntry> {
+ const { derived, mentions, structured } = traceReferences(vault, noteIdentity(notePath));
+ return Object.freeze(
+ [...derived, ...mentions]
+ .toSorted(byPath)
+ .map((entry) =>
+ Object.freeze({ ...entry, structuredProvenance: structured.has(entry.path) }),
+ ),
+ );
+}
+
/**
* Original source file(s) outside `Brain/`: the imported artifact itself.
* A source that lives inside `Brain/` (or that has no on-disk file β€” e.g. a
@@ -507,14 +673,15 @@ export function deleteBySource(
sourceFile: string,
opts: DeleteBySourceOptions = {},
): SourceCleanupPlan {
- const canonical = canonicalNotePath(sourceFile);
+ const identity = exactSourceIdentity(sourceFile);
+ const canonical = identity.canonical;
const confirm = opts.confirm === true;
const includeOriginals = opts.includeOriginals === true;
// Vault-identity write guard (context-integrity-gates, Unit J).
// Dry-run (the default) plans and writes nothing, so it stays ungated.
if (confirm) assertVaultIdentityForWrite(vault);
- const { derived, mentions } = traceReferences(vault, sourceFile);
+ const { derived, mentions } = traceReferences(vault, identity);
const originals = findOriginals(vault, canonical);
const manifestKey = readManifest(vault).entries[canonical] !== undefined ? canonical : null;
const blastRadius = derived.length + mentions.length + originals.length;
diff --git a/src/core/brain/types.ts b/src/core/brain/types.ts
index a3f28692..453adca2 100644
--- a/src/core/brain/types.ts
+++ b/src/core/brain/types.ts
@@ -42,6 +42,12 @@ export type BrainSignalSign = (typeof BRAIN_SIGNAL_SIGN)[keyof typeof BRAIN_SIGN
* `@osb` marker in a vault file.
* - `session` β€” replayed from a session JSONL by
* `o2b brain import-session`.
+ *
+ * `extracted` and `auto_extract` are deliberately separate members:
+ * both mine a session, but one is a regex over structure and the other
+ * is a model reading prose, and their trust profiles differ forever.
+ * Folding the second into the first would make a model-authored signal
+ * indistinguishable from a deterministic one the day after it is written.
*/
export const BRAIN_SIGNAL_SOURCE_TYPE = {
live: "live",
@@ -49,18 +55,31 @@ export const BRAIN_SIGNAL_SOURCE_TYPE = {
session: "session",
/** Regex fact extraction (Memory Integrity Suite). */
extracted: "extracted",
+ /**
+ * Model-mined from an imported session by `o2b brain extract-signals`
+ * (salience-lifecycle-enrichment). Speculative by construction: the
+ * inbox trial lane plus the dream pass is the only route to a
+ * confirmed preference.
+ */
+ autoExtract: "auto_extract",
} as const;
export type BrainSignalSourceType =
(typeof BRAIN_SIGNAL_SOURCE_TYPE)[keyof typeof BRAIN_SIGNAL_SOURCE_TYPE];
-const BRAIN_SIGNAL_SOURCE_TYPE_VALUES: ReadonlyArray<BrainSignalSourceType> =
- Object.values(BRAIN_SIGNAL_SOURCE_TYPE);
+/**
+ * The membership list, exported so a refusal can NAME the vocabulary
+ * instead of restating it. Both refusal sites in `signal.ts` used to
+ * carry a hand-written "'live', 'inline', or 'session'" that had already
+ * gone stale on `extracted`; a message that omits a legal value teaches
+ * the reader the wrong contract.
+ */
+export const BRAIN_SIGNAL_SOURCE_TYPES: ReadonlyArray<BrainSignalSourceType> = Object.freeze(
+ Object.values(BRAIN_SIGNAL_SOURCE_TYPE),
+);
/** Type-guard for the enum union β€” used by writer + parser. */
export function isBrainSignalSourceType(v: unknown): v is BrainSignalSourceType {
- return (
- typeof v === "string" && (BRAIN_SIGNAL_SOURCE_TYPE_VALUES as ReadonlyArray<string>).includes(v)
- );
+ return typeof v === "string" && (BRAIN_SIGNAL_SOURCE_TYPES as ReadonlyArray<string>).includes(v);
}
export const BRAIN_PREFERENCE_STATUS = {
@@ -459,6 +478,17 @@ export const BRAIN_LOG_EVENT_KIND = {
* records only runs that actually examined documents.
*/
eventAnchorBackfill: "event-anchor-backfill",
+ /**
+ * `expiration-set` (unit 3c) - a signal's or preference's
+ * `expiration_date` was set, changed, or explicitly cleared after the
+ * artifact was written. Payload carries the `target` wikilink, its
+ * `kind`, the new `expiration` and the `previous` one (both spelled
+ * `none` when absent), and the `agent`. Both sides are recorded because
+ * "cleared" and "moved to a later date" are different decisions and the
+ * frontmatter afterwards cannot tell them apart. A no-op re-set writes
+ * no event, so the log records changes and not calls.
+ */
+ expirationSet: "expiration-set",
} as const;
export type BrainLogEventKind = (typeof BRAIN_LOG_EVENT_KIND)[keyof typeof BRAIN_LOG_EVENT_KIND];
@@ -1269,6 +1299,16 @@ export interface BrainDreamConfig {
* byte-identical. Absent is treated as `false`.
*/
readonly heal_enrich_enabled?: boolean;
+ /**
+ * Salience-lifecycle-enrichment (unit 1). Minimum combined salience
+ * score, in `[0, 1]`, a fact must reach to enter the rollup ladder's
+ * fold set. See `salience-gate.ts` for the formula. Absent (the
+ * default) leaves the gate OPEN: nothing is scored, every fact is
+ * counted, and the run behaves exactly as it did before the gate
+ * existed. Excluded facts are always named in the dream summary, so
+ * raising this never drops anything silently.
+ */
+ readonly salience_threshold?: number;
}
export interface BrainRetireConfig {
diff --git a/src/core/brain/write-session/types.ts b/src/core/brain/write-session/types.ts
index 76709b05..68d28bd3 100644
--- a/src/core/brain/write-session/types.ts
+++ b/src/core/brain/write-session/types.ts
@@ -14,6 +14,8 @@
* record; the envelope grammar below is shared and stable.
*/
+import type { LlmStepFields } from "../llm-step.ts";
+
/** Session kinds. `artifact` writes one note; `panel` deliberates. */
export type WriteSessionKind = "artifact" | "panel";
@@ -112,18 +114,21 @@ export interface WriteSessionProbe {
* The JSON envelope every operation returns. Stable grammar shared by
* the CLI verb and the MCP tool; `existing` is populated only when the
* target path already holds content the caller must decide about.
+ *
+ * This is the DURABLE superset of the shared envelope spine
+ * ({@link LlmStepFields} in `../llm-step.ts`): the generation fields are
+ * inherited from it so the three lanes speaking this grammar cannot drift
+ * apart, while the session-backed fields below - and a `status` that
+ * widens past `needs-llm-step` to the whole lifecycle - stay here, where
+ * the session record backs them.
*/
-export interface WriteSessionEnvelope {
+export interface WriteSessionEnvelope extends LlmStepFields {
readonly status: WriteSessionStatus;
readonly session_id: string;
readonly kind: WriteSessionKind;
- readonly step: string;
- readonly prompt: string;
- readonly schema_hints: ReadonlyArray<string>;
readonly errors: ReadonlyArray<WriteSessionError>;
readonly attempts_left: number;
readonly expires_at: string;
- readonly target_path: string;
readonly existing: ExistingTargetInfo | null;
}
diff --git a/src/mcp/brain-tools.ts b/src/mcp/brain-tools.ts
index 5d34f1bf..cf1cd452 100644
--- a/src/mcp/brain-tools.ts
+++ b/src/mcp/brain-tools.ts
@@ -29,6 +29,8 @@ import { HYGIENE_TOOLS } from "./brain/hygiene-tools.ts";
import { NER_TOOLS } from "./brain/ner-tools.ts";
import { INGEST_TOOLS } from "./brain/ingest-tools.ts";
import { DISTILL_TOOLS } from "./brain/distill-tools.ts";
+import { EXTRACT_TOOLS } from "./brain/extract-tools.ts";
+import { DESIGN_NOTE_TOOLS } from "./brain/design-note-tools.ts";
import { RESEARCH_TOOLS } from "./brain/research-tools.ts";
import { DERIVE_TOOLS } from "./brain/derive-tools.ts";
import { NOTES_TOOLS } from "./brain/notes-tools.ts";
@@ -65,6 +67,8 @@ export const BRAIN_TOOLS: ReadonlyArray<ToolDefinition> = Object.freeze([
...NER_TOOLS,
...INGEST_TOOLS,
...DISTILL_TOOLS,
+ ...EXTRACT_TOOLS,
+ ...DESIGN_NOTE_TOOLS,
...RESEARCH_TOOLS,
...DERIVE_TOOLS,
...NOTES_TOOLS,
diff --git a/src/mcp/brain/design-note-tools.ts b/src/mcp/brain/design-note-tools.ts
new file mode 100644
index 00000000..ff64de40
--- /dev/null
+++ b/src/mcp/brain/design-note-tools.ts
@@ -0,0 +1,130 @@
+/**
+ * One-shot design-note tool (salience-lifecycle-enrichment, unit 7,
+ * t_c87644b4).
+ *
+ * The one-shot sibling of `brain_write_session`'s panel lane. Called with
+ * a topic alone it grounds that topic in the vault's tensions, decisions
+ * and truth projections and returns one needs-llm-step envelope; called
+ * with a `note` it validates the answer - shape, then the
+ * exactly-one-recommended rule - and commits under `Brain/decisions/`.
+ * OSB runs no model on either path.
+ */
+
+import { commitDesignNote, DesignNoteError, planDesignNote } from "../../core/brain/design-note.ts";
+import { ResponseCheckError } from "../../core/brain/response-checks.ts";
+import { ResponseShapeError } from "../../core/brain/response-shape.ts";
+import { resolveAgentName } from "../../core/config.ts";
+import { coerceStr } from "../coerce.ts";
+import { MCP_PREVIEW_BUDGET } from "../preview-budget.ts";
+import type { ServerContext, ToolDefinition } from "../tool-contract.ts";
+import { vaultRelativeSafe, wrapToolErrors } from "./shared.ts";
+
+const TOOL = "brain_design_note";
+
+/** The refusal classes this tool reports as caller errors, not server faults. */
+const NAMED_REFUSALS = [DesignNoteError, ResponseShapeError, ResponseCheckError];
+
+async function toolBrainDesignNote(
+ ctx: ServerContext,
+ args: Record<string, unknown>,
+): Promise<Record<string, unknown>> {
+ const topic = coerceStr(args, "topic", true)!;
+ const agentArg = coerceStr(args, "agent", false);
+ const agent =
+ agentArg && agentArg.trim().length > 0
+ ? agentArg
+ : resolveAgentName(ctx.configPath ?? undefined);
+
+ return wrapToolErrors(TOOL, NAMED_REFUSALS, async () => {
+ if (args["note"] === undefined) {
+ const report = planDesignNote(ctx.vault, topic, { now: new Date() });
+ const g = report.grounding;
+ return {
+ phase: "plan",
+ topic: report.topic,
+ slug: report.slug,
+ generated_at: report.generatedAt,
+ target_path: report.targetPath,
+ grounding: {
+ tensions: g.tensions,
+ decisions: g.decisions,
+ truth_slots: g.truthSlots,
+ conflicts: g.conflicts,
+ counts: g.counts,
+ // Named, not implied: a store this vault has nothing in is a
+ // different answer from a store that matched nothing.
+ empty_stores: g.emptyStores,
+ },
+ llm_step: report.llmStep,
+ };
+ }
+ const res = commitDesignNote(ctx.vault, topic, args["note"], { agent, now: new Date() });
+ return {
+ phase: "commit",
+ topic: res.topic,
+ slug: res.slug,
+ // Vault-relative, like every other path this server emits: an MCP
+ // response lands in model context, and the absolute host path is
+ // not this surface's to hand out.
+ path: vaultRelativeSafe(ctx.vault, res.path),
+ recommended: res.recommended,
+ alternative_count: res.alternativeCount,
+ };
+ });
+}
+
+export const DESIGN_NOTE_TOOLS: ReadonlyArray<ToolDefinition> = Object.freeze([
+ {
+ name: TOOL,
+ description:
+ "One-shot design note; runs no model. Without `note` it grounds the topic in the vault's tensions, decisions and truth projections and returns one needs-llm-step envelope, naming any store the vault holds nothing in. With `note` it commits under Brain/decisions/; not one recommendation refuses.",
+ inputSchema: {
+ type: "object",
+ properties: {
+ topic: {
+ type: "string",
+ description: "What the design note is about; also the grounding query.",
+ },
+ note: {
+ type: "object",
+ description: "The written note; omit to get the grounding and the envelope instead.",
+ properties: {
+ title: { type: "string", description: "Title of the design note." },
+ summary: {
+ type: "string",
+ description: "Optional one-paragraph summary placed above the alternatives.",
+ },
+ alternatives: {
+ type: "array",
+ description: "Named alternatives; exactly one may set recommended.",
+ items: {
+ type: "object",
+ properties: {
+ name: { type: "string", description: "Short name of the alternative." },
+ approach: { type: "string", description: "What this alternative does." },
+ tradeoffs: { type: "string", description: "What it costs and what it buys." },
+ recommended: {
+ type: "boolean",
+ description: "True on exactly one alternative; zero or two refuses the note.",
+ },
+ },
+ required: ["name", "approach", "tradeoffs", "recommended"],
+ additionalProperties: false,
+ },
+ },
+ },
+ required: ["title", "alternatives"],
+ additionalProperties: false,
+ },
+ agent: {
+ type: "string",
+ description: "Optional agent identity override; defaults to the server-resolved name.",
+ },
+ },
+ required: ["topic"],
+ additionalProperties: false,
+ },
+ previewBudget: MCP_PREVIEW_BUDGET,
+ handler: toolBrainDesignNote,
+ },
+]);
diff --git a/src/mcp/brain/extract-tools.ts b/src/mcp/brain/extract-tools.ts
new file mode 100644
index 00000000..57c5b754
--- /dev/null
+++ b/src/mcp/brain/extract-tools.ts
@@ -0,0 +1,136 @@
+/**
+ * Session signal-mining tool (salience-lifecycle-enrichment, unit 2,
+ * t_1dace26d).
+ *
+ * One tool, two phases, mirroring the CLI verb. Called without `items`
+ * it is read-only and returns the mining plan plus the single
+ * needs-llm-step envelope; called with `items` it validates the answer
+ * and writes the accepted ones as speculative inbox signals. OSB runs no
+ * model on either path.
+ */
+
+import {
+ commitExtractedSignals,
+ ExtractSignalsError,
+ planExtractSignals,
+} from "../../core/brain/extract-signals.ts";
+import { ResponseCheckError } from "../../core/brain/response-checks.ts";
+import { ResponseShapeError } from "../../core/brain/response-shape.ts";
+import { resolveAgentName } from "../../core/config.ts";
+import { coerceStr } from "../coerce.ts";
+import { MCP_PREVIEW_BUDGET } from "../preview-budget.ts";
+import type { ServerContext, ToolDefinition } from "../tool-contract.ts";
+import { vaultRelativeSafe, wrapToolErrors } from "./shared.ts";
+
+const TOOL = "brain_extract_signals";
+
+/** The refusal classes this tool reports as caller errors, not server faults. */
+const NAMED_REFUSALS = [ExtractSignalsError, ResponseShapeError, ResponseCheckError];
+
+async function toolBrainExtractSignals(
+ ctx: ServerContext,
+ args: Record<string, unknown>,
+): Promise<Record<string, unknown>> {
+ const session = coerceStr(args, "session", true)!;
+ const agentArg = coerceStr(args, "agent", false);
+ const agent =
+ agentArg && agentArg.trim().length > 0
+ ? agentArg
+ : resolveAgentName(ctx.configPath ?? undefined);
+
+ return wrapToolErrors(TOOL, NAMED_REFUSALS, async () => {
+ // Absent `items` is the plan phase. An empty array is NOT: it is an
+ // answer claiming the session states nothing, and it goes through the
+ // validators like any other so the caller gets one contract.
+ if (args["items"] === undefined) {
+ const plan = planExtractSignals(ctx.vault, session, { now: new Date() });
+ return {
+ phase: "plan",
+ session_id: plan.sessionId,
+ generated_at: plan.generatedAt,
+ boundary_decision: plan.boundaryDecision,
+ turns_scanned: plan.turnsScanned,
+ turns_mined: plan.turnsMined.map((t) => ({ turn_id: t.turnId, text: t.text })),
+ cap: plan.cap,
+ confidence_floor: plan.confidenceFloor,
+ llm_step: plan.llmStep,
+ };
+ }
+ const res = commitExtractedSignals(
+ ctx.vault,
+ session,
+ { items: args["items"] },
+ { agent, now: new Date() },
+ );
+ return {
+ phase: "commit",
+ session_id: res.sessionId,
+ // Vault-relative, like every other path this server emits: an MCP
+ // response lands in model context, and the absolute host path is
+ // not this surface's to hand out.
+ written: res.written.map((w) => ({
+ id: w.id,
+ path: vaultRelativeSafe(ctx.vault, w.path),
+ topic: w.topic,
+ })),
+ staged: res.staged,
+ deduped: res.deduped,
+ durability_rejected: res.durabilityRejected,
+ rejected: res.rejected.map((r) => ({ topic: r.topic, reason: r.reason })),
+ };
+ });
+}
+
+export const EXTRACT_TOOLS: ReadonlyArray<ToolDefinition> = Object.freeze([
+ {
+ name: TOOL,
+ description:
+ "Mine taste signals from an imported session's USER turns; runs no model. Without `items` returns the turns plus one needs-llm-step envelope. With `items` writes them to Brain/inbox/ as speculative `source_type: auto_extract` signals. Over the cap or under the floor refuses the payload.",
+ inputSchema: {
+ type: "object",
+ properties: {
+ session: {
+ type: "string",
+ description: "Recall session id of an already-imported session.",
+ },
+ items: {
+ type: "array",
+ description: "Mined signals; omit to get the plan and the envelope instead.",
+ items: {
+ type: "object",
+ properties: {
+ topic: { type: "string", description: "Stable kebab-slug naming the rule." },
+ signal: {
+ type: "string",
+ enum: ["positive", "negative"],
+ description: "positive = the rule to follow; negative = what to avoid.",
+ },
+ principle: {
+ type: "string",
+ description: "One imperative line stating the rule.",
+ },
+ confidence: {
+ type: "number",
+ description: "How sure the caller is; items under the floor refuse the payload.",
+ },
+ scope: {
+ type: "string",
+ description: "Optional soft category, e.g. `writing`, `coding`.",
+ },
+ },
+ required: ["topic", "signal", "principle", "confidence"],
+ additionalProperties: false,
+ },
+ },
+ agent: {
+ type: "string",
+ description: "Optional agent identity override; defaults to the server-resolved name.",
+ },
+ },
+ required: ["session"],
+ additionalProperties: false,
+ },
+ previewBudget: MCP_PREVIEW_BUDGET,
+ handler: toolBrainExtractSignals,
+ },
+]);
diff --git a/src/mcp/brain/feedback-tools.ts b/src/mcp/brain/feedback-tools.ts
index 0543a6c0..9bfcc0e5 100644
--- a/src/mcp/brain/feedback-tools.ts
+++ b/src/mcp/brain/feedback-tools.ts
@@ -28,9 +28,12 @@ import {
import {
applyDreamBundle,
discardDreamBundle,
+ DreamRetriageError,
listDreamBundles,
+ retriageDreamBundle,
stageDream,
validateDreamBundle,
+ type DreamRetriageEntry,
} from "../../core/brain/dream-stage.ts";
import { BRAIN_ROLES } from "../../core/brain/trust/role.ts";
import { resolveEffectiveScope, writeSignal } from "../../core/brain/signal.ts";
@@ -43,6 +46,14 @@ import {
} from "../../core/brain/write-advisory.ts";
import { loadFeedbackDefaultScopeSafe } from "../../core/brain/policy.ts";
import { writePreference } from "../../core/brain/preference.ts";
+import { normalizeExpirationDate } from "../../core/brain/expiration.ts";
+import {
+ EXPIRATION_CLEAR,
+ ExpirationTargetNotFoundError,
+ ExpirationValueError,
+ InvalidExpirationTargetError,
+ setExpiration,
+} from "../../core/brain/expiration-set.ts";
import { gatedOwnerScopeView, type OwnerScopeView } from "../../core/brain/owner-scope-view.ts";
import { brainArtifactSlug } from "../../core/brain/wikilink.ts";
import { validateBrainFeedbackInput } from "../../core/brain/sessions/validate-feedback.ts";
@@ -64,6 +75,7 @@ import {
resolveSharedNamespace,
} from "../../core/brain/shared-namespace.ts";
import { INTERNAL_ERROR, INVALID_PARAMS, MCPError } from "../protocol.ts";
+import { MCP_PREVIEW_BUDGET } from "../preview-budget.ts";
import type { ServerContext, ToolDefinition } from "../tool-contract.ts";
import {
emitObservedUse,
@@ -132,6 +144,19 @@ async function toolBrainFeedback(
// signal writer so a retried / double-delivered feedback call dedupes
// instead of appending a second signal. Absent β†’ historical behaviour.
const idempotencyKey = coerceStr(args, "idempotency_key", false);
+ // Creation-time expiration (unit 3c). Validated through the one
+ // chokepoint BEFORE the signal write, so an unparseable date refuses
+ // the whole call rather than landing a signal and then failing on the
+ // preference beside it.
+ const expiresRaw = coerceStr(args, "expires", false);
+ let expires: string | undefined;
+ if (expiresRaw !== null && expiresRaw !== undefined) {
+ try {
+ expires = normalizeExpirationDate(expiresRaw);
+ } catch (err) {
+ throw new MCPError(INVALID_PARAMS, `brain_feedback: expires: ${(err as Error).message}`);
+ }
+ }
const now = new Date();
const createdAt = isoSecond(now);
const signalStamp = eventTime ?? now;
@@ -166,6 +191,7 @@ async function toolBrainFeedback(
// supplied, so a live "remember" stays byte-identical.
...(eventTime ? { valid_from: signalCreatedAt, recorded_at: signalCreatedAt } : {}),
...(idempotencyKey ? { idempotency_key: idempotencyKey } : {}),
+ ...(expires !== undefined ? { expiration_date: expires } : {}),
};
const sigResult = writeSignal(ctx.vault, signalInput, writeOpts);
// A deduped signal means this whole feedback call is a retry of one
@@ -256,6 +282,9 @@ async function toolBrainFeedback(
// preferences. This writer now matches it.
confidence_value: 0,
...(effectiveScope !== undefined ? { scope: effectiveScope } : {}),
+ // The same lifetime the signal carries: a rule confirmed from an
+ // observation that expires on a date does not outlive it.
+ ...(expires !== undefined ? { expiration_date: expires } : {}),
},
// Ownership is resolved by the writer, never echoed from `agent`:
// that argument is caller-supplied, and a caller must not be able to
@@ -414,12 +443,13 @@ async function toolBrainDream(
action !== "stage" &&
action !== "validate" &&
action !== "apply" &&
+ action !== "retriage" &&
action !== "discard" &&
action !== "list"
) {
throw new MCPError(
INVALID_PARAMS,
- "brain_dream: action must be run|stage|validate|apply|discard|list",
+ "brain_dream: action must be run|stage|validate|apply|retriage|discard|list",
);
}
const dryRun = coerceBool(args, "dry_run");
@@ -488,7 +518,7 @@ async function toolBrainDream(
// Staged lifecycle (t_ae8a8ec0): stage -> validate -> apply over a
// persisted bundle; dream() stays the only promotion engine.
const runIdArg = coerceStr(args, "run_id", false);
- if ((action === "validate" || action === "apply" || action === "discard") && !runIdArg) {
+ if (action !== "list" && action !== "stage" && !runIdArg) {
throw new MCPError(INVALID_PARAMS, `brain_dream action=${action}: run_id is required`);
}
const now = nowDate ?? new Date();
@@ -530,6 +560,48 @@ async function toolBrainDream(
: {}),
};
}
+ case "retriage": {
+ // Read-only: it re-runs the salience gate against the current
+ // threshold and reports what would move. The bundle is not
+ // rewritten, so a caller that likes the new partition re-stages.
+ let outcome;
+ try {
+ outcome = retriageDreamBundle(ctx.vault, runIdArg!, stageOpts);
+ } catch (exc) {
+ if (exc instanceof DreamRetriageError) {
+ throw new MCPError(INVALID_PARAMS, `brain_dream: ${exc.message}`);
+ }
+ throw exc;
+ }
+ const scopedDelta = (
+ entries: ReadonlyArray<DreamRetriageEntry>,
+ ): Array<Record<string, unknown>> =>
+ dreamView
+ .keep(entries, (entry) => [entry.pref_id, entry.path])
+ .map((entry) => ({
+ pref_id: entry.pref_id,
+ path: entry.path,
+ score: entry.score,
+ staged_score: entry.staged_score,
+ }));
+ return {
+ action,
+ run_id: runIdArg,
+ staged_threshold: outcome.stagedThreshold,
+ current_threshold: outcome.currentThreshold,
+ changed: outcome.changed,
+ considered: outcome.considered,
+ admitted: outcome.admitted,
+ // Counts before the owner filter, names after it: a scoped
+ // caller is still told HOW MANY facts moved, and only the
+ // identities it may not see are withheld.
+ newly_admitted_count: outcome.newlyAdmitted.length,
+ newly_excluded_count: outcome.newlyExcluded.length,
+ newly_admitted: scopedDelta(outcome.newlyAdmitted),
+ newly_excluded: scopedDelta(outcome.newlyExcluded),
+ notes: [...outcome.notes],
+ };
+ }
case "discard": {
return { action, run_id: runIdArg, removed: discardDreamBundle(ctx.vault, runIdArg!) };
}
@@ -622,6 +694,26 @@ async function toolBrainDream(
age_days: q.age_days,
failed_gates: [...q.failed_gates],
})),
+ // The salience gate over the rollup fold set. `threshold: null` says
+ // the gate was absent, and the two counts are reported before the
+ // owner filter so a scoped caller still learns how many facts were
+ // held back even where it may not see their names.
+ salience_gate: {
+ threshold: summary.salience_gate.threshold,
+ considered: summary.salience_gate.considered,
+ admitted: summary.salience_gate.admitted,
+ excluded_count: summary.salience_gate.excluded.length,
+ excluded: dreamView
+ .keep(summary.salience_gate.excluded, (entry) => [entry.pref_id, entry.path])
+ .map((entry) => ({
+ pref_id: entry.pref_id,
+ path: entry.path,
+ score: entry.score,
+ mass: entry.mass,
+ confidence: entry.confidence,
+ reuse: entry.reuse,
+ })),
+ },
snapshot_path: summary.snapshot_path
? vaultRelativeSafe(ctx.vault, summary.snapshot_path)
: null,
@@ -795,6 +887,56 @@ async function toolBrainNote(
// ----- brain_write_session (Agent Write Contract Suite, v0.41.0) ------------
+/**
+ * Post-creation expiration mutation (unit 3c).
+ *
+ * A tool of its own rather than an action on `brain_lifecycle`, and the
+ * reason is how each addresses its subject: every `brain_lifecycle`
+ * action takes a vault-relative PATH and runs it through a note-path
+ * envelope, while a signal or preference is addressed by id and lives
+ * under the `Brain/` root that envelope exists to refuse. Folding them
+ * together would mean carving an exception into that refusal.
+ */
+const EXPIRE_TOOL = "brain_expire";
+
+async function toolBrainExpire(
+ ctx: ServerContext,
+ args: Record<string, unknown>,
+): Promise<Record<string, unknown>> {
+ const id = coerceStr(args, "id", true)!;
+ const expires = coerceStr(args, "expires", true)!;
+ const agent = coerceStr(args, "agent", false);
+ try {
+ const res = setExpiration(ctx.vault, id, expires, {
+ ...(agent ? { agent } : {}),
+ });
+ return {
+ id: res.id,
+ kind: res.kind,
+ path: res.path,
+ expiration: res.expiration,
+ previous: res.previous,
+ changed: res.changed,
+ };
+ } catch (err) {
+ // Each of the three is the caller's fault and each has a different
+ // next move: fix the date, fix the id, or use a surface that takes a
+ // path. They keep their own class name as the reported code.
+ if (
+ err instanceof ExpirationValueError ||
+ err instanceof ExpirationTargetNotFoundError ||
+ err instanceof InvalidExpirationTargetError
+ ) {
+ throw new MCPError(INVALID_PARAMS, `${EXPIRE_TOOL}: ${err.message}`, { code: err.name });
+ }
+ if (err instanceof MCPError) throw err;
+ throw new MCPError(
+ INTERNAL_ERROR,
+ `${EXPIRE_TOOL}: ${err instanceof Error ? err.message : String(err)}`,
+ );
+ }
+}
+
export const FEEDBACK_TOOLS: ReadonlyArray<ToolDefinition> = Object.freeze([
{
name: "brain_feedback",
@@ -850,6 +992,11 @@ export const FEEDBACK_TOOLS: ReadonlyArray<ToolDefinition> = Object.freeze([
description:
"Optional client key that dedupes retried calls: same key + same payload is a no-op; same key + different payload is rejected.",
},
+ expires: {
+ type: "string",
+ description:
+ "Optional YYYY-MM-DD or ISO-8601 lifetime. Past it the signal (and any force-confirmed preference) drops out of default reads; the file is never deleted.",
+ },
},
required: ["topic", "signal", "principle"],
additionalProperties: false,
@@ -859,19 +1006,19 @@ export const FEEDBACK_TOOLS: ReadonlyArray<ToolDefinition> = Object.freeze([
{
name: "brain_dream",
description:
- "Deterministic learning pass over `Brain/inbox/`. action=run (default) promotes inline; the staged lifecycle persists a reviewable bundle: stage -> validate -> apply (or discard), plus list. Typically scheduled via cron.",
+ "Deterministic learning pass over `Brain/inbox/`. action=run (default) promotes inline; the staged lifecycle persists a reviewable bundle: stage -> validate -> apply (or discard), plus list and retriage. Typically scheduled via cron.",
inputSchema: {
type: "object",
properties: {
action: {
type: "string",
- enum: ["run", "stage", "validate", "apply", "discard", "list"],
+ enum: ["run", "stage", "validate", "apply", "retriage", "discard", "list"],
description:
- "run executes inline; stage persists a proposal bundle; validate/apply/discard manage one bundle by run_id; list shows bundles.",
+ "run executes inline; stage persists a bundle; validate/apply/discard manage one by run_id; retriage re-scores a bundle's salience gate; list shows bundles.",
},
run_id: {
type: "string",
- description: "Bundle id for validate/apply/discard (from action=stage or list).",
+ description: "Bundle id for validate/apply/retriage/discard (from action=stage or list).",
},
dry_run: {
type: "boolean",
@@ -1024,4 +1171,31 @@ export const FEEDBACK_TOOLS: ReadonlyArray<ToolDefinition> = Object.freeze([
},
handler: toolBrainObservedUse,
},
+ {
+ name: EXPIRE_TOOL,
+ description:
+ "Set, change or clear the expiration_date of one signal or preference, by id. An expired memory is filtered out of default reads and never deleted or moved. Clearing is the explicit word 'none'.",
+ inputSchema: {
+ type: "object",
+ properties: {
+ id: {
+ type: "string",
+ description:
+ "Artifact id: sig-<date>-<slug>, pref-<slug> or ret-<slug>. Never a path - this surface does not accept one.",
+ },
+ expires: {
+ type: "string",
+ description: `YYYY-MM-DD, an ISO-8601 timestamp, or '${EXPIRATION_CLEAR}' to clear. An unparseable value is refused before any write.`,
+ },
+ agent: {
+ type: "string",
+ description: "Optional agent identity stamped on the audit event.",
+ },
+ },
+ required: ["id", "expires"],
+ additionalProperties: false,
+ },
+ previewBudget: MCP_PREVIEW_BUDGET,
+ handler: toolBrainExpire,
+ },
]);
diff --git a/src/mcp/brain/lifecycle-file-tools.ts b/src/mcp/brain/lifecycle-file-tools.ts
index 54109971..11dd7e1e 100644
--- a/src/mcp/brain/lifecycle-file-tools.ts
+++ b/src/mcp/brain/lifecycle-file-tools.ts
@@ -89,6 +89,18 @@ function renderResult(res: NoteLifecycleResult): Record<string, unknown> {
next_command: res.references.index.nextCommand,
},
},
+ // `null` when no cascade was asked for, which is a different answer
+ // from a cascade that found nothing. Rendered on every response so a
+ // caller reads the distinction rather than inferring it from an
+ // absent key.
+ cascade:
+ res.cascade === null
+ ? null
+ : {
+ deletion_set: [...res.cascade.deletionSet],
+ reported_files: [...res.cascade.reportedFiles],
+ scanned_scope: res.cascade.scannedScope,
+ },
};
}
@@ -110,6 +122,7 @@ async function toolBrainNoteLifecycle(
const to = coerceStr(args, "to", false) ?? undefined;
const apply = coerceBoolOptional(args, "apply");
const confirm = coerceBoolOptional(args, "confirm");
+ const deleteLinked = coerceBoolOptional(args, "delete_linked");
const { expect, strict } = readCountGuardArgs(args);
try {
@@ -119,6 +132,7 @@ async function toolBrainNoteLifecycle(
...(to !== undefined ? { to } : {}),
...(apply !== undefined ? { apply } : {}),
...(confirm !== undefined ? { confirm } : {}),
+ ...(deleteLinked !== undefined ? { deleteLinked } : {}),
expect,
strict,
});
@@ -328,7 +342,7 @@ export const LIFECYCLE_FILE_TOOLS: ReadonlyArray<ToolDefinition> = Object.freeze
{
name: TOOL,
description:
- "Note-file lifecycle. action: rename changes the filename in place; move changes the directory; archive displaces the note under Archive/ mirroring its path; delete removes it. Dry-run unless apply; delete also needs confirm. Rewrites inbound [[links]] and reports how stale the index is.",
+ "Note-file lifecycle. action: rename renames in place; move changes the directory; archive displaces the note under Archive/; delete removes it, and delete_linked extends that to files whose frontmatter derives them from it alone. Dry-run unless apply; delete needs confirm. Rewrites [[links]].",
inputSchema: {
type: "object",
properties: {
@@ -357,11 +371,16 @@ export const LIFECYCLE_FILE_TOOLS: ReadonlyArray<ToolDefinition> = Object.freeze
description:
"delete: explicit confirmation. Without it an applied delete is refused, because no archive covers a note outside Brain/.",
},
+ delete_linked: {
+ type: "boolean",
+ description:
+ "delete only: also remove Brain files whose frontmatter names this note as their source and traces SOLELY to it. A prose mention is reported, never deleted.",
+ },
expect: {
type: "integer",
minimum: 0,
description:
- "Assert the number of files holding an inbound reference; a mismatch aborts before any write.",
+ "Assert the count before any write: the deletion set under delete_linked, otherwise the files holding an inbound reference. A mismatch aborts.",
},
strict: {
type: "boolean",
diff --git a/src/mcp/brain/procedure-tools.ts b/src/mcp/brain/procedure-tools.ts
index 670617d9..7de69f77 100644
--- a/src/mcp/brain/procedure-tools.ts
+++ b/src/mcp/brain/procedure-tools.ts
@@ -17,7 +17,9 @@ import {
resolveSkillProposalEvidence,
type SkillContractInput,
} from "../../core/brain/skill-proposals.ts";
+import { commitSkillPageDraft, planSkillPageDrafts } from "../../core/brain/skill-page-drafts.ts";
import { deriveSkillUsage } from "../../core/brain/skill-usage.ts";
+import { resolveSkillsDir } from "../../core/config.ts";
import {
listProceduralMemory,
markProceduralMemoryUsed,
@@ -63,12 +65,53 @@ async function toolBrainSkillProposals(
const slug = requiredStringArg("brain_skill_proposals", args, "slug");
const note = optionalStringArg("brain_skill_proposals", args, "note");
const contract = readSkillContract(args);
+ // Resolved from THIS server's config chain: a `mature_page` accept
+ // materializes a SKILL.md into whichever skills root it names, and the
+ // core cannot know which chain the server was started with.
+ const skillsRoot = resolveSkillsDir(ctx.configPath ?? undefined);
const reviewed = acceptSkillProposal(ctx.vault, slug, {
...(note ? { note } : {}),
...(contract ? { contract } : {}),
+ ...(skillsRoot !== null ? { skillsRoot } : {}),
});
return { ...reviewed };
}
+ if (operation === "page_candidates") {
+ // Read-only: which mature vault pages deserve a skill, each with its
+ // own needs-llm-step envelope, plus every page the gate turned down
+ // with the reason it did.
+ const skillsDir = resolveSkillsDir(ctx.configPath ?? undefined);
+ const report = planSkillPageDrafts(ctx.vault, {
+ now: new Date(),
+ ...(ctx.repoRoot ? { repoRoot: ctx.repoRoot } : {}),
+ ...(skillsDir !== null ? { skillsDir } : {}),
+ });
+ return {
+ generated_at: report.generatedAt,
+ pages_scanned: report.pagesScanned,
+ admitted: report.admitted.map((c) => ({
+ path: c.path,
+ title: c.title,
+ tier: c.tier,
+ lifecycle: c.lifecycle,
+ confidence: c.confidence,
+ reuse_score: c.reuseScore,
+ reuse_observations: c.reuseObservations,
+ llm_step: c.llmStep,
+ })),
+ skipped: report.skipped.map((s) => ({
+ path: s.path,
+ title: s.title,
+ reason: s.reason,
+ detail: s.detail,
+ })),
+ };
+ }
+ if (operation === "page_draft") {
+ const page = requiredStringArg("brain_skill_proposals", args, "page");
+ const result = commitSkillPageDraft(ctx.vault, page, args["draft"], { now: new Date() });
+ return { ...result };
+ }
if (operation === "evidence") {
const slug = requiredStringArg("brain_skill_proposals", args, "slug");
return { ...resolveSkillProposalEvidence(ctx.vault, slug) };
@@ -104,7 +147,8 @@ async function toolBrainSkillProposals(
}
throw new MCPError(
INVALID_PARAMS,
- "brain_skill_proposals: operation must be one of learn|list|accept|reject|recover|usage|evidence",
+ "brain_skill_proposals: operation must be one of " +
+ "learn|list|accept|reject|recover|usage|evidence|page_candidates|page_draft",
);
}
@@ -268,13 +312,23 @@ export const PROCEDURE_TOOLS: ReadonlyArray<ToolDefinition> = Object.freeze([
{
name: "brain_skill_proposals",
description:
- "Deterministic skill proposals from continuity records: learn, list, accept, reject; resolve abandoned accept sequences (recover); read per-skill invocation and offer-attribution counts (usage); resolve a proposal's self-reported support against the recorded procedural outcome ledger (evidence).",
+ "Skill proposals: learn, list, accept, reject; recover abandoned accepts; usage counts; evidence against the outcome ledger. page_candidates gates mature vault pages (tier, lifecycle, confidence, reuse; skips ones a skill covers), one envelope each; page_draft stages the returned draft.",
inputSchema: {
type: "object",
properties: {
operation: {
type: "string",
- enum: ["learn", "list", "accept", "reject", "recover", "usage", "evidence"],
+ enum: [
+ "learn",
+ "list",
+ "accept",
+ "reject",
+ "recover",
+ "usage",
+ "evidence",
+ "page_candidates",
+ "page_draft",
+ ],
description: "Tool operation.",
},
discard_unreadable: {
@@ -315,6 +369,35 @@ export const PROCEDURE_TOOLS: ReadonlyArray<ToolDefinition> = Object.freeze([
items: { type: "string" },
description: "accept only: checks that confirm the procedure worked.",
},
+ page: {
+ type: "string",
+ description: "page_draft only: vault-relative path of the page the draft came from.",
+ },
+ draft: {
+ type: "object",
+ description: "page_draft only: the SKILL.md draft written for that page.",
+ properties: {
+ name: {
+ type: "string",
+ description: "Skill directory name: lowercase letters, digits, single hyphens.",
+ },
+ description: {
+ type: "string",
+ description: "One line naming when an agent should reach for this skill.",
+ },
+ triggers: {
+ type: "array",
+ items: { type: "string" },
+ description: "Keywords a matcher scores the skill on; each must be non-empty.",
+ },
+ body: {
+ type: "string",
+ description: "The SKILL.md body: imperative and self-contained.",
+ },
+ },
+ required: ["name", "description", "triggers", "body"],
+ additionalProperties: false,
+ },
},
required: ["operation"],
additionalProperties: false,
diff --git a/tests/cli/brain-capture.test.ts b/tests/cli/brain-capture.test.ts
new file mode 100644
index 00000000..7f88b37b
--- /dev/null
+++ b/tests/cli/brain-capture.test.ts
@@ -0,0 +1,131 @@
+/**
+ * `o2b brain capture` - the operator-facing ingress into the capture
+ * contract (unit 3b / t_5e338af1).
+ *
+ * The defect. `writeCaptureNote` had exactly one caller, the inbound
+ * Telegram bot, so a capture could only enter a vault through a chat
+ * channel that most installs never configure. Everything downstream of it
+ * - the staging area, the drain, `/catchup` - was reachable only through
+ * that one door.
+ *
+ * Claims pinned here:
+ *
+ * 1. The verb writes a real capture note into the staging area, carrying
+ * the source, the sender and the guidance it was given.
+ * 2. The body may arrive as an argument or on stdin; the two produce the
+ * same page.
+ * 3. Guidance reaches the page's `## Guidance` section rather than the
+ * captured body.
+ * 4. A refusal is NAMED and exits 2, on both the human and the `--json`
+ * surface - never a bare stack trace and never exit 0.
+ */
+
+import { afterEach, beforeEach, expect, test } from "bun:test";
+import { existsSync, mkdirSync, mkdtempSync, readFileSync, rmSync } from "node:fs";
+import { tmpdir } from "node:os";
+import { join } from "node:path";
+
+import { bootstrapBrain } from "../../src/core/brain/init.ts";
+import { listStagedCaptures } from "../../src/core/brain/capture/capture-note.ts";
+import { atomicWriteFileSync } from "../../src/core/fs-atomic.ts";
+import { runCli } from "../helpers/run-cli.ts";
+
+let tmp: string;
+let vault: string;
+
+beforeEach(() => {
+ tmp = mkdtempSync(join(tmpdir(), "o2b-cli-capture-"));
+ vault = join(tmp, "vault");
+ mkdirSync(vault, { recursive: true });
+ const configPath = join(tmp, "config.yaml");
+ atomicWriteFileSync(configPath, `vault: ${vault}\n`);
+ bootstrapBrain(vault, { configPath });
+});
+
+afterEach(() => {
+ rmSync(tmp, { recursive: true, force: true });
+});
+
+test("captures a body argument with its source, sender and guidance", async () => {
+ const res = await runCli([
+ "brain",
+ "capture",
+ "read the Rust async book",
+ "--source",
+ "cli",
+ "--sender",
+ "sol",
+ "--guidance",
+ "queue as reading, not a task",
+ "--vault",
+ vault,
+ "--json",
+ ]);
+ expect(res.returncode).toBe(0);
+ const body = JSON.parse(res.stdout) as {
+ id: string;
+ path: string;
+ guidance: string | null;
+ source: string;
+ sender: string;
+ };
+ expect(body.id.startsWith("cap-")).toBe(true);
+ expect(body.source).toBe("cli");
+ expect(body.sender).toBe("sol");
+ expect(body.guidance).toBe("queue as reading, not a task");
+
+ const staged = listStagedCaptures(vault);
+ expect(staged).toHaveLength(1);
+ expect(staged[0]!.body).toBe("read the Rust async book");
+ expect(staged[0]!.guidance).toBe("queue as reading, not a task");
+ // The guidance is a body section, not a frontmatter value.
+ expect(readFileSync(join(vault, body.path), "utf8")).toContain("## Guidance");
+ expect(existsSync(join(vault, body.path))).toBe(true);
+});
+
+test("the body may arrive on stdin instead of as an argument", async () => {
+ const res = await runCli(["brain", "capture", "--source", "cli", "--vault", vault, "--json"], {
+ stdin: "piped from somewhere\n",
+ });
+ expect(res.returncode).toBe(0);
+ const staged = listStagedCaptures(vault);
+ expect(staged).toHaveLength(1);
+ expect(staged[0]!.body).toBe("piped from somewhere");
+});
+
+test("an empty body is refused by name, exit 2, and writes nothing", async () => {
+ const res = await runCli(["brain", "capture", "--source", "cli", "--vault", vault], {
+ stdin: " \n",
+ });
+ expect(res.returncode).toBe(2);
+ expect(res.stderr).toContain("body");
+ expect(listStagedCaptures(vault)).toHaveLength(0);
+});
+
+test("--json carries the refusal too, rather than printing it to stderr alone", async () => {
+ const res = await runCli(["brain", "capture", "--source", "cli", "--vault", vault, "--json"], {
+ stdin: "\n",
+ });
+ expect(res.returncode).toBe(2);
+ const body = JSON.parse(res.stdout) as { ok: boolean; message: string };
+ expect(body.ok).toBe(false);
+ expect(body.message).toContain("body");
+ expect(listStagedCaptures(vault)).toHaveLength(0);
+});
+
+test("blank guidance is refused rather than stored as an empty section", async () => {
+ const res = await runCli([
+ "brain",
+ "capture",
+ "text",
+ "--source",
+ "cli",
+ "--guidance",
+ " ",
+ "--vault",
+ vault,
+ ]);
+ expect(res.returncode).toBe(2);
+ expect(res.stderr).toContain("guidance");
+ expect(listStagedCaptures(vault)).toHaveLength(0);
+});
diff --git a/tests/cli/brain-design-note.test.ts b/tests/cli/brain-design-note.test.ts
new file mode 100644
index 00000000..0da94c25
--- /dev/null
+++ b/tests/cli/brain-design-note.test.ts
@@ -0,0 +1,173 @@
+/**
+ * `o2b brain design-note` and `brain_design_note`
+ * (salience-lifecycle-enrichment, unit 7, t_c87644b4). Claims pinned here:
+ *
+ * 1. The grounding phase's `--json` payload carries the three stores'
+ * matches, their counts, the NAMED empty stores, and one envelope.
+ * 2. The commit phase's `--json` payload names the note and the single
+ * recommended alternative.
+ * 3. A payload that does not recommend exactly one alternative exits 1
+ * with the refusal in `--json`, and writes nothing.
+ * 4. A missing topic is a usage error (exit 2), and the verb has its own
+ * `--help`.
+ * 5. The MCP tool answers over the same core, both phases, and the path
+ * it reports is vault-relative - no MCP response carries the
+ * absolute host path.
+ */
+
+import { afterEach, beforeEach, expect, test } from "bun:test";
+import { existsSync, mkdirSync, mkdtempSync, rmSync, writeFileSync } from "node:fs";
+import { tmpdir } from "node:os";
+import { join } from "node:path";
+
+import { recordDecision } from "../../src/core/brain/decisions/record.ts";
+import { buildToolTable, findTool } from "../../src/mcp/tools.ts";
+import type { ServerContext } from "../../src/mcp/tool-contract.ts";
+import { runCli } from "../helpers/run-cli.ts";
+
+const TOPIC = "vector index storage";
+let tmp: string;
+let vault: string;
+let configPath: string;
+
+function note(...flags: ReadonlyArray<boolean>): Record<string, unknown> {
+ return {
+ title: "Where the vector index lives",
+ alternatives: flags.map((recommended, i) => ({
+ name: `option-${i}`,
+ approach: `Store the index with option-${i}.`,
+ tradeoffs: "Write cost against read latency.",
+ recommended,
+ })),
+ };
+}
+
+function run(args: ReadonlyArray<string>) {
+ return runCli(["brain", "design-note", ...args, "--vault", vault], {
+ env: { OPEN_SECOND_BRAIN_CONFIG: configPath },
+ });
+}
+
+beforeEach(() => {
+ tmp = mkdtempSync(join(tmpdir(), "o2b-cli-design-note-"));
+ vault = join(tmp, "vault");
+ mkdirSync(join(vault, "Brain"), { recursive: true });
+ configPath = join(tmp, "config.yaml");
+ writeFileSync(configPath, `vault: ${vault}\n`);
+ recordDecision(vault, {
+ title: "Vector index storage location",
+ chosen: "Keep the index outside the vault",
+ assumption: "Sync clients must not replicate a binary index",
+ reviewDate: "2027-01-01",
+ agent: "tester",
+ });
+});
+
+afterEach(() => {
+ rmSync(tmp, { recursive: true, force: true });
+});
+
+test("the grounding phase --json carries counts, named empty stores and one envelope", async () => {
+ const r = await run([TOPIC, "--json"]);
+ expect(r.returncode).toBe(0);
+ const payload = JSON.parse(r.stdout) as {
+ ok: boolean;
+ topic: string;
+ target_path: string;
+ grounding: {
+ decisions: Array<{ title: string }>;
+ counts: { tensions: number; decisions: number; truthSlots: number; conflicts: number };
+ empty_stores: string[];
+ };
+ llm_step: { status: string; step: string; target_path: string };
+ };
+ expect(payload.ok).toBe(true);
+ expect(payload.topic).toBe(TOPIC);
+ expect(payload.grounding.decisions.map((d) => d.title)).toEqual([
+ "Vector index storage location",
+ ]);
+ expect(payload.grounding.counts.decisions).toBe(1);
+ // The decision store held something; the other two hold nothing at all
+ // and say so by name.
+ expect(payload.grounding.empty_stores.toSorted()).toEqual(["tensions", "truth"]);
+ expect(payload.llm_step.status).toBe("needs-llm-step");
+ expect(payload.llm_step.step).toBe("design-note");
+ expect(payload.llm_step.target_path).toBe(payload.target_path);
+});
+
+test("the commit phase --json names the note and its one recommendation", async () => {
+ const r = await run([TOPIC, "--payload", JSON.stringify(note(false, true)), "--json"]);
+ expect(r.returncode).toBe(0);
+ const payload = JSON.parse(r.stdout) as {
+ ok: boolean;
+ path: string;
+ recommended: string;
+ alternative_count: number;
+ };
+ expect(payload.ok).toBe(true);
+ expect(payload.recommended).toBe("option-1");
+ expect(payload.alternative_count).toBe(2);
+ expect(existsSync(payload.path)).toBe(true);
+ expect(payload.path).toContain(join("Brain", "decisions"));
+});
+
+test("a payload recommending nothing exits 1, names the count, and writes nothing", async () => {
+ const r = await run([TOPIC, "--payload", JSON.stringify(note(false, false)), "--json"]);
+ expect(r.returncode).toBe(1);
+ const payload = JSON.parse(r.stdout) as { ok: boolean; message: string };
+ expect(payload.ok).toBe(false);
+ expect(payload.message).toContain("exactly one");
+ expect(payload.message).toContain("found 0 of 2");
+});
+
+test("a missing topic is a usage error", async () => {
+ const r = await run([]);
+ expect(r.returncode).toBe(2);
+ expect(r.stderr).toContain("o2b brain design-note");
+});
+
+test("--help prints the verb's own usage", async () => {
+ const r = await runCli(["brain", "design-note", "--help"], {
+ env: { OPEN_SECOND_BRAIN_CONFIG: configPath },
+ });
+ expect(r.returncode).toBe(0);
+ expect(r.stdout.startsWith("usage:")).toBe(true);
+ expect(r.stdout).toContain("o2b brain design-note");
+});
+
+test("the MCP tool answers both phases over the same core", async () => {
+ const ctx: ServerContext = { vault, configPath, repoRoot: null };
+ const tool = findTool(buildToolTable("full"), "brain_design_note");
+
+ const planned = (await tool.handler(ctx, { topic: TOPIC })) as {
+ phase: string;
+ grounding: { empty_stores: string[] };
+ llm_step: { step: string };
+ };
+ expect(planned.phase).toBe("plan");
+ expect(planned.llm_step.step).toBe("design-note");
+ expect(planned.grounding.empty_stores.toSorted()).toEqual(["tensions", "truth"]);
+
+ const committed = (await tool.handler(ctx, { topic: TOPIC, note: note(true) })) as {
+ phase: string;
+ recommended: string;
+ path: string;
+ };
+ expect(committed.phase).toBe("commit");
+ expect(committed.recommended).toBe("option-0");
+ // Vault-relative on the MCP surface, and the response carries the host
+ // path nowhere - an MCP payload lands in model context. The CLI keeps
+ // the absolute path it has always printed; that one runs on the host.
+ expect(committed.path).toMatch(/^Brain[/\\]decisions[/\\]/);
+ expect(existsSync(join(vault, committed.path))).toBe(true);
+ expect(JSON.stringify(committed)).not.toContain(vault);
+
+ await expect(
+ Promise.resolve(tool.handler(ctx, { topic: "another topic", note: note(true, true) })),
+ ).rejects.toThrow("exactly one");
+});
+
+test("is a full-tier tool, absent from the writer surface", () => {
+ expect(buildToolTable("full").find((t) => t.name === "brain_design_note")).toBeDefined();
+ expect(buildToolTable("writer").find((t) => t.name === "brain_design_note")).toBeUndefined();
+});
diff --git a/tests/cli/brain-dream-operator-surface.test.ts b/tests/cli/brain-dream-operator-surface.test.ts
index f712df6f..30285083 100644
--- a/tests/cli/brain-dream-operator-surface.test.ts
+++ b/tests/cli/brain-dream-operator-surface.test.ts
@@ -16,7 +16,12 @@
* - `--gate <name>=<true|false>` steers one run and leaves
* `Brain/_brain.yaml` byte-identical;
* - the same two capabilities exist on MCP `brain_dream`;
- * - with neither flag present the verb is byte-identical to today.
+ * - with neither flag present the verb is byte-identical to today;
+ * - a CONFIGURED salience threshold is named on the human stream -
+ * admitted of considered, and the threshold - so an exclusion is not
+ * invisible to an operator who never passes `--json`. An open gate
+ * adds nothing, which is what keeps the byte-identical claim above
+ * true.
*/
import { afterEach, beforeEach, describe, expect, spyOn, test } from "bun:test";
@@ -25,8 +30,11 @@ import { tmpdir } from "node:os";
import { join } from "node:path";
import { bootstrapBrain } from "../../src/core/brain/init.ts";
+import { writePreference } from "../../src/core/brain/preference.ts";
import { writeSignal } from "../../src/core/brain/signal.ts";
+import { BRAIN_PREFERENCE_STATUS } from "../../src/core/brain/types.ts";
import { DREAM_PHASE } from "../../src/core/brain/dream-phases.ts";
+import { atomicWriteFileSync } from "../../src/core/fs-atomic.ts";
import { JSONRPC_VERSION, MCPServer, PROTOCOL_VERSION } from "../../src/mcp/index.ts";
import { cmdBrainDream } from "../../src/cli/brain/verbs/dream.ts";
import { runCli } from "../helpers/run-cli.ts";
@@ -381,6 +389,54 @@ describe("byte-identical when absent", () => {
});
});
+describe("the salience gate on the human stream", () => {
+ test("a configured threshold is reported; --json is unchanged", async () => {
+ writePreference(vault, {
+ slug: "quiet",
+ topic: "quiet",
+ principle: "Nothing has ever applied this.",
+ created_at: "2026-01-01T00:00:00Z",
+ unconfirmed_until: "2026-01-08T00:00:00Z",
+ confirmed_at: "2026-01-08T00:00:00Z",
+ status: BRAIN_PREFERENCE_STATUS.confirmed,
+ evidenced_by: [],
+ last_evidence_at: "2026-05-29T00:00:00Z",
+ });
+ atomicWriteFileSync(
+ brainConfigPath(),
+ "schema_version: 1\ndream:\n salience_threshold: 0.2\n",
+ );
+
+ const human = await runCli([
+ "brain",
+ "dream",
+ "--dry-run",
+ "--now",
+ "2026-05-30T10:00:00Z",
+ "--vault",
+ vault,
+ ]);
+ expect(human.returncode).toBe(0);
+ // Without this line an exclusion is invisible on this stream: the
+ // ladder simply folds fewer facts and never says why.
+ expect(human.stdout).toContain("salience_gate: 0 of 1 fact(s) admitted (threshold 0.2)");
+
+ const asJson = await runCli([
+ "brain",
+ "dream",
+ "--dry-run",
+ "--now",
+ "2026-05-30T10:00:00Z",
+ "--vault",
+ vault,
+ "--json",
+ ]);
+ const payload = JSON.parse(asJson.stdout) as { salience_gate: { threshold: number } };
+ // The machine stream carried the gate all along and is untouched.
+ expect(payload.salience_gate.threshold).toBe(0.2);
+ });
+});
+
describe("the manifest advertises both flags", () => {
test("help --json models --step and --gate on brain dream", async () => {
const r = await runCli(["help", "--json"]);
diff --git a/tests/cli/brain-dream-retriage.test.ts b/tests/cli/brain-dream-retriage.test.ts
new file mode 100644
index 00000000..b93a1161
--- /dev/null
+++ b/tests/cli/brain-dream-retriage.test.ts
@@ -0,0 +1,275 @@
+/**
+ * `o2b brain dream retriage <run-id>` (salience-lifecycle-enrichment,
+ * unit 1, t_de8a0b2d).
+ *
+ * A staged bundle records the salience partition it was staged with. A
+ * later threshold change silently changes what a re-stage would fold, so
+ * `retriage` is the read-only answer to "what would move": it re-runs the
+ * gate against the CURRENT threshold and reports the delta. It never
+ * touches the bundle - re-staging stays the operator's decision.
+ *
+ * Claims pinned here:
+ * 1. A staged bundle records its salience partition in the manifest,
+ * including the open-gate case (`threshold: null`).
+ * 2. `retriage` after raising the threshold names every fact that
+ * would newly be excluded, with both the staged and the current
+ * score, and leaves the bundle byte-identical.
+ * 3. Lowering the threshold back reports the newly-admitted set with
+ * the same shape.
+ * 4. An unchanged threshold reports `changed: false` and empty deltas.
+ * 5. An unknown bundle is refused by name on both streams, exit 2,
+ * with a `--json` failure shape.
+ * 6. A bundle staged before the gate existed is refused by name rather
+ * than compared against an assumed-open partition.
+ * 7. The action requires a run id, like its validate/apply/discard
+ * siblings.
+ * 8. A manifest whose recorded counts are not numbers is refused by
+ * name, like its threshold and its exclusion list - never coerced
+ * into a NaN that reports a phantom fold-set change.
+ */
+
+import { afterEach, beforeEach, expect, test } from "bun:test";
+import { 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 { appendLogEvent } from "../../src/core/brain/log.ts";
+import { brainConfigPath } from "../../src/core/brain/paths.ts";
+import { writePreference } from "../../src/core/brain/preference.ts";
+import {
+ BRAIN_APPLY_RESULT,
+ BRAIN_LOG_EVENT_KIND,
+ BRAIN_PREFERENCE_STATUS,
+} from "../../src/core/brain/types.ts";
+import { atomicWriteFileSync } from "../../src/core/fs-atomic.ts";
+import { runCli } from "../helpers/run-cli.ts";
+
+const NOW = "2026-06-01T00:00:00Z";
+const LOUD = "loud";
+const QUIET = ["quiet-a", "quiet-b", "quiet-c"] as const;
+
+let tmp: string;
+let vault: string;
+let configPath: string;
+
+beforeEach(() => {
+ tmp = mkdtempSync(join(tmpdir(), "o2b-retriage-"));
+ vault = join(tmp, "vault");
+ configPath = join(tmp, "config.yaml");
+ writeFileSync(configPath, `vault: ${vault}\nagent_name: claude\n`, "utf8");
+ bootstrapBrain(vault, { configPath });
+ setThreshold(null);
+ for (const slug of [LOUD, ...QUIET]) {
+ const loud = slug === LOUD;
+ writePreference(vault, {
+ slug,
+ topic: slug,
+ principle: `principle for ${slug}`,
+ created_at: "2026-01-01T00:00:00Z",
+ unconfirmed_until: "2026-01-08T00:00:00Z",
+ confirmed_at: "2026-01-08T00:00:00Z",
+ status: BRAIN_PREFERENCE_STATUS.confirmed,
+ evidenced_by: [],
+ applied_count: loud ? 8 : 0,
+ violated_count: 0,
+ // Both kinds carry recent evidence dates so the stale-no-evidence
+ // auto-retire never fires; the quiet ones differ only in having no
+ // applied/violated counters and no apply-evidence in the log, which
+ // is exactly what the gate reads.
+ last_evidence_at: "2026-05-30T00:00:00Z",
+ confidence_value: loud ? 0.8 : 0,
+ });
+ }
+ for (const day of ["2026-05-27", "2026-05-28", "2026-05-29", "2026-05-30"]) {
+ appendLogEvent(vault, {
+ timestamp: `${day}T00:00:00Z`,
+ eventType: BRAIN_LOG_EVENT_KIND.applyEvidence,
+ body: {
+ preference: `[[pref-${LOUD}]]`,
+ artifact: "[[src/foo.ts]]",
+ agent: "tester",
+ result: BRAIN_APPLY_RESULT.applied,
+ },
+ });
+ }
+});
+
+afterEach(() => {
+ rmSync(tmp, { recursive: true, force: true });
+});
+
+function setThreshold(threshold: number | null): void {
+ const block = threshold === null ? "" : `dream:\n salience_threshold: ${threshold}\n`;
+ atomicWriteFileSync(brainConfigPath(vault), `schema_version: 1\n${block}`);
+}
+
+async function cli(args: ReadonlyArray<string>): Promise<{
+ stdout: string;
+ stderr: string;
+ returncode: number;
+}> {
+ return runCli([...args, "--vault", vault], { env: { OPEN_SECOND_BRAIN_CONFIG: configPath } });
+}
+
+async function stageBundle(): Promise<string> {
+ const r = await cli(["brain", "dream", "stage", "--now", NOW, "--json"]);
+ expect(r.returncode).toBe(0);
+ return String(JSON.parse(r.stdout)["run_id"]);
+}
+
+function manifestPath(runId: string): string {
+ return join(vault, "Brain", "dream", "staged", runId, "manifest.json");
+}
+
+function manifest(runId: string): Record<string, unknown> {
+ return JSON.parse(readFileSync(manifestPath(runId), "utf8")) as Record<string, unknown>;
+}
+
+test("a staged bundle records its salience partition, open gate included", async () => {
+ const runId = await stageBundle();
+ const salience = manifest(runId)["salience"] as Record<string, unknown>;
+ expect(salience).toBeDefined();
+ expect(salience["threshold"]).toBeNull();
+ expect(salience["considered"]).toBe(4);
+ expect(salience["admitted"]).toBe(4);
+ expect(salience["excluded"]).toEqual([]);
+});
+
+test("raising the threshold names every newly-excluded fact and leaves the bundle alone", async () => {
+ const runId = await stageBundle();
+ const before = readFileSync(manifestPath(runId), "utf8");
+ setThreshold(0.2);
+
+ const r = await cli(["brain", "dream", "retriage", runId, "--now", NOW, "--json"]);
+ expect(r.returncode).toBe(0);
+ const payload = JSON.parse(r.stdout) as Record<string, unknown>;
+ expect(payload["run_id"]).toBe(runId);
+ expect(payload["staged_threshold"]).toBeNull();
+ expect(payload["current_threshold"]).toBe(0.2);
+ expect(payload["changed"]).toBe(true);
+ const newlyExcluded = payload["newly_excluded"] as Array<Record<string, unknown>>;
+ expect(newlyExcluded.map((e) => e["pref_id"])).toEqual(QUIET.map((slug) => `pref-${slug}`));
+ for (const entry of newlyExcluded) {
+ expect(entry["path"]).toBe(`Brain/preferences/${entry["pref_id"]}.md`);
+ expect(entry["score"]).toBe(0);
+ // Nothing was scored at stage time, so there is no staged score to
+ // report - and the field says so rather than inventing a zero.
+ expect(entry["staged_score"]).toBeNull();
+ }
+ expect(payload["newly_admitted"]).toEqual([]);
+ // Read-only: the bundle is exactly as it was staged.
+ expect(readFileSync(manifestPath(runId), "utf8")).toBe(before);
+});
+
+test("lowering the threshold reports the newly-admitted set", async () => {
+ setThreshold(0.2);
+ const runId = await stageBundle();
+ expect((manifest(runId)["salience"] as Record<string, unknown>)["admitted"]).toBe(1);
+ setThreshold(0);
+
+ const r = await cli(["brain", "dream", "retriage", runId, "--now", NOW, "--json"]);
+ expect(r.returncode).toBe(0);
+ const payload = JSON.parse(r.stdout) as Record<string, unknown>;
+ expect(payload["changed"]).toBe(true);
+ const newlyAdmitted = payload["newly_admitted"] as Array<Record<string, unknown>>;
+ expect(newlyAdmitted.map((e) => e["pref_id"])).toEqual(QUIET.map((slug) => `pref-${slug}`));
+ expect(newlyAdmitted[0]!["staged_score"]).toBe(0);
+ expect(payload["newly_excluded"]).toEqual([]);
+});
+
+test("an unchanged threshold reports no delta at all", async () => {
+ setThreshold(0.2);
+ const runId = await stageBundle();
+ const r = await cli(["brain", "dream", "retriage", runId, "--now", NOW, "--json"]);
+ expect(r.returncode).toBe(0);
+ const payload = JSON.parse(r.stdout) as Record<string, unknown>;
+ expect(payload["changed"]).toBe(false);
+ expect(payload["newly_admitted"]).toEqual([]);
+ expect(payload["newly_excluded"]).toEqual([]);
+ expect(payload["staged_threshold"]).toBe(0.2);
+ expect(payload["current_threshold"]).toBe(0.2);
+});
+
+test("the human stream names the delta as well", async () => {
+ const runId = await stageBundle();
+ setThreshold(0.2);
+ const r = await cli(["brain", "dream", "retriage", runId, "--now", NOW]);
+ expect(r.returncode).toBe(0);
+ expect(r.stdout).toContain("newly excluded: 3");
+ for (const slug of QUIET) expect(r.stdout).toContain(`pref-${slug}`);
+});
+
+test("an unknown bundle is refused by name, exit 2, on both streams", async () => {
+ const human = await cli(["brain", "dream", "retriage", "stage-2026-06-01-000000", "--now", NOW]);
+ expect(human.returncode).toBe(2);
+ expect(human.stderr).toContain("stage-2026-06-01-000000");
+
+ const asJson = await cli([
+ "brain",
+ "dream",
+ "retriage",
+ "stage-2026-06-01-000000",
+ "--now",
+ NOW,
+ "--json",
+ ]);
+ expect(asJson.returncode).toBe(2);
+ const payload = JSON.parse(asJson.stdout) as Record<string, unknown>;
+ expect(payload["ok"]).toBe(false);
+ expect(payload["run_id"]).toBe("stage-2026-06-01-000000");
+ expect(String(payload["message"])).toContain("stage-2026-06-01-000000");
+});
+
+test("a bundle staged before the gate existed is refused, never assumed open", async () => {
+ const runId = await stageBundle();
+ const raw = manifest(runId);
+ delete raw["salience"];
+ writeFileSync(manifestPath(runId), JSON.stringify(raw, null, 2) + "\n", "utf8");
+
+ const r = await cli(["brain", "dream", "retriage", runId, "--now", NOW, "--json"]);
+ expect(r.returncode).toBe(2);
+ const payload = JSON.parse(r.stdout) as Record<string, unknown>;
+ expect(payload["ok"]).toBe(false);
+ expect(String(payload["message"])).toMatch(/re-stage/);
+});
+
+test("a non-numeric recorded count is refused by name, never coerced to NaN", async () => {
+ const runId = await stageBundle();
+ const raw = manifest(runId);
+ const salience = raw["salience"] as Record<string, unknown>;
+ salience["considered"] = "four";
+ writeFileSync(manifestPath(runId), JSON.stringify(raw, null, 2) + "\n", "utf8");
+
+ const r = await cli(["brain", "dream", "retriage", runId, "--now", NOW, "--json"]);
+ expect(r.returncode).toBe(2);
+ const payload = JSON.parse(r.stdout) as Record<string, unknown>;
+ expect(payload["ok"]).toBe(false);
+ // Named, and named as the count it is: `Number("four")` is NaN, which
+ // would have passed silently and then reported a fold-set size change
+ // on every retriage of this bundle.
+ expect(String(payload["message"])).toContain("considered");
+});
+
+test("retriage requires a run id, like its validate and apply siblings", async () => {
+ const r = await cli(["brain", "dream", "retriage", "--now", NOW]);
+ expect(r.returncode).toBe(2);
+ expect(r.stderr).toContain("retriage");
+});
+
+test("--step and --gate stay refused on the retriage action", async () => {
+ const runId = await stageBundle();
+ const r = await cli([
+ "brain",
+ "dream",
+ "retriage",
+ runId,
+ "--gate",
+ "heal_enrich=true",
+ "--json",
+ ]);
+ expect(r.returncode).toBe(2);
+ const payload = JSON.parse(r.stdout) as Record<string, unknown>;
+ expect(payload["ok"]).toBe(false);
+ expect(payload["action"]).toBe("retriage");
+});
diff --git a/tests/cli/brain-expiration.test.ts b/tests/cli/brain-expiration.test.ts
new file mode 100644
index 00000000..5aa6c777
--- /dev/null
+++ b/tests/cli/brain-expiration.test.ts
@@ -0,0 +1,184 @@
+/**
+ * The two expiration surfaces on the CLI (unit 3c / t_5e338af1).
+ *
+ * `expiration_date` was writable only from inside the core: `o2b brain
+ * feedback` had no flag for it, and nothing anywhere could change one
+ * after the write. These are the two doors that close that gap, and this
+ * file covers their own share of it - the flags, the exit codes, the
+ * `--json` shapes - while `tests/core/brain/expiration-set.test.ts` owns
+ * the mutation semantics.
+ *
+ * Claims pinned here:
+ *
+ * 1. `feedback --expires` stamps the signal it writes, and the
+ * force-confirmed preference beside it, with the same normalised date.
+ * 2. `expire <id> --expires <date>` sets one after the fact, and
+ * `--expires none` clears it - a word, never an empty string.
+ * 3. An unparseable date is refused by name on both verbs, exits 2, and
+ * writes nothing.
+ * 4. An id naming no artifact is refused by name rather than reported as
+ * a successful no-op.
+ */
+
+import { afterEach, beforeEach, expect, test } from "bun:test";
+import { mkdirSync, mkdtempSync, readFileSync, readdirSync, rmSync } from "node:fs";
+import { tmpdir } from "node:os";
+import { join } from "node:path";
+
+import { bootstrapBrain } from "../../src/core/brain/init.ts";
+import { atomicWriteFileSync } from "../../src/core/fs-atomic.ts";
+import { runCli } from "../helpers/run-cli.ts";
+
+let tmp: string;
+let vault: string;
+
+beforeEach(() => {
+ tmp = mkdtempSync(join(tmpdir(), "o2b-cli-expiration-"));
+ vault = join(tmp, "vault");
+ mkdirSync(vault, { recursive: true });
+ const configPath = join(tmp, "config.yaml");
+ atomicWriteFileSync(configPath, `vault: ${vault}\n`);
+ bootstrapBrain(vault, { configPath });
+});
+
+afterEach(() => {
+ rmSync(tmp, { recursive: true, force: true });
+});
+
+/** Record one signal (optionally force-confirmed) and return its ids. */
+async function feedback(extra: string[]): Promise<{ signalId: string; preferenceId?: string }> {
+ const res = await runCli([
+ "brain",
+ "feedback",
+ "--topic",
+ "staging-endpoint",
+ "--signal",
+ "positive",
+ "--principle",
+ "Use the staging endpoint.",
+ "--vault",
+ vault,
+ "--json",
+ ...extra,
+ ]);
+ expect(res.returncode).toBe(0);
+ const body = JSON.parse(res.stdout) as { signal_id: string; preference_id?: string };
+ return {
+ signalId: body.signal_id,
+ ...(body.preference_id ? { preferenceId: body.preference_id } : {}),
+ };
+}
+
+test("feedback --expires stamps the signal and the force-confirmed preference", async () => {
+ const { signalId, preferenceId } = await feedback([
+ "--expires",
+ "2026-07-15",
+ "--force-confirmed",
+ ]);
+ expect(readFileSync(join(vault, "Brain/inbox", `${signalId}.md`), "utf8")).toContain(
+ "expiration_date: 2026-07-15",
+ );
+ expect(preferenceId).toBeDefined();
+ expect(readFileSync(join(vault, "Brain/preferences", `${preferenceId}.md`), "utf8")).toContain(
+ "expiration_date: 2026-07-15",
+ );
+});
+
+test("feedback refuses an unparseable --expires by name and writes no signal", async () => {
+ const res = await runCli([
+ "brain",
+ "feedback",
+ "--topic",
+ "staging-endpoint",
+ "--signal",
+ "positive",
+ "--principle",
+ "Use the staging endpoint.",
+ "--expires",
+ "next tuesday",
+ "--vault",
+ vault,
+ ]);
+ expect(res.returncode).not.toBe(0);
+ expect(res.stderr).toContain("expiration_date");
+ expect(readdirSync(join(vault, "Brain/inbox")).filter((n) => n.endsWith(".md"))).toHaveLength(0);
+});
+
+test("expire sets, changes and clears an expiration on an existing signal", async () => {
+ const { signalId } = await feedback([]);
+
+ const set = await runCli([
+ "brain",
+ "expire",
+ signalId,
+ "--expires",
+ "2026-07-15",
+ "--vault",
+ vault,
+ "--json",
+ ]);
+ expect(set.returncode).toBe(0);
+ const setBody = JSON.parse(set.stdout) as {
+ ok: boolean;
+ expiration: string | null;
+ previous: string | null;
+ changed: boolean;
+ };
+ expect(setBody.ok).toBe(true);
+ expect(setBody.expiration).toBe("2026-07-15");
+ expect(setBody.previous).toBeNull();
+
+ const cleared = await runCli([
+ "brain",
+ "expire",
+ signalId,
+ "--expires",
+ "none",
+ "--vault",
+ vault,
+ "--json",
+ ]);
+ expect(cleared.returncode).toBe(0);
+ const clearedBody = JSON.parse(cleared.stdout) as {
+ expiration: string | null;
+ previous: string | null;
+ };
+ expect(clearedBody.expiration).toBeNull();
+ expect(clearedBody.previous).toBe("2026-07-15");
+ expect(readFileSync(join(vault, "Brain/inbox", `${signalId}.md`), "utf8")).not.toContain(
+ "expiration_date",
+ );
+});
+
+test("expire refuses a junk date by name and leaves the artifact alone", async () => {
+ const { signalId } = await feedback([]);
+ const before = readFileSync(join(vault, "Brain/inbox", `${signalId}.md`), "utf8");
+ const res = await runCli(["brain", "expire", signalId, "--expires", "soon", "--vault", vault]);
+ expect(res.returncode).toBe(2);
+ expect(res.stderr).toContain("expiration_date");
+ expect(readFileSync(join(vault, "Brain/inbox", `${signalId}.md`), "utf8")).toBe(before);
+});
+
+test("expire on a nonexistent id refuses by name rather than reporting a no-op", async () => {
+ const res = await runCli([
+ "brain",
+ "expire",
+ "pref-nobody-home",
+ "--expires",
+ "2026-07-15",
+ "--vault",
+ vault,
+ "--json",
+ ]);
+ expect(res.returncode).toBe(2);
+ const body = JSON.parse(res.stdout) as { ok: boolean; message: string };
+ expect(body.ok).toBe(false);
+ expect(body.message).toContain("pref-nobody-home");
+});
+
+test("expire without --expires is a usage refusal, not a silent read", async () => {
+ const { signalId } = await feedback([]);
+ const res = await runCli(["brain", "expire", signalId, "--vault", vault]);
+ expect(res.returncode).toBe(2);
+ expect(res.stderr).toContain("--expires");
+});
diff --git a/tests/cli/brain-extract-signals.test.ts b/tests/cli/brain-extract-signals.test.ts
new file mode 100644
index 00000000..3db9a8b0
--- /dev/null
+++ b/tests/cli/brain-extract-signals.test.ts
@@ -0,0 +1,135 @@
+/**
+ * `o2b brain extract-signals` CLI surface (salience-lifecycle-enrichment,
+ * unit 2, t_1dace26d). Claims pinned here:
+ *
+ * 1. The plan phase's `--json` payload carries the mined turns, the two
+ * limits, and exactly one needs-llm-step envelope.
+ * 2. The commit phase's `--json` payload names what it wrote.
+ * 3. A refused payload exits 1 and carries the refusal in `--json` under
+ * `ok: false` - never a stack trace and never a zero exit.
+ * 4. A missing session reference is a usage error (exit 2).
+ * 5. The verb has its own `--help`, not a dump of the whole brain help.
+ */
+
+import { afterEach, beforeEach, expect, test } from "bun:test";
+import { mkdirSync, mkdtempSync, rmSync, writeFileSync } from "node:fs";
+import { tmpdir } from "node:os";
+import { join } from "node:path";
+
+import { AUTO_EXTRACT_PER_SESSION_CAP } from "../../src/core/brain/extract-signals.ts";
+import { importSessionRecall } from "../../src/core/brain/session-recall.ts";
+import { runCli } from "../helpers/run-cli.ts";
+
+const SESSION = "sess-cli";
+let tmp: string;
+let vault: string;
+let configPath: string;
+
+const ITEM = {
+ topic: "heading-style",
+ signal: "positive",
+ principle: "Name the release theme in the heading.",
+ confidence: 0.91,
+};
+
+function run(args: ReadonlyArray<string>) {
+ return runCli(["brain", "extract-signals", ...args, "--vault", vault], {
+ env: { OPEN_SECOND_BRAIN_CONFIG: configPath },
+ });
+}
+
+beforeEach(() => {
+ tmp = mkdtempSync(join(tmpdir(), "o2b-cli-extract-"));
+ vault = join(tmp, "vault");
+ mkdirSync(join(vault, "Brain"), { recursive: true });
+ configPath = join(tmp, "config.yaml");
+ writeFileSync(configPath, `vault: ${vault}\n`);
+ importSessionRecall(vault, {
+ sessionId: SESSION,
+ turns: [
+ {
+ turnId: "t1",
+ timestamp: "2026-08-22T09:01:00Z",
+ role: "user",
+ text: "Always name the release theme in the heading.",
+ },
+ ],
+ createdAt: "2026-08-22T10:00:00Z",
+ });
+});
+
+afterEach(() => {
+ rmSync(tmp, { recursive: true, force: true });
+});
+
+test("the plan phase --json carries the turns, the limits, and one envelope", async () => {
+ const r = await run([SESSION, "--json"]);
+ expect(r.returncode).toBe(0);
+ const payload = JSON.parse(r.stdout) as {
+ ok: boolean;
+ session_id: string;
+ turns_mined: Array<{ turn_id: string; text: string }>;
+ cap: number;
+ confidence_floor: number;
+ llm_step: { status: string; step: string; target_path: string };
+ };
+ expect(payload.ok).toBe(true);
+ expect(payload.session_id).toBe(SESSION);
+ expect(payload.turns_mined.map((t) => t.turn_id)).toEqual(["t1"]);
+ expect(payload.cap).toBe(AUTO_EXTRACT_PER_SESSION_CAP);
+ expect(payload.confidence_floor).toBeGreaterThan(0);
+ expect(payload.llm_step.status).toBe("needs-llm-step");
+ expect(payload.llm_step.target_path).toBe("Brain/inbox");
+});
+
+test("the commit phase --json names what it wrote", async () => {
+ const r = await run([SESSION, "--payload", JSON.stringify({ items: [ITEM] }), "--json"]);
+ expect(r.returncode).toBe(0);
+ const payload = JSON.parse(r.stdout) as {
+ ok: boolean;
+ written: Array<{ id: string; path: string; topic: string }>;
+ staged: number;
+ deduped: number;
+ durability_rejected: number;
+ };
+ expect(payload.ok).toBe(true);
+ expect(payload.written.map((w) => w.topic)).toEqual(["heading-style"]);
+ expect(payload.staged).toBe(0);
+ expect(payload.deduped).toBe(0);
+ expect(payload.durability_rejected).toBe(0);
+});
+
+test("a refused payload exits 1 and names the limit in --json", async () => {
+ const items = Array.from({ length: AUTO_EXTRACT_PER_SESSION_CAP + 1 }, (_v, i) => ({
+ ...ITEM,
+ topic: `topic-${i}`,
+ }));
+ const r = await run([SESSION, "--payload", JSON.stringify({ items }), "--json"]);
+ expect(r.returncode).toBe(1);
+ const payload = JSON.parse(r.stdout) as { ok: boolean; message: string };
+ expect(payload.ok).toBe(false);
+ expect(payload.message).toContain(String(AUTO_EXTRACT_PER_SESSION_CAP));
+});
+
+test("an unimported session is refused by name, not reported as empty", async () => {
+ const r = await run(["sess-nowhere", "--json"]);
+ expect(r.returncode).toBe(1);
+ const payload = JSON.parse(r.stdout) as { ok: boolean; message: string };
+ expect(payload.ok).toBe(false);
+ expect(payload.message).toContain("sess-nowhere");
+});
+
+test("a missing session reference is a usage error", async () => {
+ const r = await run([]);
+ expect(r.returncode).toBe(2);
+ expect(r.stderr).toContain("o2b brain extract-signals");
+});
+
+test("--help prints the verb's own usage", async () => {
+ const r = await runCli(["brain", "extract-signals", "--help"], {
+ env: { OPEN_SECOND_BRAIN_CONFIG: configPath },
+ });
+ expect(r.returncode).toBe(0);
+ expect(r.stdout.startsWith("usage:")).toBe(true);
+ expect(r.stdout).toContain("o2b brain extract-signals");
+});
diff --git a/tests/cli/brain-note-lifecycle-help.test.ts b/tests/cli/brain-note-lifecycle-help.test.ts
index 5b99ead3..f0f57641 100644
--- a/tests/cli/brain-note-lifecycle-help.test.ts
+++ b/tests/cli/brain-note-lifecycle-help.test.ts
@@ -53,7 +53,15 @@ describe("verb help", () => {
describe("the manifest declares the flags the verbs actually accept", () => {
test("note-lifecycle", () => {
const declared = (brainVerb("note-lifecycle")?.flags ?? []).map((f) => f.name).toSorted();
- expect(declared).toEqual(["apply", "config", "confirm", "expect", "strict", "vault"]);
+ expect(declared).toEqual([
+ "apply",
+ "config",
+ "confirm",
+ "delete-linked",
+ "expect",
+ "strict",
+ "vault",
+ ]);
});
test("scaffold-stub", () => {
diff --git a/tests/cli/brain-note-lifecycle.test.ts b/tests/cli/brain-note-lifecycle.test.ts
index 6c9b57b3..963c3569 100644
--- a/tests/cli/brain-note-lifecycle.test.ts
+++ b/tests/cli/brain-note-lifecycle.test.ts
@@ -15,7 +15,7 @@
*/
import { afterEach, beforeEach, 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 { join } from "node:path";
@@ -182,3 +182,70 @@ test("--expect aborts before writing when the inbound count disagrees", async ()
expect(res.stderr).toContain("matched 1");
expect(existsSync(join(vault, "Projects/Old.md"))).toBe(true);
});
+
+test("--delete-linked prints the deletion set and the reported set separately", async () => {
+ note("Imports/Bench.md", "rows\n");
+ note("Projects/Reader.md", "[[Imports/Bench]]\n");
+ mkdirSync(join(vault, "Brain", "inbox"), { recursive: true });
+ writeFileSync(
+ join(vault, "Brain", "inbox", "sig-derived.md"),
+ '---\nid: sig-derived\nkind: brain-signal\nsource:\n - "[[Imports/Bench]]"\n---\n\nbody\n',
+ );
+
+ const dry = await runCli([
+ "brain",
+ "note-lifecycle",
+ "delete",
+ "Imports/Bench.md",
+ "--delete-linked",
+ "--vault",
+ vault,
+ ]);
+ expect(dry.returncode).toBe(0);
+ expect(dry.stdout).toContain("deletion set (2, scope Brain/)");
+ expect(dry.stdout).toContain("Brain/inbox/sig-derived.md");
+ expect(dry.stdout).toContain("reported, not deleted (1)");
+ expect(dry.stdout).toContain("Projects/Reader.md");
+ expect(existsSync(join(vault, "Imports/Bench.md"))).toBe(true);
+
+ const applied = await runCli([
+ "brain",
+ "note-lifecycle",
+ "delete",
+ "Imports/Bench.md",
+ "--delete-linked",
+ "--vault",
+ vault,
+ "--apply",
+ "--confirm",
+ "--expect",
+ "2",
+ "--json",
+ ]);
+ expect(applied.returncode).toBe(0);
+ const body = JSON.parse(applied.stdout) as {
+ cascade: { deletion_set: string[]; reported_files: string[]; scanned_scope: string };
+ };
+ expect(body.cascade.deletion_set).toEqual(["Imports/Bench.md", "Brain/inbox/sig-derived.md"]);
+ expect(existsSync(join(vault, "Brain", "inbox", "sig-derived.md"))).toBe(false);
+ // Reported, therefore untouched - and still naming the note it lost.
+ expect(readFileSync(join(vault, "Projects/Reader.md"), "utf8")).toContain("[[Imports/Bench]]");
+});
+
+test("--delete-linked on a rename is a refusal, not a silently ignored flag", async () => {
+ note("Projects/Old.md", "x\n");
+ const res = await runCli([
+ "brain",
+ "note-lifecycle",
+ "rename",
+ "Projects/Old.md",
+ "Projects/New.md",
+ "--delete-linked",
+ "--vault",
+ vault,
+ "--apply",
+ ]);
+ expect(res.returncode).not.toBe(0);
+ expect(res.stderr).toContain("delete-linked");
+ expect(existsSync(join(vault, "Projects/Old.md"))).toBe(true);
+});
diff --git a/tests/cli/brain-skill-page-drafts.test.ts b/tests/cli/brain-skill-page-drafts.test.ts
new file mode 100644
index 00000000..635f646e
--- /dev/null
+++ b/tests/cli/brain-skill-page-drafts.test.ts
@@ -0,0 +1,146 @@
+/**
+ * `o2b brain skill-proposals page-candidates | page-draft` and the
+ * `brain_skill_proposals` operations behind them
+ * (salience-lifecycle-enrichment, unit 4, t_abaec26b). Claims pinned here:
+ *
+ * 1. `page-candidates --json` carries the admitted pages with one envelope
+ * each and every skip with its reason.
+ * 2. `page-draft --json` stages a pending proposal and says so.
+ * 3. `page-draft` without a payload is a usage error, not a silent no-op.
+ * 4. The MCP tool exposes the same two operations over the same core, and
+ * accept through it materializes the SKILL.md under the configured
+ * skills root.
+ */
+
+import { afterEach, beforeEach, expect, 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 } from "../../src/core/brain/continuity/store.ts";
+import { buildToolTable, findTool } from "../../src/mcp/tools.ts";
+import type { ServerContext } from "../../src/mcp/tool-contract.ts";
+import { runCli } from "../helpers/run-cli.ts";
+
+const PAGE = "notes/release-ritual.md";
+const DRAFT = {
+ name: "release-ritual",
+ description: "Cut a release the way this vault says releases are cut.",
+ triggers: ["release", "tag"],
+ body: "1. Name the theme.\n2. Cut the branch.",
+};
+
+let tmp: string;
+let vault: string;
+let skillsRoot: string;
+let configPath: string;
+
+function run(args: ReadonlyArray<string>) {
+ return runCli(["brain", "skill-proposals", ...args, "--vault", vault], {
+ env: { OPEN_SECOND_BRAIN_CONFIG: configPath },
+ });
+}
+
+beforeEach(() => {
+ tmp = mkdtempSync(join(tmpdir(), "o2b-cli-skill-pages-"));
+ vault = join(tmp, "vault");
+ skillsRoot = join(tmp, "skills");
+ mkdirSync(join(vault, "Brain", "notes"), { recursive: true });
+ mkdirSync(join(vault, "notes"), { recursive: true });
+ mkdirSync(skillsRoot, { recursive: true });
+ configPath = join(tmp, "config.yaml");
+ writeFileSync(configPath, `vault: ${vault}\nskills_dir: ${skillsRoot}\n`);
+ writeFileSync(
+ join(vault, PAGE),
+ [
+ "---",
+ "title: Release ritual",
+ "tier: core",
+ "_lifecycle: verified",
+ "_confidence: high",
+ "created_at: 2026-08-01T00:00:00Z",
+ "---",
+ "",
+ "Name the theme, cut the branch, run the gates.",
+ "",
+ ].join("\n"),
+ );
+ writeFileSync(
+ join(vault, "notes", "scratch.md"),
+ ["---", "title: Scratch", "tier: peripheral", "---", "", "Nothing here.", ""].join("\n"),
+ );
+ appendContinuityRecord(vault, {
+ kind: "recall_observed_use",
+ createdAt: "2026-08-22T10:00:00Z",
+ sourceRefs: [{ id: "reuse:release-ritual" }],
+ payload: {
+ session_id: "sess-reuse",
+ entries: [
+ { path: PAGE, verdict: "USED" },
+ { path: PAGE, verdict: "USED" },
+ ],
+ },
+ });
+});
+
+afterEach(() => {
+ rmSync(tmp, { recursive: true, force: true });
+});
+
+test("page-candidates --json carries admitted envelopes and named skips", async () => {
+ const r = await run(["page-candidates", "--json"]);
+ expect(r.returncode).toBe(0);
+ const payload = JSON.parse(r.stdout) as {
+ pages_scanned: number;
+ admitted: Array<{ path: string; llm_step: { status: string; step: string } }>;
+ skipped: Array<{ path: string; reason: string; detail: string }>;
+ };
+ expect(payload.pages_scanned).toBeGreaterThanOrEqual(2);
+ expect(payload.admitted.map((a) => a.path)).toEqual([PAGE]);
+ expect(payload.admitted[0]!.llm_step.status).toBe("needs-llm-step");
+ expect(payload.admitted[0]!.llm_step.step).toBe("skill-page-draft");
+ const scratch = payload.skipped.find((s) => s.path === "notes/scratch.md");
+ expect(scratch?.reason).toBe("tier_below_core");
+ expect(scratch?.detail.length).toBeGreaterThan(0);
+});
+
+test("page-draft --json stages a pending proposal inside the vault", async () => {
+ const r = await run(["page-draft", PAGE, "--payload", JSON.stringify(DRAFT), "--json"]);
+ expect(r.returncode).toBe(0);
+ const payload = JSON.parse(r.stdout) as { outcome: string; slug: string; path: string };
+ expect(payload.outcome).toBe("created");
+ expect(payload.path.startsWith(join(vault, "Brain"))).toBe(true);
+ expect(existsSync(join(skillsRoot, DRAFT.name, "SKILL.md"))).toBe(false);
+});
+
+test("page-draft without a payload is a usage error", async () => {
+ const r = await run(["page-draft", PAGE]);
+ expect(r.returncode).not.toBe(0);
+ expect(r.stderr).toContain("--payload");
+});
+
+test("the MCP tool plans, drafts, and accepts into the configured skills root", async () => {
+ const ctx: ServerContext = { vault, configPath, repoRoot: null };
+ const tool = findTool(buildToolTable("full"), "brain_skill_proposals");
+
+ const planned = (await tool.handler(ctx, { operation: "page_candidates" })) as {
+ admitted: Array<{ path: string }>;
+ };
+ expect(planned.admitted.map((a) => a.path)).toEqual([PAGE]);
+
+ const drafted = (await tool.handler(ctx, {
+ operation: "page_draft",
+ page: PAGE,
+ draft: DRAFT,
+ })) as { outcome: string; slug: string };
+ expect(drafted.outcome).toBe("created");
+
+ const accepted = (await tool.handler(ctx, {
+ operation: "accept",
+ slug: drafted.slug,
+ })) as { status: string; skillPath?: string };
+ expect(accepted.status).toBe("accepted");
+ const skillFile = join(skillsRoot, DRAFT.name, "SKILL.md");
+ expect(accepted.skillPath).toBe(skillFile);
+ expect(readFileSync(skillFile, "utf8")).toContain(`name: ${DRAFT.name}`);
+});
diff --git a/tests/cli/skill-proposals-recover.test.ts b/tests/cli/skill-proposals-recover.test.ts
index 522bfde7..2a9f2ebf 100644
--- a/tests/cli/skill-proposals-recover.test.ts
+++ b/tests/cli/skill-proposals-recover.test.ts
@@ -75,7 +75,7 @@ describe("o2b brain skill-proposals recover", () => {
phase: "archive",
startedAt: LEARNED_AT.toISOString(),
acceptedExisted: false,
- procedureExisted: false,
+ materializedExisted: false,
});
const r = await runCli(["brain", "skill-proposals", "recover", "--vault", vault]);
diff --git a/tests/core/architecture/expiration-chokepoint.test.ts b/tests/core/architecture/expiration-chokepoint.test.ts
new file mode 100644
index 00000000..6c49716c
--- /dev/null
+++ b/tests/core/architecture/expiration-chokepoint.test.ts
@@ -0,0 +1,131 @@
+/**
+ * One door onto `expiration_date`, measured rather than described.
+ *
+ * `expiration.ts` states the bargain in its own header: the READ side
+ * fails open on a value it cannot parse, so a hand-corrupted date
+ * surfaces rather than silently hiding a memory. That tolerance is only
+ * safe while every WRITE is validated. A second writer stamping the field
+ * without {@link normalizeExpirationDate} would turn a documented
+ * fail-open into a memory that never expires and nobody notices - and it
+ * would do so silently, which is exactly the shape a census exists for.
+ *
+ * The population is syntactic and the rule is one line: a module under
+ * `src/` that STAMPS the expiration field into a frontmatter map must
+ * also name the validator. Two narrowings are stated rather than hidden.
+ * First, this does not prove the two are on the same code path - nothing
+ * syntactic can - so what it guarantees is that a new writer cannot land
+ * without the validator being in front of the author's eyes. Second, a
+ * bare `expiration_date:` object key counts only in a module that also
+ * composes a page: on its own that spelling is how a READ surface
+ * projects a value it parsed, and how a caller builds the writer input
+ * the writer then validates, so counting it everywhere would report those
+ * as bypasses.
+ *
+ * Claims pinned here:
+ *
+ * 1. Every module assigning `expiration_date` imports and calls
+ * `normalizeExpirationDate`.
+ * 2. The census is not vacuous: the writers it knows about are actually
+ * found by the detector.
+ */
+
+import { describe, expect, test } from "bun:test";
+import { readdirSync, readFileSync } from "node:fs";
+import { join, relative } from "node:path";
+
+import { EXPIRATION_DATE_FIELD } from "../../../src/core/brain/expiration.ts";
+import { lexSource } from "../../helpers/source-lexer.ts";
+
+const REPO_ROOT = join(import.meta.dir, "..", "..", "..");
+const SRC_ROOT = join(REPO_ROOT, "src");
+
+/** The one validator every write must pass through. */
+const CHOKEPOINT = "normalizeExpirationDate";
+
+/** Every TypeScript module extension the runtime will load and run. */
+const MODULE_EXTENSIONS: ReadonlyArray<string> = Object.freeze([".ts", ".mts", ".cts", ".tsx"]);
+
+/**
+ * The writers this census expects to find, so a detector that stopped
+ * matching fails loudly instead of sweeping an empty set clean.
+ */
+const KNOWN_WRITERS: ReadonlyArray<string> = Object.freeze([
+ "src/core/brain/signal.ts",
+ "src/core/brain/preference.ts",
+ "src/core/brain/expiration-set.ts",
+]);
+
+interface Module {
+ readonly path: string;
+ /** Comments and string bodies blanked, offsets preserved. */
+ readonly code: string;
+}
+
+function readSrcTree(): Module[] {
+ const files: Module[] = [];
+ const walk = (dir: string): void => {
+ for (const entry of readdirSync(dir, { withFileTypes: true })) {
+ const abs = join(dir, entry.name);
+ if (entry.isDirectory()) walk(abs);
+ else if (MODULE_EXTENSIONS.some((ext) => entry.name.endsWith(ext))) {
+ files.push({
+ path: relative(REPO_ROOT, abs).split("\\").join("/"),
+ code: lexSource(readFileSync(abs, "utf8")).code,
+ });
+ }
+ }
+ };
+ walk(SRC_ROOT);
+ return files.toSorted((a, b) => (a.path < b.path ? -1 : a.path > b.path ? 1 : 0));
+}
+
+/**
+ * Stamping the field INTO a frontmatter map: the computed-member form,
+ * through the exported constant or through the literal key. This is the
+ * shape all three shipped writers use, and it is deliberately narrower
+ * than "mentions the field".
+ */
+const STAMP_RE = new RegExp(
+ String.raw`\[\s*(?:EXPIRATION_DATE_FIELD|["']${EXPIRATION_DATE_FIELD}["'])\s*\]\s*=[^=]`,
+);
+
+/**
+ * The object-literal spelling, `{ expiration_date: value }`.
+ *
+ * On its own this is ambiguous and mostly innocent: it is how a READ
+ * surface projects a value it just parsed (`query-tools.ts` does exactly
+ * that), and how a caller builds the writer INPUT that the writer then
+ * validates. It counts as a write only in a module that also composes a
+ * page - which is the case this census is about, and stating the
+ * narrowing is the difference between a measurement and a claim.
+ */
+const LITERAL_KEY_RE = new RegExp(String.raw`\b${EXPIRATION_DATE_FIELD}\s*:`);
+
+/** The writers that put a frontmatter map on disk. */
+const PAGE_WRITERS: ReadonlyArray<string> = Object.freeze([
+ "writeFrontmatterAtomic",
+ "writeFrontmatter",
+ "formatFrontmatter",
+]);
+
+const MODULES = readSrcTree();
+const WRITERS = MODULES.filter(
+ (m) =>
+ STAMP_RE.test(m.code) ||
+ (LITERAL_KEY_RE.test(m.code) && PAGE_WRITERS.some((call) => m.code.includes(`${call}(`))),
+);
+
+describe("the expiration chokepoint", () => {
+ test("every module that assigns expiration_date names the validator", () => {
+ const bypassing = WRITERS.filter((m) => !m.code.includes(CHOKEPOINT)).map((m) => m.path);
+ // Named, not counted: the failure has to say which file.
+ expect(bypassing).toEqual([]);
+ });
+
+ test("the census is not vacuous", () => {
+ const found = new Set(WRITERS.map((m) => m.path));
+ const missing = KNOWN_WRITERS.filter((path) => !found.has(path));
+ expect(missing).toEqual([]);
+ expect(MODULES.length).toBeGreaterThan(200);
+ });
+});
diff --git a/tests/core/architecture/write-site-census.test.ts b/tests/core/architecture/write-site-census.test.ts
index 3aba98e9..ea9c593f 100644
--- a/tests/core/architecture/write-site-census.test.ts
+++ b/tests/core/architecture/write-site-census.test.ts
@@ -899,11 +899,15 @@ const DIRECT_WRITE_EXCLUSIONS: Readonly<Record<string, WriteExclusion>> = Object
// --- Mixed: an accept protocol that moves, appends and rolls back ------
"src/core/brain/skill-proposals.ts": {
categories: [C.appendOnlyLedger, C.lifecycleMove, C.retentionDelete],
- calls: ["appendFileSync", "rmSync", "unlinkSync"],
+ calls: ["appendFileSync", "rmSync", "rmdirSync", "unlinkSync"],
reason:
"appends one JSON line per verifier rejection; unlinks the pending proposal only " +
"after the accepted copy landed through `writeFrontmatterAtomic`; and removes " +
- "the accepted copy and its procedure when a journalled accept is rolled back.",
+ "the accepted copy and the artifact it materialised when a journalled accept is " +
+ "rolled back. The `rmdirSync` is part of that rollback: a `mature_page` accept " +
+ "creates a skill directory to hold its SKILL.md, and `rmdirSync` refuses a " +
+ "non-empty directory, so the empty shell goes and a directory holding anything " +
+ "else stays.",
},
});
@@ -1086,8 +1090,17 @@ const DIRECT_WRITE_ROWS = 68;
* migration manifest through the same helper. The shared class is the
* half of this census that needs no exclusion, so a module arriving here
* is the outcome the record wants.
+ *
+ * 97 -> 98: `src/core/brain/expiration-set.ts`, the post-creation
+ * expiration mutation, rewrites a signal's or preference's frontmatter
+ * through `writeFrontmatterAtomic` - a new module in the shared class,
+ * which is where a new writer belongs.
+ *
+ * 98 -> 99: `src/core/brain/design-note.ts` commits its note through
+ * `writeFrontmatterAtomic`, exclusively, so it needs no exclusion either -
+ * it arrives in the class the record wants modules to arrive in.
*/
-const SHARED_HELPER_ROWS = 97;
+const SHARED_HELPER_ROWS = 99;
describe("in-vault write-site census", () => {
test("every direct-fs write site carries a written exclusion", () => {
diff --git a/tests/core/brain.sessions.import.test.ts b/tests/core/brain.sessions.import.test.ts
index 2825893e..7ea88a77 100644
--- a/tests/core/brain.sessions.import.test.ts
+++ b/tests/core/brain.sessions.import.test.ts
@@ -365,3 +365,41 @@ describe("per-skill invocation telemetry", () => {
expect(usage.find((u) => u.skill === "release")!.invocationCount).toBe(2);
});
});
+
+/**
+ * The new model-mining lane (salience-lifecycle-enrichment, unit 2) added a
+ * `source_type` member and a second way to turn a session into signals.
+ * `import-session` is not that lane and must not have moved: it still
+ * stamps `session`, and re-running it over the same log produces the same
+ * bytes on disk, which is what "byte-identical" has to mean for a test that
+ * cannot reach the previous release.
+ */
+describe("import-session is untouched by the model-mining lane", () => {
+ function inboxBytes(): ReadonlyArray<readonly [string, string]> {
+ const dir = brainDirs(tmp).inbox;
+ return readdirSync(dir)
+ .filter((name) => name.endsWith(".md"))
+ .toSorted()
+ .map((name) => [name, readFileSync(join(dir, name), "utf8")] as const);
+ }
+
+ test("every imported signal is stamped `session`, never `auto_extract`", async () => {
+ await importSession(tmp, CLAUDE, { agent: "test" });
+ const files = inboxBytes();
+ expect(files.length).toBeGreaterThan(0);
+ for (const [name, body] of files) {
+ expect(`${name} stamps session: ${body.includes("source_type: session")}`).toBe(
+ `${name} stamps session: true`,
+ );
+ expect(body).not.toContain("auto_extract");
+ }
+ });
+
+ test("a second import over the same log leaves the inbox bytes unchanged", async () => {
+ const now = new Date("2026-08-22T10:00:00Z");
+ await importSession(tmp, CLAUDE, { agent: "test", now });
+ const before = inboxBytes();
+ await importSession(tmp, CLAUDE, { agent: "test", now });
+ expect(inboxBytes()).toEqual(before);
+ });
+});
diff --git a/tests/core/brain.types.test.ts b/tests/core/brain.types.test.ts
index 3a1faca5..26a506f0 100644
--- a/tests/core/brain.types.test.ts
+++ b/tests/core/brain.types.test.ts
@@ -131,6 +131,9 @@ describe("BRAIN_* const enums", () => {
// silence-is-not-an-answer U7 (t_9d2a5f11) recovery point created β€”
// the counterpart `rollback` has had since it shipped
"snapshot",
+ // salience-lifecycle-enrichment unit 3c (t_5e338af1) expiration set,
+ // changed or explicitly cleared after the artifact was written
+ "expiration-set",
]);
const actual = new Set<string>(Object.values(BRAIN_LOG_EVENT_KIND));
expect(actual).toEqual(expected);
diff --git a/tests/core/brain/architect-codegraph-region.test.ts b/tests/core/brain/architect-codegraph-region.test.ts
new file mode 100644
index 00000000..0e2d083c
--- /dev/null
+++ b/tests/core/brain/architect-codegraph-region.test.ts
@@ -0,0 +1,234 @@
+/**
+ * The architect overview's codegraph verdict region
+ * (salience-lifecycle-enrichment, unit 5 / t_3a418d07).
+ *
+ * Claims pinned here:
+ * 1. An `indexed` partner report renders a `graph-present` line carrying
+ * the node, file and edge counts plus the health verdict.
+ * 2. Each of the four non-indexed states renders `graph-absent,
+ * lexical-only` and names its OWN state and reason - the four are not
+ * collapsed into one "no graph" sentence, because their remediations
+ * differ (`codegraph init` is the wrong advice for `error`).
+ * 3. Health warnings are listed by code, so a present-but-unhealthy
+ * graph cannot be read as a clean one.
+ * 4. The region body is a self-describing provenance stamp: state,
+ * counts and health are all in it, so a stale region says what it was
+ * stamped from.
+ * 5. Operator prose outside the regions survives a regeneration that
+ * moves the verdict - the declared byte-identity exception is scoped
+ * to the region, not to the note.
+ * 6. A fixed report renders byte-identically on re-run.
+ * 7. The region draws on the EXISTING partner report only: the generator
+ * asks for the project it is documenting (one candidate, no wider
+ * scan) and adds no partner CLI vocabulary of its own.
+ */
+
+import { afterEach, beforeEach, 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 { generateArchDocs } from "../../../src/core/brain/architect/generate.ts";
+import type {
+ CodegraphReport,
+ CodegraphReportOptions,
+} from "../../../src/core/partner/codegraph-report.ts";
+
+let tmp: string;
+let project: string;
+let vault: string;
+
+const CLI_PATH = "/usr/local/bin/codegraph";
+
+function reportWith(index: CodegraphReport["index"], cliPath: string | null = CLI_PATH) {
+ return (): CodegraphReport => ({
+ schema_version: 1,
+ project: "/repos/demo-app",
+ cli: { available: cliPath !== null, path: cliPath },
+ index,
+ cargo_workspace: null,
+ cargo_workspace_reason: "no Cargo.toml in project root (not a Rust project)",
+ });
+}
+
+/** The overview text produced with `report` as the partner verdict. */
+function overviewWith(report: () => CodegraphReport, into = vault): string {
+ const res = generateArchDocs(into, project, { codegraphReport: report });
+ return readFileSync(res.overviewPath, "utf8");
+}
+
+/** The body of one sentinel region, without its sentinel lines. */
+function regionBody(text: string, id: string): string {
+ const begin = `<!-- o2b:begin ${id} -->\n`;
+ const end = `\n<!-- o2b:end ${id} -->`;
+ const from = text.indexOf(begin);
+ expect(from).toBeGreaterThanOrEqual(0);
+ const to = text.indexOf(end, from);
+ expect(to).toBeGreaterThan(from);
+ return text.slice(from + begin.length, to);
+}
+
+function freshVault(name: string): string {
+ const made = join(tmp, name);
+ mkdirSync(join(made, "Brain"), { recursive: true });
+ return made;
+}
+
+beforeEach(() => {
+ tmp = mkdtempSync(join(tmpdir(), "o2b-architect-codegraph-"));
+ project = join(tmp, "demo-app");
+ mkdirSync(join(project, "src", "core"), { recursive: true });
+ writeFileSync(join(project, "package.json"), JSON.stringify({ name: "demo-app" }));
+ writeFileSync(join(project, "src", "core", "engine.ts"), "// x\n");
+ vault = freshVault("vault");
+});
+
+afterEach(() => {
+ rmSync(tmp, { recursive: true, force: true });
+});
+
+test("an indexed partner report stamps graph-present with counts and health", () => {
+ const body = regionBody(
+ overviewWith(
+ reportWith({
+ state: "indexed",
+ node_count: 1240,
+ file_count: 210,
+ edge_count: 5680,
+ health: { ok: true, warnings: [] },
+ }),
+ ),
+ "codegraph",
+ );
+
+ expect(body).toContain("graph-present");
+ expect(body).not.toContain("graph-absent");
+ expect(body).toContain("State: indexed");
+ expect(body).toContain("Nodes: 1240");
+ expect(body).toContain("Files: 210");
+ expect(body).toContain("Edges: 5680");
+ expect(body).toContain("Health: ok");
+ expect(body).toContain(CLI_PATH);
+});
+
+test("an unhealthy but present graph names every finding by code", () => {
+ const body = regionBody(
+ overviewWith(
+ reportWith({
+ state: "indexed",
+ node_count: 12,
+ file_count: 3,
+ edge_count: 0,
+ health: {
+ ok: false,
+ warnings: [
+ { code: "collapsed-edges", message: "graph has 12 node(s) but 0 edges" },
+ { code: "self-loops", message: "1 self-loop edge(s)" },
+ ],
+ },
+ }),
+ ),
+ "codegraph",
+ );
+
+ expect(body).toContain("graph-present");
+ expect(body).toContain("Health: 2 warning(s) [collapsed-edges, self-loops]");
+ expect(body).toContain("- collapsed-edges: graph has 12 node(s) but 0 edges");
+ expect(body).toContain("- self-loops: 1 self-loop edge(s)");
+});
+
+/**
+ * The four states that are NOT a graph. Each keeps its own name and its
+ * own reason: `not_indexed` sends the operator to `codegraph init`,
+ * `error` deliberately must not.
+ */
+const ABSENT_STATES = [
+ { state: "no_project", reason: "no code project in scope" },
+ { state: "absent", reason: "codegraph CLI not on PATH (optional partner)" },
+ { state: "not_indexed", reason: "run: codegraph init /repos/demo-app" },
+ { state: "error", reason: "codegraph status did not answer within 5000ms and was stopped" },
+] as const;
+
+for (const { state, reason } of ABSENT_STATES) {
+ test(`the ${state} state renders graph-absent and names itself`, () => {
+ const body = regionBody(
+ overviewWith(reportWith({ state, reason }, state === "absent" ? null : CLI_PATH)),
+ "codegraph",
+ );
+
+ expect(body).toContain("graph-absent, lexical-only");
+ expect(body).not.toContain("graph-present");
+ expect(body).toContain(`State: ${state}`);
+ expect(body).toContain(`Reason: ${reason}`);
+ });
+}
+
+test("the four absent states render four distinct bodies", () => {
+ const bodies = ABSENT_STATES.map(({ state, reason }) =>
+ regionBody(
+ overviewWith(reportWith({ state, reason }), freshVault(`vault-${state}`)),
+ "codegraph",
+ ),
+ );
+ expect(new Set(bodies).size).toBe(ABSENT_STATES.length);
+});
+
+test("operator prose outside the regions survives a moving verdict", () => {
+ const indexed = reportWith({
+ state: "indexed",
+ node_count: 5,
+ file_count: 2,
+ edge_count: 7,
+ health: { ok: true, warnings: [] },
+ });
+ const first = generateArchDocs(vault, project, { codegraphReport: indexed });
+ const prose = "\nOperator: the graph verdict is advisory, the scan is not.\n";
+ writeFileSync(first.overviewPath, readFileSync(first.overviewPath, "utf8") + prose);
+
+ const second = generateArchDocs(vault, project, {
+ codegraphReport: reportWith({ state: "absent", reason: "partner uninstalled" }, null),
+ });
+ const after = readFileSync(second.overviewPath, "utf8");
+
+ expect(after).toContain("Operator: the graph verdict is advisory, the scan is not.");
+ expect(after).toContain("graph-absent, lexical-only");
+ expect(second.updated).toBe(1);
+ // Only the verdict region moved: every other region is byte-identical.
+ const before = readFileSync(first.overviewPath, "utf8");
+ for (const id of ["summary", "modules", "entry-points", "dependencies"]) {
+ expect(regionBody(after, id)).toBe(regionBody(before, id));
+ }
+});
+
+test("a fixed report regenerates the overview byte-identically", () => {
+ const report = reportWith({
+ state: "indexed",
+ node_count: 5,
+ file_count: 2,
+ edge_count: 7,
+ health: { ok: true, warnings: [] },
+ });
+ const first = generateArchDocs(vault, project, { codegraphReport: report });
+ const before = readFileSync(first.overviewPath, "utf8");
+ const second = generateArchDocs(vault, project, { codegraphReport: report });
+
+ expect(readFileSync(second.overviewPath, "utf8")).toBe(before);
+ expect(second.created).toBe(0);
+ expect(second.updated).toBe(0);
+});
+
+test("the verdict is asked for the documented project, with no wider scan", () => {
+ const asked: CodegraphReportOptions[] = [];
+ generateArchDocs(vault, project, {
+ codegraphReport: (options) => {
+ asked.push(options);
+ return reportWith({ state: "no_project", reason: "no code project in scope" })();
+ },
+ });
+
+ expect(asked).toHaveLength(1);
+ expect(asked[0]!.cwd).toBe(project);
+ expect(asked[0]!.vault).toBe(vault);
+ // One candidate directory inspected: the project this overview is about.
+ expect(asked[0]!.limit).toBe(1);
+});
diff --git a/tests/core/brain/architect-concurrent-runs.test.ts b/tests/core/brain/architect-concurrent-runs.test.ts
index 756edfb8..f7bf8d09 100644
--- a/tests/core/brain/architect-concurrent-runs.test.ts
+++ b/tests/core/brain/architect-concurrent-runs.test.ts
@@ -40,8 +40,8 @@ import { repoKey } from "../../../src/core/brain/git/identity.ts";
/** Enough notes that one run's write loop outlasts another run's plan. */
const MODULES = 40;
const FILES_PER_MODULE = 3;
-/** One overview plus one note per module. */
-const NOTE_COUNT = MODULES + 1;
+/** The overview, the key-decisions note, and one note per module. */
+const NOTE_COUNT = MODULES + 2;
const RUNNERS = 3;
const SPAWN_TIMEOUT_MS = 60_000;
@@ -176,7 +176,9 @@ describe("concurrent architect runs on one repo", () => {
expect(first.created).toBe(NOTE_COUNT);
// One module gains a file and a new module appears: overview.md and
- // m00.md change, znew.md is new, the other 39 notes are already right.
+ // m00.md change, znew.md is new, and the other 40 notes - the 39
+ // untouched modules plus the key-decisions note, whose candidate set
+ // did not move - are already right.
writeFileSync(join(project, "src", "m00", "extra.ts"), "// extra\n", "utf8");
mkdirSync(join(project, "src", "znew"), { recursive: true });
writeFileSync(join(project, "src", "znew", "a.ts"), "// new\n", "utf8");
diff --git a/tests/core/brain/architect-decisions-note.test.ts b/tests/core/brain/architect-decisions-note.test.ts
new file mode 100644
index 00000000..b11a0ffd
--- /dev/null
+++ b/tests/core/brain/architect-decisions-note.test.ts
@@ -0,0 +1,237 @@
+/**
+ * The architect key-decisions note
+ * (salience-lifecycle-enrichment, unit 6 / t_041c571f).
+ *
+ * Claims pinned here:
+ * 1. Every architect run plans a key-decisions note beside the overview,
+ * with its own frontmatter kind, and counts it in the run tally.
+ * 2. The note lists the repo's ADR candidates - title, sha, and the
+ * matched signals - from `Brain/decisions/candidates/`.
+ * 3. Candidates stamped with another `repo_key` are filtered out. The
+ * candidate store is vault-global; the note is repo-scoped.
+ * 4. A repo with no candidates gets an explicit empty-state line, not a
+ * missing note and not an empty region.
+ * 5. Entries are ordered codepoint-stably, so the note does not shuffle
+ * between runs or between hosts.
+ * 6. A candidate whose frontmatter carries no sha is listed and says so.
+ * A malformed draft is reported, never silently dropped.
+ * 7. Unchanged project AND unchanged vault regenerate byte-identically;
+ * a new candidate moves the decisions note and nothing else. That is
+ * the declared byte-identity exception, scoped.
+ */
+
+import { afterEach, beforeEach, 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 { generateArchDocs } from "../../../src/core/brain/architect/generate.ts";
+
+let tmp: string;
+let project: string;
+let vault: string;
+let candidates: string;
+
+function seed(relPath: string, content = "// x\n"): void {
+ const abs = join(project, relPath);
+ mkdirSync(join(abs, ".."), { recursive: true });
+ writeFileSync(abs, content);
+}
+
+interface CandidateSeed {
+ readonly file: string;
+ readonly repoKey: string;
+ readonly sha?: string;
+ readonly signals?: ReadonlyArray<string>;
+ readonly title: string;
+}
+
+function seedCandidate(seedInput: CandidateSeed): void {
+ mkdirSync(candidates, { recursive: true });
+ const lines = [
+ "---",
+ "kind: adr-candidate",
+ "status: candidate",
+ `repo_key: ${seedInput.repoKey}`,
+ ...(seedInput.sha === undefined ? [] : [`sha: ${seedInput.sha}`]),
+ `signals: [${(seedInput.signals ?? ["conventional_breaking"]).join(", ")}]`,
+ "---",
+ "",
+ `# ADR candidate: ${seedInput.title}`,
+ "",
+ "## Decision",
+ "",
+ "Draft pending operator review.",
+ "",
+ ];
+ writeFileSync(join(candidates, seedInput.file), lines.join("\n"));
+}
+
+/** The body of one sentinel region, without its sentinel lines. */
+function regionBody(text: string, id: string): string {
+ const begin = `<!-- o2b:begin ${id} -->\n`;
+ const end = `\n<!-- o2b:end ${id} -->`;
+ const from = text.indexOf(begin);
+ expect(from).toBeGreaterThanOrEqual(0);
+ const to = text.indexOf(end, from);
+ expect(to).toBeGreaterThan(from);
+ return text.slice(from + begin.length, to);
+}
+
+beforeEach(() => {
+ tmp = mkdtempSync(join(tmpdir(), "o2b-architect-decisions-"));
+ project = join(tmp, "demo-app");
+ mkdirSync(project, { recursive: true });
+ writeFileSync(join(project, "package.json"), JSON.stringify({ name: "demo-app" }));
+ seed("src/core/engine.ts");
+ vault = join(tmp, "vault");
+ mkdirSync(join(vault, "Brain"), { recursive: true });
+ candidates = join(vault, "Brain", "decisions", "candidates");
+});
+
+afterEach(() => {
+ rmSync(tmp, { recursive: true, force: true });
+});
+
+test("a run plans a key-decisions note beside the overview", () => {
+ const res = generateArchDocs(vault, project);
+
+ expect(res.decisionsPath).toBe(join(res.dir, "decisions.md"));
+ const note = readFileSync(res.decisionsPath, "utf8");
+ expect(note).toContain("kind: arch-decisions");
+ expect(note).toContain(`repo_key: ${res.repoKey}`);
+ expect(note).toContain("<!-- o2b:begin decisions -->");
+ // Overview + decisions + one module.
+ expect(res.created).toBe(3);
+});
+
+test("a repo with no candidates gets an explicit empty-state line", () => {
+ const res = generateArchDocs(vault, project);
+ const body = regionBody(readFileSync(res.decisionsPath, "utf8"), "decisions");
+
+ expect(body).toContain("No decision candidates recorded for this repository.");
+});
+
+test("candidates for this repo are listed with title, sha and signals", () => {
+ const key = generateArchDocs(vault, project).repoKey;
+ seedCandidate({
+ file: "adr-abc123def456-migrate-to-jsonl-store.md",
+ repoKey: key,
+ sha: "abc123def456789",
+ signals: ["conventional_breaking", "breaking_change_footer"],
+ title: "migrate to jsonl store",
+ });
+
+ const res = generateArchDocs(vault, project);
+ const body = regionBody(readFileSync(res.decisionsPath, "utf8"), "decisions");
+
+ expect(body).toContain("ADR candidate: migrate to jsonl store");
+ expect(body).toContain("abc123def456789");
+ expect(body).toContain("conventional_breaking, breaking_change_footer");
+ expect(body).toContain("Brain/decisions/candidates/adr-abc123def456-migrate-to-jsonl-store");
+ expect(body).not.toContain("No decision candidates recorded");
+});
+
+test("a candidate stamped with another repo_key is not listed", () => {
+ const key = generateArchDocs(vault, project).repoKey;
+ seedCandidate({
+ file: "adr-000000000001-ours.md",
+ repoKey: key,
+ sha: "000000000001",
+ title: "ours",
+ });
+ seedCandidate({
+ file: "adr-000000000002-theirs.md",
+ repoKey: "some-other-repo-deadbeef",
+ sha: "000000000002",
+ title: "theirs",
+ });
+
+ const res = generateArchDocs(vault, project);
+ const body = regionBody(readFileSync(res.decisionsPath, "utf8"), "decisions");
+
+ expect(body).toContain("ours");
+ expect(body).not.toContain("theirs");
+});
+
+test("entries are ordered codepoint-stably", () => {
+ const key = generateArchDocs(vault, project).repoKey;
+ for (const [file, title] of [
+ ["adr-000000000003-charlie.md", "charlie"],
+ ["adr-000000000001-alpha.md", "alpha"],
+ ["adr-000000000002-Bravo.md", "Bravo"],
+ ] as const) {
+ seedCandidate({ file, repoKey: key, sha: file.slice(4, 16), title });
+ }
+
+ const res = generateArchDocs(vault, project);
+ const body = regionBody(readFileSync(res.decisionsPath, "utf8"), "decisions");
+ const order = body
+ .split("\n")
+ .filter((line) => line.startsWith("- "))
+ .map((line) => line.slice(line.lastIndexOf("|") + 1, line.indexOf("]]")));
+
+ expect(order).toEqual(["ADR candidate: alpha", "ADR candidate: Bravo", "ADR candidate: charlie"]);
+});
+
+test("a candidate with no recorded sha is listed and says so", () => {
+ const key = generateArchDocs(vault, project).repoKey;
+ seedCandidate({ file: "adr-nosha-orphan.md", repoKey: key, title: "orphan draft" });
+
+ const res = generateArchDocs(vault, project);
+ const body = regionBody(readFileSync(res.decisionsPath, "utf8"), "decisions");
+
+ expect(body).toContain("orphan draft");
+ expect(body).toContain("sha unrecorded");
+});
+
+test("an unchanged project and an unchanged vault regenerate byte-identically", () => {
+ const key = generateArchDocs(vault, project).repoKey;
+ seedCandidate({
+ file: "adr-000000000001-first.md",
+ repoKey: key,
+ sha: "000000000001",
+ title: "first",
+ });
+
+ const first = generateArchDocs(vault, project);
+ const overviewBefore = readFileSync(first.overviewPath, "utf8");
+ const decisionsBefore = readFileSync(first.decisionsPath, "utf8");
+
+ const second = generateArchDocs(vault, project);
+ expect(second.created).toBe(0);
+ expect(second.updated).toBe(0);
+ expect(readFileSync(second.overviewPath, "utf8")).toBe(overviewBefore);
+ expect(readFileSync(second.decisionsPath, "utf8")).toBe(decisionsBefore);
+
+ // The declared exception, scoped: a new candidate is a vault change, so
+ // the decisions note moves and every other note stands still.
+ seedCandidate({
+ file: "adr-000000000002-second.md",
+ repoKey: key,
+ sha: "000000000002",
+ title: "second",
+ });
+ const third = generateArchDocs(vault, project);
+ expect(third.updated).toBe(1);
+ expect(readFileSync(third.overviewPath, "utf8")).toBe(overviewBefore);
+ expect(readFileSync(third.decisionsPath, "utf8")).not.toBe(decisionsBefore);
+});
+
+test("operator prose in the decisions note survives regeneration", () => {
+ const first = generateArchDocs(vault, project);
+ const prose = "\nOperator: ADR-1 supersedes the second entry.\n";
+ writeFileSync(first.decisionsPath, readFileSync(first.decisionsPath, "utf8") + prose);
+
+ seedCandidate({
+ file: "adr-000000000001-first.md",
+ repoKey: first.repoKey,
+ sha: "000000000001",
+ title: "first",
+ });
+ const second = generateArchDocs(vault, project);
+ const after = readFileSync(second.decisionsPath, "utf8");
+
+ expect(after).toContain("Operator: ADR-1 supersedes the second entry.");
+ expect(after).toContain("first");
+});
diff --git a/tests/core/brain/architect-module-map.test.ts b/tests/core/brain/architect-module-map.test.ts
new file mode 100644
index 00000000..08467f5c
--- /dev/null
+++ b/tests/core/brain/architect-module-map.test.ts
@@ -0,0 +1,140 @@
+/**
+ * The architect overview's Mermaid containment diagram
+ * (salience-lifecycle-enrichment, unit 6 / t_041c571f).
+ *
+ * Claims pinned here:
+ * 1. The `module-map` region carries a Mermaid block whose ONLY edges
+ * run from the project root to a module. The scanner records no
+ * import graph (`scan.ts`: "Import-graph analysis is explicitly out
+ * of scope"), so a diagram with module-to-module edges would be
+ * drawing relations nothing measured.
+ * 2. Each module node is labeled with its name, its file count, and its
+ * dominant language; a module with no extension to count says so
+ * rather than rendering a blank label.
+ * 3. Module order is codepoint-stable and does not depend on the host
+ * collation.
+ * 4. A module name carrying Mermaid-hostile characters is entity-escaped
+ * in the label, and node ids never derive from the name at all.
+ * 5. The same facts render a byte-identical block.
+ */
+
+import { afterEach, beforeEach, 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 { generateArchDocs } from "../../../src/core/brain/architect/generate.ts";
+
+let tmp: string;
+let project: string;
+
+function seed(relPath: string, content = "// x\n"): void {
+ const abs = join(project, relPath);
+ mkdirSync(join(abs, ".."), { recursive: true });
+ writeFileSync(abs, content);
+}
+
+function freshVault(name: string): string {
+ const made = join(tmp, name);
+ mkdirSync(join(made, "Brain"), { recursive: true });
+ return made;
+}
+
+/** The body of one sentinel region, without its sentinel lines. */
+function regionBody(text: string, id: string): string {
+ const begin = `<!-- o2b:begin ${id} -->\n`;
+ const end = `\n<!-- o2b:end ${id} -->`;
+ const from = text.indexOf(begin);
+ expect(from).toBeGreaterThanOrEqual(0);
+ const to = text.indexOf(end, from);
+ expect(to).toBeGreaterThan(from);
+ return text.slice(from + begin.length, to);
+}
+
+function moduleMap(vaultName = "vault"): string {
+ const res = generateArchDocs(freshVault(vaultName), project);
+ return regionBody(readFileSync(res.overviewPath, "utf8"), "module-map");
+}
+
+/** The `a --> b` lines of a Mermaid block, in order. */
+function edges(block: string): ReadonlyArray<string> {
+ return block
+ .split("\n")
+ .map((line) => line.trim())
+ .filter((line) => line.includes("-->"));
+}
+
+beforeEach(() => {
+ tmp = mkdtempSync(join(tmpdir(), "o2b-architect-modulemap-"));
+ project = join(tmp, "demo-app");
+ mkdirSync(project, { recursive: true });
+ writeFileSync(join(project, "package.json"), JSON.stringify({ name: "demo-app" }));
+ seed("src/core/engine.ts");
+ seed("src/core/util.ts");
+ seed("src/cli/main.ts");
+});
+
+afterEach(() => {
+ rmSync(tmp, { recursive: true, force: true });
+});
+
+test("the region renders a Mermaid block of root-to-module containment only", () => {
+ const block = moduleMap();
+
+ expect(block).toContain("```mermaid");
+ expect(block).toContain("graph TD");
+ expect(block.trimEnd().endsWith("```")).toBe(true);
+
+ // One edge per module, and every one of them leaves the root node.
+ const drawn = edges(block);
+ expect(drawn).toHaveLength(2);
+ expect(drawn.every((edge) => edge.startsWith("root -->"))).toBe(true);
+});
+
+test("each module node carries its file count and dominant language", () => {
+ seed("src/core/notes.md");
+ seed("src/core/more.ts");
+ // A module whose files have no extension has no language to name.
+ seed("src/scripts/Makefile", "all:\n");
+
+ const block = moduleMap();
+
+ expect(block).toContain("cli");
+ expect(block).toContain("1 file(s)");
+ // core: 3 .ts against 1 .md, so .ts dominates.
+ expect(block).toContain("4 file(s)");
+ expect(block).toContain(".ts");
+ expect(block).toContain("no language detected");
+});
+
+test("module order is codepoint-stable, not collation-dependent", () => {
+ seed("src/Zed/z.ts");
+ seed("src/api/a.ts");
+
+ const block = moduleMap();
+ const drawn = edges(block);
+ const named = drawn.map((edge) => edge.slice(edge.indexOf('["') + 2, edge.indexOf("<br/>")));
+
+ // Uppercase before lowercase: codepoint order, which is what a
+ // locale-aware collator would NOT produce.
+ expect(named).toEqual(["Zed", "api", "cli", "core"]);
+});
+
+test("a Mermaid-hostile module name is escaped and never becomes a node id", () => {
+ seed('src/a"b<c>#d/x.ts');
+
+ const block = moduleMap();
+
+ // The raw characters never reach the rendered label.
+ expect(block).not.toContain('a"b');
+ expect(block).not.toContain("<c>");
+ expect(block).toContain("a#quot;b#lt;c#gt;#35;d");
+ // Node ids are positional, so no name can produce an invalid one.
+ for (const edge of edges(block)) {
+ expect(edge).toMatch(/^root --> mod\d+\["/);
+ }
+});
+
+test("the same facts render a byte-identical block", () => {
+ expect(moduleMap("vault-b")).toBe(moduleMap("vault-a"));
+});
diff --git a/tests/core/brain/architect-progress.test.ts b/tests/core/brain/architect-progress.test.ts
index 60699ec5..7547886e 100644
--- a/tests/core/brain/architect-progress.test.ts
+++ b/tests/core/brain/architect-progress.test.ts
@@ -86,15 +86,16 @@ describe("architect progress", () => {
test("the walk counts without a denominator, the render stage has one", () => {
const { events, sink } = record();
- // src/cli, src/core and one nested module: 3 notes, 2 of them modules.
+ // src/cli and src/core are the two modules; the overview and the
+ // key-decisions note bring the render stage to 4 notes.
generateArchDocs(freshVault("vault"), project, { onProgress: sink });
const walk = events.filter((e) => e.stage === ARCHITECT_STAGE.walk);
const render = events.filter((e) => e.stage === ARCHITECT_STAGE.render);
expect(walk.every((e) => e.total === undefined)).toBe(true);
expect(walk.at(-1)?.completed).toBeGreaterThan(0);
- expect(render.every((e) => e.total === 3)).toBe(true);
- expect(render.at(-1)?.completed).toBe(3);
+ expect(render.every((e) => e.total === 4)).toBe(true);
+ expect(render.at(-1)?.completed).toBe(4);
});
test("the scan stops at a boundary when the deadline has passed", () => {
diff --git a/tests/core/brain/capture/capture-note.test.ts b/tests/core/brain/capture/capture-note.test.ts
index c7b25ec9..c156a43c 100644
--- a/tests/core/brain/capture/capture-note.test.ts
+++ b/tests/core/brain/capture/capture-note.test.ts
@@ -18,6 +18,7 @@ import {
archiveCapture,
capturesSince,
listStagedCaptures,
+ readCaptureNote,
readCatchupWatermark,
writeCaptureNote,
writeCatchupWatermark,
@@ -149,3 +150,98 @@ test("writeCaptureNote retries a name lost between the probe and the create", ()
expect(second.id).toBe(`${first.id}-2`);
expect(existsSync(join(vault, second.path))).toBe(true);
});
+
+/**
+ * Per-capture guidance (unit 3b / t_5e338af1).
+ *
+ * Claims pinned below:
+ *
+ * 1. Guidance round-trips verbatim through the `## Guidance` body section
+ * without leaking into the captured body.
+ * 2. Two captures differing ONLY in guidance are two captures: the id hash
+ * reads the field, so they do not collapse into the `-2` allocator.
+ * 3. A capture written without guidance keeps the historical id, byte for
+ * byte - the field is additive and the hash segment is conditional.
+ * 4. A body that itself ends in a `## Guidance` heading is still read back
+ * as body, because the split is gated on the frontmatter marker rather
+ * than on finding the heading - and when the capture DOES carry
+ * guidance, the split takes the last separator, so the quoted section
+ * stays in the body and the writer's own guidance comes back whole.
+ * 5. Empty or whitespace-only guidance is refused by name, never stored as
+ * an empty section.
+ */
+
+test("guidance round-trips verbatim and stays out of the body", () => {
+ const written = writeCaptureNote(vault, {
+ body: "capture a thought",
+ provenance: prov(),
+ guidance: "file this under research, not tasks",
+ });
+ expect(written.guidance).toBe("file this under research, not tasks");
+ expect(written.body).toBe("capture a thought");
+
+ const read = readCaptureNote(vault, written.id);
+ expect(read).not.toBeNull();
+ expect(read!.guidance).toBe("file this under research, not tasks");
+ expect(read!.body).toBe("capture a thought");
+});
+
+test("a capture with no guidance reads back with none", () => {
+ const written = writeCaptureNote(vault, { body: "plain", provenance: prov() });
+ expect(written.guidance).toBeNull();
+ expect(readCaptureNote(vault, written.id)!.guidance).toBeNull();
+});
+
+test("two captures differing only in guidance get distinct ids", () => {
+ const a = writeCaptureNote(vault, {
+ body: "same text",
+ provenance: prov(),
+ guidance: "route to inbox",
+ });
+ const b = writeCaptureNote(vault, {
+ body: "same text",
+ provenance: prov(),
+ guidance: "route to archive",
+ });
+ expect(a.id).not.toBe(b.id);
+ // Distinct by HASH, not by the collision allocator's numeric suffix.
+ expect(b.id.endsWith("-2")).toBe(false);
+});
+
+test("adding guidance does not move the id of a capture that has none", () => {
+ const plain = writeCaptureNote(vault, { body: "same text", provenance: prov() });
+ rmSync(join(vault, plain.path));
+ const again = writeCaptureNote(vault, { body: "same text", provenance: prov() });
+ expect(again.id).toBe(plain.id);
+});
+
+test("a body that ends in its own Guidance heading is still all body", () => {
+ const body = "notes\n\n## Guidance\n\nquoted from somewhere else";
+ const written = writeCaptureNote(vault, { body, provenance: prov() });
+ const read = readCaptureNote(vault, written.id)!;
+ expect(read.guidance).toBeNull();
+ expect(read.body).toBe(body);
+});
+
+test("a quoted Guidance section inside the body does not steal the real guidance", () => {
+ // Both halves are present here: the body quotes a document that has its
+ // own `## Guidance` heading, AND the capture carries guidance of its
+ // own. The split has to take the LAST separator - the one the writer
+ // appended - or the quotation's head becomes the instruction and the
+ // rest of the quotation is lost from the body.
+ const body = "notes\n\n## Guidance\n\nquoted from somewhere else";
+ const written = writeCaptureNote(vault, {
+ body,
+ provenance: prov(),
+ guidance: "file this under research",
+ });
+ const read = readCaptureNote(vault, written.id)!;
+ expect(read.guidance).toBe("file this under research");
+ expect(read.body).toBe(body);
+});
+
+test("empty guidance is refused by name rather than stored as an empty section", () => {
+ expect(() =>
+ writeCaptureNote(vault, { body: "text", provenance: prov(), guidance: " " }),
+ ).toThrow(CaptureContractError);
+});
diff --git a/tests/core/brain/design-note.test.ts b/tests/core/brain/design-note.test.ts
new file mode 100644
index 00000000..d958bd2c
--- /dev/null
+++ b/tests/core/brain/design-note.test.ts
@@ -0,0 +1,209 @@
+/**
+ * One-shot design notes (salience-lifecycle-enrichment, unit 7,
+ * t_c87644b4). Claims pinned here:
+ *
+ * 1. The grounding pass reads all three stores - tensions, decisions,
+ * truth projections - and matches them to the topic.
+ * 2. A store with nothing in it is a NAMED empty grounding, never a
+ * failure and never an unexplained absence.
+ * 3. Topic filtering is real: an unrelated record does not ground a note.
+ * 4. The report carries exactly one needs-llm-step envelope.
+ * 5. The cardinality check enforces EXACTLY ONE recommended alternative;
+ * zero and two-plus are both refused, and the refusal states the count.
+ * 6. A validated note commits under `Brain/decisions/` with the panel
+ * siblings' filename shape, and a second commit for the same topic and
+ * day is refused rather than silently overwriting.
+ */
+
+import { afterEach, beforeEach, expect, test } from "bun:test";
+import { existsSync, mkdirSync, mkdtempSync, readFileSync, rmSync } from "node:fs";
+import { tmpdir } from "node:os";
+import { join } from "node:path";
+
+import {
+ commitDesignNote,
+ DESIGN_NOTE_STORE,
+ designNoteGrounding,
+ planDesignNote,
+} from "../../../src/core/brain/design-note.ts";
+import { recordDecision } from "../../../src/core/brain/decisions/record.ts";
+import { NEEDS_LLM_STEP } from "../../../src/core/brain/llm-step.ts";
+import { ResponseCheckError } from "../../../src/core/brain/response-checks.ts";
+import { ResponseShapeError } from "../../../src/core/brain/response-shape.ts";
+import { appendClaimEvent } from "../../../src/core/brain/truth/store.ts";
+import { persistTension } from "../../../src/core/brain/tensions.ts";
+
+let vault: string;
+const NOW = new Date("2026-08-22T10:00:00Z");
+const TOPIC = "vector index storage";
+
+function alternative(name: string, recommended: boolean): Record<string, unknown> {
+ return {
+ name,
+ approach: `Store the index with ${name}.`,
+ tradeoffs: `${name} trades write cost for read latency.`,
+ recommended,
+ };
+}
+
+function payload(...flags: ReadonlyArray<boolean>): Record<string, unknown> {
+ return {
+ title: "Where the vector index lives",
+ alternatives: flags.map((recommended, i) => alternative(`option-${i}`, recommended)),
+ };
+}
+
+/** Materialize one tension whose subject is the topic under study. */
+function seedTension(): void {
+ persistTension(
+ vault,
+ {
+ aId: "pref-index-inside",
+ bId: "pref-index-outside",
+ subject: "vector index storage",
+ jaccard: 0.7,
+ aSign: "positive",
+ bSign: "negative",
+ aQuote: "Keep the vector index storage inside the vault.",
+ bQuote: "Never keep the vector index storage inside the vault.",
+ action: "ask_user",
+ },
+ { agent: "tester", now: NOW },
+ );
+}
+
+beforeEach(() => {
+ vault = mkdtempSync(join(tmpdir(), "o2b-design-note-"));
+ mkdirSync(join(vault, "Brain"), { recursive: true });
+});
+
+afterEach(() => {
+ rmSync(vault, { recursive: true, force: true });
+});
+
+test("an empty vault grounds the note in a NAMED emptiness, not a failure", () => {
+ const grounding = designNoteGrounding(vault, TOPIC);
+ expect(grounding.counts).toEqual({ tensions: 0, decisions: 0, truthSlots: 0, conflicts: 0 });
+ expect([...grounding.emptyStores].toSorted()).toEqual(
+ [DESIGN_NOTE_STORE.decisions, DESIGN_NOTE_STORE.tensions, DESIGN_NOTE_STORE.truth].toSorted(),
+ );
+ // The report is still produced, with its envelope.
+ const report = planDesignNote(vault, TOPIC, { now: NOW });
+ expect(report.llmStep.status).toBe(NEEDS_LLM_STEP);
+ expect(report.grounding.emptyStores.length).toBe(3);
+});
+
+test("the grounding pass reads all three stores and matches them to the topic", () => {
+ seedTension();
+ recordDecision(vault, {
+ title: "Vector index storage location",
+ chosen: "Keep the index outside the vault",
+ assumption: "Sync clients must not replicate a binary index",
+ reviewDate: "2027-01-01",
+ agent: "tester",
+ now: NOW,
+ });
+ recordDecision(vault, {
+ title: "Breakfast cereal ranking",
+ chosen: "Muesli",
+ assumption: "Nobody asked",
+ reviewDate: "2027-01-01",
+ agent: "tester",
+ now: NOW,
+ });
+ appendClaimEvent(vault, {
+ agent: "tester",
+ entity: "vector index",
+ aspect: "storage",
+ value: "outside the vault",
+ source: "[[notes/index.md]]",
+ ts: NOW.toISOString(),
+ });
+
+ const grounding = designNoteGrounding(vault, TOPIC);
+ expect(grounding.counts.tensions).toBeGreaterThanOrEqual(1);
+ expect(grounding.decisions.map((d) => d.title)).toEqual(["Vector index storage location"]);
+ expect(grounding.counts.truthSlots).toBeGreaterThanOrEqual(1);
+ // Every store held something, so nothing is reported empty.
+ expect(grounding.emptyStores).toEqual([]);
+});
+
+test("a populated store that matches nothing grounds nothing but is not reported empty", () => {
+ recordDecision(vault, {
+ title: "Breakfast cereal ranking",
+ chosen: "Muesli",
+ assumption: "Nobody asked",
+ reviewDate: "2027-01-01",
+ agent: "tester",
+ now: NOW,
+ });
+ const grounding = designNoteGrounding(vault, TOPIC);
+ expect(grounding.decisions).toEqual([]);
+ expect(grounding.emptyStores).not.toContain(DESIGN_NOTE_STORE.decisions);
+});
+
+test("the report carries exactly one envelope, naming the note it will become", () => {
+ const report = planDesignNote(vault, TOPIC, { now: NOW });
+ expect(report.llmStep.step).toBe("design-note");
+ expect(report.llmStep.target_path).toBe(report.targetPath);
+ expect(report.targetPath).toBe("Brain/decisions/design-2026-08-22-vector-index-storage.md");
+ expect(report.llmStep.prompt).toContain(TOPIC);
+ expect(report.llmStep.schema_hints.length).toBeGreaterThan(0);
+});
+
+test("zero recommended alternatives is refused, and the refusal states the count", () => {
+ let caught: unknown;
+ try {
+ commitDesignNote(vault, TOPIC, payload(false, false), { agent: "tester", now: NOW });
+ } catch (err) {
+ caught = err;
+ }
+ expect(caught).toBeInstanceOf(ResponseCheckError);
+ expect((caught as Error).message).toContain("exactly one");
+ expect((caught as Error).message).toContain("0");
+});
+
+test("two recommended alternatives is refused, and the refusal states the count", () => {
+ let caught: unknown;
+ try {
+ commitDesignNote(vault, TOPIC, payload(true, true, false), { agent: "tester", now: NOW });
+ } catch (err) {
+ caught = err;
+ }
+ expect(caught).toBeInstanceOf(ResponseCheckError);
+ expect((caught as Error).message).toContain("2");
+});
+
+test("a malformed alternative is refused by the shape layer", () => {
+ expect(() =>
+ commitDesignNote(
+ vault,
+ TOPIC,
+ {
+ title: "T",
+ alternatives: [{ name: "a", approach: " ", tradeoffs: "t", recommended: true }],
+ },
+ { agent: "tester", now: NOW },
+ ),
+ ).toThrow(ResponseShapeError);
+});
+
+test("exactly one recommended alternative commits the note under Brain/decisions", () => {
+ const res = commitDesignNote(vault, TOPIC, payload(false, true), { agent: "tester", now: NOW });
+ expect(res.path).toBe(
+ join(vault, "Brain", "decisions", "design-2026-08-22-vector-index-storage.md"),
+ );
+ expect(existsSync(res.path)).toBe(true);
+ const body = readFileSync(res.path, "utf8");
+ expect(body).toContain("kind: brain-design-note");
+ expect(body).toContain("topic: vector index storage");
+ expect(body).toContain("option-1");
+ expect(body).toContain("recommended");
+});
+
+test("a second note for the same topic and day is refused, never overwritten", () => {
+ commitDesignNote(vault, TOPIC, payload(true), { agent: "tester", now: NOW });
+ expect(() =>
+ commitDesignNote(vault, TOPIC, payload(true), { agent: "tester", now: NOW }),
+ ).toThrow(/design-2026-08-22-vector-index-storage/);
+});
diff --git a/tests/core/brain/dream-salience-gate.test.ts b/tests/core/brain/dream-salience-gate.test.ts
new file mode 100644
index 00000000..a011e44c
--- /dev/null
+++ b/tests/core/brain/dream-salience-gate.test.ts
@@ -0,0 +1,250 @@
+/**
+ * The salience gate inside one dream pass (salience-lifecycle-
+ * enrichment, unit 1, t_de8a0b2d).
+ *
+ * The dream pass has no per-item model lane: its entire model delegation
+ * is the count-triggered rollup ladder. So the gate governs exactly one
+ * thing - which facts enter the ladder's fold set - and nothing else.
+ *
+ * Claims pinned here:
+ * 1. With no `dream.salience_threshold` configured the gate is OPEN
+ * and says so: the summary carries `threshold: null`, admits every
+ * fact, and the ladder counts the unfiltered fold set.
+ * 2. The open gate scores nothing. Observed-use records - the one
+ * scorer input the rest of the pass never reads - cannot change a
+ * run with the threshold unset: two vaults identical but for those
+ * records produce the same summary and the same decisions on disk.
+ * 3. That probe is load-bearing: with a threshold set, the same
+ * records DO change the partition, so claim 2 is not vacuous.
+ * 4. A configured threshold keeps low-salience facts out of the fold
+ * set, so a ladder rung that would have fired on the raw count does
+ * not fire on the admitted count.
+ * 5. An excluded fact is never silently dropped: the summary names it
+ * by id and path and carries the score and the three raw signals.
+ * 6. The gate is reported on the no-op summary too - a pass that
+ * changed nothing still has to explain what it considered.
+ * 7. A malformed threshold in `_brain.yaml` is refused by name, not
+ * ignored.
+ */
+
+import { afterEach, beforeEach, expect, test } from "bun:test";
+import { existsSync, mkdtempSync, readdirSync, readFileSync, rmSync, statSync } from "node:fs";
+import { tmpdir } from "node:os";
+import { join } from "node:path";
+
+import { dream } from "../../../src/core/brain/dream.ts";
+import { bootstrapBrain } from "../../../src/core/brain/init.ts";
+import { emitObservedUse } from "../../../src/core/brain/observed-use.ts";
+import { appendLogEvent } from "../../../src/core/brain/log.ts";
+import { brainConfigPath } from "../../../src/core/brain/paths.ts";
+import { writePreference } from "../../../src/core/brain/preference.ts";
+import {
+ BRAIN_APPLY_RESULT,
+ BRAIN_LOG_EVENT_KIND,
+ BRAIN_PREFERENCE_STATUS,
+} from "../../../src/core/brain/types.ts";
+import { atomicWriteFileSync } from "../../../src/core/fs-atomic.ts";
+import { sha256Hex } from "../../../src/core/integrity/digest.ts";
+
+const NOW = new Date("2026-06-01T00:00:00Z");
+/** Facts the ladder needs before it emits a rollup envelope. */
+const FACT_THRESHOLD = 3;
+/** Fold-set members: one loud fact, three quiet ones. */
+const LOUD = "loud";
+const QUIET = ["quiet-a", "quiet-b", "quiet-c"] as const;
+/** A threshold every quiet fact misses and the loud one clears. */
+const THRESHOLD = 0.2;
+
+let tmp: string;
+
+beforeEach(() => {
+ tmp = mkdtempSync(join(tmpdir(), "o2b-dream-salience-"));
+});
+
+afterEach(() => {
+ rmSync(tmp, { recursive: true, force: true });
+});
+
+/** `_brain.yaml` with the ladder armed and, optionally, a gate threshold. */
+function configBody(threshold: number | string | null): string {
+ const gate = threshold === null ? "" : `dream:\n salience_threshold: ${threshold}\n`;
+ return (
+ `schema_version: 1\n${gate}` +
+ `rollup:\n fact_threshold: ${FACT_THRESHOLD}\n identity_threshold: 5\n`
+ );
+}
+
+/**
+ * A vault holding one loud fact (repeated applied-evidence) and three
+ * quiet ones (no evidence at all).
+ */
+function makeVault(name: string, threshold: number | string | null): string {
+ const vault = join(tmp, name);
+ bootstrapBrain(vault, {});
+ atomicWriteFileSync(brainConfigPath(vault), configBody(null));
+ for (const slug of [LOUD, ...QUIET]) {
+ const loud = slug === LOUD;
+ writePreference(vault, {
+ slug,
+ topic: slug,
+ principle: `principle for ${slug}`,
+ created_at: "2026-01-01T00:00:00Z",
+ unconfirmed_until: "2026-01-08T00:00:00Z",
+ // Recent confirmation keeps the stale-no-evidence auto-retire off
+ // every fact, the quiet ones included: the refresh pass recomputes
+ // `last_evidence_at` from the log, so a fact with no log events
+ // falls back to `confirmed_at` for that check. The quiet facts
+ // therefore differ from the loud one in exactly what the gate
+ // reads - no counters, no apply-evidence, no observed use.
+ confirmed_at: "2026-05-30T00:00:00Z",
+ status: BRAIN_PREFERENCE_STATUS.confirmed,
+ evidenced_by: [],
+ applied_count: loud ? 8 : 0,
+ violated_count: 0,
+ last_evidence_at: loud ? "2026-05-30T00:00:00Z" : null,
+ confidence_value: loud ? 0.8 : 0,
+ });
+ }
+ for (const day of ["2026-05-27", "2026-05-28", "2026-05-29", "2026-05-30"]) {
+ appendLogEvent(vault, {
+ timestamp: `${day}T00:00:00Z`,
+ eventType: BRAIN_LOG_EVENT_KIND.applyEvidence,
+ body: {
+ preference: `[[pref-${LOUD}]]`,
+ artifact: "[[src/foo.ts]]",
+ agent: "tester",
+ result: BRAIN_APPLY_RESULT.applied,
+ },
+ });
+ }
+ // The threshold lands last: a refused config would otherwise stop the
+ // fixture's own writes before the pass under test ever runs.
+ atomicWriteFileSync(brainConfigPath(vault), configBody(threshold));
+ return vault;
+}
+
+/** Observed-use verdicts for every quiet fact: the gate-only probe. */
+function seedReuse(vault: string): void {
+ emitObservedUse(vault, {
+ host: "test",
+ createdAt: "2026-05-31T00:00:00Z",
+ entries: QUIET.map((slug) => ({ id: `pref-${slug}`, verdict: "USED" as const })),
+ });
+}
+
+/**
+ * Everything a pass durably DECIDES, and nothing that merely records the
+ * run or names the vault. The audit log is excluded because it stamps
+ * the pre-run archive's byte size, and the probe below legitimately
+ * makes that archive bigger by adding a continuity record; `_BRAIN.md`
+ * and `vault-id.json` carry the vault's own name and random id. What
+ * those artifacts wrap is this list, and the run summary is compared
+ * separately.
+ */
+const DECISION_PATHS = [
+ "preferences",
+ "retired",
+ "inbox",
+ "active.md",
+ "lessons.md",
+ "rollup-ladder.json",
+] as const;
+
+/** Content digest over the pass's durable decisions. */
+function brainDigest(vault: string): string {
+ const rows: string[] = [];
+ const walk = (path: string, rel: string): void => {
+ if (!existsSync(path)) return;
+ if (!statSync(path).isDirectory()) {
+ rows.push(`${rel}=${readFileSync(path, "utf8")}`);
+ return;
+ }
+ for (const name of readdirSync(path).toSorted()) walk(join(path, name), `${rel}/${name}`);
+ };
+ for (const entry of DECISION_PATHS) walk(join(vault, "Brain", entry), entry);
+ return sha256Hex(rows.join("\n"));
+}
+
+/** One summary as JSON, with the vault's own root elided. */
+function withoutVaultRoot(summary: unknown, vault: string): string {
+ return JSON.stringify(summary).replaceAll(vault, "<vault>");
+}
+
+test("with no threshold the gate reports itself absent and admits every fact", () => {
+ const vault = makeVault("open", null);
+ const summary = dream(vault, { now: NOW, dryRun: true });
+ expect(summary.salience_gate.threshold).toBeNull();
+ expect(summary.salience_gate.considered).toBe(4);
+ expect(summary.salience_gate.admitted).toBe(4);
+ expect(summary.salience_gate.excluded).toEqual([]);
+ // Four facts against a ladder threshold of three: the rung fires.
+ expect(summary.rollups).toHaveLength(1);
+});
+
+test("the open gate scores nothing: observed-use records cannot change the run", () => {
+ const control = makeVault("control", null);
+ const probe = makeVault("probe", null);
+ seedReuse(probe);
+
+ const a = dream(control, { now: NOW });
+ const b = dream(probe, { now: NOW });
+ expect(withoutVaultRoot(b, probe)).toBe(withoutVaultRoot(a, control));
+ expect(brainDigest(probe)).toBe(brainDigest(control));
+});
+
+test("the same probe does change the partition once a threshold is set", () => {
+ const control = makeVault("gated-control", THRESHOLD);
+ const probe = makeVault("gated-probe", THRESHOLD);
+ seedReuse(probe);
+
+ const a = dream(control, { now: NOW, dryRun: true });
+ const b = dream(probe, { now: NOW, dryRun: true });
+ expect(a.salience_gate.admitted).toBe(1);
+ expect(b.salience_gate.admitted).toBe(4);
+ expect(b.salience_gate.excluded).toEqual([]);
+});
+
+test("a configured threshold keeps low-salience facts out of the fold set", () => {
+ const vault = makeVault("gated", THRESHOLD);
+ const summary = dream(vault, { now: NOW, dryRun: true });
+ expect(summary.salience_gate.threshold).toBe(THRESHOLD);
+ expect(summary.salience_gate.considered).toBe(4);
+ expect(summary.salience_gate.admitted).toBe(1);
+ // One admitted fact is below the ladder's threshold of three, so the
+ // rung the raw count would have fired does not fire.
+ expect(summary.rollups).toEqual([]);
+});
+
+test("every excluded fact is named with its score and its three raw signals", () => {
+ const vault = makeVault("named", THRESHOLD);
+ const summary = dream(vault, { now: NOW, dryRun: true });
+ expect(summary.salience_gate.excluded.map((e) => e.pref_id)).toEqual(
+ QUIET.map((slug) => `pref-${slug}`),
+ );
+ for (const entry of summary.salience_gate.excluded) {
+ expect(entry.path).toBe(`Brain/preferences/${entry.pref_id}.md`);
+ expect(entry.score).toBeLessThan(THRESHOLD);
+ expect(entry.mass).toBe(0);
+ expect(entry.confidence).toBe(0);
+ expect(entry.reuse).toBe(0);
+ }
+});
+
+test("a no-op run still explains what the gate considered", () => {
+ const vault = makeVault("noop", THRESHOLD);
+ // The first pass settles whatever the fixture changes; the second
+ // changes nothing and takes the no-op path.
+ dream(vault, { now: NOW });
+ const summary = dream(vault, { now: NOW });
+ expect(summary.changed).toBe(false);
+ expect(summary.salience_gate.threshold).toBe(THRESHOLD);
+ expect(summary.salience_gate.considered).toBe(4);
+ expect(summary.salience_gate.excluded).toHaveLength(3);
+});
+
+test("a malformed threshold is refused by name rather than ignored", () => {
+ for (const bad of ["2", "-0.5", "yes"]) {
+ const vault = makeVault(`bad-${bad}`, bad);
+ expect(() => dream(vault, { now: NOW, dryRun: true })).toThrow(/dream\.salience_threshold/);
+ }
+});
diff --git a/tests/core/brain/expiration-set.test.ts b/tests/core/brain/expiration-set.test.ts
new file mode 100644
index 00000000..a05f3fce
--- /dev/null
+++ b/tests/core/brain/expiration-set.test.ts
@@ -0,0 +1,266 @@
+/**
+ * Post-creation expiration mutation (unit 3c / t_5e338af1).
+ *
+ * The defect, both halves of it. `expiration_date` had a validator, a
+ * writer parameter on both artifact kinds, and a fully-wired read side -
+ * and no surface anywhere that set it. A memory's lifetime could
+ * therefore be declared only by a caller writing straight to the core
+ * API, and could never be changed at all: nothing in the tree rewrites
+ * that field after the write. `brain_update_note` cannot reach a
+ * preference (its path envelope refuses the `Brain/` root, and that
+ * refusal is load-bearing), so the mutation needs a surface of its own.
+ *
+ * Claims pinned here:
+ *
+ * 1. Setting an expiration on a signal or a preference stamps the
+ * NORMALISED value and leaves every other frontmatter field intact.
+ * 2. Changing an existing expiration replaces it; clearing removes the
+ * key entirely rather than writing an empty string.
+ * 3. Every value goes through `normalizeExpirationDate`, so an
+ * unparseable date is refused by name and the file is untouched.
+ * 4. An id that names no artifact is refused by name - never a silent
+ * no-op that reads as success.
+ * 5. An artifact mutated to expire drops out of the DEFAULT query after
+ * its date and comes back under `showExpired`, which is the whole
+ * point of setting one.
+ * 6. `changed: false` means what it says: the stored value is compared
+ * through the same chokepoint the incoming one goes through, so an
+ * equivalent spelling writes no bytes and logs no event.
+ */
+
+import { afterEach, beforeEach, describe, expect, test } from "bun:test";
+import { existsSync, mkdtempSync, readdirSync, readFileSync, rmSync } from "node:fs";
+import { tmpdir } from "node:os";
+import { join } from "node:path";
+
+import { bootstrapBrain } from "../../../src/core/brain/init.ts";
+import {
+ EXPIRATION_CLEAR,
+ ExpirationTargetNotFoundError,
+ ExpirationValueError,
+ setExpiration,
+} from "../../../src/core/brain/expiration-set.ts";
+import { queryByTopic } from "../../../src/core/brain/query.ts";
+import { writePreference } from "../../../src/core/brain/preference.ts";
+import { writeSignal } from "../../../src/core/brain/signal.ts";
+import { atomicWriteFileSync } from "../../../src/core/fs-atomic.ts";
+
+let vault: string;
+let configHome: string;
+let configPath: string;
+
+const CREATED = "2026-06-01T00:00:00Z";
+
+beforeEach(() => {
+ vault = mkdtempSync(join(tmpdir(), "o2b-expiration-set-"));
+ configHome = mkdtempSync(join(tmpdir(), "o2b-expiration-set-cfg-"));
+ configPath = join(configHome, "config.yaml");
+ atomicWriteFileSync(configPath, `vault: ${vault}\n`);
+ bootstrapBrain(vault, { configPath });
+});
+
+afterEach(() => {
+ rmSync(vault, { recursive: true, force: true });
+ rmSync(configHome, { recursive: true, force: true });
+});
+
+/** Frontmatter lines of a page, minus the one field under test. */
+function frontmatterLines(text: string): string[] {
+ return text
+ .split("\n---")[0]!
+ .split("\n")
+ .filter((l) => l.length > 0 && !l.startsWith("expiration_date:"));
+}
+
+/** Every byte of the observation log, so a no-op can be shown to append none. */
+function logSnapshot(): string {
+ const dir = join(vault, "Brain", "log");
+ if (!existsSync(dir)) return "";
+ return readdirSync(dir)
+ .toSorted()
+ .map((name) => `${name}\n${readFileSync(join(dir, name), "utf8")}`)
+ .join("");
+}
+
+function seedSignal(): string {
+ return writeSignal(vault, {
+ topic: "staging-endpoint",
+ signal: "positive",
+ agent: "tester",
+ principle: "Use the staging endpoint.",
+ created_at: CREATED,
+ date: "2026-06-01",
+ slug: "staging-endpoint",
+ scope: "coding",
+ }).id;
+}
+
+function seedPreference(): string {
+ return writePreference(
+ vault,
+ {
+ slug: "staging-endpoint",
+ topic: "staging-endpoint",
+ principle: "Use the staging endpoint.",
+ created_at: CREATED,
+ unconfirmed_until: CREATED,
+ confirmed_at: CREATED,
+ status: "confirmed",
+ evidenced_by: [],
+ scope: "coding",
+ },
+ { configPath },
+ ).id;
+}
+
+describe("setting an expiration", () => {
+ test("stamps a signal and leaves its other frontmatter alone", () => {
+ const id = seedSignal();
+ const before = readFileSync(join(vault, "Brain/inbox", `${id}.md`), "utf8");
+ const res = setExpiration(vault, id, "2026-07-15");
+ expect(res.id).toBe(id);
+ expect(res.expiration).toBe("2026-07-15");
+ expect(res.previous).toBeNull();
+
+ const after = readFileSync(join(vault, res.path), "utf8");
+ expect(after).toContain("expiration_date: 2026-07-15");
+ // Every other field survives: compare the frontmatter line sets minus
+ // the one this call is allowed to add.
+ expect(frontmatterLines(after)).toEqual(frontmatterLines(before));
+ });
+
+ test("stamps a preference the same way", () => {
+ const id = seedPreference();
+ const res = setExpiration(vault, id, "2026-07-15");
+ expect(res.path).toBe(`Brain/preferences/${id}.md`);
+ expect(readFileSync(join(vault, res.path), "utf8")).toContain("expiration_date: 2026-07-15");
+ });
+
+ test("normalises the value rather than storing it verbatim", () => {
+ const id = seedSignal();
+ const res = setExpiration(vault, id, " 2026-07-15 ");
+ expect(res.expiration).toBe("2026-07-15");
+ });
+});
+
+describe("changing and clearing", () => {
+ test("a second set replaces the date and reports the previous one", () => {
+ const id = seedSignal();
+ setExpiration(vault, id, "2026-07-15");
+ const res = setExpiration(vault, id, "2026-09-01");
+ expect(res.previous).toBe("2026-07-15");
+ expect(res.expiration).toBe("2026-09-01");
+ expect(readFileSync(join(vault, res.path), "utf8")).not.toContain("2026-07-15");
+ });
+
+ test("clearing removes the key rather than writing an empty value", () => {
+ const id = seedSignal();
+ setExpiration(vault, id, "2026-07-15");
+ const res = setExpiration(vault, id, EXPIRATION_CLEAR);
+ expect(res.expiration).toBeNull();
+ expect(res.previous).toBe("2026-07-15");
+ const after = readFileSync(join(vault, res.path), "utf8");
+ expect(after).not.toContain("expiration_date");
+ });
+
+ test("re-setting the same lifetime writes nothing and logs nothing", () => {
+ const id = seedSignal();
+ const first = setExpiration(vault, id, "2026-07-15");
+ expect(first.changed).toBe(true);
+
+ // The two spellings of one lifetime: what is on disk carries padding
+ // - a hand edit, or a writer that quoted the scalar - and the caller
+ // sends the plain date. Comparing the raw stored value against the
+ // normalised new one made this a rewrite plus an audit event
+ // describing a change that did not happen.
+ const file = join(vault, first.path);
+ atomicWriteFileSync(
+ file,
+ readFileSync(file, "utf8").replace(
+ "expiration_date: 2026-07-15",
+ 'expiration_date: "2026-07-15 "',
+ ),
+ );
+ const bytesBefore = readFileSync(file, "utf8");
+ const logBefore = logSnapshot();
+
+ const res = setExpiration(vault, id, " 2026-07-15 ");
+ expect(res.changed).toBe(false);
+ expect(res.expiration).toBe("2026-07-15");
+ expect(readFileSync(file, "utf8")).toBe(bytesBefore);
+ expect(logSnapshot()).toBe(logBefore);
+ });
+
+ test("a stored value the validator cannot parse is never equal, so the set repairs it", () => {
+ const id = seedSignal();
+ const first = setExpiration(vault, id, "2026-07-15");
+ const file = join(vault, first.path);
+ atomicWriteFileSync(
+ file,
+ readFileSync(file, "utf8").replace("expiration_date: 2026-07-15", "expiration_date: junk"),
+ );
+ const res = setExpiration(vault, id, "2026-07-15");
+ expect(res.changed).toBe(true);
+ expect(readFileSync(file, "utf8")).toContain("expiration_date: 2026-07-15");
+ });
+
+ test("clearing an artifact that has none is reported, not invented", () => {
+ const id = seedSignal();
+ const res = setExpiration(vault, id, EXPIRATION_CLEAR);
+ expect(res.expiration).toBeNull();
+ expect(res.previous).toBeNull();
+ expect(res.changed).toBe(false);
+ });
+});
+
+describe("refusals", () => {
+ test("an unparseable date is refused by name and writes nothing", () => {
+ const id = seedSignal();
+ const before = readFileSync(join(vault, "Brain/inbox", `${id}.md`), "utf8");
+ expect(() => setExpiration(vault, id, "next tuesday")).toThrow(ExpirationValueError);
+ expect(readFileSync(join(vault, "Brain/inbox", `${id}.md`), "utf8")).toBe(before);
+ });
+
+ test("an impossible calendar date is refused too", () => {
+ const id = seedSignal();
+ expect(() => setExpiration(vault, id, "2026-13-40")).toThrow(ExpirationValueError);
+ });
+
+ test("an id naming no artifact is refused rather than silently succeeding", () => {
+ expect(() => setExpiration(vault, "pref-nobody-home", "2026-07-15")).toThrow(
+ ExpirationTargetNotFoundError,
+ );
+ });
+});
+
+describe("what an expiration is FOR", () => {
+ test("a mutated artifact drops out of the default query after its date", () => {
+ const signalId = seedSignal();
+ seedPreference();
+ setExpiration(vault, signalId, "2026-07-15");
+
+ const live = queryByTopic(vault, "staging-endpoint", { now: new Date("2026-07-15T12:00:00Z") });
+ expect(live.signals.map((s) => s.id)).toContain(signalId);
+
+ const lapsed = queryByTopic(vault, "staging-endpoint", {
+ now: new Date("2026-07-16T00:00:01Z"),
+ });
+ expect(lapsed.signals.map((s) => s.id)).not.toContain(signalId);
+
+ const audited = queryByTopic(vault, "staging-endpoint", {
+ now: new Date("2026-07-16T00:00:01Z"),
+ showExpired: true,
+ });
+ expect(audited.signals.map((s) => s.id)).toContain(signalId);
+ });
+
+ test("clearing puts it back in the default query", () => {
+ const signalId = seedSignal();
+ setExpiration(vault, signalId, "2026-07-15");
+ setExpiration(vault, signalId, EXPIRATION_CLEAR);
+ const after = queryByTopic(vault, "staging-endpoint", {
+ now: new Date("2027-01-01T00:00:00Z"),
+ });
+ expect(after.signals.map((s) => s.id)).toContain(signalId);
+ });
+});
diff --git a/tests/core/brain/extract-signals.test.ts b/tests/core/brain/extract-signals.test.ts
new file mode 100644
index 00000000..1339eb4c
--- /dev/null
+++ b/tests/core/brain/extract-signals.test.ts
@@ -0,0 +1,301 @@
+/**
+ * Model-mined session signals (salience-lifecycle-enrichment, unit 2,
+ * t_1dace26d). Claims pinned here:
+ *
+ * 1. Phase one reads an ALREADY-IMPORTED session and returns a report
+ * carrying exactly one needs-llm-step envelope built on the spine.
+ * 2. The prompt mines USER turns only, mirroring the import path's rule,
+ * and the envelope is deterministic for a fixed set of turns.
+ * 3. A session with no imported turns, and one whose turns are all
+ * non-user, are refused BY NAME - never reported as an empty mine.
+ * 4. A session the capture boundary ignores is refused by name.
+ * 5. Phase two refuses an over-cap payload naming the cap and the count.
+ * 6. Phase two refuses an under-floor item naming the floor and the value.
+ * 7. A conforming payload writes `source_type: auto_extract` signals into
+ * `Brain/inbox/`, and each carries the session provenance.
+ * 8. The durability denylist rejects items by name, never silently.
+ * 9. Write approval on stages every accepted item into `Brain/pending/`
+ * instead, and writes nothing to the inbox.
+ * 10. A repeated payload dedups against the signals already on disk.
+ * 11. A write that fails PART WAY through the items is reported as the
+ * partial write it is: the error names the items already on disk and
+ * the one that failed, rather than leaving the caller to discover
+ * them.
+ */
+
+import { afterEach, beforeEach, expect, test } from "bun:test";
+import { existsSync, mkdirSync, mkdtempSync, readFileSync, readdirSync, rmSync } from "node:fs";
+import { tmpdir } from "node:os";
+import { join } from "node:path";
+
+import {
+ AUTO_EXTRACT_CONFIDENCE_FLOOR,
+ AUTO_EXTRACT_PER_SESSION_CAP,
+ commitExtractedSignals,
+ ExtractSignalsError,
+ ExtractSignalsWriteError,
+ planExtractSignals,
+} from "../../../src/core/brain/extract-signals.ts";
+import { NEEDS_LLM_STEP } from "../../../src/core/brain/llm-step.ts";
+import { ResponseCheckError } from "../../../src/core/brain/response-checks.ts";
+import { ResponseShapeError } from "../../../src/core/brain/response-shape.ts";
+import { bootstrapBrain } from "../../../src/core/brain/init.ts";
+import { brainConfigPath } from "../../../src/core/brain/paths.ts";
+import { atomicWriteFileSync } from "../../../src/core/fs-atomic.ts";
+import { importSessionRecall } from "../../../src/core/brain/session-recall.ts";
+import { parseSignal } from "../../../src/core/brain/signal.ts";
+import { BRAIN_SIGNAL_SOURCE_TYPE } from "../../../src/core/brain/types.ts";
+import type { SessionTurn } from "../../../src/core/brain/sessions/types.ts";
+
+let vault: string;
+const NOW = new Date("2026-08-22T10:00:00Z");
+const SESSION = "sess-alpha";
+
+/**
+ * Turns carry DISTINCT timestamps, as a real transcript does: the recall
+ * store orders raw turns chronologically and falls back to the record hash
+ * only for a tie, so a fixture that stamped one instant on every turn would
+ * pin the tie-break rather than the chronology the prompt depends on.
+ */
+let turnClock = 0;
+function turn(id: string, role: SessionTurn["role"], text: string): SessionTurn {
+ turnClock += 1;
+ const stamp = String(turnClock).padStart(2, "0");
+ return { turnId: id, timestamp: `2026-08-22T09:${stamp}:00Z`, role, text };
+}
+
+function importTurns(sessionId: string, turns: ReadonlyArray<SessionTurn>): void {
+ importSessionRecall(vault, { sessionId, turns, createdAt: NOW.toISOString() });
+}
+
+function inboxFiles(): string[] {
+ const dir = join(vault, "Brain", "inbox");
+ return existsSync(dir)
+ ? readdirSync(dir)
+ .filter((f) => f.endsWith(".md"))
+ .toSorted()
+ : [];
+}
+
+function pendingFiles(): string[] {
+ const dir = join(vault, "Brain", "pending");
+ return existsSync(dir)
+ ? readdirSync(dir)
+ .filter((f) => f.endsWith(".md"))
+ .toSorted()
+ : [];
+}
+
+function item(overrides: Record<string, unknown> = {}): Record<string, unknown> {
+ return {
+ topic: "release-notes-style",
+ signal: "positive",
+ principle: "Name the release theme in the heading, never the ticket id.",
+ confidence: 0.9,
+ ...overrides,
+ };
+}
+
+beforeEach(() => {
+ turnClock = 0;
+ vault = mkdtempSync(join(tmpdir(), "o2b-extract-signals-"));
+ mkdirSync(join(vault, "Brain"), { recursive: true });
+ importTurns(SESSION, [
+ turn("t1", "user", "Always name the release theme in the heading."),
+ turn("t2", "assistant", "Understood - I will use the theme."),
+ turn("t3", "user", "And never abbreviate the module names."),
+ ]);
+});
+
+afterEach(() => {
+ rmSync(vault, { recursive: true, force: true });
+});
+
+test("phase one carries exactly one spine envelope over the user turns", () => {
+ const plan = planExtractSignals(vault, SESSION, { now: NOW });
+ expect(plan.sessionId).toBe(SESSION);
+ expect(plan.turnsScanned).toBe(3);
+ expect(plan.turnsMined.map((t) => t.turnId)).toEqual(["t1", "t3"]);
+ expect(plan.llmStep.status).toBe(NEEDS_LLM_STEP);
+ expect(plan.llmStep.prompt).toContain("Always name the release theme");
+ // The assistant turn is not mining material.
+ expect(plan.llmStep.prompt).not.toContain("Understood - I will use the theme");
+ expect(plan.llmStep.schema_hints.length).toBeGreaterThan(0);
+ expect(plan.llmStep.target_path).toBe("Brain/inbox");
+ expect(plan.cap).toBe(AUTO_EXTRACT_PER_SESSION_CAP);
+ expect(plan.confidenceFloor).toBe(AUTO_EXTRACT_CONFIDENCE_FLOOR);
+});
+
+test("the envelope is deterministic for a fixed set of turns", () => {
+ const first = planExtractSignals(vault, SESSION, { now: NOW });
+ const second = planExtractSignals(vault, SESSION, { now: NOW });
+ expect(second.llmStep).toEqual(first.llmStep);
+});
+
+test("a session with no imported turns is refused by name", () => {
+ expect(() => planExtractSignals(vault, "sess-missing", { now: NOW })).toThrow(
+ ExtractSignalsError,
+ );
+ expect(() => planExtractSignals(vault, "sess-missing", { now: NOW })).toThrow(/sess-missing/);
+});
+
+test("a session whose turns are all non-user is refused by name", () => {
+ importTurns("sess-quiet", [turn("q1", "assistant", "Only I spoke here.")]);
+ expect(() => planExtractSignals(vault, "sess-quiet", { now: NOW })).toThrow(/user/);
+});
+
+test("a session the capture boundary ignores is refused by name", () => {
+ bootstrapBrain(vault);
+ const path = brainConfigPath(vault);
+ atomicWriteFileSync(
+ path,
+ `${readFileSync(path, "utf8")}\nsessions:\n ignore_patterns:\n - "cron-*"\n`,
+ );
+ importTurns("cron-nightly", [turn("c1", "user", "Nightly cron chatter.")]);
+ expect(() => planExtractSignals(vault, "cron-nightly", { now: NOW })).toThrow(/cron-nightly/);
+ expect(() => planExtractSignals(vault, "cron-nightly", { now: NOW })).toThrow(/ignore/);
+});
+
+test("an over-cap payload is refused naming the cap and the count", () => {
+ const overCap = AUTO_EXTRACT_PER_SESSION_CAP + 1;
+ const items = Array.from({ length: overCap }, (_v, i) => item({ topic: `topic-${i}` }));
+ let caught: unknown;
+ try {
+ commitExtractedSignals(vault, SESSION, { items }, { agent: "tester", now: NOW });
+ } catch (err) {
+ caught = err;
+ }
+ expect(caught).toBeInstanceOf(ResponseCheckError);
+ expect((caught as Error).message).toContain(String(AUTO_EXTRACT_PER_SESSION_CAP));
+ expect((caught as Error).message).toContain(String(overCap));
+ expect(inboxFiles()).toEqual([]);
+});
+
+test("an under-floor item is refused naming the floor and the value", () => {
+ const low = 0.11;
+ let caught: unknown;
+ try {
+ commitExtractedSignals(
+ vault,
+ SESSION,
+ { items: [item({ confidence: low })] },
+ { agent: "tester", now: NOW },
+ );
+ } catch (err) {
+ caught = err;
+ }
+ expect(caught).toBeInstanceOf(ResponseCheckError);
+ expect((caught as Error).message).toContain(String(AUTO_EXTRACT_CONFIDENCE_FLOOR));
+ expect((caught as Error).message).toContain(String(low));
+ expect(inboxFiles()).toEqual([]);
+});
+
+test("a structurally malformed payload is refused by the shape layer", () => {
+ expect(() =>
+ commitExtractedSignals(
+ vault,
+ SESSION,
+ { items: [{ topic: "t", signal: "sideways", principle: "p", confidence: 0.9 }] },
+ { agent: "tester", now: NOW },
+ ),
+ ).toThrow(ResponseShapeError);
+ expect(inboxFiles()).toEqual([]);
+});
+
+test("a conforming payload writes auto_extract signals into the inbox", () => {
+ const res = commitExtractedSignals(
+ vault,
+ SESSION,
+ {
+ items: [item(), item({ topic: "module-names", principle: "Never abbreviate module names." })],
+ },
+ { agent: "tester", now: NOW },
+ );
+ expect(res.written.length).toBe(2);
+ expect(res.staged).toBe(0);
+ const files = inboxFiles();
+ expect(files.length).toBe(2);
+ const body = readFileSync(join(vault, "Brain", "inbox", files[0]!), "utf8");
+ expect(body).toContain(`source_type: ${BRAIN_SIGNAL_SOURCE_TYPE.autoExtract}`);
+ expect(body).toContain(`session_ref: ${SESSION}`);
+});
+
+test("the durability denylist rejects an item by name rather than dropping it", () => {
+ const res = commitExtractedSignals(
+ vault,
+ SESSION,
+ { items: [item(), item({ topic: "noise", principle: "temporary scratch note" })] },
+ {
+ agent: "tester",
+ now: NOW,
+ durabilityDenylist: [/scratch/],
+ },
+ );
+ expect(res.written.length).toBe(1);
+ expect(res.rejected.map((r) => r.topic)).toEqual(["noise"]);
+ expect(res.rejected[0]!.reason.length).toBeGreaterThan(0);
+});
+
+test("write approval on stages every item into pending and writes no inbox file", () => {
+ const res = commitExtractedSignals(
+ vault,
+ SESSION,
+ { items: [item()] },
+ { agent: "tester", now: NOW, writeApprovalEnabled: true },
+ );
+ expect(res.staged).toBe(1);
+ expect(pendingFiles().length).toBe(1);
+ expect(inboxFiles()).toEqual([]);
+});
+
+test("a repeated payload dedups against the signals already on disk", () => {
+ const payload = { items: [item()] };
+ commitExtractedSignals(vault, SESSION, payload, { agent: "tester", now: NOW });
+ const second = commitExtractedSignals(vault, SESSION, payload, { agent: "tester", now: NOW });
+ expect(second.written.length).toBe(0);
+ expect(second.deduped).toBe(1);
+ expect(inboxFiles().length).toBe(1);
+});
+
+test("a mid-loop write failure names what is already on disk and what failed", () => {
+ // The failing write is a real one, not a stub: `topic` becomes the
+ // signal's slug and a colon is not a legal filename character, so the
+ // second item cannot be written after the first already has been.
+ const items = [item(), item({ topic: "module:names", principle: "Never abbreviate a module." })];
+ let caught: unknown;
+ try {
+ commitExtractedSignals(vault, SESSION, { items }, { agent: "tester", now: NOW });
+ } catch (err) {
+ caught = err;
+ }
+ expect(caught).toBeInstanceOf(ExtractSignalsWriteError);
+ const err = caught as ExtractSignalsWriteError;
+ expect(err.topic).toBe("module:names");
+ expect(err.written.map((w) => w.topic)).toEqual(["release-notes-style"]);
+ expect(err.remaining).toBe(1);
+ // The accounting is in the message too, for a caller that only logs it.
+ expect(err.message).toContain(err.written[0]!.id);
+ // The first item stayed on disk: this is a partial write, and saying so
+ // is the whole point.
+ expect(inboxFiles().length).toBe(1);
+});
+
+test("the new source_type round-trips and an unknown member is still refused", () => {
+ const res = commitExtractedSignals(
+ vault,
+ SESSION,
+ { items: [item()] },
+ { agent: "tester", now: NOW },
+ );
+ const parsed = parseSignal(res.written[0]!.path);
+ expect(parsed.source_type).toBe(BRAIN_SIGNAL_SOURCE_TYPE.autoExtract);
+ // The vocabulary is still closed: the parser refuses a member nobody
+ // declared, and names the whole legal set rather than a stale subset.
+ const path = res.written[0]!.path;
+ atomicWriteFileSync(
+ path,
+ readFileSync(path, "utf8").replace("source_type: auto_extract", "source_type: sideways"),
+ );
+ expect(() => parseSignal(path)).toThrow(/auto_extract/);
+ expect(() => parseSignal(path)).toThrow(/sideways/);
+});
diff --git a/tests/core/brain/llm-step.test.ts b/tests/core/brain/llm-step.test.ts
new file mode 100644
index 00000000..a9d8bd46
--- /dev/null
+++ b/tests/core/brain/llm-step.test.ts
@@ -0,0 +1,229 @@
+/**
+ * Needs-llm-step envelope spine (salience-lifecycle-enrichment, unit 0).
+ *
+ * Three shapes already speak this grammar - the durable write-session
+ * envelope, the diarization step, the rollup envelope - and until now none
+ * of them named it. The spine names it once. What this suite pins:
+ *
+ * 1. The spine field set is exactly `status`, `step`, `prompt`,
+ * `schema_hints`, `target_path`: the intersection of the three, and
+ * nothing beyond it. A field only two of them carry is not spine.
+ * 2. `buildNeedsLlmStep` stamps the status literal itself, so no
+ * construction site can spell it a fourth way - including a fields
+ * object that carries a `status` of its own at runtime.
+ * 3. The built envelope is frozen and owns its hint list: the array the
+ * caller passed cannot mutate the envelope afterwards.
+ * 4. Key order of the built object is `status` first, then the caller's
+ * fields in declaration order - the serialized shape the CLI and MCP
+ * surfaces already emit for these envelopes.
+ * 5. A blank step, prompt, or target_path is refused by name; an empty
+ * hint list is legal (a step can genuinely carry no hints).
+ * 6. Adoption is type-level and additive: the diarization step and the
+ * rollup envelope ARE the spine, and the durable `WriteSessionEnvelope`
+ * still carries every spine field with the same names and types.
+ * 7. Adoption changed no bytes: a rollup envelope serializes exactly as it
+ * did before the spine landed, key order included, and the diarization
+ * step's key order is unchanged.
+ */
+
+import { afterEach, beforeEach, expect, test } from "bun:test";
+import { mkdirSync, mkdtempSync, rmSync } from "node:fs";
+import { tmpdir } from "node:os";
+import { join } from "node:path";
+
+import { diarize } from "../../../src/core/brain/diarization.ts";
+import { upsertEntity } from "../../../src/core/brain/entities/registry.ts";
+import {
+ buildNeedsLlmStep,
+ LlmStepError,
+ NEEDS_LLM_STEP,
+ NEEDS_LLM_STEP_KEYS,
+ type LlmStepFields,
+ type NeedsLlmStep,
+} from "../../../src/core/brain/llm-step.ts";
+import { planRollupLadder } from "../../../src/core/brain/rollup-ladder.ts";
+import type { WriteSessionEnvelope } from "../../../src/core/brain/write-session/types.ts";
+
+const RUN_ID = "dream-2026-07-19-100000";
+const NOW = new Date("2026-07-19T10:00:00Z");
+
+/**
+ * The rollup envelope exactly as it serialized before the spine existed,
+ * captured from the ladder on the parent commit. Byte-for-byte, key order
+ * included - this envelope crosses the CLI and MCP boundaries as JSON.
+ */
+const ROLLUP_ENVELOPE_JSON_BEFORE_SPINE =
+ '{"status":"needs-llm-step","step":"rollup:fact","tier":"fact","produces":"rollup",' +
+ '"prompt":"Consolidate the 5 new fact items since the last rollup into one rollup-tier ' +
+ 'summary note. Cite the items you fold in; submit the full note.",' +
+ '"schema_hints":["frontmatter: required YAML block with at least a `kind` key",' +
+ '"tier: rollup (the rollup\'s tier weight)"],' +
+ '"target_path":"Brain/rollups/rollup-rollup-dream-2026-07-19-100000.md"}';
+
+/** Compile-time pin: anything passed here carries the whole spine. */
+function acceptsSpine(_envelope: NeedsLlmStep): void {}
+/** Compile-time pin: anything passed here carries the spine's payload fields. */
+function acceptsSpineFields(_fields: LlmStepFields): void {}
+
+function fired() {
+ const plan = planRollupLadder({
+ factCount: 5,
+ ledger: null,
+ thresholds: { fact: 5, identity: 2 },
+ runId: RUN_ID,
+ });
+ return plan.entries[0]!.envelope;
+}
+
+test("the spine field set is the intersection of the shapes that already speak the grammar", () => {
+ expect([...NEEDS_LLM_STEP_KEYS]).toEqual([
+ "status",
+ "step",
+ "prompt",
+ "schema_hints",
+ "target_path",
+ ]);
+ const built = buildNeedsLlmStep({
+ step: "s",
+ prompt: "p",
+ schema_hints: [],
+ target_path: "Brain/x.md",
+ });
+ // The constant cannot drift from the builder's own output.
+ expect(Object.keys(built)).toEqual([...NEEDS_LLM_STEP_KEYS]);
+});
+
+test("the builder stamps the status literal and freezes what it returns", () => {
+ const built = buildNeedsLlmStep({
+ step: "profile-prose",
+ prompt: "Write the prose.",
+ schema_hints: ["body: replace only the marker"],
+ target_path: "Brain/profiles/ent-person-ada.md",
+ });
+ expect(built.status).toBe(NEEDS_LLM_STEP);
+ expect(NEEDS_LLM_STEP).toBe("needs-llm-step");
+ expect(Object.isFrozen(built)).toBe(true);
+ expect(Object.isFrozen(built.schema_hints)).toBe(true);
+});
+
+test("the envelope owns its hint list: mutating the caller's array cannot reach it", () => {
+ const hints = ["body: replace only the marker"];
+ const built = buildNeedsLlmStep({
+ step: "profile-prose",
+ prompt: "Write the prose.",
+ schema_hints: hints,
+ target_path: "Brain/profiles/ent-person-ada.md",
+ });
+ hints.push("smuggled");
+ expect(built.schema_hints).toEqual(["body: replace only the marker"]);
+});
+
+test("status leads the key order and the caller's extra fields keep their place", () => {
+ const built = buildNeedsLlmStep({
+ step: "rollup:fact",
+ tier: "fact",
+ produces: "rollup",
+ prompt: "Consolidate.",
+ schema_hints: ["tier: rollup"],
+ target_path: "Brain/rollups/r.md",
+ });
+ expect(Object.keys(built)).toEqual([
+ "status",
+ "step",
+ "tier",
+ "produces",
+ "prompt",
+ "schema_hints",
+ "target_path",
+ ]);
+});
+
+test("a runtime status on the caller's fields cannot displace the stamped literal", () => {
+ // The type forbids this; a payload assembled at runtime - a spread of a
+ // wider record, a parsed object - does not go through the type.
+ const hostile = {
+ status: "done",
+ step: "profile-prose",
+ prompt: "Write the prose.",
+ schema_hints: ["a hint"],
+ target_path: "Brain/profiles/p.md",
+ } as unknown as LlmStepFields;
+ const built = buildNeedsLlmStep(hostile);
+ expect(built.status).toBe(NEEDS_LLM_STEP);
+ // And it does not reappear later in the object either.
+ expect(Object.keys(built)).toEqual([...NEEDS_LLM_STEP_KEYS]);
+});
+
+test("a blank step, prompt, or target path is refused by name", () => {
+ const base = {
+ step: "profile-prose",
+ prompt: "Write the prose.",
+ schema_hints: ["a hint"],
+ target_path: "Brain/profiles/p.md",
+ };
+ expect(() => buildNeedsLlmStep({ ...base, step: " " })).toThrow(LlmStepError);
+ expect(() => buildNeedsLlmStep({ ...base, step: " " })).toThrow(/step/);
+ expect(() => buildNeedsLlmStep({ ...base, prompt: "" })).toThrow(/prompt/);
+ expect(() => buildNeedsLlmStep({ ...base, target_path: "\t" })).toThrow(/target_path/);
+ // A step with nothing to hint at is legal.
+ expect(buildNeedsLlmStep({ ...base, schema_hints: [] }).schema_hints).toEqual([]);
+});
+
+test("the rollup envelope is the spine, and serializes as it did before adoption", () => {
+ const envelope = fired();
+ acceptsSpine(envelope);
+ acceptsSpineFields(envelope);
+ expect(JSON.stringify(envelope)).toBe(ROLLUP_ENVELOPE_JSON_BEFORE_SPINE);
+ for (const key of NEEDS_LLM_STEP_KEYS) expect(Object.hasOwn(envelope, key)).toBe(true);
+});
+
+test("the durable write-session envelope still carries every spine field", () => {
+ const envelope: WriteSessionEnvelope = {
+ status: "needs-llm-step",
+ session_id: "ws-1",
+ kind: "artifact",
+ step: "artifact",
+ prompt: "Write the note.",
+ schema_hints: ["frontmatter: kind"],
+ errors: [],
+ attempts_left: 3,
+ expires_at: "2026-07-20T10:00:00Z",
+ target_path: "Brain/notes/n.md",
+ existing: null,
+ };
+ // The superset keeps its own fields; only the spine payload is shared,
+ // because its `status` widens to the full session-status union.
+ acceptsSpineFields(envelope);
+ for (const key of NEEDS_LLM_STEP_KEYS) expect(Object.hasOwn(envelope, key)).toBe(true);
+});
+
+let vault: string;
+
+beforeEach(() => {
+ vault = mkdtempSync(join(tmpdir(), "o2b-llm-step-"));
+ mkdirSync(join(vault, "Brain"), { recursive: true });
+ upsertEntity(vault, {
+ category: "person",
+ name: "Ada Lovelace",
+ agent: "test",
+ now: NOW,
+ body: "Ada Lovelace designed an early programming method.",
+ });
+});
+
+afterEach(() => {
+ rmSync(vault, { recursive: true, force: true });
+});
+
+test("the diarization step is the spine, with its key order unchanged", () => {
+ const report = diarize(vault, { query: "Ada Lovelace" }, { now: NOW });
+ acceptsSpine(report.llmStep);
+ expect(Object.keys(report.llmStep)).toEqual([
+ "status",
+ "step",
+ "prompt",
+ "schema_hints",
+ "target_path",
+ ]);
+ expect(report.llmStep.status).toBe(NEEDS_LLM_STEP);
+});
diff --git a/tests/core/brain/notes/note-delete-linked.test.ts b/tests/core/brain/notes/note-delete-linked.test.ts
new file mode 100644
index 00000000..c830f5f9
--- /dev/null
+++ b/tests/core/brain/notes/note-delete-linked.test.ts
@@ -0,0 +1,349 @@
+/**
+ * `--delete-linked`: a note delete that may also remove the files whose
+ * whole reason to exist was that note (unit 3a / t_5e338af1).
+ *
+ * The defect this closes. A note delete removes one file and reports the
+ * inbound references it strands. When the note was an imported source,
+ * those references are not navigation aids - they are a summary page, a
+ * signal and a preference that say nothing except what that note said, and
+ * an operator removing the note had to hand-chase every one of them. The
+ * remedy already exists for the ingest side (`deleteBySource`) and is
+ * deliberately narrow, and that narrowness is the whole design: only a
+ * single-purpose derived file tracing SOLELY to the subject is ever
+ * deleted; anything else that merely references it is REPORTED.
+ *
+ * Claims pinned here:
+ *
+ * 1. Without the flag, delete is byte-identical to before: no cascade is
+ * computed and no derived file is touched.
+ * 2. A dry run with the flag lists the deletion set (the note plus its
+ * solely-derived files) and the report-only references SEPARATELY, and
+ * writes nothing.
+ * 3. The derived-set fold walks `Brain/` and SAYS SO on the response, so a
+ * caller can tell a scope boundary from an empty result - user notes
+ * are outside the fold by construction and are reported, never deleted.
+ * 4. A Brain page citing a SECOND source is reported and preserved, even
+ * under confirm. The module header's commitment - a delete rewrites
+ * nothing and reports what it strands - stands for everything outside
+ * the solely-derived set.
+ * 5. Confirm removes exactly the listed set, behind ONE recovery point
+ * covering the Brain half of it, with the verdict saying that the note
+ * itself is outside every archive.
+ * 6. The count guard asserts the DELETION SET size under the flag (not the
+ * inbound-reference count), and a mismatch aborts before any unlink.
+ * 7. The flag belongs to delete alone; on any other action it is refused
+ * by name rather than ignored.
+ * 8. A Brain page that only MENTIONS the note - a `[[wikilink]]` in prose
+ * and no `source:` array - is reported and never deleted, however
+ * derived-looking the directory it sits in. The solely-derived test is
+ * vacuously true for a page declaring no provenance at all, so the
+ * cascade demands declared provenance on top of it.
+ */
+
+import { afterEach, beforeEach, describe, expect, test } from "bun:test";
+import { existsSync, mkdirSync, mkdtempSync, rmSync, writeFileSync } from "node:fs";
+import { tmpdir } from "node:os";
+import { join } from "node:path";
+
+import { bootstrapBrain } from "../../../../src/core/brain/init.ts";
+import {
+ DERIVED_SET_SCOPE,
+ NOTE_LIFECYCLE_ACTION,
+ noteLifecycle,
+ NoteLifecycleError,
+} from "../../../../src/core/brain/notes/lifecycle.ts";
+import { CountGuardError } from "../../../../src/core/brain/count-guard.ts";
+import { RECOVERABILITY_STATE } from "../../../../src/core/brain/gates/recoverability.ts";
+import { writePreference } from "../../../../src/core/brain/preference.ts";
+import { writeSignal } from "../../../../src/core/brain/signal.ts";
+import { atomicWriteFileSync } from "../../../../src/core/fs-atomic.ts";
+
+let vault: string;
+let configHome: string;
+
+const TARGET = "Imports/Benchmark.md";
+const OTHER = "Imports/Legit.md";
+const NOW = new Date("2026-06-01T00:00:00Z");
+
+beforeEach(() => {
+ vault = mkdtempSync(join(tmpdir(), "o2b-delete-linked-"));
+ configHome = mkdtempSync(join(tmpdir(), "o2b-delete-linked-cfg-"));
+ const configPath = join(configHome, "config.yaml");
+ atomicWriteFileSync(configPath, `vault: ${vault}\n`);
+ bootstrapBrain(vault, { configPath });
+});
+
+afterEach(() => {
+ rmSync(vault, { recursive: true, force: true });
+ rmSync(configHome, { recursive: true, force: true });
+});
+
+function note(rel: string, body: string): void {
+ const abs = join(vault, rel);
+ mkdirSync(join(abs, ".."), { recursive: true });
+ writeFileSync(abs, body);
+}
+
+/**
+ * A vault where the note under test has one solely-derived signal, one
+ * preference folded from it, one signal that also cites a second note, and
+ * one ordinary user note that merely links to it.
+ */
+function seed(): { solelyDerived: string; shared: string } {
+ note(TARGET, "---\ntitle: Benchmark\n---\n\nrows\n");
+ note(OTHER, "---\ntitle: Legit\n---\n\nprose\n");
+ note("Projects/Reader.md", `See [[${"Imports/Benchmark"}]] for the numbers.\n`);
+
+ const solely = writeSignal(vault, {
+ topic: "bench",
+ signal: "positive",
+ agent: "tester",
+ principle: "Only the benchmark note says this.",
+ created_at: "2026-06-01T00:00:00Z",
+ date: "2026-06-01",
+ slug: "bench-only",
+ source: ["[[Imports/Benchmark]]"],
+ });
+ const shared = writeSignal(vault, {
+ topic: "bench",
+ signal: "positive",
+ agent: "tester",
+ principle: "Two notes say this.",
+ created_at: "2026-06-01T00:00:00Z",
+ date: "2026-06-01",
+ slug: "bench-shared",
+ source: ["[[Imports/Benchmark]]", "[[Imports/Legit]]"],
+ });
+ writePreference(vault, {
+ slug: "bench-pref",
+ topic: "bench",
+ principle: "Folded from the benchmark signal alone.",
+ created_at: "2026-06-01T00:00:00Z",
+ unconfirmed_until: "2026-06-08T00:00:00Z",
+ status: "confirmed",
+ evidenced_by: [`[[${solely.id}]]`],
+ });
+ return { solelyDerived: solely.path, shared: shared.path };
+}
+
+/** `Brain/inbox/sig-x.md` from an absolute path. */
+function vaultRel(abs: string): string {
+ return abs
+ .slice(vault.length + 1)
+ .split("\\")
+ .join("/");
+}
+
+describe("the flag is opt-in", () => {
+ test("a delete without it computes no cascade and touches no derived file", async () => {
+ const { solelyDerived } = seed();
+ const res = await noteLifecycle(vault, {
+ action: NOTE_LIFECYCLE_ACTION.delete,
+ path: TARGET,
+ apply: true,
+ confirm: true,
+ now: NOW,
+ });
+ expect(res.cascade).toBeNull();
+ expect(existsSync(solelyDerived)).toBe(true);
+ });
+
+ test("it is refused by name on an action that is not a delete", async () => {
+ seed();
+ await expect(
+ noteLifecycle(vault, {
+ action: NOTE_LIFECYCLE_ACTION.rename,
+ path: TARGET,
+ to: "Imports/Renamed.md",
+ deleteLinked: true,
+ apply: true,
+ }),
+ ).rejects.toThrow(NoteLifecycleError);
+ expect(existsSync(join(vault, TARGET))).toBe(true);
+ });
+});
+
+describe("the dry run", () => {
+ test("lists the deletion set and the report-only references separately", async () => {
+ const { solelyDerived, shared } = seed();
+ const res = await noteLifecycle(vault, {
+ action: NOTE_LIFECYCLE_ACTION.delete,
+ path: TARGET,
+ deleteLinked: true,
+ now: NOW,
+ });
+
+ expect(res.applied).toBe(false);
+ expect(res.cascade).not.toBeNull();
+ const cascade = res.cascade!;
+ // The note itself is first; the derived files follow, sorted.
+ expect(cascade.deletionSet[0]).toBe(TARGET);
+ expect(cascade.deletionSet).toContain(vaultRel(solelyDerived));
+ // The preference folded solely from that signal rides along.
+ expect(cascade.deletionSet.some((p) => p.includes("pref-bench-pref"))).toBe(true);
+ // The shared signal and the user note are reported, never in the set.
+ expect(cascade.deletionSet).not.toContain(vaultRel(shared));
+ expect(cascade.reportedFiles).toContain(vaultRel(shared));
+ expect(cascade.reportedFiles).toContain("Projects/Reader.md");
+ // Nothing overlaps: a path is either deleted or reported, never both.
+ for (const path of cascade.reportedFiles) {
+ expect(cascade.deletionSet).not.toContain(path);
+ }
+ // And nothing was written.
+ expect(existsSync(join(vault, TARGET))).toBe(true);
+ expect(existsSync(solelyDerived)).toBe(true);
+ expect(res.snapshot).toBeNull();
+ });
+
+ test("names the scope the derived-set fold actually walked", async () => {
+ seed();
+ const res = await noteLifecycle(vault, {
+ action: NOTE_LIFECYCLE_ACTION.delete,
+ path: TARGET,
+ deleteLinked: true,
+ now: NOW,
+ });
+ expect(res.cascade!.scannedScope).toBe(DERIVED_SET_SCOPE);
+ // A user note outside that scope is reported rather than folded in.
+ expect(res.cascade!.reportedFiles).toContain("Projects/Reader.md");
+ });
+});
+
+describe("a prose mention is not a derivation", () => {
+ /**
+ * A Brain page inside a derivation directory whose only tie to the note
+ * is a `[[wikilink]]` in its body: no `source:` array, no `source_path`,
+ * nothing declaring where it came from.
+ */
+ const PROSE_ONLY = "Brain/inbox/sig-2026-06-01-prose-mention.md";
+
+ function seedProseMention(): void {
+ note(
+ PROSE_ONLY,
+ [
+ "---",
+ "id: sig-2026-06-01-prose-mention",
+ "topic: bench",
+ "signal: positive",
+ "---",
+ "",
+ "The operator compared this against [[Imports/Benchmark]] once.",
+ "",
+ ].join("\n"),
+ );
+ }
+
+ test("the dry run reports it and leaves it out of the deletion set", async () => {
+ seed();
+ seedProseMention();
+ const res = await noteLifecycle(vault, {
+ action: NOTE_LIFECYCLE_ACTION.delete,
+ path: TARGET,
+ deleteLinked: true,
+ now: NOW,
+ });
+ expect(res.cascade!.deletionSet).not.toContain(PROSE_ONLY);
+ expect(res.cascade!.reportedFiles).toContain(PROSE_ONLY);
+ });
+
+ test("confirm leaves it on disk", async () => {
+ const { solelyDerived } = seed();
+ seedProseMention();
+ const res = await noteLifecycle(vault, {
+ action: NOTE_LIFECYCLE_ACTION.delete,
+ path: TARGET,
+ deleteLinked: true,
+ apply: true,
+ confirm: true,
+ now: NOW,
+ });
+ expect(res.applied).toBe(true);
+ // The page that DECLARED the note as its source is gone; the one that
+ // only wrote its name in a sentence is not.
+ expect(existsSync(solelyDerived)).toBe(false);
+ expect(existsSync(join(vault, PROSE_ONLY))).toBe(true);
+ });
+});
+
+describe("confirm", () => {
+ test("removes exactly the listed set and preserves every shared reference", async () => {
+ const { solelyDerived, shared } = seed();
+ const plan = await noteLifecycle(vault, {
+ action: NOTE_LIFECYCLE_ACTION.delete,
+ path: TARGET,
+ deleteLinked: true,
+ now: NOW,
+ });
+ const planned = [...plan.cascade!.deletionSet];
+
+ const res = await noteLifecycle(vault, {
+ action: NOTE_LIFECYCLE_ACTION.delete,
+ path: TARGET,
+ deleteLinked: true,
+ apply: true,
+ confirm: true,
+ now: NOW,
+ });
+ expect(res.applied).toBe(true);
+ expect([...res.cascade!.deletionSet]).toEqual(planned);
+ for (const path of planned) expect(existsSync(join(vault, path))).toBe(false);
+ // The shared signal and the user note survive, unrewritten.
+ expect(existsSync(shared)).toBe(true);
+ expect(existsSync(join(vault, "Projects/Reader.md"))).toBe(true);
+ expect(res.references.filesRewritten).toBe(0);
+ expect(existsSync(solelyDerived)).toBe(false);
+ });
+
+ test("takes ONE recovery point and says what it does not cover", async () => {
+ seed();
+ const res = await noteLifecycle(vault, {
+ action: NOTE_LIFECYCLE_ACTION.delete,
+ path: TARGET,
+ deleteLinked: true,
+ apply: true,
+ confirm: true,
+ now: NOW,
+ });
+ expect(res.snapshot).not.toBeNull();
+ expect(existsSync(res.snapshot!.path)).toBe(true);
+ // The Brain half of the set is inside the archive; the note is not.
+ expect(res.recoverability.state).toBe(RECOVERABILITY_STATE.partial);
+ expect(res.recoverability.blockers).toContain("outside_brain_root");
+ });
+});
+
+describe("the count guard", () => {
+ test("asserts the deletion-set size and aborts before any unlink", async () => {
+ const { solelyDerived } = seed();
+ await expect(
+ noteLifecycle(vault, {
+ action: NOTE_LIFECYCLE_ACTION.delete,
+ path: TARGET,
+ deleteLinked: true,
+ apply: true,
+ confirm: true,
+ expect: 1,
+ now: NOW,
+ }),
+ ).rejects.toThrow(CountGuardError);
+ expect(existsSync(join(vault, TARGET))).toBe(true);
+ expect(existsSync(solelyDerived)).toBe(true);
+
+ const plan = await noteLifecycle(vault, {
+ action: NOTE_LIFECYCLE_ACTION.delete,
+ path: TARGET,
+ deleteLinked: true,
+ now: NOW,
+ });
+ const res = await noteLifecycle(vault, {
+ action: NOTE_LIFECYCLE_ACTION.delete,
+ path: TARGET,
+ deleteLinked: true,
+ apply: true,
+ confirm: true,
+ expect: plan.cascade!.deletionSet.length,
+ now: NOW,
+ });
+ expect(res.applied).toBe(true);
+ });
+});
diff --git a/tests/core/brain/response-checks.test.ts b/tests/core/brain/response-checks.test.ts
new file mode 100644
index 00000000..276859bc
--- /dev/null
+++ b/tests/core/brain/response-checks.test.ts
@@ -0,0 +1,178 @@
+/**
+ * Semantic-checker registry (salience-lifecycle-enrichment, unit 0).
+ *
+ * `ShapeDescriptor` is deliberately shallow, so constraints that read more
+ * than one value at a time - cardinality, cross-item rules, caps and floors
+ * - cannot be written there without deepening the descriptor language the
+ * response-shape layer keeps flat on purpose. They live here instead, beside
+ * it, following the research citation check that already validates set
+ * membership next to its descriptor. What this suite pins:
+ *
+ * 1. A check registers under a surface name and is found by it; the
+ * registry can name every surface it holds.
+ * 2. Registration is fail-loud: a second check for the same surface throws
+ * rather than silently replacing the first, and a blank surface is
+ * refused.
+ * 3. The gate is FAIL-CLOSED: asserting a surface nobody registered throws
+ * a named refusal. An unchecked surface must never read as a clean one.
+ * 4. A conforming payload passes silently, like `assertResponseShape`.
+ * 5. A violating payload throws `ResponseCheckError` carrying the surface,
+ * the first violation's code and path, and the complete violation list -
+ * routing is on fields, never on parsed prose.
+ * 6. Violation codes come from the frozen vocabulary: a check returning a
+ * code outside it is itself refused, so no refusal reaches a caller
+ * unnamed.
+ * 7. The constraints the descriptor language cannot express are expressible
+ * here - a worked cardinality rule (exactly one recommended alternative)
+ * and a worked cross-item rule (every cited source was consulted).
+ */
+
+import { expect, test } from "bun:test";
+
+import {
+ assertResponseCheck,
+ getResponseCheck,
+ listResponseCheckSurfaces,
+ registerResponseCheck,
+ ResponseCheckError,
+ SEMANTIC_VIOLATION_CODES,
+ semanticViolation,
+ type ResponseCheck,
+} from "../../../src/core/brain/response-checks.ts";
+import { SHAPE_ROOT_PATH } from "../../../src/core/brain/response-shape.ts";
+
+/** Payload shape the worked cardinality example validates. */
+interface Alternatives {
+ readonly alternatives: ReadonlyArray<{ readonly name: string; readonly recommended: boolean }>;
+}
+
+const exactlyOneRecommended: ResponseCheck = (payload) => {
+ const alternatives = (payload as Alternatives).alternatives;
+ const recommended = alternatives.filter((a) => a.recommended);
+ if (recommended.length === 1) return [];
+ return [
+ semanticViolation(
+ SEMANTIC_VIOLATION_CODES.cardinality,
+ `${SHAPE_ROOT_PATH}.alternatives`,
+ `expected exactly one recommended alternative, found ${recommended.length}`,
+ ),
+ ];
+};
+
+test("a check registers under a surface name and is found by it", () => {
+ const surface = "test_lookup";
+ registerResponseCheck(surface, exactlyOneRecommended);
+ expect(getResponseCheck(surface)).toBe(exactlyOneRecommended);
+ expect(listResponseCheckSurfaces()).toContain(surface);
+ expect(getResponseCheck("test_never_registered")).toBeUndefined();
+});
+
+test("registration is fail-loud: no duplicate surface, no blank surface", () => {
+ const surface = "test_duplicate";
+ registerResponseCheck(surface, exactlyOneRecommended);
+ expect(() => registerResponseCheck(surface, exactlyOneRecommended)).toThrow(/already registered/);
+ expect(() => registerResponseCheck(" ", exactlyOneRecommended)).toThrow(/surface/);
+});
+
+test("asserting a surface nobody registered is a named refusal, never a clean pass", () => {
+ let thrown: unknown;
+ try {
+ assertResponseCheck("test_unregistered_surface", { anything: true });
+ } catch (err) {
+ thrown = err;
+ }
+ expect(thrown).toBeInstanceOf(ResponseCheckError);
+ const error = thrown as ResponseCheckError;
+ expect(error.code).toBe(SEMANTIC_VIOLATION_CODES.unregistered);
+ expect(error.surface).toBe("test_unregistered_surface");
+ expect(error.message).toContain("test_unregistered_surface");
+});
+
+test("a conforming payload passes silently", () => {
+ const surface = "test_conforming";
+ registerResponseCheck(surface, exactlyOneRecommended);
+ expect(() =>
+ assertResponseCheck(surface, {
+ alternatives: [
+ { name: "a", recommended: true },
+ { name: "b", recommended: false },
+ ],
+ }),
+ ).not.toThrow();
+});
+
+test("a violating payload throws with the surface, the code, the path, and every violation", () => {
+ const surface = "test_violating";
+ registerResponseCheck(surface, exactlyOneRecommended);
+ let thrown: unknown;
+ try {
+ assertResponseCheck(surface, {
+ alternatives: [
+ { name: "a", recommended: true },
+ { name: "b", recommended: true },
+ ],
+ });
+ } catch (err) {
+ thrown = err;
+ }
+ expect(thrown).toBeInstanceOf(ResponseCheckError);
+ const error = thrown as ResponseCheckError;
+ expect(error.name).toBe("ResponseCheckError");
+ expect(error.surface).toBe(surface);
+ expect(error.code).toBe(SEMANTIC_VIOLATION_CODES.cardinality);
+ expect(error.path).toBe("$.alternatives");
+ expect(error.violations).toHaveLength(1);
+ expect(Object.isFrozen(error.violations)).toBe(true);
+ expect(error.message).toBe(
+ `${surface} response checks violated: $.alternatives: expected exactly one recommended alternative, found 2`,
+ );
+});
+
+test("a check returning a code outside the frozen vocabulary is itself refused", () => {
+ const surface = "test_unnamed_code";
+ registerResponseCheck(surface, () => [
+ { code: "made_up_code", path: SHAPE_ROOT_PATH, message: "no" } as never,
+ ]);
+ expect(() => assertResponseCheck(surface, {})).toThrow(/made_up_code/);
+ expect(Object.isFrozen(SEMANTIC_VIOLATION_CODES)).toBe(true);
+});
+
+test("cross-item rules the descriptor language cannot express live here", () => {
+ const surface = "test_cross_item";
+ registerResponseCheck(surface, (payload) => {
+ const report = payload as {
+ readonly sources: ReadonlyArray<string>;
+ readonly findings: ReadonlyArray<{ readonly sources: ReadonlyArray<string> }>;
+ };
+ const consulted = new Set(report.sources);
+ return report.findings.flatMap((finding, index) =>
+ finding.sources
+ .filter((source) => !consulted.has(source))
+ .map((source) =>
+ semanticViolation(
+ SEMANTIC_VIOLATION_CODES.setMembership,
+ `${SHAPE_ROOT_PATH}.findings[${index}].sources`,
+ `cites a source not in the consulted set: ${JSON.stringify(source)}`,
+ ),
+ ),
+ );
+ });
+
+ expect(() =>
+ assertResponseCheck(surface, { sources: ["a"], findings: [{ sources: ["a"] }] }),
+ ).not.toThrow();
+
+ let thrown: unknown;
+ try {
+ assertResponseCheck(surface, {
+ sources: ["a"],
+ findings: [{ sources: ["a"] }, { sources: ["b", "c"] }],
+ });
+ } catch (err) {
+ thrown = err;
+ }
+ const error = thrown as ResponseCheckError;
+ expect(error.code).toBe(SEMANTIC_VIOLATION_CODES.setMembership);
+ expect(error.violations).toHaveLength(2);
+ expect(error.path).toBe("$.findings[1].sources");
+});
diff --git a/tests/core/brain/response-shape.test.ts b/tests/core/brain/response-shape.test.ts
index 4f5eea79..07cecdfe 100644
--- a/tests/core/brain/response-shape.test.ts
+++ b/tests/core/brain/response-shape.test.ts
@@ -18,8 +18,11 @@ import { parseDeriveFactInput } from "../../../src/core/brain/derived-fact.ts";
import { parseResearchReportInput } from "../../../src/core/brain/research/research.ts";
import {
DERIVED_FACT_SHAPE,
+ DESIGN_NOTE_SHAPE,
DISTILL_CLAIMS_SHAPE,
+ EXTRACTED_SIGNALS_SHAPE,
MODEL_AUTHORED_SHAPES,
+ SKILL_PAGE_DRAFT_SHAPE,
RESEARCH_REPORT_SHAPE,
ResponseShapeError,
SHAPE_DESCRIPTOR_KEYS,
@@ -137,7 +140,14 @@ describe("assertResponseShape", () => {
describe("model-authored descriptors", () => {
test("one descriptor per model-authored write path, all registered", () => {
expect(new Set(Object.values(MODEL_AUTHORED_SHAPES))).toEqual(
- new Set([DISTILL_CLAIMS_SHAPE, DERIVED_FACT_SHAPE, RESEARCH_REPORT_SHAPE]),
+ new Set([
+ DISTILL_CLAIMS_SHAPE,
+ DERIVED_FACT_SHAPE,
+ RESEARCH_REPORT_SHAPE,
+ EXTRACTED_SIGNALS_SHAPE,
+ SKILL_PAGE_DRAFT_SHAPE,
+ DESIGN_NOTE_SHAPE,
+ ]),
);
});
diff --git a/tests/core/brain/salience-gate.test.ts b/tests/core/brain/salience-gate.test.ts
new file mode 100644
index 00000000..cea17316
--- /dev/null
+++ b/tests/core/brain/salience-gate.test.ts
@@ -0,0 +1,302 @@
+/**
+ * Deterministic salience gate over the dream rollup fold set
+ * (salience-lifecycle-enrichment, unit 1, t_de8a0b2d).
+ *
+ * Claims pinned here:
+ * 1. The combined score is a weighted sum of three named components
+ * whose weights sum to exactly 1, so a score can never leave [0, 1].
+ * 2. Scoring is deterministic and pure: the same components yield a
+ * byte-identical score every time, in any order.
+ * 3. Each component is monotone - raising one signal never lowers the
+ * score - and an all-zero item scores exactly 0.
+ * 4. A component outside its domain is refused BY NAME, never clamped:
+ * a clamped signal is a silently wrong score.
+ * 5. The gate partitions at `score >= threshold`, admits the boundary
+ * case, and names every excluded item with its score.
+ * 6. An absent threshold is the documented open gate: nothing is
+ * scored, `admitted === considered`, `excluded` is empty, and the
+ * verdict says the threshold is absent rather than omitting it.
+ * 7. A malformed threshold is refused by name at the resolve seam,
+ * mirroring the dream-gate override doctrine (dream-gates.ts).
+ * 8. The collector REUSES lessons.ts, confidence.ts and
+ * observed-use.ts: every component equals what those modules return
+ * for the same vault, so there is no second copy of that math.
+ */
+
+import { afterEach, beforeEach, expect, test } from "bun:test";
+import { mkdtempSync, rmSync } from "node:fs";
+import { tmpdir } from "node:os";
+import { join } from "node:path";
+
+import { computeConfidence } from "../../../src/core/brain/confidence.ts";
+import { bootstrapBrain } from "../../../src/core/brain/init.ts";
+import { computeLessons } from "../../../src/core/brain/lessons.ts";
+import { appendLogEvent } from "../../../src/core/brain/log.ts";
+import { emitObservedUse, observedReuseRates } from "../../../src/core/brain/observed-use.ts";
+import { DEFAULT_BRAIN_CONFIG } from "../../../src/core/brain/policy.ts";
+import { parsePreference, writePreference } from "../../../src/core/brain/preference.ts";
+import {
+ applySalienceGate,
+ collectSalienceFoldSet,
+ gateFoldSet,
+ openSalienceGate,
+ resolveSalienceThreshold,
+ SALIENCE_CONFIDENCE_WEIGHT,
+ SALIENCE_MASS_HALF_SATURATION,
+ SALIENCE_MASS_WEIGHT,
+ SALIENCE_REUSE_WEIGHT,
+ SalienceGateError,
+ scoreSalience,
+ type SalienceFoldItem,
+} from "../../../src/core/brain/salience-gate.ts";
+import {
+ BRAIN_APPLY_RESULT,
+ BRAIN_LOG_EVENT_KIND,
+ BRAIN_PREFERENCE_STATUS,
+ type BrainConfig,
+} from "../../../src/core/brain/types.ts";
+
+const NOW = new Date("2026-06-01T00:00:00Z");
+
+function cfgWith(threshold?: number): BrainConfig {
+ const dream =
+ threshold === undefined
+ ? DEFAULT_BRAIN_CONFIG.dream
+ : { ...DEFAULT_BRAIN_CONFIG.dream, salience_threshold: threshold };
+ return { ...DEFAULT_BRAIN_CONFIG, dream };
+}
+
+function item(prefId: string, mass: number, confidence: number, reuse: number): SalienceFoldItem {
+ return {
+ pref_id: prefId,
+ path: `Brain/preferences/${prefId}.md`,
+ score: scoreSalience({ mass, confidence, reuse }),
+ };
+}
+
+// ----- 1-3: the formula ----------------------------------------------------
+
+test("the three component weights sum to exactly one", () => {
+ expect(SALIENCE_MASS_WEIGHT + SALIENCE_CONFIDENCE_WEIGHT + SALIENCE_REUSE_WEIGHT).toBe(1);
+});
+
+test("an item with no signal at all scores exactly zero", () => {
+ const scored = scoreSalience({ mass: 0, confidence: 0, reuse: 0 });
+ expect(scored.score).toBe(0);
+ expect(scored.mass_component).toBe(0);
+});
+
+test("the score is bounded by one and saturates as the decayed mass grows", () => {
+ const huge = scoreSalience({ mass: 1e9, confidence: 1, reuse: 1 });
+ expect(huge.score).toBeLessThanOrEqual(1);
+ expect(huge.score).toBeGreaterThan(0.99);
+ // Half-saturation is the documented anchor: mass == the constant maps
+ // the mass component to exactly half its range.
+ const half = scoreSalience({ mass: SALIENCE_MASS_HALF_SATURATION, confidence: 0, reuse: 0 });
+ expect(half.mass_component).toBe(0.5);
+ expect(half.score).toBe(SALIENCE_MASS_WEIGHT * 0.5);
+});
+
+test("scoring is deterministic: the same components score identically every time", () => {
+ const a = scoreSalience({ mass: 1.25, confidence: 0.4, reuse: 0.75 });
+ const b = scoreSalience({ mass: 1.25, confidence: 0.4, reuse: 0.75 });
+ expect(JSON.stringify(a)).toBe(JSON.stringify(b));
+});
+
+test("each component is monotone: raising one signal never lowers the score", () => {
+ const base = scoreSalience({ mass: 1, confidence: 0.5, reuse: 0.5 }).score;
+ expect(scoreSalience({ mass: 2, confidence: 0.5, reuse: 0.5 }).score).toBeGreaterThan(base);
+ expect(scoreSalience({ mass: 1, confidence: 0.9, reuse: 0.5 }).score).toBeGreaterThan(base);
+ expect(scoreSalience({ mass: 1, confidence: 0.5, reuse: 0.9 }).score).toBeGreaterThan(base);
+});
+
+// ----- 4: refusals rather than clamps --------------------------------------
+
+test("a component outside its domain is refused by name, never clamped", () => {
+ expect(() => scoreSalience({ mass: -1, confidence: 0, reuse: 0 })).toThrow(/mass/);
+ expect(() => scoreSalience({ mass: 0, confidence: 1.5, reuse: 0 })).toThrow(/confidence/);
+ expect(() => scoreSalience({ mass: 0, confidence: 0, reuse: Number.NaN })).toThrow(/reuse/);
+ try {
+ scoreSalience({ mass: 0, confidence: -0.1, reuse: 0 });
+ throw new Error("expected a refusal");
+ } catch (exc) {
+ expect(exc).toBeInstanceOf(SalienceGateError);
+ expect((exc as SalienceGateError).field).toBe("confidence");
+ }
+});
+
+// ----- 5-6: the partition --------------------------------------------------
+
+test("the gate admits at the threshold and names every excluded item", () => {
+ const low = item("pref-low", 0, 0, 0);
+ const mid = item("pref-mid", SALIENCE_MASS_HALF_SATURATION, 0, 0);
+ const threshold = mid.score.score;
+ const verdict = gateFoldSet([low, mid], threshold);
+ expect(verdict.threshold).toBe(threshold);
+ expect(verdict.considered).toBe(2);
+ // Boundary case is admitted: `score >= threshold`.
+ expect(verdict.admitted).toBe(1);
+ expect(verdict.excluded.map((e) => e.pref_id)).toEqual(["pref-low"]);
+ const excluded = verdict.excluded[0]!;
+ expect(excluded.path).toBe("Brain/preferences/pref-low.md");
+ expect(excluded.score).toBe(0);
+ expect(excluded.mass).toBe(0);
+ expect(excluded.confidence).toBe(0);
+ expect(excluded.reuse).toBe(0);
+});
+
+test("the excluded list is ordered by preference id, independent of input order", () => {
+ const items = [item("pref-c", 0, 0, 0), item("pref-a", 0, 0, 0), item("pref-b", 0, 0, 0)];
+ const forward = gateFoldSet(items, 0.5);
+ const reversed = gateFoldSet(items.toReversed(), 0.5);
+ expect(forward.excluded.map((e) => e.pref_id)).toEqual(["pref-a", "pref-b", "pref-c"]);
+ expect(JSON.stringify(forward)).toBe(JSON.stringify(reversed));
+});
+
+test("an absent threshold is an explicitly open gate, not an omitted field", () => {
+ const verdict = openSalienceGate(7);
+ expect(verdict.threshold).toBeNull();
+ expect("threshold" in verdict).toBe(true);
+ expect(verdict.considered).toBe(7);
+ expect(verdict.admitted).toBe(7);
+ expect(verdict.excluded).toEqual([]);
+});
+
+// ----- 7: the config seam --------------------------------------------------
+
+test("an unset threshold resolves to null - the documented open gate", () => {
+ expect(resolveSalienceThreshold(cfgWith())).toBeNull();
+});
+
+test("a configured threshold resolves verbatim", () => {
+ expect(resolveSalienceThreshold(cfgWith(0.25))).toBe(0.25);
+});
+
+test("a malformed threshold is refused by name instead of ignored", () => {
+ for (const bad of [1.5, -0.1, Number.NaN, Number.POSITIVE_INFINITY]) {
+ expect(() => resolveSalienceThreshold(cfgWith(bad))).toThrow(/dream\.salience_threshold/);
+ }
+ expect(() => resolveSalienceThreshold(cfgWith("0.5" as unknown as number))).toThrow(
+ /dream\.salience_threshold/,
+ );
+});
+
+// ----- 8: the collector reuses the three existing signal sources -----------
+
+let tmp: string;
+let vault: string;
+
+beforeEach(() => {
+ tmp = mkdtempSync(join(tmpdir(), "o2b-salience-"));
+ vault = join(tmp, "vault");
+ bootstrapBrain(vault, {});
+});
+
+afterEach(() => {
+ rmSync(tmp, { recursive: true, force: true });
+});
+
+/** Write one confirmed preference with the given evidence counters. */
+function seedPreference(slug: string, applied: number, violated: number): string {
+ return writePreference(vault, {
+ slug,
+ topic: slug,
+ principle: `principle for ${slug}`,
+ created_at: "2026-01-01T00:00:00Z",
+ unconfirmed_until: "2026-01-08T00:00:00Z",
+ confirmed_at: "2026-01-08T00:00:00Z",
+ status: BRAIN_PREFERENCE_STATUS.confirmed,
+ evidenced_by: [],
+ applied_count: applied,
+ violated_count: violated,
+ last_evidence_at: "2026-05-25T00:00:00Z",
+ }).path;
+}
+
+function seedApplyEvidence(prefId: string, timestamp: string, result: string): void {
+ appendLogEvent(vault, {
+ timestamp,
+ eventType: BRAIN_LOG_EVENT_KIND.applyEvidence,
+ body: { preference: `[[${prefId}]]`, artifact: "[[src/foo.ts]]", agent: "tester", result },
+ });
+}
+
+test("every collected component equals what the source module returns", () => {
+ const path = seedPreference("loud", 4, 0);
+ seedApplyEvidence("pref-loud", "2026-05-28T00:00:00Z", BRAIN_APPLY_RESULT.applied);
+ seedApplyEvidence("pref-loud", "2026-05-29T00:00:00Z", BRAIN_APPLY_RESULT.applied);
+ emitObservedUse(vault, {
+ host: "test",
+ createdAt: "2026-05-30T00:00:00Z",
+ entries: [{ id: "pref-loud", verdict: "USED" }],
+ });
+
+ const pref = parsePreference(path);
+ const cfg = cfgWith(0.1);
+ const items = collectSalienceFoldSet({
+ vault,
+ preferences: [{ path, pref }],
+ cfg,
+ now: NOW,
+ });
+ expect(items).toHaveLength(1);
+ const only = items[0]!;
+ expect(only.pref_id).toBe("pref-loud");
+ expect(only.path).toBe("Brain/preferences/pref-loud.md");
+
+ const lesson = computeLessons(vault, [pref], [], { now: NOW }).find((l) => l.id === "pref-loud")!;
+ expect(only.score.mass).toBe(Math.max(lesson.positiveMass, lesson.negativeMass));
+ expect(only.score.confidence).toBe(
+ computeConfidence(pref.applied_count, pref.violated_count, pref.last_evidence_at, cfg, NOW)
+ .value,
+ );
+ expect(only.score.reuse).toBe(observedReuseRates(vault).get("pref-loud")!.score);
+});
+
+test("a preference with no evidence anywhere collects a zero score, not an absent one", () => {
+ const path = seedPreference("silent", 0, 0);
+ const items = collectSalienceFoldSet({
+ vault,
+ preferences: [{ path, pref: parsePreference(path) }],
+ cfg: cfgWith(0.1),
+ now: NOW,
+ });
+ expect(items).toHaveLength(1);
+ expect(items[0]!.score.score).toBe(0);
+});
+
+test("applySalienceGate scores nothing when no threshold is configured", () => {
+ const path = seedPreference("loud", 4, 0);
+ seedApplyEvidence("pref-loud", "2026-05-29T00:00:00Z", BRAIN_APPLY_RESULT.applied);
+ const verdict = applySalienceGate({
+ vault,
+ preferences: [{ path, pref: parsePreference(path) }],
+ cfg: cfgWith(),
+ now: NOW,
+ });
+ expect(verdict.threshold).toBeNull();
+ expect(verdict.considered).toBe(1);
+ expect(verdict.admitted).toBe(1);
+ expect(verdict.excluded).toEqual([]);
+});
+
+test("applySalienceGate excludes the quiet preference once a threshold is set", () => {
+ const loud = seedPreference("loud", 6, 0);
+ const quiet = seedPreference("quiet", 0, 0);
+ for (const day of ["2026-05-26", "2026-05-27", "2026-05-28", "2026-05-29"]) {
+ seedApplyEvidence("pref-loud", `${day}T00:00:00Z`, BRAIN_APPLY_RESULT.applied);
+ }
+ const preferences = [
+ { path: loud, pref: parsePreference(loud) },
+ { path: quiet, pref: parsePreference(quiet) },
+ ];
+ const verdict = applySalienceGate({
+ vault,
+ preferences,
+ cfg: cfgWith(0.2),
+ now: NOW,
+ });
+ expect(verdict.considered).toBe(2);
+ expect(verdict.admitted).toBe(1);
+ expect(verdict.excluded.map((e) => e.pref_id)).toEqual(["pref-quiet"]);
+});
diff --git a/tests/core/brain/skill-accept-dead-ends.test.ts b/tests/core/brain/skill-accept-dead-ends.test.ts
index e3a455a8..4ceca7c6 100644
--- a/tests/core/brain/skill-accept-dead-ends.test.ts
+++ b/tests/core/brain/skill-accept-dead-ends.test.ts
@@ -137,7 +137,7 @@ describe("an unreadable accept journal names the command that clears it", () =>
phase: "archive",
startedAt: ACCEPTED_AT.toISOString(),
acceptedExisted: false,
- procedureExisted: false,
+ materializedExisted: false,
});
const corrupt = corruptJournal("ghost");
diff --git a/tests/core/brain/skill-contract.test.ts b/tests/core/brain/skill-contract.test.ts
index f808c738..bfc91e14 100644
--- a/tests/core/brain/skill-contract.test.ts
+++ b/tests/core/brain/skill-contract.test.ts
@@ -247,7 +247,7 @@ describe("the accept sequence survives a crash at each of its three gaps", () =>
phase,
startedAt: ACCEPTED_AT.toISOString(),
acceptedExisted: false,
- procedureExisted: false,
+ materializedExisted: false,
});
}
diff --git a/tests/core/brain/skill-page-drafts.test.ts b/tests/core/brain/skill-page-drafts.test.ts
new file mode 100644
index 00000000..8b6a0edc
--- /dev/null
+++ b/tests/core/brain/skill-page-drafts.test.ts
@@ -0,0 +1,312 @@
+/**
+ * Skill drafts from mature vault pages (salience-lifecycle-enrichment,
+ * unit 4, t_abaec26b). Claims pinned here:
+ *
+ * 1. The maturity gate admits a page only when all three page-meta
+ * dimensions hold - core tier, non-stale lifecycle, high confidence -
+ * and each rejection is NAMED per page, never a silent absence.
+ * 2. Observed reuse is the evidence floor: a page nothing has reused is
+ * skipped by name even with a perfect trio.
+ * 3. An installed skill already covering a page skips it by name.
+ * 4. Exactly one spine envelope is built per ADMITTED page, and none for
+ * a skipped one.
+ * 5. A draft payload is refused structurally (blank fields) and
+ * semantically (a name that is not a valid skill directory name).
+ * 6. A validated draft is staged as a PENDING proposal inside the vault
+ * under the new `mature_page` pattern kind, and nothing is written
+ * outside the vault before accept.
+ * 7. Accept materializes a well-formed SKILL.md under the configured
+ * skills root through the WAL-protected accept path.
+ * 8. Rejection is sticky: a rejected page does not resurface as a draft.
+ * 9. A page path that climbs out of the vault is refused by name before
+ * anything is staged - the draft's provenance is confined like every
+ * other vault write.
+ * 10. The name charset is re-applied at MATERIALIZE time: a pending
+ * proposal whose `skill_name` was edited to something that is not a
+ * directory name is refused on accept, and nothing lands under the
+ * skills root.
+ */
+
+import { afterEach, beforeEach, expect, test } from "bun:test";
+import {
+ existsSync,
+ mkdirSync,
+ mkdtempSync,
+ readFileSync,
+ readdirSync,
+ rmSync,
+ writeFileSync,
+} from "node:fs";
+import { tmpdir } from "node:os";
+import { basename, join } from "node:path";
+
+import { appendContinuityRecord } from "../../../src/core/brain/continuity/store.ts";
+import { writeSkillAcceptJournal } from "../../../src/core/brain/skill-accept-journal.ts";
+import { NEEDS_LLM_STEP } from "../../../src/core/brain/llm-step.ts";
+import { ResponseCheckError } from "../../../src/core/brain/response-checks.ts";
+import { ResponseShapeError } from "../../../src/core/brain/response-shape.ts";
+import {
+ commitSkillPageDraft,
+ MATURE_PAGE_REUSE_FLOOR,
+ planSkillPageDrafts,
+ SKILL_PAGE_SKIP_REASON,
+ SkillPageDraftError,
+} from "../../../src/core/brain/skill-page-drafts.ts";
+import {
+ acceptSkillProposal,
+ listPendingSkillProposals,
+ MATURE_PAGE_PATTERN_KIND,
+ recoverSkillProposalAccepts,
+ rejectSkillProposal,
+} from "../../../src/core/brain/skill-proposals.ts";
+
+let vault: string;
+let skillsRoot: string;
+const NOW = new Date("2026-08-22T10:00:00Z");
+const FRESH = "2026-08-01T00:00:00Z";
+const ANCIENT = "2020-01-01T00:00:00Z";
+
+const MATURE_PAGE = "notes/release-ritual.md";
+
+function writePage(
+ rel: string,
+ meta: { title: string; tier?: string; lifecycle?: string; confidence?: string; created?: string },
+): void {
+ const abs = join(vault, rel);
+ mkdirSync(join(abs, ".."), { recursive: true });
+ writeFileSync(
+ abs,
+ [
+ "---",
+ `title: ${meta.title}`,
+ `tier: ${meta.tier ?? "core"}`,
+ `_lifecycle: ${meta.lifecycle ?? "verified"}`,
+ `_confidence: ${meta.confidence ?? "high"}`,
+ `created_at: ${meta.created ?? FRESH}`,
+ "---",
+ "",
+ "# Release ritual",
+ "",
+ "Name the theme, cut the branch, run the gates, tag the commit.",
+ "",
+ ].join("\n"),
+ );
+}
+
+/** Record `used` verdicts for `path` so it clears the reuse floor. */
+function recordReuse(path: string, used: number): void {
+ appendContinuityRecord(vault, {
+ kind: "recall_observed_use",
+ createdAt: NOW.toISOString(),
+ sourceRefs: [{ id: `reuse:${path}:${used}` }],
+ payload: {
+ session_id: "sess-reuse",
+ entries: Array.from({ length: used }, () => ({ path, verdict: "USED" })),
+ },
+ });
+}
+
+function plan() {
+ return planSkillPageDrafts(vault, { now: NOW, skillsDir: skillsRoot });
+}
+
+function skipReasonFor(rel: string): string | undefined {
+ return plan().skipped.find((s) => s.path === rel)?.reason;
+}
+
+const DRAFT = {
+ name: "release-ritual",
+ description: "Cut a release the way this vault says releases are cut.",
+ triggers: ["release", "tag", "changelog"],
+ body: "1. Name the theme.\n2. Cut the branch.\n3. Run the gates.\n4. Tag the commit.",
+};
+
+beforeEach(() => {
+ vault = mkdtempSync(join(tmpdir(), "o2b-skill-pages-"));
+ mkdirSync(join(vault, "Brain"), { recursive: true });
+ skillsRoot = join(vault, "..", `skills-${Math.random().toString(36).slice(2)}`);
+ mkdirSync(skillsRoot, { recursive: true });
+ writePage(MATURE_PAGE, { title: "Release ritual" });
+ recordReuse(MATURE_PAGE, 4);
+});
+
+afterEach(() => {
+ rmSync(vault, { recursive: true, force: true });
+ rmSync(skillsRoot, { recursive: true, force: true });
+});
+
+test("a page clearing the trio and the reuse floor is admitted with one envelope", () => {
+ const report = plan();
+ expect(report.admitted.map((a) => a.path)).toEqual([MATURE_PAGE]);
+ const candidate = report.admitted[0]!;
+ expect(candidate.llmStep.status).toBe(NEEDS_LLM_STEP);
+ expect(candidate.llmStep.prompt).toContain("Name the theme, cut the branch");
+ expect(candidate.llmStep.schema_hints.length).toBeGreaterThan(0);
+ expect(candidate.reuseScore).toBeGreaterThanOrEqual(MATURE_PAGE_REUSE_FLOOR);
+});
+
+test("each trio dimension rejects by name, and no envelope is built for it", () => {
+ writePage("notes/low-tier.md", { title: "Low tier", tier: "supporting" });
+ writePage("notes/stale.md", { title: "Stale", lifecycle: "stable", created: ANCIENT });
+ writePage("notes/unsure.md", { title: "Unsure", confidence: "medium" });
+ for (const rel of ["notes/low-tier.md", "notes/stale.md", "notes/unsure.md"]) recordReuse(rel, 4);
+
+ expect(skipReasonFor("notes/low-tier.md")).toBe(SKILL_PAGE_SKIP_REASON.tier);
+ expect(skipReasonFor("notes/stale.md")).toBe(SKILL_PAGE_SKIP_REASON.lifecycle);
+ expect(skipReasonFor("notes/unsure.md")).toBe(SKILL_PAGE_SKIP_REASON.confidence);
+ expect(plan().admitted.map((a) => a.path)).toEqual([MATURE_PAGE]);
+});
+
+test("a page nothing has reused is skipped by the evidence floor", () => {
+ writePage("notes/unused.md", { title: "Unused" });
+ expect(skipReasonFor("notes/unused.md")).toBe(SKILL_PAGE_SKIP_REASON.reuse);
+});
+
+test("a page an installed skill already covers is skipped, and the skip is named", () => {
+ mkdirSync(join(skillsRoot, "release-ritual"), { recursive: true });
+ writeFileSync(
+ join(skillsRoot, "release-ritual", "SKILL.md"),
+ ["---", "name: release-ritual", "description: Already installed.", "---", "", "Body.", ""].join(
+ "\n",
+ ),
+ );
+ const report = plan();
+ expect(report.admitted).toEqual([]);
+ const skip = report.skipped.find((s) => s.path === MATURE_PAGE);
+ expect(skip?.reason).toBe(SKILL_PAGE_SKIP_REASON.covered);
+ expect(skip?.detail).toContain("release-ritual");
+});
+
+test("a blank draft field is refused by the shape layer and stages nothing", () => {
+ expect(() =>
+ commitSkillPageDraft(vault, MATURE_PAGE, { ...DRAFT, description: " " }, { now: NOW }),
+ ).toThrow(ResponseShapeError);
+ expect(listPendingSkillProposals(vault)).toEqual([]);
+});
+
+test("a name that is not a valid skill directory name is refused by the semantic check", () => {
+ let caught: unknown;
+ try {
+ commitSkillPageDraft(vault, MATURE_PAGE, { ...DRAFT, name: "Release Ritual!" }, { now: NOW });
+ } catch (err) {
+ caught = err;
+ }
+ expect(caught).toBeInstanceOf(ResponseCheckError);
+ expect((caught as Error).message).toContain("Release Ritual!");
+ expect(listPendingSkillProposals(vault)).toEqual([]);
+});
+
+test("a page path escaping the vault is refused by name and stages nothing", () => {
+ // The escape target exists, so only the confinement check can refuse it:
+ // an existence probe alone would confirm it and stage the proposal.
+ const outside = join(vault, "..", "outside-page.md");
+ writeFileSync(outside, "# Not this vault's page\n");
+ try {
+ let caught: unknown;
+ try {
+ commitSkillPageDraft(vault, "../outside-page.md", DRAFT, { now: NOW });
+ } catch (err) {
+ caught = err;
+ }
+ expect(caught).toBeInstanceOf(SkillPageDraftError);
+ expect((caught as Error).message).toContain("outside-page.md");
+ expect(listPendingSkillProposals(vault)).toEqual([]);
+ } finally {
+ rmSync(outside, { force: true });
+ }
+});
+
+test("an edited skill_name is refused at materialize time and nothing reaches the skills root", () => {
+ const res = commitSkillPageDraft(vault, MATURE_PAGE, DRAFT, { now: NOW });
+ // What a hand edit of the pending proposal can do that the draft-time
+ // check cannot see: the accept write passes no vault confinement,
+ // because the skills root may legitimately sit outside the vault.
+ const pendingFile = readFileSync(res.path, "utf8");
+ // Unique per run, so the assertion below cannot be satisfied - or
+ // defeated - by a directory some other run left behind.
+ const escapeName = `${basename(skillsRoot)}-escaped`;
+ writeFileSync(
+ res.path,
+ pendingFile.replace(`skill_name: ${DRAFT.name}`, `skill_name: ../${escapeName}`),
+ );
+ const before = readdirSync(skillsRoot);
+ const escapeTarget = join(skillsRoot, "..", escapeName);
+
+ try {
+ expect(() => acceptSkillProposal(vault, res.slug, { now: NOW, skillsRoot })).toThrow(
+ "skill directory name",
+ );
+ expect(readdirSync(skillsRoot)).toEqual(before);
+ // Not merely "outside the root the operator configured": before the
+ // charset was re-applied here, this wrote a SKILL.md into the skills
+ // root's PARENT directory.
+ expect(existsSync(escapeTarget)).toBe(false);
+ } finally {
+ rmSync(escapeTarget, { recursive: true, force: true });
+ }
+});
+
+test("a validated draft stages a pending mature_page proposal inside the vault", () => {
+ const before = readdirSync(skillsRoot);
+ const res = commitSkillPageDraft(vault, MATURE_PAGE, DRAFT, { now: NOW });
+ expect(res.outcome).toBe("created");
+ expect(res.path.startsWith(join(vault, "Brain"))).toBe(true);
+ const pending = listPendingSkillProposals(vault);
+ expect(pending.map((p) => p.patternKind)).toEqual([MATURE_PAGE_PATTERN_KIND]);
+ // Nothing outside the vault moved before accept.
+ expect(readdirSync(skillsRoot)).toEqual(before);
+});
+
+test("accept materializes a well-formed SKILL.md under the skills root", () => {
+ const res = commitSkillPageDraft(vault, MATURE_PAGE, DRAFT, { now: NOW });
+ const accepted = acceptSkillProposal(vault, res.slug, { now: NOW, skillsRoot });
+ expect(accepted.status).toBe("accepted");
+ const skillFile = join(skillsRoot, DRAFT.name, "SKILL.md");
+ expect(accepted.skillPath).toBe(skillFile);
+ expect(existsSync(skillFile)).toBe(true);
+ const body = readFileSync(skillFile, "utf8");
+ expect(body).toContain(`name: ${DRAFT.name}`);
+ expect(body).toContain(DRAFT.description);
+ expect(body).toContain("triggers:");
+ expect(body).toContain("Cut the branch.");
+ // The pending copy is gone and the accepted archive is in the vault.
+ expect(listPendingSkillProposals(vault)).toEqual([]);
+ expect(accepted.proposalPath.startsWith(join(vault, "Brain"))).toBe(true);
+});
+
+test("rejection is sticky: a rejected page does not resurface as a draft", () => {
+ const res = commitSkillPageDraft(vault, MATURE_PAGE, DRAFT, { now: NOW });
+ rejectSkillProposal(vault, res.slug, { note: "not a skill" });
+ const again = commitSkillPageDraft(vault, MATURE_PAGE, DRAFT, { now: NOW });
+ expect(again.outcome).toBe("suppressed");
+ expect(listPendingSkillProposals(vault)).toEqual([]);
+});
+
+test("the accept journal records the SKILL.md path, so a rollback removes exactly it", () => {
+ const res = commitSkillPageDraft(vault, MATURE_PAGE, DRAFT, { now: NOW });
+ const skillDir = join(skillsRoot, DRAFT.name);
+ const skillFile = join(skillDir, "SKILL.md");
+ mkdirSync(skillDir, { recursive: true });
+ writeFileSync(skillFile, "half-written\n");
+
+ // A crash between the two writes leaves a journal naming the target the
+ // sequence was about to create; the resolver has to follow that path,
+ // not re-derive a procedure path from the slug.
+ writeSkillAcceptJournal(vault, {
+ slug: res.slug,
+ id: res.id,
+ phase: "materialize",
+ startedAt: NOW.toISOString(),
+ acceptedExisted: false,
+ materializedExisted: false,
+ materializedPath: skillFile,
+ });
+ const recovered = recoverSkillProposalAccepts(vault);
+
+ expect(recovered).toEqual([{ slug: res.slug, action: "rolled_back" }]);
+ expect(existsSync(skillFile)).toBe(false);
+ // The now-empty directory the sequence created goes with it.
+ expect(existsSync(skillDir)).toBe(false);
+ // The pending draft survives untouched - nothing was committed.
+ expect(listPendingSkillProposals(vault).map((p) => p.slug)).toEqual([res.slug]);
+});
diff --git a/tests/core/install/tool-ceiling.test.ts b/tests/core/install/tool-ceiling.test.ts
index 79b0e501..8790dd36 100644
--- a/tests/core/install/tool-ceiling.test.ts
+++ b/tests/core/install/tool-ceiling.test.ts
@@ -340,7 +340,7 @@ describe("the capability report states the ceiling it runs under", () => {
test("the advertised count is the one a host lists, not the registered one", () => {
const evaluated = report("cursor");
- expect(evaluated.available_tool_count).toBe(110);
+ expect(evaluated.available_tool_count).toBe(113);
expect(evaluated.advertised_tool_count).toBe(7);
});
});
diff --git a/tests/mcp/agent-scope-matrix.test.ts b/tests/mcp/agent-scope-matrix.test.ts
index eba5bacc..3182bb89 100644
--- a/tests/mcp/agent-scope-matrix.test.ts
+++ b/tests/mcp/agent-scope-matrix.test.ts
@@ -324,8 +324,8 @@ const REASONS_REACHING_OWNER_CONTENT: ReadonlySet<string> = new Set([REASON.owne
* `docs/mcp.md` and the release notes. Equalities, not floors - see the
* test that reads them.
*/
-const PROBE_ENTRY_COUNT = 96;
-const PROBE_RECIPE_COUNT = 220;
+const PROBE_ENTRY_COUNT = 99;
+const PROBE_RECIPE_COUNT = 226;
const PROBE_TWO_SIDED_COUNT = 31;
/**
@@ -601,6 +601,30 @@ const NON_CONTENT: ReadonlyArray<ProbeEntry> = [
REASON.writerEcho,
),
},
+ {
+ name: "brain_design_note",
+ calls: [
+ { args: { topic: "probe topic" }, reason: REASON.ownerlessLane },
+ {
+ args: {
+ topic: "probe topic",
+ note: {
+ title: "Probe",
+ alternatives: [
+ {
+ name: "only",
+ approach: "probe approach",
+ tradeoffs: "probe tradeoffs",
+ recommended: true,
+ },
+ ],
+ },
+ },
+ reason: REASON.writerEcho,
+ label: "commit",
+ },
+ ],
+ },
{ name: "brain_diarize", calls: one({ entity: "probe-entity" }, REASON.ownerlessLane) },
{
name: "brain_distill_source",
@@ -623,6 +647,7 @@ const NON_CONTENT: ReadonlyArray<ProbeEntry> = [
{ args: { action: "validate", run_id: "run-probe-absent" }, reason: REASON.aggregateOnly },
{ args: { action: "apply", run_id: "run-probe-absent" }, reason: REASON.aggregateOnly },
{ args: { action: "discard", run_id: "run-probe-absent" }, reason: REASON.aggregateOnly },
+ { args: { action: "retriage", run_id: "run-probe-absent" }, reason: REASON.aggregateOnly },
],
},
{
@@ -637,6 +662,34 @@ const NON_CONTENT: ReadonlyArray<ProbeEntry> = [
calls: one({ dataset: "datasets/probe-absent.jsonl" }, REASON.configuredCorpus),
},
{ name: "brain_event_trace", calls: one({ date: LOG_EVENT_DATE }, REASON.ownerFiltered) },
+ {
+ name: "brain_expire",
+ calls: one(
+ { id: `sig-2026-05-01-${NEUTRAL_SIGNAL_SLUG}`, expires: "2030-01-01" },
+ REASON.callerNamedArtifact,
+ ),
+ },
+ {
+ name: "brain_extract_signals",
+ calls: [
+ { args: { session: "sess-probe" }, reason: REASON.sessionLane },
+ {
+ args: {
+ session: "sess-probe",
+ items: [
+ {
+ topic: "probe",
+ signal: "positive",
+ principle: "probe principle",
+ confidence: 0.9,
+ },
+ ],
+ },
+ reason: REASON.writerEcho,
+ label: "commit",
+ },
+ ],
+ },
{
name: "brain_feedback",
calls: one(
@@ -1160,7 +1213,7 @@ test("the matrix classifies every tool exactly once", () => {
});
test("the tool count is unchanged: an argument was added, never a tool", () => {
- expect(TOOLS.length).toBe(110);
+ expect(TOOLS.length).toBe(113);
});
test("every argument-scoped surface declares agent_scope in its input schema", () => {
diff --git a/tests/mcp/brain-expire-tool.test.ts b/tests/mcp/brain-expire-tool.test.ts
new file mode 100644
index 00000000..918f16c3
--- /dev/null
+++ b/tests/mcp/brain-expire-tool.test.ts
@@ -0,0 +1,153 @@
+/**
+ * The MCP half of expiration (unit 3c / t_5e338af1): `expires` on
+ * `brain_feedback` and the `brain_expire` tool beside it.
+ *
+ * The core owns the mutation semantics
+ * (`tests/core/brain/expiration-set.test.ts`); what belongs here is the
+ * tool surface's own share - that the argument reaches the writer, that a
+ * bad date is the CALLER's fault with a typed code rather than an
+ * internal fault, and that the response distinguishes a change from a
+ * no-op.
+ *
+ * Claims pinned here:
+ *
+ * 1. `brain_feedback` with `expires` stamps the signal and the
+ * force-confirmed preference with the same normalised date.
+ * 2. An unparseable `expires` refuses the whole call before any signal is
+ * written - not a signal followed by a failure on the preference.
+ * 3. `brain_expire` sets, changes and clears by id, reporting both sides
+ * of the change.
+ * 4. A junk date, an unknown id, and an id shape this surface cannot
+ * address are each INVALID_PARAMS carrying their own code.
+ */
+
+import { afterEach, beforeEach, describe, expect, test } from "bun:test";
+import { existsSync, mkdtempSync, readFileSync, readdirSync, rmSync, writeFileSync } from "node:fs";
+import { tmpdir } from "node:os";
+import { join } from "node:path";
+
+import { bootstrapBrain } from "../../src/core/brain/init.ts";
+import { FEEDBACK_TOOLS } from "../../src/mcp/brain/feedback-tools.ts";
+import { MCPError } from "../../src/mcp/protocol.ts";
+import type { ServerContext } from "../../src/mcp/tool-contract.ts";
+
+let tmp: string;
+let vault: string;
+let ctx: ServerContext;
+
+beforeEach(() => {
+ tmp = mkdtempSync(join(tmpdir(), "o2b-mcp-expire-"));
+ vault = join(tmp, "vault");
+ const configPath = join(tmp, "config.yaml");
+ writeFileSync(configPath, `vault: ${vault}\nagent_name: claude\n`);
+ bootstrapBrain(vault, { configPath });
+ ctx = { vault, configPath, repoRoot: null };
+});
+
+afterEach(() => {
+ rmSync(tmp, { recursive: true, force: true });
+});
+
+const feedbackTool = FEEDBACK_TOOLS.find((t) => t.name === "brain_feedback")!;
+const expireTool = FEEDBACK_TOOLS.find((t) => t.name === "brain_expire")!;
+
+async function feedback(args: Record<string, unknown>): Promise<Record<string, unknown>> {
+ return (await feedbackTool.handler(ctx, {
+ topic: "staging-endpoint",
+ signal: "positive",
+ principle: "Use the staging endpoint.",
+ ...args,
+ })) as Record<string, unknown>;
+}
+
+async function expire(args: Record<string, unknown>): Promise<Record<string, unknown>> {
+ return (await expireTool.handler(ctx, args)) as Record<string, unknown>;
+}
+
+describe("brain_feedback expires", () => {
+ test("stamps the signal and the force-confirmed preference", async () => {
+ const res = await feedback({ expires: "2026-07-15", force_confirmed: true });
+ const signalId = res["signal_id"] as string;
+ const prefId = res["preference_id"] as string;
+ expect(readFileSync(join(vault, "Brain/inbox", `${signalId}.md`), "utf8")).toContain(
+ "expiration_date: 2026-07-15",
+ );
+ expect(readFileSync(join(vault, "Brain/preferences", `${prefId}.md`), "utf8")).toContain(
+ "expiration_date: 2026-07-15",
+ );
+ });
+
+ test("an unparseable expires refuses before anything is written", async () => {
+ let caught: unknown;
+ try {
+ await feedback({ expires: "next tuesday" });
+ } catch (err) {
+ caught = err;
+ }
+ expect(caught).toBeInstanceOf(MCPError);
+ expect((caught as MCPError).message).toContain("expiration_date");
+ expect(readdirSync(join(vault, "Brain/inbox")).filter((n) => n.endsWith(".md"))).toHaveLength(
+ 0,
+ );
+ });
+});
+
+/** Assert one refusal reaches the caller as INVALID_PARAMS with its code. */
+async function expectRefusal(args: Record<string, unknown>, code: string): Promise<void> {
+ let caught: unknown;
+ try {
+ await expire(args);
+ } catch (err) {
+ caught = err;
+ }
+ expect(caught).toBeInstanceOf(MCPError);
+ expect((caught as MCPError).data).toMatchObject({ code });
+}
+
+describe("brain_expire", () => {
+ test("sets, changes and clears by id, reporting both sides", async () => {
+ const signalId = (await feedback({}))["signal_id"] as string;
+
+ const set = await expire({ id: signalId, expires: "2026-07-15" });
+ expect(set["kind"]).toBe("signal");
+ expect(set["expiration"]).toBe("2026-07-15");
+ expect(set["previous"]).toBeNull();
+ expect(set["changed"]).toBe(true);
+
+ const moved = await expire({ id: signalId, expires: "2026-09-01" });
+ expect(moved["previous"]).toBe("2026-07-15");
+ expect(moved["expiration"]).toBe("2026-09-01");
+
+ const cleared = await expire({ id: signalId, expires: "none" });
+ expect(cleared["expiration"]).toBeNull();
+ expect(cleared["previous"]).toBe("2026-09-01");
+ expect(readFileSync(join(vault, "Brain/inbox", `${signalId}.md`), "utf8")).not.toContain(
+ "expiration_date",
+ );
+ });
+
+ test("re-setting the same date is reported as unchanged, not as a write", async () => {
+ const signalId = (await feedback({}))["signal_id"] as string;
+ await expire({ id: signalId, expires: "2026-07-15" });
+ const again = await expire({ id: signalId, expires: "2026-07-15" });
+ expect(again["changed"]).toBe(false);
+ });
+
+ test("a junk date, an unknown id and an unaddressable shape each carry a code", async () => {
+ const signalId = (await feedback({}))["signal_id"] as string;
+ await expectRefusal({ id: signalId, expires: "soon" }, "ExpirationValueError");
+ await expectRefusal(
+ { id: "pref-nobody-home", expires: "2026-07-15" },
+ "ExpirationTargetNotFoundError",
+ );
+ await expectRefusal(
+ { id: "Projects/Note.md", expires: "2026-07-15" },
+ "InvalidExpirationTargetError",
+ );
+ // The artifact is untouched by any of them.
+ expect(existsSync(join(vault, "Brain/inbox", `${signalId}.md`))).toBe(true);
+ expect(readFileSync(join(vault, "Brain/inbox", `${signalId}.md`), "utf8")).not.toContain(
+ "expiration_date",
+ );
+ });
+});
diff --git a/tests/mcp/brain-tools-parity.test.ts b/tests/mcp/brain-tools-parity.test.ts
index 4e58181b..1874dd0e 100644
--- a/tests/mcp/brain-tools-parity.test.ts
+++ b/tests/mcp/brain-tools-parity.test.ts
@@ -51,7 +51,19 @@
* archive it took does not cover a note living outside `Brain/`) and
* `brain_scaffold_stub` (the unresolved wikilink targets the search index
* holds, and the verb that materialises a note for one - the list REFUSES
- * a missing or partially-resolved index rather than reporting zero).
+ * a missing or partially-resolved index rather than reporting zero); the
+ * salience-lifecycle-enrichment release added three: `brain_expire` (set,
+ * change or clear the `expiration_date` of one signal or preference by id
+ * - the mutation half of a field that until now could only be declared at
+ * creation, kept off `brain_lifecycle` because every action there
+ * addresses its subject by a note PATH and the path envelope refuses the
+ * `Brain/` root these artifacts live under), `brain_extract_signals` (the
+ * batch counterpart to regex fact extraction: hands the calling agent one
+ * session's user turns inside a needs-llm-step envelope and writes the
+ * validated answer as speculative `source_type: auto_extract` inbox
+ * signals), and `brain_design_note` (the one-shot sibling of the panel
+ * lane: a read-only grounding pass over tension, decision and truth
+ * records, one envelope, and a committed note under `Brain/decisions/`).
*/
import { describe, expect, test } from "bun:test";
@@ -85,12 +97,15 @@ const FROZEN_BRAIN_TOOL_NAMES = [
"brain_deep_synthesis",
"brain_delete_by_source",
"brain_derive_fact",
+ "brain_design_note",
"brain_diarize",
"brain_distill_source",
"brain_doctor",
"brain_dream",
"brain_entity",
"brain_event_trace",
+ "brain_expire",
+ "brain_extract_signals",
"brain_feedback",
"brain_foresight",
"brain_generation_reports",
diff --git a/tests/mcp/extract-signals-tool.test.ts b/tests/mcp/extract-signals-tool.test.ts
new file mode 100644
index 00000000..3cca71ce
--- /dev/null
+++ b/tests/mcp/extract-signals-tool.test.ts
@@ -0,0 +1,119 @@
+/**
+ * `brain_extract_signals` MCP tool (salience-lifecycle-enrichment,
+ * unit 2, t_1dace26d). Claims pinned here:
+ *
+ * 1. Called without `items` the tool is the read-only plan phase and
+ * returns exactly one needs-llm-step envelope.
+ * 2. Called with `items` it commits, and the written signals carry the
+ * new `auto_extract` source type.
+ * 3. An over-cap payload is refused as a caller error, not a server
+ * fault, and nothing is written.
+ * 4. The tool is full-tier, absent from the writer surface.
+ * 5. A committed signal's path is vault-relative: no MCP response of
+ * this tool carries the absolute host path.
+ */
+
+import { afterEach, beforeEach, expect, test } from "bun:test";
+import { existsSync, mkdirSync, mkdtempSync, readdirSync, rmSync, writeFileSync } from "node:fs";
+import { tmpdir } from "node:os";
+import { join } from "node:path";
+
+import { AUTO_EXTRACT_PER_SESSION_CAP } from "../../src/core/brain/extract-signals.ts";
+import { importSessionRecall } from "../../src/core/brain/session-recall.ts";
+import { buildToolTable, findTool } from "../../src/mcp/tools.ts";
+import type { ServerContext } from "../../src/mcp/tool-contract.ts";
+
+const TOOL = "brain_extract_signals";
+const SESSION = "sess-mcp";
+let tmp: string;
+let vault: string;
+let ctx: ServerContext;
+
+function tool() {
+ return findTool(buildToolTable("full"), TOOL);
+}
+
+function inboxCount(): number {
+ const dir = join(vault, "Brain", "inbox");
+ return existsSync(dir) ? readdirSync(dir).filter((f) => f.endsWith(".md")).length : 0;
+}
+
+const ITEM = {
+ topic: "heading-style",
+ signal: "positive",
+ principle: "Name the release theme in the heading.",
+ confidence: 0.88,
+};
+
+beforeEach(() => {
+ tmp = mkdtempSync(join(tmpdir(), "o2b-extract-mcp-"));
+ vault = join(tmp, "vault");
+ mkdirSync(join(vault, "Brain"), { recursive: true });
+ const configPath = join(tmp, "config.yaml");
+ writeFileSync(configPath, `vault: "${vault}"\n`);
+ importSessionRecall(vault, {
+ sessionId: SESSION,
+ turns: [
+ {
+ turnId: "t1",
+ timestamp: "2026-08-22T09:01:00Z",
+ role: "user",
+ text: "Always name the release theme in the heading.",
+ },
+ ],
+ createdAt: "2026-08-22T10:00:00Z",
+ });
+ ctx = { vault, configPath, repoRoot: null };
+});
+
+afterEach(() => {
+ rmSync(tmp, { recursive: true, force: true });
+});
+
+test("without items it plans and returns one needs-llm-step envelope", async () => {
+ const res = (await tool().handler(ctx, { session: SESSION })) as {
+ phase: string;
+ turns_mined: ReadonlyArray<{ turn_id: string }>;
+ llm_step: { status: string; step: string; target_path: string };
+ };
+ expect(res.phase).toBe("plan");
+ expect(res.turns_mined.map((t) => t.turn_id)).toEqual(["t1"]);
+ expect(res.llm_step.status).toBe("needs-llm-step");
+ expect(res.llm_step.step).toBe("extract-signals");
+ expect(res.llm_step.target_path).toBe("Brain/inbox");
+ expect(inboxCount()).toBe(0);
+});
+
+test("with items it commits them as auto_extract signals", async () => {
+ const res = (await tool().handler(ctx, { session: SESSION, items: [ITEM] })) as {
+ phase: string;
+ written: ReadonlyArray<{ topic: string }>;
+ };
+ expect(res.phase).toBe("commit");
+ expect(res.written.map((w) => w.topic)).toEqual(["heading-style"]);
+ expect(inboxCount()).toBe(1);
+});
+
+test("the committed path is vault-relative, never the host path", async () => {
+ const res = (await tool().handler(ctx, { session: SESSION, items: [ITEM] })) as {
+ written: ReadonlyArray<{ path: string }>;
+ };
+ expect(res.written[0]!.path).toMatch(/^Brain[/\\]inbox[/\\]sig-/);
+ expect(JSON.stringify(res)).not.toContain(vault);
+});
+
+test("an over-cap payload is refused and writes nothing", async () => {
+ const items = Array.from({ length: AUTO_EXTRACT_PER_SESSION_CAP + 1 }, (_v, i) => ({
+ ...ITEM,
+ topic: `topic-${i}`,
+ }));
+ await expect(Promise.resolve(tool().handler(ctx, { session: SESSION, items }))).rejects.toThrow(
+ String(AUTO_EXTRACT_PER_SESSION_CAP),
+ );
+ expect(inboxCount()).toBe(0);
+});
+
+test("is a full-tier tool, absent from the writer surface", () => {
+ expect(buildToolTable("full").find((t) => t.name === TOOL)).toBeDefined();
+ expect(buildToolTable("writer").find((t) => t.name === TOOL)).toBeUndefined();
+});
diff --git a/tests/mcp/mcp.test.ts b/tests/mcp/mcp.test.ts
index 62533862..9f1b01d6 100644
--- a/tests/mcp/mcp.test.ts
+++ b/tests/mcp/mcp.test.ts
@@ -290,6 +290,10 @@ describe("tool listing", () => {
"brain_deep_synthesis",
// Subject diarization (knowledge-intake-and-consolidation, t_28ba3fc4).
"brain_diarize",
+ // Model-mined session signals (salience-lifecycle-enrichment, t_1dace26d).
+ "brain_extract_signals",
+ // One-shot design note (salience-lifecycle-enrichment, t_c87644b4).
+ "brain_design_note",
"brain_idea_discovery",
// Entity Truth & Self-Improving Dream Suite.
"brain_truth",
@@ -339,6 +343,8 @@ describe("tool listing", () => {
// Route-level MCP latency (context-pack-economics-observability).
"brain_route_metrics",
"brain_scaffold_stub",
+ // Expiration mutation by id (salience-lifecycle-enrichment unit 3c).
+ "brain_expire",
// Shadow-only retrieval advisor (retrieval-quality-and-context-delivery).
"brain_retrieval_plan",
// Durable token-impact ledger (context-pack-economics-observability).
@@ -710,7 +716,15 @@ describe("stdio loop", () => {
// wiring-what-exists B2 t_ae62fabd) = 109.
// + brain_scaffold_stub (materialise a note for an unresolved wikilink
// target, wiring-what-exists B3 t_783b37f8) = 110.
- expect(list.result.tools.length).toBe(110);
+ // + brain_expire (set / change / clear a signal's or preference's
+ // expiration_date by id, salience-lifecycle-enrichment unit 3c
+ // t_5e338af1) = 111.
+ // + brain_extract_signals (model-mined session signals,
+ // salience-lifecycle-enrichment t_1dace26d) = 112.
+ // + brain_design_note (one-shot design note grounded in tension,
+ // decision and truth records, salience-lifecycle-enrichment
+ // t_c87644b4) = 113.
+ expect(list.result.tools.length).toBe(113);
});
test("returns parse error for invalid JSON", async () => {
diff --git a/tests/mcp/note-lifecycle.test.ts b/tests/mcp/note-lifecycle.test.ts
index 1895b3b5..97e89f95 100644
--- a/tests/mcp/note-lifecycle.test.ts
+++ b/tests/mcp/note-lifecycle.test.ts
@@ -157,3 +157,58 @@ describe("dispatch", () => {
expect(existsSync(join(vault, "Projects/Old.md"))).toBe(true);
});
});
+
+/**
+ * `delete_linked` on the tool surface (unit 3a / t_5e338af1). The fold and
+ * the ladder are the core's; what belongs here is that the boolean reaches
+ * it, that the two lists and the scanned scope are rendered, and that a
+ * response without the flag says `null` rather than an empty cascade.
+ */
+describe("delete_linked", () => {
+ test("renders the deletion set, the reported set and the scanned scope", async () => {
+ note("Imports/Bench.md", "rows\n");
+ note("Projects/Reader.md", "[[Imports/Bench]]\n");
+ mkdirSync(join(vault, "Brain", "inbox"), { recursive: true });
+ writeFileSync(
+ join(vault, "Brain", "inbox", "sig-derived.md"),
+ '---\nid: sig-derived\nkind: brain-signal\nsource:\n - "[[Imports/Bench]]"\n---\n\nbody\n',
+ );
+
+ const res = await call({ action: "delete", path: "Imports/Bench.md", delete_linked: true });
+ const cascade = res["cascade"] as {
+ deletion_set: string[];
+ reported_files: string[];
+ scanned_scope: string;
+ };
+ expect(cascade.deletion_set).toEqual(["Imports/Bench.md", "Brain/inbox/sig-derived.md"]);
+ expect(cascade.reported_files).toContain("Projects/Reader.md");
+ expect(cascade.scanned_scope).toBe("Brain/");
+ // A dry run: nothing went.
+ expect(existsSync(join(vault, "Brain", "inbox", "sig-derived.md"))).toBe(true);
+ });
+
+ test("a response without the flag carries cascade: null, not an empty one", async () => {
+ note("Projects/Gone.md", "x\n");
+ const res = await call({ action: "delete", path: "Projects/Gone.md" });
+ expect(res["cascade"]).toBeNull();
+ });
+
+ test("the flag is refused on an action that removes nothing", async () => {
+ note("Projects/Old.md", "x\n");
+ let caught: unknown;
+ try {
+ await call({
+ action: "rename",
+ path: "Projects/Old.md",
+ to: "Projects/New.md",
+ apply: true,
+ delete_linked: true,
+ });
+ } catch (err) {
+ caught = err;
+ }
+ expect(caught).toBeInstanceOf(MCPError);
+ expect((caught as MCPError).data).toMatchObject({ code: "cascade_forbidden" });
+ expect(existsSync(join(vault, "Projects/Old.md"))).toBe(true);
+ });
+});
diff --git a/tests/mcp/owner-scope-refusal.test.ts b/tests/mcp/owner-scope-refusal.test.ts
index 1f3199a6..86e2f7a8 100644
--- a/tests/mcp/owner-scope-refusal.test.ts
+++ b/tests/mcp/owner-scope-refusal.test.ts
@@ -67,7 +67,7 @@ const AGENT_ARG_NAME = "agent";
* pinned so a tool joining or leaving the set is a decision somebody
* makes on purpose.
*/
-const AGENT_ARGUMENT_TOOL_COUNT = 21;
+const AGENT_ARGUMENT_TOOL_COUNT = 24;
/** Tools that accept a caller-supplied owner scope, derived the same way. */
const AGENT_SCOPE_TOOL_COUNT = 13;
@@ -310,8 +310,11 @@ test("every tool declaring agent_scope is covered by that one seam", () => {
});
/**
- * The write side of the same echo: 21 tools accept a caller-supplied
- * `agent` and stamp it verbatim. That is `passthrough`, shipped and
+ * The write side of the same echo: the {@link AGENT_ARGUMENT_TOOL_COUNT}
+ * tools of that population accept a caller-supplied `agent` and stamp it
+ * verbatim. The size is stated in the constant and nowhere else, so a
+ * tool joining the set cannot leave a stale number behind in this
+ * paragraph. That is `passthrough`, shipped and
* ungated, and this unit does not gate it - `brain_generation_reports`
* uses the same argument as a LIST FILTER, so a blanket refusal at the
* seam would change a read as well as a write. What this pins is the
diff --git a/tests/mcp/removed-tools.test.ts b/tests/mcp/removed-tools.test.ts
index f9571dcf..e13e220b 100644
--- a/tests/mcp/removed-tools.test.ts
+++ b/tests/mcp/removed-tools.test.ts
@@ -183,5 +183,13 @@ test("the shadow surface is gone: no hidden tools, removed names unlisted", asyn
// wiring-what-exists B2 t_ae62fabd) = 109.
// + brain_scaffold_stub (materialise a note for an unresolved wikilink
// target, wiring-what-exists B3 t_783b37f8) = 110.
- expect(list.result.tools.length).toBe(110);
+ // + brain_expire (set / change / clear a signal's or preference's
+ // expiration_date by id, salience-lifecycle-enrichment unit 3c
+ // t_5e338af1) = 111.
+ // + brain_extract_signals (model-mined session signals,
+ // salience-lifecycle-enrichment t_1dace26d) = 112.
+ // + brain_design_note (one-shot design note grounded in tension,
+ // decision and truth records, salience-lifecycle-enrichment
+ // t_c87644b4) = 113.
+ expect(list.result.tools.length).toBe(113);
});