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

Agent presence and self-improvement - implementation plan

Four implementation lanes with strictly disjoint file ownership plus one integrator. Each task is TDD-ready: write the failing test first, run it and see the expected failure, implement until green, refactor green, then run the repo formatter (./node_modules/.bin/oxfmt, not bunx oxfmt) and the repo lint on the task's own files before every commit, and commit only that task's own files with git commit --only <paths> (never a plain git add + git commit). Each lane runs ONLY its own new or changed test files locally (never the full suite); the integrator runs the full gates. Test runs use a throwaway HOME (env HOME=$(mktemp -d) bun test <paths>). Version bump, CHANGELOG assembly and the release-wide docs pass are the pr-prepare phase and are intentionally absent here.

Staged commit order: pure modules commit FIRST so dependent lanes unblock - Lane B's Task B1 (the shared writer) and Lane A's Tasks A1-A2 (the pure scoring leaves) are the earliest commits on the branch; Lane C may not start until B1's commit lands; Lane D is independent of everything.

Dependency-wait rule: a lane whose task depends on another lane's committed file polls git log -- <file> for the upstream lane's commit every 30 seconds, for at most 12 minutes. If the commit has not landed when the cap expires, the lane STOPS and reports which pinned-contract file it is waiting on; it never builds against uncommitted code and never re-implements another lane's module locally.

Cross-lane contracts (frozen before lane work starts)

These are the pinned shapes every lane builds against. A lane that needs to change one stops and renegotiates in this document first; it never narrows an exported shape unilaterally.

  • K1 - the shared rules-block writer (Lane B owns; Lanes B and C consume; committed FIRST).
    • src/core/install/rules-block.ts: export const RULES_BLOCK_ID = Object.freeze({ usage: "usage", lessons: "lessons" } as const); export type RulesBlockId = (typeof RULES_BLOCK_ID)[keyof typeof RULES_BLOCK_ID]; export const RULES_BLOCK_MARKERS: Readonly<Record<RulesBlockId, { readonly begin: string; readonly end: string }>> - the usage entry is the settled DEFAULT_BEGIN_MARKER/DEFAULT_END_MARKER from src/core/install/managed-block.ts re-exported under the map (the checker's contract spellings); the lessons entry is <!-- >>> open-second-brain lessons >>> --> / <!-- >>> open-second-brain lessons <<< -->.
    • export function renderRulesBlock(blockId: RulesBlockId, body: string): { readonly beginMarker: string; readonly endMarker: string; readonly document: string }.
    • export function readRulesBlock(file: string, blockId: RulesBlockId): string | null - null when no pair of that spelling exists; throws RulesBlockError on multiple/unpaired/reversed pairs (wrapping ManagedBlockError).
    • export const RULES_BLOCK_STATE = Object.freeze({ absent: "absent", current: "current", drifted: "drifted" } as const); export function rulesBlockDrift(file: string, blockId: RulesBlockId, canonicalBody: string): { readonly state: RulesBlockState; readonly extracted: string | null } - read-only.
    • export interface RulesBlockWriteOptions { readonly dryRun?: boolean; readonly force?: boolean; readonly installedAtMs?: number | null }; export interface RulesBlockWriteResult { readonly changed: boolean; readonly backupPath: string | null }; export function writeRulesBlock(file: string, blockId: RulesBlockId, canonicalBody: string, opts?: RulesBlockWriteOptions): RulesBlockWriteResult - refuses with RulesBlockError (kind user-modified-block) when the existing block diverges from canonicalBody AND the file mtime is newer than installedAtMs, unless force; takes an exclusive-create, collision-laddered backup of the current file before the first write and returns its path; writes atomically via atomicWriteFileSync; byte-compares so a re-apply is changed: false; dryRun writes nothing.
    • export function removeRulesBlock(file: string, blockId: RulesBlockId, opts?: { readonly dryRun?: boolean }): { readonly removed: boolean } - a named skip (removed false) when no pair exists; never unlinks the file.
  • K2 - the canonical usage body and the installer mapping (Lane B owns).
    • src/core/brain/writeback-contract.ts gains exactly one export: export const CANONICAL_WRITEBACK_BLOCK_BODY: string - the gate clauses (marker-writeback guardrail token, same-turn rule, atomic-fact rule) merged with the cross-project-pointer usage content (read Brain/active.md at session start, brain_feedback, brain_apply_evidence, the do-not-dream rule); self-tested to satisfy missingWritebackGateClauses. No other change to the checker; it stays write-free.
    • src/core/install/instruction-block.ts: export function instructionBlockTargetFor(target: InstallTargetId): string | null - HOST_INSTRUCTION_PRECEDENCE[target][0] for targets with an entry, null otherwise (named skip); export interface InstructionBlockPlan { readonly path: string; readonly exists: boolean; readonly changed: boolean; readonly diff: string; readonly note: string | null }; export function planInstructionBlock(env: InstallEnv): InstructionBlockPlan (vault-root path, pure read + diff render); export function applyInstructionBlock(env: InstallEnv, opts: { readonly dryRun?: boolean; readonly force?: boolean; readonly approved: InstructionBlockPlan }): { readonly backupPath: string | null } - refuses when the on-disk bytes moved since the approved preview (typed RulesBlockError, kind preview-drift); instruction-block lock I/O with export const INSTRUCTION_BLOCK_LOCK_FILE = "instruction-block.lock.json".
  • K3 - the lessons promotion kernel (Lane C owns; the CLI verb, doctor and status consume exactly this).
    • src/core/brain/lessons-promotion.ts: export const LESSONS_PROMOTION_SCOPES_CONFIG_KEY = "lessons.promotion.scopes"; export interface LessonPromotionCandidate { readonly prefId: string; readonly principle: string; readonly scope: string; readonly tier: LessonTier; readonly confidence: BrainConfidence; readonly contentHash: string }; export const LESSON_PROMOTION_BLOCKED = Object.freeze({ scope_not_enabled: "scope_not_enabled", unconfirmed: "unconfirmed", low_confidence: "low_confidence", tier_not_preferred: "tier_not_preferred", not_approved: "not_approved", stale_approval: "stale_approval", denied: "denied" } as const); export function lessonPromotionCandidates(preferences, lessons, approvals, opts: { readonly enabledScopes: ReadonlyArray<string> }): { readonly promotable: ReadonlyArray<LessonPromotionCandidate>; readonly blocked: ReadonlyArray<{ readonly prefId: string; readonly reason: LessonPromotionBlocked }> } - pure; export function renderLessonsBlockBody(promotable: ReadonlyArray<LessonPromotionCandidate>): string - deterministic (tier, then scope, then id ordering; no timestamps; bounded by the lessons.limit config); export const LESSONS_APPROVALS_FILE = "lessons-approvals.json"; export interface LessonApprovalRow { readonly prefId: string; readonly decision: "approved" | "denied"; readonly decidedAt: string; readonly decidedBy: "yes-flag" | "interactive-yes"; readonly approvedContentHash: string; readonly targets: ReadonlyArray<string>; readonly blockId: RulesBlockId; readonly lastPromotedAt: string | null }; export function readLessonApprovals(vault: string): ReadonlyArray<LessonApprovalRow>; export function recordLessonApproval(vault: string, row: LessonApprovalRow): void (atomic write). Qualification requires preference-derived only, confirmed, high, preferred, scope enabled, approval fresh (hash match) - every non-member carries exactly one named blocked reason.
  • K4 - the skill rewrite kernels (Lane A owns; the proposal pipeline, CLI and MCP faces consume exactly this).
    • src/core/brain/skill-rewrite-tasks.ts: export const SKILL_BENCHMARKS_DIR = "skill-benchmarks" (under Brain/); export const SKILL_BENCH_TASK_KIND = Object.freeze({ invocation_transcript: "invocation_transcript" } as const); export const SKILL_BENCH_CHECK = Object.freeze({ tool_used: "tool_used", artifact_created: "artifact_created", step_order: "step_order", forbidden_step: "forbidden_step", output_field: "output_field" } as const); export interface SkillBenchmarkTask { readonly id: string; readonly kind: SkillBenchTaskKind; readonly input: string; readonly expects: ReadonlyArray<SkillBenchExpectation> }; export interface SkillBenchmarkTaskSet { readonly skillName: string; readonly tasks: ReadonlyArray<SkillBenchmarkTask>; readonly hash: string }; export function parseSkillBenchmarkTasks(raw: unknown, source: string): SkillBenchmarkTaskSet - fail-fast named errors in the parseBenchFixture style; hash is sha256Hex(canonicalJson(tasks)).
    • src/core/brain/skill-rewrite-spec.ts: export const SKILL_REWRITE_SPEC_SCHEMA = "o2b.skill-rewrite.v1"; export const SKILL_REWRITE_SPLIT_RULE = "hash-order-70-30"; export const SKILL_REWRITE_METRIC = "tasks_passed_rate"; export const SKILL_REWRITE_VERDICT = Object.freeze({ promote: "promote", hold: "hold", not_enough_evidence: "not_enough_evidence" } as const); export interface SkillRewriteSpec { readonly schemaVersion: string; readonly skillName: string; readonly tasksHash: string; readonly seed: number; readonly splitRule: string; readonly devTaskIds: ReadonlyArray<string>; readonly heldoutTaskIds: ReadonlyArray<string>; readonly requiredMargin: number; readonly minDevTasks: number }; export function buildSkillRewriteSpec(skillName: string, tasks: SkillBenchmarkTaskSet, opts?: { readonly seed?: number }): SkillRewriteSpec; export function verifyRewriteTake(spec: SkillRewriteSpec, tasks: SkillBenchmarkTaskSet): { readonly ok: boolean; readonly reason: string | null } - refuses a task set whose hash no longer matches the receipt.
    • src/core/brain/skill-rewrite.ts: export const SKILL_REWRITE_STEP = "skill-rewrite-task"; export function buildRewriteEnvelopes(candidateBody: string, spec: SkillRewriteSpec, tasks: SkillBenchmarkTaskSet): ReadonlyArray<NeedsLlmStep> - asserts every envelope task id is a devTaskIds member (held-out ids are refused by construction); export interface RewriteTaskScore { readonly taskId: string; readonly passed: boolean; readonly failedChecks: ReadonlyArray<string> }; export function scoreRewriteTranscripts(submissions: ReadonlyArray<unknown>, tasks: SkillBenchmarkTaskSet): ReadonlyArray<RewriteTaskScore> - validates the submitted transcript shape and scores structural predicates only; export function selectRewriteCandidate(baseline: ReadonlyArray<RewriteTaskScore>, candidate: ReadonlyArray<RewriteTaskScore>, spec: SkillRewriteSpec): { readonly verdict: SkillRewriteVerdict; readonly baselineRate: number; readonly candidateRate: number }; export function checkRewriteHeldout(candidate: ReadonlyArray<RewriteTaskScore>, spec: SkillRewriteSpec): SkillRewriteVerdict - a miss downgrades promote to hold; export function resolveSkillRewriteMode(raw: string | undefined): "gated" | "iterative" - unknown values are named errors.
    • src/core/brain/skill-proposals.ts extension: export const SCORED_REWRITE_PATTERN_KIND = "scored_rewrite" added to SkillProposalPatternKind; the staged proposal carries rewrites_skill, spec_hash, baseline_score, candidate_score, heldout_score beside the existing SKILL_DRAFT_* contract keys; the accept journal entry gains priorContentPath and compensateSkillAccept restores prior bytes from it.
    • src/core/brain/skill-accept-journal.ts extension: priorContentPath?: string on SkillAcceptJournalEntry, parsed and written like the existing fields.
    • src/core/brain/continuity/types.ts extension: "skill_rewrite_eval_grade" added to the union and to CONTINUITY_RECORD_KINDS in the same edit; the record carries ids, scores and per-check verdicts with the spec hash - never task text, never transcript text.
    • src/core/config.ts extensions: SKILL_REWRITE_MODE_CONFIG_KEY = "skill_rewrite.mode" (env twin OPEN_SECOND_BRAIN_SKILL_REWRITE_MODE) and SKILL_REWRITE_JUDGE_CMD_CONFIG_KEY = "skill_rewrite_judge_cmd" (env twin), resolved with the flat-key + env-twin pattern.
  • K5 - shared registries are append-only. Files listed in the shared table below are edited by a lane only in its lane-final task, appends only (never edits, reorders or deletes another lane's entries), and committed in that lane's own final commit via git commit --only. The integrator re-freezes ordering and prose.

File ownership table

Each file is owned by exactly one lane (or nobody). A lane that needs a file outside its ownership stops and renegotiates this contract; it never reaches into another lane's files.

Files Owner
src/core/install/rules-block.ts, src/core/install/instruction-block.ts Lane B
src/core/brain/writeback-contract.ts, src/cli/install/install.ts, src/cli/install/uninstall-target.ts Lane B
tests/core/install/rules-block.test.ts, tests/core/install/instruction-block.test.ts, tests/cli/install-instruction-step.test.ts, tests/core/install/uninstall-instruction-step.test.ts Lane B
src/core/brain/lessons-promotion.ts, src/cli/brain/verbs/lessons.ts, src/core/brain/doctor/lessons-block-check.ts, src/core/brain/status.ts, src/core/brain/types.ts (log kinds), src/core/brain/policy/blocks/lessons.ts Lane C
tests/core/brain/lessons-promotion.test.ts, tests/cli/brain-lessons.test.ts, tests/core/brain/doctor/lessons-block-check.test.ts, tests/mcp/lessons-status-report.test.ts Lane C
src/core/brain/skill-rewrite-tasks.ts, src/core/brain/skill-rewrite-spec.ts, src/core/brain/skill-rewrite.ts, src/core/brain/skill-proposals.ts, src/core/brain/skill-accept-journal.ts, src/core/brain/continuity/types.ts, src/core/brain/paths.ts, src/cli/brain/verbs/skill-proposals.ts, src/mcp/brain/procedure-tools.ts, tests/fixtures/skill-bench/** Lane A
tests/core/brain/skill-rewrite-tasks.test.ts, tests/core/brain/skill-rewrite-spec.test.ts, tests/core/brain/skill-rewrite.test.ts, tests/core/brain/skill-proposals-rewrite.test.ts, tests/cli/skill-rewrite-verb.test.ts, tests/mcp/skill-rewrite-status.test.ts Lane A
src/core/install/adapters/codex.ts, README.md, install/codex.md Lane D
tests/core/install/adapters/codex-chatgpt-note.test.ts Lane D
src/core/config.ts Renegotiated: Lane A and Lane C each append their own keys in their lane-final commits per K5 (flat-key blocks are additive; no reordering).
src/core/brain/writeback-contract.ts consumers (src/core/doctor-readiness.ts), src/core/brain/write-gate.ts, src/core/brain/standing-rules.ts, src/core/brain/content-hash.ts, src/core/install/managed-block.ts, src/core/integrity/digest.ts, src/core/reliability/command-bridge.ts, src/core/decision-model/eval-spec.ts, src/core/bench/fixture.ts, src/core/brain/llm-step.ts, src/core/runtime/host-facts.ts, hooks/**, src/core/brain/dream*.ts Nobody - read-only precedents; no lane modifies them except through the shared protocol rows below

Shared files (K5 append-only protocol): src/core/state/surfaces.ts (Lane B appends the instruction-block lock row, Lane C the lessons-approvals row, Lane A the skill-benchmarks row - each in its lane-final commit); src/core/config.ts (Lane A and Lane C, own keys only); src/cli/command-manifest.ts and src/cli/brain/help-text.ts (Lane A the skill-proposals subcommands, Lane C the lessons verb, each appends its own rows); tests/cli/manifest-completeness.test.ts, tests/cli/help-surface-parity.test.ts, tests/cli/completions.test.ts (Lane A and C, each appends its own entries); tests/core/architecture/verdict-vocabulary-census.test.ts (Lane A registers the rewrite verdict/metric kinds, Lane C the lessons-block state vocabulary, each its own entries); tests/core/architecture/state-surface-census.test.ts consumers and tests/core/state/surfaces.test.ts (each lane extends for its own row); docs/cli-reference.md (each lane appends its own rows); docs/observability.md (Lane A grade-record row, Lane C lessons-block row).

Census obligations (exact files; a lane lands its registrations with the code that trips them, never retrofitted)

  • Lane A: tests/core/architecture/write-site-census.test.ts (the benchmark-path and journal-copy writes route through shared atomic writers; any direct node:fs content write needs a categorised DIRECT_WRITE_EXCLUSIONS row - the existing skill-proposals.ts :1109 and skill-accept-journal.ts :744 rows are the templates and must be updated for the new call shapes); tests/core/architecture/destructive-site-census.test.ts (the rollback's restore/rm sites in the extended journal compensation name their recovery); tests/core/architecture/append-shard-census.test.ts (the grade record appends through the continuity store; a raw append for a rewrite round ledger would need an APPEND_ALLOW_LIST row - avoid); tests/core/architecture/import-cycles.test.ts (skill-rewrite-tasks.ts and skill-rewrite-spec.ts stay true leaves, import type included); tests/core/architecture/state-surface-census.test.ts (Brain/skill-benchmarks/ row with sources attribution); tests/core/brain/continuity/reader-census.test.ts (the rewrite module reads continuity records on the correct side of the store/read-model split); tests/core/architecture/claim-attribution-census.test.ts (the skill_rewrite_eval_grade kind); tests/core/architecture/visibility-surface-census.test.ts and the src/mcp/registry-guard.ts conventions (the read-only rewrite-status surface, beside the brain_skill_proposals row at src/core/search/visibility-surface-registry.ts:773); tests/core/architecture/verdict-vocabulary-census.test.ts (SKILL_REWRITE_VERDICT, SKILL_REWRITE_METRIC, the check vocabulary); tests/core/architecture/progress-census.test.ts (a Safeguard-taking options type carries a synchronous progress sink or a written reason); tests/core/architecture/egress-census.test.ts (no dest-style parameter - the judge rides the command bridge; a --out flag would create an obligation). tests/core/architecture/host-facts-census.test.ts stays untouched by construction.
  • Lane B: tests/core/architecture/write-site-census.test.ts (rules-block.ts/instruction-block.ts write vault-root files through atomicWriteFileSync and the exclusive-create backup helper - shared-class rows, no exclusions; a direct writeFileSync binding fails the census); tests/core/architecture/state-surface-census.test.ts (instruction-block.lock.json row, sources naming the installer module); tests/core/install/ownership.test.ts (vault-rooted joins only - no home/XDG/temp anchors, no OUT_OF_VAULT_STATE row; any cwd targeting would create one and is out of scope); tests/core/architecture/egress-census.test.ts (the canonical body is static text plus the vault path - never vault memory content, no redactor owed); tests/core/brain/vault-guard-census.test.ts (writeback-contract.ts stays write-free so it never enters the walked population); tests/core/architecture/import-cycles.test.ts and tests/core/layering.test.ts (core/install -> core/brain/writeback-contract -> core/install/managed-block acyclic; core never process.exit or writes stdout); tests/core/architecture/host-facts-census.test.ts (no new target, the step reuses the existing "managed-block" kind in INSTALL_STEP_KINDS - both censuses satisfied by construction); doctor exit codes unchanged (INSTALL_EXIT reuse).
  • Lane C: tests/core/architecture/write-site-census.test.ts (the lessons verbs write vault-root rules files ONLY through the shared K1 writer - no new direct writer anywhere in the lane); tests/core/architecture/state-surface-census.test.ts (lessons-approvals.json row with sources attributing every module naming the file or its constant); tests/core/architecture/verdict-vocabulary-census.test.ts (the lessons-block state findings reuse the K1 RULES_BLOCK_STATE family plus the named stale-lessons extension, registered); tests/core/architecture/append-shard-census.test.ts and the log-chain doctor checks stay green with the three new log event kinds; tests/core/architecture/destructive-site-census.test.ts (the lane never unlinks; removal is uninstall's business under Lane B's path); tests/core/architecture/visibility-surface-census.test.ts (MCP stays report-only through existing tools - a new tool would require registry rows in both directions and is avoided by design).

Lane B - the shared rules-block writer and the installer step (t_ba41a78a)

Task B1: the writer module (commits FIRST on the branch)

  • Files: new src/core/install/rules-block.ts per contract K1; new tests/core/install/rules-block.test.ts.
  • Acceptance: the failing-first tests prove: renderRulesBlock for usage emits the settled default marker spellings and for lessons the HTML-comment pair; writeRulesBlock on a file with operator content preserves every byte outside the block, is idempotent (second apply reports changed: false and byte-equal output), detects and preserves CRLF line endings, takes exactly one exclusive-create laddered backup before the first write and none on a no-op, refuses a block that diverged from canonical on a file newer than installedAtMs with kind user-modified-block unless force, refuses through a symlink by name, and refuses multiple/unpaired/reversed pairs of the block's own spelling by wrapping ManagedBlockError; readRulesBlock returns null when only a DIFFERENT block id's pair exists; removeRulesBlock removes only the pair it owns, collapses its own padding, and is a named skip when absent; dryRun writes nothing on every path.
  • Depends on: none.

Task B2: canonical body constant and the installer module

  • Files: modified src/core/brain/writeback-contract.ts (CANONICAL_WRITEBACK_BLOCK_BODY + docblock/recovery wording per K2); modified tests/core/brain/writeback-contract.test.ts (the self-test: missingWritebackGateClauses(CANONICAL_WRITEBACK_BLOCK_BODY) empty; the audit still grades a lessons-only file missing-block and a both-blocks file by its own pair alone); new src/core/install/instruction-block.ts per K2; new tests/core/install/instruction-block.test.ts.
  • Acceptance: the failing-first tests prove: the constant satisfies the checker (self-test) and its diff preview renders; instructionBlockTargetFor returns AGENTS.md for codex/cursor/opencode/aider, GEMINI.md for gemini-cli, null for copilot-cli/grok/kiro/pi/generic (named skips) - derived from HOST_INSTRUCTION_PRECEDENCE, asserted to follow the table if it ever grows; planInstructionBlock reads with the checker's posture (lstat first, symlink refused), reports exists/changed/diff and a gemini-cli postNote; applyInstructionBlock refuses preview drift by name, writes atomically with a backup, records the lock round-trip (schema version, applied_at, owned files, begin marker), and the forced rewrite of a docs-snippet-style non-conforming body upgrades the file to conforming (asserted through the real auditWritebackContractFile); the gemini-cli note and the absent-file creation case are plan-visible.
  • Depends on: B1.

Task B3: install and uninstall wiring

  • Files: modified src/cli/install/install.ts (plan augmentation + the post-adapter apply step in runTarget under the existing consent gate); modified src/cli/install/uninstall-target.ts (the reverse step against the lock); new tests/cli/install-instruction-step.test.ts; new tests/core/install/uninstall-instruction-step.test.ts.
  • Acceptance: the failing-first tests prove: the rendered plan includes the instruction step (or its named skip) for every target; one consent verdict covers adapter write and instruction write (the --yes/interactive/headless-refused matrix from the existing install suite, exit 6 preserved); exit 4 on a user-modified-block refusal; a failure after the adapter apply exits non-zero and a re-run converges (idempotent); uninstall removes the lock-recorded pair, is a named skip when markers are absent, and clears the lock; o2b install --check behavior is unchanged (the readiness probe remains the block auditor).
  • Depends on: B2.

Task B4: state surface, census registrations and docs (lane final)

  • Files: modified src/core/state/surfaces.ts (instruction-block.lock.json row) with tests/core/architecture/state-surface-census.test.ts consumers and tests/core/state/surfaces.test.ts; tests/core/architecture/write-site-census.test.ts and tests/core/install/ownership.test.ts verified green with the new module (shared-class rows); docs rows in docs/cli-reference.md and a pointer update in docs/cross-project-pointer.md (manual installers are pointed at the install command).
  • Acceptance: the failing-first tests prove: the surfaces census binds the new row in both directions and o2b state status renders it; the write-site census passes with the shared-writer routing and fails if a direct write is introduced; ownership sweep passes with no out-of-vault anchors; the docs rows name the instruction step per target.
  • Depends on: B3.

Lane C - operator-approved lesson promotion (t_1e952e43)

Task C1: promotion kernel and approvals ledger

  • Files: new src/core/brain/lessons-promotion.ts per contract K3; modified src/core/brain/policy/blocks/lessons.ts (lessons.promotion.scopes resolution with env twin, absent-or-empty disables with a named count); modified src/core/brain/types.ts (log event kinds lessons-approved/lessons-denied/lessons-promoted); new tests/core/brain/lessons-promotion.test.ts.
  • Acceptance: the failing-first tests prove: qualification is the exact conjunction (preference-derived, confirmed, high, preferred, scope enabled, approval fresh) and every non-member carries exactly one named blocked reason from the closed set; a stale approval (content-hash mismatch against _content_hash) drops the lesson from promotable and reports stale_approval; renderLessonsBlockBody is deterministic (same inputs, identical bytes; tier-then-scope-then-id order; no timestamps; bounded by lessons.limit); the rendered body satisfies no contract-clause requirement of the usage block and vice versa (the blocks are independent); the ledger round-trips atomically and readLessonApprovals never reads Brain/; the writer calls go through K1 only (a source-scanning assertion that the module never imports node:fs write functions directly).
  • Depends on: B1's COMMIT (dependency-wait rule: poll git log -- src/core/install/rules-block.ts, 30 s interval, 12 min cap).

Task C2: operator verbs

  • Files: new src/cli/brain/verbs/lessons.ts (cmdBrainLessons: candidates read-only; approve <pref-id> / deny <pref-id> with the install consent ladder shape; refresh-blocks re-rendering and writing blocks under management); SHARED appends: src/cli/command-manifest.ts, src/cli/brain/help-text.ts, tests/cli/manifest-completeness.test.ts, tests/cli/help-surface-parity.test.ts, tests/cli/completions.test.ts; new tests/cli/brain-lessons.test.ts.
  • Acceptance: the failing-first tests prove: candidates lists promotable plus blocked-with-reasons and is read-only; approve renders the plan (target files, block diff), refuses headless without --yes (exit 6 vocabulary), records the ledger row only after a successful K1 write, and appends the lessons-approved event; deny records without writing rules files and suppresses future promotion for that id; refresh-blocks is a no-op (named) when no block exists under management, never CREATES a block (creation is approve's write), and updates last_promoted_at; a stale lesson drops from the block on refresh and is reported by name.
  • Depends on: C1.

Task C3: doctor, status and report-only MCP

  • Files: new src/core/brain/doctor/lessons-block-check.ts (readiness rows per candidate file: absent | current | drifted | stale-lessons beside the existing writeback_contract probe) with tests/core/brain/doctor/lessons-block-check.test.ts; modified src/core/brain/status.ts (approved/denied/stale counts in the snapshot); new tests/mcp/lessons-status-report.test.ts (counts visible through the existing status plumbing; no new MCP tool name registered anywhere).
  • Acceptance: the failing-first tests prove: a vault with a managed block whose lessons went stale yields the named finding with the refresh command; a current block is silent; the counts match the ledger plus derived staleness; MCP output carries the counts without a new tool and the frozen tool-name parity set is untouched; the doctor never mutates and never throws.
  • Depends on: C1 (C2 for the next-command wording only).

Task C4: state surface, census registrations and docs (lane final)

  • Files: modified src/core/state/surfaces.ts (lessons-approvals.json row) with the census consumers and tests/core/state/surfaces.test.ts; tests/core/architecture/verdict-vocabulary-census.test.ts (the lessons-block state vocabulary); docs rows in docs/cli-reference.md and docs/observability.md.
  • Acceptance: the failing-first tests prove: the state-surface census binds the row with sources attribution covering every module naming the file; the verdict census accepts the state vocabulary and fails on an unregistered member; the docs name the approval tier, the verb family and the trust boundary (operator-only writes).
  • Depends on: C2, C3.

Lane A - benchmark-gated skill rewrites (t_635e3e72, the L anchor)

Task A1: task-set kernel (pure leaf, commits early)

  • Files: new src/core/brain/skill-rewrite-tasks.ts per contract K4; new tests/core/brain/skill-rewrite-tasks.test.ts; new tests/fixtures/skill-bench/<example-skill>/tasks.json.
  • Acceptance: the failing-first tests prove: the parser accepts a valid set and rejects every malformed shape with a named error naming the source path (missing id, unknown kind, unknown check, empty expects, duplicate ids, non-string input); the closed vocabularies are frozen and answered by their guards; the hash is sha256Hex(canonicalJson(tasks)), stable across parses and sensitive to any task byte; the module imports nothing from the layer above (import-cycles green).
  • Depends on: none.

Task A2: spec kernel (pure leaf, commits early)

  • Files: new src/core/brain/skill-rewrite-spec.ts per contract K4; new tests/core/brain/skill-rewrite-spec.test.ts; new tests/fixtures/skill-bench/<example-skill>/spec.json.
  • Acceptance: the failing-first tests prove: buildSkillRewriteSpec derives dev/heldout membership deterministically from the seed and the split rule (same tasks hash plus seed, identical receipt), the receipt covers every task id exactly once across the two arms, verifyRewriteTake accepts the matching set and refuses a changed set with the hash in the reason, and the schema constant is refused-by-name on read when unknown.
  • Depends on: A1.

Task A3: gate kernels - envelopes, scoring, selection, held-out, mode

  • Files: new src/core/brain/skill-rewrite.ts per contract K4; new tests/core/brain/skill-rewrite.test.ts.
  • Acceptance: the failing-first tests prove: buildRewriteEnvelopes emits one needs-llm-step per DEV task carrying the candidate body and task input, and refuses (named) when any task id is not a dev member - held-out contamination is refused by construction; scoreRewriteTranscripts validates the submitted shape (named refusals) and scores only structural predicates, reporting per-check failures by check id, and never scores a self-reported success field; selectRewriteCandidate implements the three arms exactly (strict beat by margin with n met promotes, a tie holds, a short dev n is not_enough_evidence); checkRewriteHeldout downgrades promote to hold on a held-out miss and passes promote through on a full pass; resolveSkillRewriteMode accepts gated/iterative and errors by name on anything else; the grade-record assembly carries ids, scores and check verdicts with the spec hash and NEVER task or transcript text (an assertion over the serialized record).
  • Depends on: A2.

Task A4: apply path - proposal pipeline, journal prior content, continuity kind, config

  • Files: modified src/core/brain/skill-proposals.ts (SCORED_REWRITE_PATTERN_KIND, scored contract fields, prior-content capture before the skills-root overwrite, content-restoring rollback in compensateSkillAccept); modified src/core/brain/skill-accept-journal.ts (priorContentPath field + parse); modified src/core/brain/continuity/types.ts (skill_rewrite_eval_grade in the union AND CONTINUITY_RECORD_KINDS, same edit); modified src/core/brain/paths.ts (benchmark dir and journal-copy paths); modified src/core/config.ts (Lane A's two keys per K5); new tests/core/brain/skill-proposals-rewrite.test.ts.
  • Acceptance: the failing-first tests prove: a promoted candidate stages a scored_rewrite pending proposal carrying rewrites_skill and the three scores plus the spec hash; acceptance goes through acceptSkillProposal unchanged and bumps the version by the evolve precedent; the journal captures the prior SKILL.md bytes before the overwrite and a simulated crash mid-accept rolls back to the INCUMBENT BODY (content, not just existence) with the journal retained for recovery exactly as the dead-ends suite pins today; the new continuity kind passes the kind guard and the reader census; an unknown skill_rewrite.mode value is a named config error; gate failures stage nothing (a hold round leaves the proposal tree unchanged and writes only the grade record).
  • Depends on: A3.

Task A5: CLI verbs, MCP status, census registrations and docs (lane final)

  • Files: modified src/cli/brain/verbs/skill-proposals.ts (rewrite-plan <skill>: validate task set + spec, print the frozen receipt and the dev envelopes; rewrite-score <skill> --rounds-dir <dir>: score submitted transcripts, run selection and held-out gates, print the verdict, stage the pending proposal on promote-only); modified src/mcp/brain/procedure-tools.ts (read-only rewrite status: current spec receipt, last grade verdicts; MCP never accepts and never scores); modified src/core/state/surfaces.ts (Brain/skill-benchmarks/ row) with the census consumers; SHARED appends: src/cli/command-manifest.ts, src/cli/brain/help-text.ts, tests/cli/manifest-completeness.test.ts, tests/cli/help-surface-parity.test.ts, tests/cli/completions.test.ts, tests/core/architecture/verdict-vocabulary-census.test.ts, tests/core/architecture/claim-attribution-census.test.ts, tests/core/architecture/visibility-surface-census.test.ts rows, tests/core/brain/continuity/reader-census.test.ts, docs/cli-reference.md, docs/observability.md; new tests/cli/skill-rewrite-verb.test.ts; new tests/mcp/skill-rewrite-status.test.ts.
  • Acceptance: the failing-first tests prove: rewrite-plan refuses a missing or receipt-mismatched task set by name and prints the receipt plus dev envelopes; rewrite-score reports per-task check outcomes and the verdict, stages nothing on hold/not_enough_evidence, stages the proposal on promote after the held-out pass, and exits non-zero naming the reason on a refused take; the MCP status surface is read-only and reach-filtered like its neighbors; all census registrations bind (each census fails when the corresponding registration is removed); the manifest, help and completion surfaces match the dispatcher.
  • Depends on: A4.

Lane D - ChatGPT desktop alias of the codex target (t_8b793376)

Task D1: detect note

  • Files: modified src/core/install/adapters/codex.ts (the detect() note names ChatGPT desktop as a reader of the shared config when the codex binary is absent; the note stays a note - no status, plan, apply or verify change); new tests/core/install/adapters/codex-chatgpt-note.test.ts.
  • Acceptance: the failing-first tests prove: with the binary absent and a config.toml present, the note names ChatGPT desktop and the config merge; with the binary present the note is unchanged; detect status values (not-installed | drift | installed) are unchanged for every scenario; the host-facts census and the frozen target vocabulary stay green (no new id).
  • Depends on: none.

Task D2: docs rows (lane final)

  • Files: modified README.md (a supported-clients row naming ChatGPT desktop with the codex install command); modified install/codex.md (a ChatGPT desktop section: shared config path, what install writes, uninstall behavior).
  • Acceptance: the failing-first check is a docs-content assertion in tests/core/install/adapters/codex-chatgpt-note.test.ts: the README row and the codex guide name ChatGPT desktop and the exact install command, so docs drift fails a test.
  • Depends on: D1.

Integrator

Task I1: reconciliation and full gates

  • Files: the shared files if any lane overlap needs re-freezing (src/core/state/surfaces.ts final row order, src/core/config.ts key blocks, src/cli/command-manifest.ts and src/cli/brain/help-text.ts order, the tests/cli/* shared guards, docs/cli-reference.md and docs/observability.md coherence pass).
  • Acceptance: the full local gates pass in CI order - formatter check, bun run lint, bun run typecheck, and the FULL test suite (the only place the full suite runs); every user-visible surface added by lanes A-D has a docs row; the census registries hold with all four lanes' registrations; no placeholders anywhere; the branch contains only lane commits plus this reconciliation.
  • Depends on: B4, C4, A5, D2.

Commit shape

  • Lane commits use conventional messages on this branch, each committing only its own files via git commit --only <paths>: feat(install): shared rules-block writer for agent instruction files (B1), feat(install): brain-usage block installer step for agent rules files (B2-B4), feat(brain): operator-approved lesson promotion into agent rules files (C1-C4), feat(brain): benchmark-gated skill rewrite loop (A1-A5), feat(install): name ChatGPT desktop as a codex config reader (D1-D2). Shared-registry appends ride each lane's final task commit through the same --only rule.
  • The brainstorm artifacts commit separately as chore(brainstorm): agent-presence-self-improvement before any lane work.
  • Review gates beyond tests: any diff showing a rules-file write outside the K1 writer, a rules-file write reachable from a hook, dream or MCP path, an agent-approvable lesson path, held-out task text in a dev envelope or a grade record, a scored input that reads the agent's own success claim, or a new InstallTargetId for the ChatGPT alias is a defect regardless of test outcome.