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.
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 }>>- theusageentry is the settledDEFAULT_BEGIN_MARKER/DEFAULT_END_MARKERfromsrc/core/install/managed-block.tsre-exported under the map (the checker's contract spellings); thelessonsentry 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; throwsRulesBlockErroron multiple/unpaired/reversed pairs (wrappingManagedBlockError).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 withRulesBlockError(kinduser-modified-block) when the existing block diverges fromcanonicalBodyAND the file mtime is newer thaninstalledAtMs, unlessforce; takes an exclusive-create, collision-laddered backup of the current file before the first write and returns its path; writes atomically viaatomicWriteFileSync; byte-compares so a re-apply ischanged: false;dryRunwrites nothing.export function removeRulesBlock(file: string, blockId: RulesBlockId, opts?: { readonly dryRun?: boolean }): { readonly removed: boolean }- a named skip (removed false) when no pair exists; neverunlinks the file.
- K2 - the canonical usage body and the installer mapping (Lane B owns).
src/core/brain/writeback-contract.tsgains 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 (readBrain/active.mdat session start,brain_feedback,brain_apply_evidence, the do-not-dream rule); self-tested to satisfymissingWritebackGateClauses. 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 (typedRulesBlockError, kindpreview-drift); instruction-block lock I/O withexport 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 thelessons.limitconfig);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"(underBrain/);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 theparseBenchFixturestyle; hash issha256Hex(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 adevTaskIdsmember (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 downgradespromotetohold;export function resolveSkillRewriteMode(raw: string | undefined): "gated" | "iterative"- unknown values are named errors.src/core/brain/skill-proposals.tsextension:export const SCORED_REWRITE_PATTERN_KIND = "scored_rewrite"added toSkillProposalPatternKind; the staged proposal carriesrewrites_skill,spec_hash,baseline_score,candidate_score,heldout_scorebeside the existingSKILL_DRAFT_*contract keys; the accept journal entry gainspriorContentPathandcompensateSkillAcceptrestores prior bytes from it.src/core/brain/skill-accept-journal.tsextension:priorContentPath?: stringonSkillAcceptJournalEntry, parsed and written like the existing fields.src/core/brain/continuity/types.tsextension:"skill_rewrite_eval_grade"added to the union and toCONTINUITY_RECORD_KINDSin 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.tsextensions:SKILL_REWRITE_MODE_CONFIG_KEY = "skill_rewrite.mode"(env twinOPEN_SECOND_BRAIN_SKILL_REWRITE_MODE) andSKILL_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 directnode:fscontent write needs a categorisedDIRECT_WRITE_EXCLUSIONSrow - the existingskill-proposals.ts:1109 andskill-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 anAPPEND_ALLOW_LISTrow - avoid);tests/core/architecture/import-cycles.test.ts(skill-rewrite-tasks.tsandskill-rewrite-spec.tsstay true leaves,import typeincluded);tests/core/architecture/state-surface-census.test.ts(Brain/skill-benchmarks/row withsourcesattribution);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(theskill_rewrite_eval_gradekind);tests/core/architecture/visibility-surface-census.test.tsand thesrc/mcp/registry-guard.tsconventions (the read-only rewrite-status surface, beside thebrain_skill_proposalsrow atsrc/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(aSafeguard-taking options type carries a synchronous progress sink or a written reason);tests/core/architecture/egress-census.test.ts(nodest-style parameter - the judge rides the command bridge; a--outflag would create an obligation).tests/core/architecture/host-facts-census.test.tsstays untouched by construction. - Lane B:
tests/core/architecture/write-site-census.test.ts(rules-block.ts/instruction-block.tswrite vault-root files throughatomicWriteFileSyncand the exclusive-create backup helper - shared-class rows, no exclusions; a directwriteFileSyncbinding fails the census);tests/core/architecture/state-surface-census.test.ts(instruction-block.lock.jsonrow,sourcesnaming the installer module);tests/core/install/ownership.test.ts(vault-rooted joins only - no home/XDG/temp anchors, noOUT_OF_VAULT_STATErow; 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.tsstays write-free so it never enters the walked population);tests/core/architecture/import-cycles.test.tsandtests/core/layering.test.ts(core/install->core/brain/writeback-contract->core/install/managed-blockacyclic; core neverprocess.exitor writes stdout);tests/core/architecture/host-facts-census.test.ts(no new target, the step reuses the existing"managed-block"kind inINSTALL_STEP_KINDS- both censuses satisfied by construction); doctor exit codes unchanged (INSTALL_EXITreuse). - 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.jsonrow withsourcesattributing every module naming the file or its constant);tests/core/architecture/verdict-vocabulary-census.test.ts(the lessons-block state findings reuse the K1RULES_BLOCK_STATEfamily plus the namedstale-lessonsextension, registered);tests/core/architecture/append-shard-census.test.tsand 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.tsper contract K1; newtests/core/install/rules-block.test.ts. - Acceptance: the failing-first tests prove:
renderRulesBlockforusageemits the settled default marker spellings and forlessonsthe HTML-comment pair;writeRulesBlockon a file with operator content preserves every byte outside the block, is idempotent (second apply reportschanged: falseand 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 thaninstalledAtMswith kinduser-modified-blockunlessforce, refuses through a symlink by name, and refuses multiple/unpaired/reversed pairs of the block's own spelling by wrappingManagedBlockError;readRulesBlockreturns null when only a DIFFERENT block id's pair exists;removeRulesBlockremoves only the pair it owns, collapses its own padding, and is a named skip when absent;dryRunwrites 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); modifiedtests/core/brain/writeback-contract.test.ts(the self-test:missingWritebackGateClauses(CANONICAL_WRITEBACK_BLOCK_BODY)empty; the audit still grades a lessons-only filemissing-blockand a both-blocks file by its own pair alone); newsrc/core/install/instruction-block.tsper K2; newtests/core/install/instruction-block.test.ts. - Acceptance: the failing-first tests prove: the constant satisfies the checker (self-test) and its diff preview renders;
instructionBlockTargetForreturns AGENTS.md for codex/cursor/opencode/aider, GEMINI.md for gemini-cli, null for copilot-cli/grok/kiro/pi/generic (named skips) - derived fromHOST_INSTRUCTION_PRECEDENCE, asserted to follow the table if it ever grows;planInstructionBlockreads with the checker's posture (lstat first, symlink refused), reports exists/changed/diff and a gemini-cli postNote;applyInstructionBlockrefuses 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 toconforming(asserted through the realauditWritebackContractFile); 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 inrunTargetunder the existing consent gate); modifiedsrc/cli/install/uninstall-target.ts(the reverse step against the lock); newtests/cli/install-instruction-step.test.ts; newtests/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-refusedmatrix from the existing install suite, exit 6 preserved); exit 4 on auser-modified-blockrefusal; 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 --checkbehavior 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.jsonrow) withtests/core/architecture/state-surface-census.test.tsconsumers andtests/core/state/surfaces.test.ts;tests/core/architecture/write-site-census.test.tsandtests/core/install/ownership.test.tsverified green with the new module (shared-class rows); docs rows indocs/cli-reference.mdand a pointer update indocs/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 statusrenders 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.tsper contract K3; modifiedsrc/core/brain/policy/blocks/lessons.ts(lessons.promotion.scopesresolution with env twin, absent-or-empty disables with a named count); modifiedsrc/core/brain/types.ts(log event kindslessons-approved/lessons-denied/lessons-promoted); newtests/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 frompromotableand reportsstale_approval;renderLessonsBlockBodyis deterministic (same inputs, identical bytes; tier-then-scope-then-id order; no timestamps; bounded bylessons.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 andreadLessonApprovalsnever readsBrain/; the writer calls go through K1 only (a source-scanning assertion that the module never importsnode:fswrite 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:candidatesread-only;approve <pref-id>/deny <pref-id>with the install consent ladder shape;refresh-blocksre-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; newtests/cli/brain-lessons.test.ts. - Acceptance: the failing-first tests prove:
candidateslists promotable plus blocked-with-reasons and is read-only;approverenders 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 thelessons-approvedevent;denyrecords without writing rules files and suppresses future promotion for that id;refresh-blocksis a no-op (named) when no block exists under management, never CREATES a block (creation is approve's write), and updateslast_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-lessonsbeside the existingwriteback_contractprobe) withtests/core/brain/doctor/lessons-block-check.test.ts; modifiedsrc/core/brain/status.ts(approved/denied/stale counts in the snapshot); newtests/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.jsonrow) with the census consumers andtests/core/state/surfaces.test.ts;tests/core/architecture/verdict-vocabulary-census.test.ts(the lessons-block state vocabulary); docs rows indocs/cli-reference.mdanddocs/observability.md. - Acceptance: the failing-first tests prove: the state-surface census binds the row with
sourcesattribution 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.tsper contract K4; newtests/core/brain/skill-rewrite-tasks.test.ts; newtests/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.tsper contract K4; newtests/core/brain/skill-rewrite-spec.test.ts; newtests/fixtures/skill-bench/<example-skill>/spec.json. - Acceptance: the failing-first tests prove:
buildSkillRewriteSpecderives 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,verifyRewriteTakeaccepts 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.tsper contract K4; newtests/core/brain/skill-rewrite.test.ts. - Acceptance: the failing-first tests prove:
buildRewriteEnvelopesemits oneneeds-llm-stepper 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;scoreRewriteTranscriptsvalidates 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;selectRewriteCandidateimplements the three arms exactly (strict beat by margin with n met promotes, a tie holds, a short dev n isnot_enough_evidence);checkRewriteHeldoutdowngradespromotetoholdon a held-out miss and passespromotethrough on a full pass;resolveSkillRewriteModeacceptsgated/iterativeand 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 incompensateSkillAccept); modifiedsrc/core/brain/skill-accept-journal.ts(priorContentPathfield + parse); modifiedsrc/core/brain/continuity/types.ts(skill_rewrite_eval_gradein the union ANDCONTINUITY_RECORD_KINDS, same edit); modifiedsrc/core/brain/paths.ts(benchmark dir and journal-copy paths); modifiedsrc/core/config.ts(Lane A's two keys per K5); newtests/core/brain/skill-proposals-rewrite.test.ts. - Acceptance: the failing-first tests prove: a promoted candidate stages a
scored_rewritepending proposal carryingrewrites_skilland the three scores plus the spec hash; acceptance goes throughacceptSkillProposalunchanged 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 unknownskill_rewrite.modevalue is a named config error; gate failures stage nothing (aholdround 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); modifiedsrc/mcp/brain/procedure-tools.ts(read-only rewrite status: current spec receipt, last grade verdicts; MCP never accepts and never scores); modifiedsrc/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.tsrows,tests/core/brain/continuity/reader-census.test.ts,docs/cli-reference.md,docs/observability.md; newtests/cli/skill-rewrite-verb.test.ts; newtests/mcp/skill-rewrite-status.test.ts. - Acceptance: the failing-first tests prove:
rewrite-planrefuses a missing or receipt-mismatched task set by name and prints the receipt plus dev envelopes;rewrite-scorereports per-task check outcomes and the verdict, stages nothing onhold/not_enough_evidence, stages the proposal onpromoteafter 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(thedetect()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); newtests/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); modifiedinstall/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.tsfinal row order,src/core/config.tskey blocks,src/cli/command-manifest.tsandsrc/cli/brain/help-text.tsorder, thetests/cli/*shared guards,docs/cli-reference.mdanddocs/observability.mdcoherence 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--onlyrule. - The brainstorm artifacts commit separately as
chore(brainstorm): agent-presence-self-improvementbefore 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
InstallTargetIdfor the ChatGPT alias is a defect regardless of test outcome.