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
30.2 KB
Raw Blame

Trust-Surface Hardening β€” implementation plan

Implemented via TDD on branch feat/trust-surface-hardening in the worktree ~/projects/tools/osb-worktrees/cycle-20261009. Six lanes run with disjoint file ownership: a lane never creates, modifies, or deletes a file another lane owns. The combined design is at docs/brainstorm/trust-surface-hardening/design.md (same branch).

Cross-lane contract (binding for every lane)

Path ownership. The tables below are exhaustive. If a task seems to need a file outside its lane, stop and reconcile through the wave coordinator β€” do not touch the file.

Lane Owns (source) Owns (tests)
A src/core/brain/secrets/* (envelope.ts, bundle.ts new; crypto.ts, store.ts modified), src/cli/brain/verbs/secret.ts, src/cli/command-manifest.ts, src/cli/help-text.ts, src/core/egress/registry.ts tests/core/brain/secrets/**, tests/cli/brain-secret.test.ts, tests/core/architecture/write-site-census.test.ts, tests/core/architecture/egress-census.test.ts, tests/cli/manifest-completeness.test.ts, tests/core/brain/vault-guard-census.test.ts, tests/core/brain/vault-identity.test.ts, tests/core/state/surfaces.test.ts (secrets dir rows only)
B src/core/secret-ref.ts, src/core/secret-resolver.ts (new), src/core/search/embeddings/registry.ts, src/core/decision-model/config.ts, src/core/brain/research/research.ts, src/core/config.ts, src/cli/main.ts, src/core/egress/guard.ts, src/mcp/error-redaction.ts tests/core/secret-ref.test.ts, tests/core/secret-resolver.test.ts (new), tests/core/egress-resolved-literals.test.ts (new), tests/core/search/embeddings.registry.test.ts, tests/core/decision-model/config.test.ts, tests/core/brain/research/research.test.ts, tests/core/config-telegram-capture.test.ts, tests/core/config.installation-secret.test.ts
C src/core/tags.ts, src/core/brain/tag-syntax.ts (new), src/core/brain/signal.ts, src/core/brain/preference.ts, src/core/brain/claude-memory-render.ts, src/core/brain/schema-pack.ts, src/core/brain/capture/capture-note.ts, src/core/brain/capture/inbox-drain.ts, src/core/brain/hygiene/types.ts, src/core/brain/hygiene/scan.ts, src/core/brain/hygiene/detectors/frontmatter-tags.ts (new) tests/core/brain/tag-syntax.test.ts (new), tests/core/brain.signal.test.ts, tests/core/brain.preference.test.ts, tests/core/brain/claude-memory-render.test.ts, tests/core/brain/hygiene-frontmatter-tags.test.ts (new), tests/core/brain/hygiene-tags.test.ts, tests/core/brain/hygiene-scan.test.ts, tests/core/brain/capture/capture-note.test.ts, tests/core/brain/capture/inbox-drain.test.ts, tests/core/brain/capture/telegram-capture.test.ts
D src/core/integrity/digest.ts, src/core/state/migrate.ts, src/core/brain/import-claude-memory.ts, src/core/brain/upgrade.ts, src/cli/brain/verbs/import-claude-memory.ts, src/cli/brain/helpers.ts tests/core/integrity/digest.test.ts, tests/core/state/migrate.test.ts, tests/core/brain/import-claude-memory-orchestrator.test.ts, tests/core/brain/upgrade.test.ts, tests/core/brain/upgrade-drift.test.ts, tests/cli/brain-import-claude-memory.test.ts, tests/cli/brain-upgrade.test.ts
E src/core/brain/session-summary.ts, src/core/brain/payload-json.ts (new), src/mcp/brain/synthesis-tools.ts, src/cli/brain/verbs/session-summary.ts, src/cli/brain/verbs/extract-signals.ts, src/cli/brain/verbs/design-note.ts, src/cli/brain/verbs/skill-proposals.ts, src/cli/brain/verbs/distill.ts tests/core/brain.session-summary.test.ts, tests/core/brain/payload-json.test.ts (new), tests/mcp/session-summary-tool.test.ts, tests/cli/brain-session-summary.test.ts (new), tests/cli/brain-extract-signals.test.ts, tests/cli/brain-design-note.test.ts, tests/cli/brain-skill-page-drafts.test.ts, tests/cli/brain-distill.test.ts
F src/core/brain/ingest/contract.ts (new), src/core/brain/ingest/content-manifest.ts, src/core/brain/ingest/batch-plan.ts, src/core/brain/ingest/checkpoint.ts, src/core/brain/source-cleanup.ts, src/mcp/brain/ingest-tools.ts, src/cli/brain/verbs/batch-plan.ts tests/core/brain/ingest/** (contract.test.ts new; content-manifest, batch-plan, batch-plan-extractable, checkpoint, reconcile, ingest modified), tests/cli/brain-batch-plan-reconcile.test.ts, tests/mcp/ingest-plan-format-reach.test.ts

Notes on the two deliberate ownership placements:

  • Egress split. src/core/egress/guard.ts is Lane B's (resolver literals wiring); src/core/egress/registry.ts and tests/core/architecture/egress-census.test.ts are Lane A's, because the credential-bundle export destination is the wave's only new egress site. The census asserts both directions (a site's module must be in the population), so Lane A's A2 lands the --out flag and the registry entry and the census rows in ONE commit β€” never split across commits.
  • Lane A exports, Lane B consumes. Lane A's A1 ships a read-only resolve export on src/core/brain/secrets/store.ts (no last_used_at stamp, no exec audit). Lane B's resolver calls that export through the module's public surface only; it must never edit secrets-module files.

Commit discipline. Every lane commits with git commit --only <paths> β€” stage and commit in ONE step. Never git add files (shared or not) followed by a plain git commit; --only is what keeps a lane from sweeping up a sibling's in-flight work.

Format and lint before every commit. Run ./node_modules/.bin/oxfmt and ./node_modules/.bin/oxlint on YOUR files only, before every commit.

The pre-commit hook checks the whole tree. .githooks/pre-commit runs bun run fmt:check (and mirror checks) over the entire worktree, not just your paths. If it blocks on a sibling lane's transient state, wait 30 s and retry, up to 5 attempts. Never pass --no-verify.

Windows-safe tests. No chmod-deny assertions without a tests/helpers/platform.ts skip guard (IS_WINDOWS, RUNNING_AS_ROOT, and the chmod-cannot-deny constant). Normalize path separators in every path assertion (compare on path.sep-normalized or forward-slash forms). The existing secrets suites already show the IS_WINDOWS skip pattern.

No scanner false positives. No identifier may contain the substring secret immediately before a quoted value of 8+ characters (plugin scanners flag it). Use names in the PRIVATE_PATH / credentialRef style. In tests, assemble credential-shaped literals at runtime via tests/helpers/fake-credentials.ts instead of writing literal-looking values.

No hardcoded natural-language phrases. All operator-facing strings are English constants hoisted next to their siblings; error and reason tokens come from closed tables, never assembled from prose; errors surface by name (stable code/token), never as ad-hoc sentences alone.

Opt-in flags. Any new config flag is opt-in with defaults preserving current behavior byte-for-byte. The wave's write-path changes are card-mandated (rejection is the feature), and each is covered by its own failing-test-first proof below.

Lane A β€” secrets envelope (cards t_e6667a56, t_592d9e91)

Task A1 β€” passphrase-wrapped keyfile, lock/unlock lifecycle, read-only resolve export (t_e6667a56)

  • Files: new src/core/brain/secrets/envelope.ts (scrypt KDF block: explicit N = 2^15, r = 8, p = 1, 32-byte out, random 16-byte salt, explicit maxmem, timingSafeEqual; versioned envelope { version, kdf: { algo, salt, n, r, p, maxmem }, wrapped }; module-level memory-only unlock holder with lock/unlock lifecycle); modified src/core/brain/secrets/crypto.ts (loadOrCreateKey detects an envelope at the keyfile path and unwraps via the holder; raw-keyfile branch unchanged); modified src/core/brain/secrets/store.ts (new read-only resolve export that decrypts a named value without the last_used_at stamp or exec audit β€” Lane B's contract; secret_locked/secret_unlocked audit actions via the existing no-values audit; every new entry point behind assertVaultIdentityForWrite where the sibling writers have it); modified src/cli/brain/verbs/secret.ts (ops lock, unlock; passphrase via stdin or --passphrase-from-env following the set ingestion pattern; wrap-on-first-unlock converts a raw keyfile); modified src/cli/command-manifest.ts, src/cli/help-text.ts (new ops modeled; loss warning stated). Tests: new tests/core/brain/secrets/envelope.test.ts; modified tests/core/brain/secrets/store.test.ts (envelope detection, locked-store named errors), tests/core/brain/secrets/exec.test.ts (exec under locked store), tests/core/brain/secrets/owner-acl.test.ts (envelope file ACL/mode, platform-guarded), tests/core/brain/secrets/sync-exposure.test.ts (wrapped-keyfile messaging), tests/cli/brain-secret.test.ts (lock/unlock ops), tests/core/brain/vault-guard-census.test.ts, tests/core/brain/vault-identity.test.ts (new entry points carry the guard), tests/core/architecture/write-site-census.test.ts (envelope.ts writes the keyfile path), tests/cli/manifest-completeness.test.ts (verify it stays green: the ratchet enumerates dispatcher switches one level deep, and brain secret sub-ops are parsed by the verb, so the manifest update is by hand in src/cli/command-manifest.ts; edit the test only if the ratchet's assertions reach the new ops).
  • Acceptance: tests/core/brain/secrets/envelope.test.ts asserts (a) wrap produces the versioned envelope at the keyfile path and the raw 32-byte DEK never appears on disk; (b) wrong passphrase fails closed via the GCM tag with a named error; (c) stored scrypt parameters round-trip and an unknown algo/version refuses by name; (d) unlock populates a process-local holder, lock clears it, and a second context over the same vault sees the named locked-store refusal; (e) the passphrase is never written anywhere under the vault (tree scan); (f) a never-wrapped store behaves byte-identically to today (regression assertions against the existing store suite's shapes). Every assertion must fail on pre-fix code (the module does not exist). Mode/ACL assertions carry the platform skip.
  • Depends on: none.

Task A2 β€” passphrase-encrypted credential bundles (t_592d9e91)

  • Files: new src/core/brain/secrets/bundle.ts (exportSecretBundle decrypts entries in memory and re-encrypts each under a key derived from the passphrase via A1's envelope; importSecretBundle verifies, reuses name/env-var validation, runs the vault-identity guard and the store lock, writes through writeStore; schema, generated_at excluded from sealed content, KDF params inside); modified src/cli/brain/verbs/secret.ts (ops export, import, --out FILE via atomicWriteFileSync, --replace for import conflicts); modified src/core/egress/registry.ts (single new site entry for the bundle export destination, honest redaction status over the non-ciphertext metadata tree β€” the deliberate wording decision, recorded in the entry's reason); modified src/cli/command-manifest.ts, src/cli/help-text.ts. Tests: new tests/core/brain/secrets/bundle.test.ts; modified tests/cli/brain-secret.test.ts (export/import ops), tests/core/architecture/egress-census.test.ts (the new site's declaration rows), tests/core/architecture/write-site-census.test.ts (bundle.ts write site).
  • Acceptance: tests/core/brain/secrets/bundle.test.ts asserts (a) export-then-import into a fresh vault restores names, env-var mappings, and allowlists; (b) wrong passphrase on import fails closed with a named error and writes nothing to the target store; (c) import refuses an existing name without --replace (exactness mirroring removeSecret); (d) the exported file's bytes contain none of the run-assembled credential literals from tests/helpers/fake-credentials.ts; (e) audit records secret_bundle_exported/secret_bundle_imported with no values; (f) unknown bundle algo/version refuses by name. Must fail on pre-fix code. The egress census must be green with A2's own commit (flag + entry + census rows land together).
  • Depends on: A1.

Lane B β€” resolver plane (card t_e5807974)

Task B1 β€” custody-store-backed provider with env fallback (t_e5807974)

  • Files: new src/core/secret-resolver.ts (secretProvider(vault) adapter composing parseSecretReference with Lane A's read-only resolve export; precedence store-first, env-fallback, EXCEPT a name the store holds under a locked envelope surfaces the named locked-store error β€” no silent env fallback; resolveNamedSecret for single values; metadata-only availability for list); modified src/core/secret-ref.ts only if the provider type moves beside SecretProvider (allowed, this lane's file). Tests: new tests/core/secret-resolver.test.ts.
  • Acceptance: tests/core/secret-resolver.test.ts asserts (a) a $secret:NAME value resolves from the custody store without stamping last_used_at and without emitting exec audit records; (b) env fallback resolves when the store does not hold the name; (c) a store-held name under a locked envelope produces the named locked-store error, not the env value; (d) malformed references keep the existing SecretReferenceError behavior; (e) resolution does not mutate the store file (byte-compare before/after). Must fail on pre-fix code (the module does not exist).
  • Depends on: A1 (the read-only resolve export).

Task B2 β€” route credential consumers through the resolver (t_e5807974)

  • Files: modified src/core/search/embeddings/registry.ts (expandRegisteredProvider probes through the merged provider), src/core/decision-model/config.ts (env-key resolution), src/core/brain/research/research.ts (fetch API keys), src/core/config.ts (Telegram token, installation secret), src/cli/main.ts (o2b secrets status/list availability from the merged provider; the exit-code contract for status stays unchanged). Tests: modified tests/core/search/embeddings.registry.test.ts, tests/core/decision-model/config.test.ts, tests/core/brain/research/research.test.ts, tests/core/config-telegram-capture.test.ts, tests/core/config.installation-secret.test.ts; new tests/core/secret-resolver.test.ts cases for merged-provider availability (same file as B1, this lane's).
  • Acceptance: the per-consumer suites assert that a $secret:NAME value in the consumer's config resolves through the store-backed provider at the use site (behavior identical to the env-provided value), that plain env values keep working byte-identically when no reference is used, and that an unresolvable reference surfaces the named resolver error instead of a silent empty value. Each consumer test must fail on pre-fix code (references resolve nothing today).
  • Depends on: B1.

Task B3 β€” egress redaction wiring for resolved values (t_e5807974)

  • Files: modified src/core/egress/guard.ts (the policy/EGRESS_REDACTION_OPTIONS composition accepts a resolved-literals list; redactForEgress and redactConfigMapping scrub them alongside the existing structural passes), src/mcp/error-redaction.ts (same literals on the MCP error path). Tests: new tests/core/egress-resolved-literals.test.ts.
  • Acceptance: tests/core/egress-resolved-literals.test.ts asserts (a) redactForEgress with a literals-bearing policy replaces each resolved value (longest first) with the standard marker before any truncation; (b) redactConfigMapping does the same; (c) with no literals the output is byte-identical to today; (d) the MCP error path scrubs resolved literals; (e) the verdict vocabulary stays within the closed census (tests/core/architecture/verdict-vocabulary-census.test.ts stays green untouched). Must fail on pre-fix code (literals cannot be injected today).
  • Depends on: B1.

Lane C β€” vault validation (cards t_11ee559f, t_151a564c)

Task C1 β€” tag syntax helper and composer enforcement (t_11ee559f, write half)

  • Files: new src/core/brain/tag-syntax.ts (isObsidianTagValue / typed field-naming error shaped like SchemaVocabularyError); modified src/core/tags.ts (the value-level predicate lives HERE, derived from the documented rule β€” one spelling, consumed, never copied); modified src/core/brain/signal.ts (composeSignalTags: extraTags entries failing the rule reject with the typed error; topic segment slugified then validated; scope segment rejected, not rewritten), src/core/brain/preference.ts (composePreferenceTags: same polarity), src/core/brain/claude-memory-render.ts (validate the derived topic/scope β€” a pin, they are slugified already). Tests: new tests/core/brain/tag-syntax.test.ts; modified tests/core/brain.signal.test.ts (new tag-syntax describe block: spaced topic yields the slugified tag, bad extraTags refuse with the field named, clean inputs byte-identical), tests/core/brain.preference.test.ts (same), tests/core/brain/claude-memory-render.test.ts (frontmatter tags always parse-shaped).
  • Acceptance: tests/core/brain/tag-syntax.test.ts asserts the rule against the src/core/tags.ts definition (accepts / nesting, rejects spaces and other specials, rejects leading slash and pure-numeric values) and that the predicate is imported, not redefined (a source-shape assertion). The composer tests must fail on pre-fix code (brain/topic/foo bar lands today).
  • Depends on: none.

Task C2 β€” frontmatter-tags hygiene detector (t_11ee559f, doctor half)

  • Files: new src/core/brain/hygiene/detectors/frontmatter-tags.ts (modeled on detectTags; reads frontmatter tags: via the existing frontmatter parser, which detectTags explicitly scopes out; findings severity info, proposed action review, frozen finding ids); modified src/core/brain/hygiene/types.ts (id registered in HYGIENE_DETECTOR_IDS), src/core/brain/hygiene/scan.ts (DETECTORS map entry; excluded from DEFAULT_SCAN_IDS β€” opt-in like tags). Tests: new tests/core/brain/hygiene-frontmatter-tags.test.ts; modified tests/core/brain/hygiene-tags.test.ts (registration pins: the new id in the closed tuple, excluded from the default sweep), tests/core/brain/hygiene-scan.test.ts (composition).
  • Acceptance: tests/core/brain/hygiene-frontmatter-tags.test.ts asserts (a) a note whose frontmatter tags: contains an unparseable value produces a finding with evidence naming the value and the rule; (b) parse-shaped tags produce nothing; (c) the detector never mutates the vault; (d) the default sweep skips it and an explicit --detectors subset runs it (pinning the existing two-policy mechanism). Must fail on pre-fix code (id unregistered, detector absent). Uses C1's predicate β€” never a local rule copy.
  • Depends on: C1.

Task C3 β€” capture vocabulary enforcement (t_151a564c)

  • Files: modified src/core/brain/schema-pack.ts (new declaredPageTypes(vault) predicate: null when no config is present, the declared page_types when declarations are non-empty; loadSchemaPack untouched); modified src/core/brain/capture/capture-note.ts (writeCaptureNote refuses an undeclared kind with the module's CaptureContractError before allocateAndCreate, naming the kind, the declared set, and the remedy), src/core/brain/capture/inbox-drain.ts (writeIdeaNote: same gate for captured-idea). Tests: modified tests/core/brain/capture/capture-note.test.ts (new cases: pack declaring page_types without brain-capture refuses before any file exists in the captures dir and before a name is consumed; declared set containing it passes; absent config fails open with byte-identical output), tests/core/brain/capture/inbox-drain.test.ts (mirror for captured-idea), tests/core/brain/capture/telegram-capture.test.ts (the typed refusal surfaces through the Telegram lane as every other contract refusal does).
  • Acceptance: the capture-note tests assert (a) refuse-before-allocate (the captures directory gains no file and the allocator consumes no name on refusal); (b) fail-open on absent config preserving today's behavior exactly; (c) kind stays the frontmatter key and parseCaptureFile still reads refused-then-fixed captures. Must fail on pre-fix code (no vocabulary consult exists today).
  • Depends on: none.

Lane D β€” sealed content adoption plans (card t_18fda844)

Task D1 β€” generalize the seal into the integrity module (t_18fda844, substrate)

  • Files: modified src/core/integrity/digest.ts (export sealWithDigest(body) and digestVerifies(body, digest) over sha256Hex(canonicalJson(body)), documented beside the persisted-digest doctrine in the module header); modified src/core/state/migrate.ts (sealManifest/manifestVerifies become thin aliases over the lifted primitives; behavior untouched). Tests: modified tests/core/integrity/digest.test.ts (seal/verify round-trip, canonical-JSON stability, tamper refusal), tests/core/state/migrate.test.ts (the existing digest-binding pins still hold through the aliases, including the :200-201 recomputation pin).
  • Acceptance: the digest test asserts seal-then-verify round-trips and that any body mutation fails verification; the migrate pins prove the aliasing changed nothing (all existing assertions pass unmodified in shape). Must fail on pre-fix code (the exports do not exist).
  • Depends on: none.

Task D2 β€” seal the Claude-memory import plan (t_18fda844)

  • Files: modified src/core/brain/import-claude-memory.ts (dry-run seals the plan body β€” plans, skipped, conflicts, relevant inputs; wall-clock fields excluded; the result carries the digest; apply accepts an approvalDigest option, re-plans, seals, and compares BEFORE the snapshot/write loop, refusing drift with a typed error whose remedy names re-run --dry-run); modified src/cli/brain/verbs/import-claude-memory.ts (--approval-digest; non-interactive apply requires it, interactive TTY keeps the existing prompt asymmetry). Tests: modified tests/core/brain/import-claude-memory-orchestrator.test.ts (digest present on dry-run; apply with the correct digest lands exactly the approved plan; apply with a stale digest refuses before any write or snapshot), tests/cli/brain-import-claude-memory.test.ts (flag plumbing; non-interactive apply without a digest refuses by name).
  • Acceptance: the orchestrator test asserts a vault mutation between dry-run and apply makes apply refuse with nothing written (byte-compare the vault tree), and that a matching digest applies bit-identically to today's clean path. Must fail on pre-fix code (no digest exists, apply never refuses).
  • Depends on: D1.

Task D3 β€” seal the brain-upgrade plan (t_18fda844)

  • Files: modified src/core/brain/upgrade.ts (UpgradePlan gains digest; sealed inside planUpgrade; applyUpgrade verifies at the top, before the drift check and the snapshot β€” a caller-supplied plan failing verification gets the drift refusal shape with a distinct message); modified src/cli/brain/helpers.ts (renderUpgradePlanJson emits the digest). Tests: modified tests/core/brain/upgrade.test.ts (self-computed plan trivially verifies; idempotent no-op unchanged), tests/core/brain/upgrade-drift.test.ts (a hand-built plan with a tampered body refuses with the seal message before the byte-drift check runs), tests/cli/brain-upgrade.test.ts (the JSON plan output carries the digest). The self-heal worker (src/core/maintenance/self-heal-upgrade.ts) is deliberately NOT edited: it computes its own plan, which verifies trivially β€” its existing suites must stay green untouched.
  • Acceptance: the drift test asserts a caller-supplied, tampered plan is refused before any write (nothing on disk changes, no snapshot taken), and the upgrade test asserts the sealed plan applies bit-identically to today. Must fail on pre-fix code (plans carry no digest and are trusted as-is).
  • Depends on: D1.

Lane E β€” sessions honesty (cards t_59d4c919, t_dac8bf7e)

Task E1 β€” divergent session summaries on single-session reads (t_59d4c919)

  • Files: modified src/core/brain/session-summary.ts (new exported divergence-aware read returning the sorted-latest digest plus digest_count, and, when the count exceeds one, divergent: true plus a bounded id/created_at/content_hash list; getSessionSummary remains a thin wrapper so no caller changes); modified src/mcp/brain/synthesis-tools.ts (the get operation spreads the additive fields via the conditional-key idiom; { found: false } untouched; id/hash lists, never full payload echoes); modified src/cli/brain/verbs/session-summary.ts (same fields on --json; one note line in text mode; the serializer gains project, fixing the verified CLI/MCP drift). Tests: modified tests/core/brain.session-summary.test.ts (two content-differing appends: the new read reports digest_count: 2 and divergent: true and still returns the sorted-latest; single record reports count 1 and no divergent key; the existing latest-wins pins survive), tests/mcp/session-summary-tool.test.ts (get after two differing writes carries the additive keys; found: false case byte-identical); new tests/cli/brain-session-summary.test.ts (CLI get: --json fields, text note line, project now serialized).
  • Acceptance: the core test asserts divergence is computed over content-differing records for one session (a duplicate-content write still dedupes to count 1), and every response is additive β€” no existing key moves or disappears. Must fail on pre-fix code (no divergence read exists; the CLI serializer omits project today).
  • Depends on: none.

Task E2 β€” named think-block strip before CLI JSON parse (t_dac8bf7e)

  • Files: new src/core/brain/payload-json.ts (strip-and-note parser: plain parse first; on failure strip one leading <think>...</think> block β€” fenced-unwrap per the llm-emulation.ts precedent β€” retry, and return the payload plus the strip fact { kind, prefixChars } or a named unparseable error; no I/O); modified src/cli/brain/verbs/extract-signals.ts, src/cli/brain/verbs/design-note.ts, src/cli/brain/verbs/skill-proposals.ts, src/cli/brain/verbs/distill.ts (route through the parser; note on the { ok: true } envelope only when stripped; the still-invalid refusal names the strip attempt; exit codes unchanged). Tests: new tests/core/brain/payload-json.test.ts; modified tests/cli/brain-extract-signals.test.ts, tests/cli/brain-design-note.test.ts, tests/cli/brain-skill-page-drafts.test.ts, tests/cli/brain-distill.test.ts (each: a <think>-prefixed payload succeeds with note present and written items identical to the clean case; garbage still exits 1 with ok: false; clean JSON output is byte-identical β€” no note key).
  • Acceptance: tests/core/brain/payload-json.test.ts asserts the strip fires only after a failed plain parse, is always reported when it happens, never rescues genuinely malformed JSON (strip-then-still-invalid keeps the named error), and handles fenced and prose-prefixed shapes per the helper's contract. The verb tests must fail on pre-fix code (a think-prefixed payload exits 1 today with the generic message).
  • Depends on: none.

Lane F β€” ingest contract (card t_586d5d8b)

Task F1 β€” contract fingerprint and manifest field (t_586d5d8b, substrate)

  • Files: new src/core/brain/ingest/contract.ts (EXTRACT_CONTRACT_VERSION with the bump-guard comment in the CHUNKER_VERSION style; computeExtractionContractFingerprint(vault) = sha256Hex(canonicalJson({ version, extractable sorted })).slice(0, 16); pure over vault config plus the constant); modified src/core/brain/ingest/content-manifest.ts (SCHEMA_VERSION to 2; SUPPORTED_SCHEMA_VERSIONS-style read accepting v1 with contract treated as changed; genuinely unknown versions still hard-refuse; manifest-wide contract: { fingerprint } persisted by serializeManifest, read by readManifest, written by updateManifest under the existing lock); modified src/core/brain/source-cleanup.ts (its direct manifest write round-trips the field). Tests: modified tests/core/brain/ingest/content-manifest.test.ts (contract field round-trip; v1 manifest reads and degrades to changed-contract; unknown version still refuses by name; cleanup preserves the field; fingerprint is stable across calls and changes when extractable changes or the version bumps); new tests/core/brain/ingest/contract.test.ts (purity: no clock, no absolute paths, no per-call options in the input).
  • Acceptance: the manifest test asserts a v1 fixture (no contract field) is accepted, every classification treats it as changed, and the next write lands as v2 with the fingerprint; the fingerprint tests must fail on pre-fix code (field and module do not exist).
  • Depends on: none.

Task F2 β€” planner comparison, plan-id folding, honest reporting (t_586d5d8b)

  • Files: modified src/core/brain/ingest/batch-plan.ts (compare fingerprints immediately after readManifest; on mismatch reclassify unchanged sources for reprocessing with a distinct typed reason token β€” "bytes changed" vs "contract changed"; plan-level contractChanged plus counts emitted conditionally); modified src/core/brain/ingest/checkpoint.ts (fold the fingerprint into computePlanId, computeSessionImportId style); modified src/mcp/brain/ingest-tools.ts (serializeBatchPlan conditional emission of the contract-changed fields); modified src/cli/brain/verbs/batch-plan.ts (surface the same reporting). Tests: modified tests/core/brain/ingest/batch-plan.test.ts (changed extractable reprocesses unchanged files under the distinct reason; identical contract skips as before), tests/core/brain/ingest/batch-plan-extractable.test.ts (gate interaction), tests/core/brain/ingest/checkpoint.test.ts (plan id changes when the contract changes; the old checkpoint is not consumed), tests/core/brain/ingest/reconcile.test.ts (gap report under a contract change), tests/core/brain/ingest/ingest.test.ts (integration: re-ingest after a contract change rewrites the summary page and the manifest as v2), tests/cli/brain-batch-plan-reconcile.test.ts, tests/mcp/ingest-plan-format-reach.test.ts (conditional wire emission β€” byte-identical when the contract is unchanged).
  • Acceptance: the batch-plan test asserts a contract change with identical bytes produces full reprocess plans carrying the contract-changed reason, and an unchanged contract produces byte-identical plans to today; the checkpoint test asserts a stale checkpoint cannot resume-skip under a new contract. Must fail on pre-fix code (no comparison, no fold).
  • Depends on: F1.