Skip to content

Garry's Opinionated OpenClaw/Hermes Agent Brain

TypeScript

Plugins declare setup's UserPromptSubmit hook; doctor and post-upgrade name --instructions-only for plugin installs

garrytan29a0de16e733
diff --git a/.claude-plugin/plugin.json b/.claude-plugin/plugin.json
index dfd8a957f7..34b1083c81 100644
--- a/.claude-plugin/plugin.json
+++ b/.claude-plugin/plugin.json
@@ -30,5 +30,18 @@
],
"cwd": "${CLAUDE_PLUGIN_ROOT}"
}
+ },
+ "hooks": {
+ "UserPromptSubmit": [
+ {
+ "hooks": [
+ {
+ "type": "command",
+ "command": "env GBRAIN_HOOK_LANE=plugin \"${CLAUDE_PLUGIN_ROOT}/.agents/gbrain-launcher\" hook user-prompt",
+ "timeout": 3
+ }
+ ]
+ }
+ ]
}
}
diff --git a/.codex-plugin/plugin.json b/.codex-plugin/plugin.json
index ef4e03ebbd..3d096ccd65 100644
--- a/.codex-plugin/plugin.json
+++ b/.codex-plugin/plugin.json
@@ -20,6 +20,21 @@
],
"skills": "./plugin/skills/",
"mcpServers": "./.codex-plugin/mcp.json",
+ "hooks": {
+ "hooks": {
+ "UserPromptSubmit": [
+ {
+ "hooks": [
+ {
+ "type": "command",
+ "command": "env GBRAIN_HOOK_LANE=plugin \"${PLUGIN_ROOT}/.agents/gbrain-launcher\" hook user-prompt --harness codex",
+ "timeout": 15
+ }
+ ]
+ }
+ ]
+ }
+ },
"interface": {
"displayName": "GBrain",
"shortDescription": "Give your agent a persistent brain: search, synthesis, memory",
diff --git a/docs/architecture/key-files/commands-5.md b/docs/architecture/key-files/commands-5.md
index d370a458fc..bc79601d34 100644
--- a/docs/architecture/key-files/commands-5.md
+++ b/docs/architecture/key-files/commands-5.md
@@ -29,7 +29,7 @@ Current behavior and load-bearing invariants; history belongs in Git and CHANGEL
- `src/commands/skillify-check.ts` — `gbrain skillpack-check` agent-readable health report. Exit 0/1/2 for CI gating; JSON for debugging. Wraps `check-resolvable --json`, `doctor --json`, and migration ledger into one payload. Required item 12 (`brain_first_compliance`) calls `analyzeSkillBrainFirst()` on the candidate SKILL.md; exits 1 when the verdict is `missing_brain_first` (external-lookup pattern present, no callout, no `brain_first: exempt`). The scaffold path in `src/core/skillify/templates.ts` pre-inserts the canonical Convention callout into new SKILL.md files so freshly-scaffolded skills pass item 12.
- `src/commands/setup.ts` + `src/cli/commands/setup.ts` — `gbrain setup <harness>` (D8), pre-connect and engine-free (`thinClient: 'none'`, `json: 'document'`): an orchestrator over the existing wiring, not a new installation system. Target first: it resolves the brain (`loadConfig`; none → a `gbrain init --pglite --no-embedding --json` child, `--providers` drops `--no-embedding`; setup prints `Brain ready at <path>` and never init's standalone quickstart or `[AGENT]` banners; on the brain it just created it runs the setup migrations init left pending (`finishFreshSetupMigrations`, `src/commands/setup-migrations.ts`: one `apply-migrations --yes --no-autopilot-install --json` child built by `setupMigrationsArgv` in `migrations/fresh-install.ts`, 60 s bound, offline; v0.11.0 is held back when its host phase would edit an existing `~/.claude/AGENTS.md`, `~/.openclaw/AGENTS.md` or OpenClaw cron manifest (`hostRewriteTargets`)) and replaces init's `[init] Migrations:` line with `[setup] Migrations: …` (a failure keeps init's hand-off plus the error code; an existing brain is not touched), and renders a `Memory:` line naming `remember` (#6606: world facts are pushed, private ones are recall-only, capture writes a page) and then `setupFirstRunNotices` once after `Next:` in human output, or under `notices` in `--json`), the source (`--source` > `GBRAIN_SOURCE` > unpinned), the launcher (`--gbrain-bin` > `resolveGbrainBin`), the surface (`--surface` > `GBRAIN_SURFACE` > the receipt's > `REGISTRATION_SURFACE`) and the registration owner, prints them, then refuses before any write with `setup_hosted_connection` (thin-client config, hosted connection receipt or remote entry: never a second, local brain) or `setup_owner_conflict` (`live_serve` from `peekLock` unless the live stdio serve is this registration's own, `unowned_entry`, `other_install` by receipt `gbrain_home`, `harness_lane` for a bootstrap harness receipt or another gbrain marker on a wanted event). Consent is three recorded decisions (`resolveConsent`): wiring scope (`--scope`, `--no-hooks`, `GBRAIN_HOOKS=0`), capture (`--capture`/`--no-capture`; a file-config `memory.auto_writeback: off` wins) and providers; read-context events come from the capability row, capture events only when accepted. Verify reuses `smokeStdioRegistration` from `doctor/checks/harness-wiring.ts`; states are `configured` → `connection-verified` → `native-pending` (`native-verified` is never claimed). `gbrain setup codex` (`runCodexSetup`/`runCodexRemove`, writer in `src/core/setup/codex.ts`) shares the target, consent, refusal and verify steps: user scope only (`--scope project` exits 2), the codex plugin (`codexPluginProvidesName`) skips the MCP table, `harness_lane` also covers a bootstrap harness receipt targeting codex or a bootstrap-lane group on a wanted event, the dry run adds a `trust` step, and the final state is `native-verified` when the codex row's push is verified and the receipt owns the trusted UserPromptSubmit hook. Unsupported harness ids (`openclaw`, `hermes`, unknown) refuse with `setup_harness_unsupported` naming the row's guide (exit 2). `GBRAIN_SETUP_ABORT_AFTER=receipt|mcp|hooks` is the crash-injection seam. Pinned by `test/setup.test.ts`.
-- `src/core/setup/brain-first.ts` + `src/core/managed-block.ts` — the brain-first instruction block every harness install writes by default (`<!-- gbrain:brain-first:begin/end -->`, `BRAIN_FIRST_VERSION`). `brainFirstTarget` names each harness's own instruction file (Claude Code `~/.claude/CLAUDE.md` or `./CLAUDE.local.md`, Codex `AGENTS.md` or an existing `AGENTS.override.md`, opencode global `AGENTS.md`, OpenClaw `<workspace>/AGENTS.md` from JSON5 `agents.defaults.workspace` (several agents need `--workspace`), Hermes `SOUL.md` after the identity text, Cursor `.cursor/rules/gbrain-brain-first.mdc`); other clients get the block printed to paste. `syncBrainFirst` splices only between the markers (idempotent, upgrades in place, preserves a damaged block and reports it), and the decision (`--no-instructions` / `GBRAIN_AGENT_INSTRUCTIONS=0`, `--instructions`, prior) is remembered in `<configDir>/agent-instructions.json` with the writer, so `--remove` on setup, `connect --install` and `bootstrap harness` (lane in `bootstrap/harness-brain-first.ts`) strips only its own blocks. Text varies by access: MCP search surface, verbs surface, or the thin-client CLI launcher (`GBRAIN-INSTRUCTIONS.md` starts with it). doctor `harness_wiring` reads the ledger plus each registered harness's default file and warns on a missing, stale or damaged block with a fix that rewrites only the block (`instructionBlockViews`, `withInstructionBlocks`). `managed-block.ts` is the shared marker splice/probe/remove that `bootstrap/instructions-block.ts` also uses (`test/setup-brain-first.test.ts`).
+- `src/core/setup/brain-first.ts` + `src/core/managed-block.ts` — the brain-first instruction block every harness install writes by default (`<!-- gbrain:brain-first:begin/end -->`, `BRAIN_FIRST_VERSION`). `brainFirstTarget` names each harness's own instruction file (Claude Code `~/.claude/CLAUDE.md` or `./CLAUDE.local.md`, Codex `AGENTS.md` or an existing `AGENTS.override.md`, opencode global `AGENTS.md`, OpenClaw `<workspace>/AGENTS.md` from JSON5 `agents.defaults.workspace` (several agents need `--workspace`), Hermes `SOUL.md` after the identity text, Cursor `.cursor/rules/gbrain-brain-first.mdc`); other clients get the block printed to paste. `syncBrainFirst` splices only between the markers (idempotent, upgrades in place, preserves a damaged block and reports it), and the decision (`--no-instructions` / `GBRAIN_AGENT_INSTRUCTIONS=0`, `--instructions`, prior) is remembered in `<configDir>/agent-instructions.json` with the writer, so `--remove` on setup, `connect --install` and `bootstrap harness` (lane in `bootstrap/harness-brain-first.ts`) strips only its own blocks. Text varies by access: MCP search surface, verbs surface, or the thin-client CLI launcher (`GBRAIN-INSTRUCTIONS.md` starts with it). doctor `harness_wiring` reads the ledger plus each registered or plugin-served harness's default file and warns on a missing, stale or damaged block with a fix that rewrites only the block (`instructionBlockViews`, `withInstructionBlocks`); `gbrain post-upgrade` prints the same command (`brain-first-upgrade-notice.ts`, `instructionBlockUpgradeHints`). The Claude Code and Codex plugin manifests declare setup's UserPromptSubmit hook with `GBRAIN_HOOK_LANE=plugin`; it yields when another gbrain lane wires the event (`bootstrap/plugin-lanes.ts` `otherLaneWiresHook`; `test/plugin-turn-hook.test.ts`). `managed-block.ts` is the shared marker splice/probe/remove that `bootstrap/instructions-block.ts` also uses (`test/setup-brain-first.test.ts`).
- `src/commands/skillify.ts` + `src/core/skillify/{generator,templates}.ts` — `gbrain skillify scaffold <name>` creates all stubs for a new skill: SKILL.md, script, tests, routing-eval.jsonl, resolver entry, filing-rules pointer. `gbrain skillify check <script>` runs the 10-step checklist (LLM evals, routing evals, check-resolvable gate, filing audit) against a candidate skill before it lands.
- `src/commands/skillpack.ts` + `src/core/skillpack/{bundle,scaffold,reference,migrate-fence,scrub-legacy,harvest,harvest-lint,copy,apply-hunks,diff-text,installer}.ts` — `install`/`uninstall` are not supported (they exit non-zero with a hint to the replacement). Surface: `scaffold` (one-time additive copy via `copyArtifacts` in `copy.ts`; refuses to overwrite; partial-state fills missing paired sources declared in SKILL.md frontmatter `sources:`), `reference` (read-only diff lens + `--apply-clean-hunks` two-way auto-apply via pure-JS unified-diff parser/applier in `apply-hunks.ts` + `diff-text.ts`; strict arguments through the `skillpack reference` row of `src/cli/strict-args.ts` (#5491): `--dry-run=true`, a typo or an unknown flag exits 2 before any write, the per-skill and `--all` grammars print separately, and `--all --apply-clean-hunks` refuses with the three-command update path; pinned by `test/skillpack-reference-strict-args.test.ts`), `migrate-fence` (one-shot strip of legacy fence; cumulative-slugs receipt → row-parsing fallback; preserves rows verbatim as user-owned routing), `scrub-legacy-fence-rows` (opt-in row cleanup with skill-present + non-empty-triggers gate), `harvest` (host→gbrain inverse with symlink-reject + canonical-path containment via a `validateUploadPath`-style gate + default-on privacy linter in `harvest-lint.ts` against `~/.gbrain/harvest-private-patterns.txt` plus built-in a built-in fork-name pattern + email + Slack-channel patterns; rollback on match). Paired-source declarations live in each SKILL.md's frontmatter `sources:` array (validated by `loadSkillSources` in `bundle.ts`). `autoDetectSkillsDir` (in `src/core/repo-root.ts`) has a `cwd_walk_up` tier ahead of `~/.openclaw/workspace` (`$OPENCLAW_WORKSPACE` precedence preserved). `gbrain skillpack check --strict` exits non-zero on drift (CI gate); top-level `gbrain skillpack-check` keeps exit-1-on-issues for cron. Companion editorial skill `skills/skillpack-harvest/SKILL.md` drives the genericization checklist. Doc: `docs/guides/skillpacks-as-scaffolding.md`. Test coverage across `test/skillpack-{copy,scaffold,reference,reference-apply,apply-hunks,migrate-fence,scrub-legacy,harvest,harvest-lint,frontmatter-sources}.test.ts` + 9-case E2E in `test/skillpack-flow.test.ts`. `installer.ts` + `test/skillpack-install.test.ts` remain because `gbrain skillpack diff` uses `diffSkill` from there.
diff --git a/docs/mcp/CLAUDE_CODE.md b/docs/mcp/CLAUDE_CODE.md
index 8506d5900d..8d77b79f08 100644
--- a/docs/mcp/CLAUDE_CODE.md
+++ b/docs/mcp/CLAUDE_CODE.md
@@ -66,6 +66,17 @@ push protocol). One approval-UX difference: the bootstrap lane pre-approves
`mcp__gbrain` via `permissions.allow` for headless runs; plugin-provided MCP
tools use the plugin lane's own approval flow.
+**Per-turn hook.** Every gbrain plugin declares the `UserPromptSubmit` hook
+`gbrain setup claude-code` writes (`gbrain hook user-prompt`, 3 s), run through
+the launcher with `GBRAIN_HOOK_LANE=plugin`. While a brain-first block is
+installed it puts the brain-first rule beside each turn (`gbrain setup
+claude-code --instructions-only` writes the block; doctor `harness_wiring` and
+`gbrain post-upgrade` name that command when it's missing), and it adds the
+setup hook's read-context block when a serve is running. When setup,
+`gbrain bootstrap` or a workspace install already wires the event in your
+user settings or the project's `.claude` settings, the plugin's hook exits
+without output, so each turn gets it once. `GBRAIN_HOOKS=0` turns it off.
+
## Option 1: Local (recommended, zero server needed)
```bash
diff --git a/docs/mcp/CODEX.md b/docs/mcp/CODEX.md
index df4234a361..11e11503e6 100644
--- a/docs/mcp/CODEX.md
+++ b/docs/mcp/CODEX.md
@@ -80,6 +80,18 @@ launches Codex, or use the bootstrap lane below. Unlike the OpenClaw bundle, the
too (setup, migrate, smoke-test, gbrain-upgrade, schema authoring) — a plugin
user IS the brain host.
+**Per-turn hook.** The plugin also declares the `UserPromptSubmit` hook
+`gbrain setup codex` writes (`gbrain hook user-prompt --harness codex`, 15 s),
+run through the launcher with `GBRAIN_HOOK_LANE=plugin`. Codex skips a plugin
+hook until you trust it: open `/hooks` in the CLI, review it, and trust it.
+While a brain-first block is installed it puts the brain-first rule beside
+each turn (`gbrain setup codex --instructions-only` writes the block; doctor
+`harness_wiring` and `gbrain post-upgrade` name that command when it's
+missing), and it adds the setup hook's read-context block when a serve is
+running. When `gbrain setup codex` or `gbrain bootstrap` already wires the
+event in `$CODEX_HOME/hooks.json`, the plugin's hook exits without output, so
+each turn gets it once. `GBRAIN_HOOKS=0` turns it off.
+
**Routing under the plugin lane.** The plugin serve is user-global and runs
with the plugin snapshot as its working directory, so the per-project
`.gbrain-source` / `.gbrain-mount` dotfiles never apply. Route the source
diff --git a/plugin-variants/gbrain-coding/.claude-plugin/plugin.json b/plugin-variants/gbrain-coding/.claude-plugin/plugin.json
index 8b2aea01b9..15fae006a8 100644
--- a/plugin-variants/gbrain-coding/.claude-plugin/plugin.json
+++ b/plugin-variants/gbrain-coding/.claude-plugin/plugin.json
@@ -30,5 +30,18 @@
],
"cwd": "${CLAUDE_PLUGIN_ROOT}"
}
+ },
+ "hooks": {
+ "UserPromptSubmit": [
+ {
+ "hooks": [
+ {
+ "type": "command",
+ "command": "env GBRAIN_HOOK_LANE=plugin \"${CLAUDE_PLUGIN_ROOT}/.agents/gbrain-launcher\" hook user-prompt",
+ "timeout": 3
+ }
+ ]
+ }
+ ]
}
}
diff --git a/plugin-variants/gbrain-coding/.codex-plugin/plugin.json b/plugin-variants/gbrain-coding/.codex-plugin/plugin.json
index 1b368b710e..168e3e7a15 100644
--- a/plugin-variants/gbrain-coding/.codex-plugin/plugin.json
+++ b/plugin-variants/gbrain-coding/.codex-plugin/plugin.json
@@ -20,6 +20,21 @@
],
"skills": "./skills/",
"mcpServers": "./.codex-plugin/mcp.json",
+ "hooks": {
+ "hooks": {
+ "UserPromptSubmit": [
+ {
+ "hooks": [
+ {
+ "type": "command",
+ "command": "env GBRAIN_HOOK_LANE=plugin \"${PLUGIN_ROOT}/.agents/gbrain-launcher\" hook user-prompt --harness codex",
+ "timeout": 15
+ }
+ ]
+ }
+ ]
+ }
+ },
"interface": {
"displayName": "GBrain",
"shortDescription": "Give your agent a persistent brain: search, synthesis, memory",
diff --git a/plugin-variants/gbrain-daily/.claude-plugin/plugin.json b/plugin-variants/gbrain-daily/.claude-plugin/plugin.json
index 0119f3cc3b..0565611561 100644
--- a/plugin-variants/gbrain-daily/.claude-plugin/plugin.json
+++ b/plugin-variants/gbrain-daily/.claude-plugin/plugin.json
@@ -30,5 +30,18 @@
],
"cwd": "${CLAUDE_PLUGIN_ROOT}"
}
+ },
+ "hooks": {
+ "UserPromptSubmit": [
+ {
+ "hooks": [
+ {
+ "type": "command",
+ "command": "env GBRAIN_HOOK_LANE=plugin \"${CLAUDE_PLUGIN_ROOT}/.agents/gbrain-launcher\" hook user-prompt",
+ "timeout": 3
+ }
+ ]
+ }
+ ]
}
}
diff --git a/plugin-variants/gbrain-daily/.codex-plugin/plugin.json b/plugin-variants/gbrain-daily/.codex-plugin/plugin.json
index 47f1fada60..955f5b2089 100644
--- a/plugin-variants/gbrain-daily/.codex-plugin/plugin.json
+++ b/plugin-variants/gbrain-daily/.codex-plugin/plugin.json
@@ -20,6 +20,21 @@
],
"skills": "./skills/",
"mcpServers": "./.codex-plugin/mcp.json",
+ "hooks": {
+ "hooks": {
+ "UserPromptSubmit": [
+ {
+ "hooks": [
+ {
+ "type": "command",
+ "command": "env GBRAIN_HOOK_LANE=plugin \"${PLUGIN_ROOT}/.agents/gbrain-launcher\" hook user-prompt --harness codex",
+ "timeout": 15
+ }
+ ]
+ }
+ ]
+ }
+ },
"interface": {
"displayName": "GBrain",
"shortDescription": "Give your agent a persistent brain: search, synthesis, memory",
diff --git a/scripts/module-size-limits.tsv b/scripts/module-size-limits.tsv
index b0e4ed0984..849bbda52d 100644
--- a/scripts/module-size-limits.tsv
+++ b/scripts/module-size-limits.tsv
@@ -34,7 +34,7 @@ src/commands/sources.ts 2093 ratchet +3 G7b-2: sources host-repo dispatch and he
src/core/link-extraction.ts 2424 ratchet grown v0.46.26.0 megawave: link-aware timeline split + delimiter-outside-links (#3957 #4062 #3737); +37 wave-k #3908 reimpl: isCrossSourceLinksEnabled config ladder; +10 wave #4277: parseTimelineEntries skips generated backlink receipts; +17 #4855: latin-fold in normalizeBasename + dir-hint step tries both slug grammars; +17: #4855 Latin stroke-letter fold; +5: #4873 ./-relative markdown links kept as live references; +34 wave review: `../y.md` sibling links resolve on the DB path + folded bare-wikilink grammar (#4873 class); +62 #4977: role-prior suppression in machine-list sections (rolePriorSuppressedRanges, EntityRef.index); +3 composed with #4985 (variation-selector strip) in the same wave; +4 #4995: markdown-link anchor strip + lowercase-candidate rationale comments; +6 pre-landing review: #4977 suppression on code-stripped content + truthful watermark/section-list comments; T2: source-qualified inference and atomic origin-scoped derived links; canonical attendance evidence, source-qualified orientation, strict attendee resolution, and relocated filesystem link scanner (command export preserved); +4: pack-owned fallback and ambiguous attendee guards Display-label attendance exclusion, indexed evidence membership, and bounded strict resolver caching; attendance-boundary review.; complete attendance resolution and fence-safe evidence traversal; frontmatter discovery, canonical basename admission and code-aware attendance comment masking; exclude inline HTML comment spans from admitted attendance ranges; +17 write-path wave: same-name rule for entity fuzzy matches + rename-alias fallback in makeResolver; +1 #5567: materialized marker ends bullet detail; +30 #5749: unique global-basename step before fuzzy and live keyword resolution (ResolveOptions, watermark note); #5765: bold **Attendees:** label accepted + LINK_EXTRACTOR_VERSION_TS bump note; +10 eval-wave N9-2/N9-3/N12-7: pack frontmatter mappings inherit FRONTMATTER_LINK_MAP direction, page-type-bound pack attended follows canonical attendance, LINK_EXTRACTOR_VERSION_TS bump note; +1 #5623: normalizeBasename collapses hyphen runs like slugifySegment (extractor watermark note); +11 #5562: parseTimelineEntries accepts dated ### headings (FS-extractor parity); +3 eval-wave N12-6: Participants accepted as attendance evidence + LINK_EXTRACTOR_VERSION_TS bump note; +22 P5 wanted pages: AuthoredRef on body link candidates; -33 lowered: P5 moved machine-section ranges to core/machine-sections.ts and stated relation types to core/line-grammar.ts; +7 P5: ExtractPageLinksOptions interface + wikilinkAuthoredRef helper (keeps extractPageLinks under the function-size limit); +32 P5: per-edge verb attachment (attachedVerb, VERB_RULES) + joined-as works_at + extractor watermark note; P5 x temporal-edges merge: verb attachment reads the verb at the link's own position in the window (excerptAnchor) and the within-page dedup (now dedupeCandidates) drops a mention of a target the page also links with a typed edge; links joined only by commas/conjunctions share the verb before the first (coordinated); board roles (BOARD_RE, BOARD_AFTER_RE) resolve to invested_in for an investor page and advises otherwise, never works_at; +1 fix wave 11 #6191: imports targetTakesVerb (role-verb target guard lives in link-target-roles.ts); v0.60.105.0 merge: #5984 Phase 5 link preparation (+6) re-summed over wave 11 at 2211; +109 Q2 Track C: stable verb-rule ids, traceLinkType/explainLinkType (reasons for every typing decision), per-occurrence typer hoisted out of extractPageLinks (makeTypeFor); unit logic lives in core/link-typing-units.ts; +25 Q2 Track C: typing-unit verb rules and vetoes in attachedVerb/traceLinkType, validity stints in explainLinkType; +4 U3: board-seat rule split out of INVESTED_RE (same verb and precedence) and investor-prior/link offsets passed to unit vetoes; +11 U2: locateLink shared by attachedVerb and the U2 post-pass in traceLinkType; -11 lowered: Q2 verdict reverted U2 (locateLink and the post-pass); +21 fix wave 13 P4.10 #6266: resolveSameDirSlug + exported resolveMarkdownLinkSlug, shared with the link validator; +41 Wave B PR 2 lane 2e: extractPageLinks split into extractBodyLinks (window-scoped, offset-shifted, pass-tagged candidates) and frontmatterLinks, plus entityRefPasses, candidateKey, rolePriorPhrases and the roleText/regexBudget/window options, so a segmented page streams through the same extractor (window and merge logic in core/page-body/segment-links.ts); +1 at the #6869 gate-ahead merge: the #6803 wave EXTRACTOR_BUMP_NOTES comment composed with lane 2e (2420 + 1); +3 G5 (GBRA-60): extractBodyLinks masks the ## Links fence (links-fence.ts), whose rows are projected as their own edges
src/core/embedding-migration.ts 1587 ratchet new row: crossed 1500 in v0.46.25.0 fix waves (#4305 #4306 chunk-model truth helpers); retired provider integration removed; safety wave: canonical projection readiness and fact-aware completion; file configuration publication retains lease-row locks; +8 transactional retained-vector rebuildability checks before destructive migration boundaries; archived eligibility: source-locked reconciliation and live/current smoke revalidation; +2 #5680: authorization_generation field and its carry-forward on same-target re-apply (settle idempotency); +10 #5226: plan carries chunks_to_restamp beside chunks_to_embed; +9 #5088: schema transition defers HNSW builds into the marker (deferred_ann_indexes), carry-forward on re-apply, verify blocks on pending/INVALID ANN indexes (build phase in embedding-ann-build.ts); +10 #5088: dim-pinned tables (query_cache, facts, and any later entry of TEXT_EMBEDDING_DIM_PINNED_TABLES) defer their HNSW through the same worklist (DEFERRED_ANN_TABLES, recordDeferredAnnIndexes); +25 wave 8 lane D1 #5885: takes in the dim-pinned column list, plan (takes_to_embed), status (takes_pending) and completion verify; +17 #5334: smoke check samples one representative chunk per distinct page (bounded index-ordered batch walk, longest chunk re-read under the page lock, title-prefixed bounded query); +1 #5334: the smoke-query length limits are shared with the worst-case budget
src/core/github-source.ts 1530 ratchet new row: crossed the 1500 unlisted cap in v0.46.23.0 review fix wave (scope-state gating, client hardening, symlink containment); merged reliability/shared-skills source integration; managed sweep lease wrapper; fix wave 3 lane A: config parser peeled to github-source-config.ts (-47), +account pin wiring and pinned-installation refresh
-src/commands/hook.ts 1945 ratchet cathedral-5 heartbeat extraction offsets part of the BrainBench-seam growth; grown v0.46.26.0 megawave hooks-ipc (#4245); +108 monthly backup check: banner + gated session-start note + detached spawn (backup/status-file readers); +28 ship-review egress hardening: per-harness capture dispatch (capture-spec), memorable gate + receipt + relay block, fail-closed unscanned/newest-guess skips; +79 ambient-writeback WP4: hookStop bank step (gate -> bankWritebackTurn -> IPC flush; gate/bank logic live in core/facts + corpus-segments); +41 adversarial fix wave: wide-tail retry when the 128KB window misses the user turn, by-design heartbeat outcome classes, source-in-name banking; +11 #5413 session-end skips claude-cli self-transcripts; +11 #5701: hook lanes pass allowOversize so a long session reaches the bounded tail read; +1 #5371: the stop-hook dirty probe ignores physical-root ownership metadata (root-metadata.ts, engine-free); 2 core memory: user-prompt context-pressure notice wiring (logic in core/context/pressure.ts; session-start composition in core/context/session-start-output.ts); +3 fix wave 11 W2.1 #6091: PreCompact/SessionEnd capture-time consent record calls (logic in core/context/capture-consent.ts); +5 fix wave 11 W2.9 #6083: the three detached-push call sites skip a managed canonical worktree (push_managed_coordinator) + import; +2 fix wave 11 integration: W1 router help guard import beside the W2 managed-root import; +2 fix wave 13 P4.9 #6399: a header-only Codex rollout ends empty_session, not parser_drift; +3 W14 P4.16 (#5799): banner and SessionStart note read livePushStatuses (predicate in core/workspace-push.ts); +1 W15 P5.7 (#4992): gitChildEnv import for the hook git probes (launches moved onto core/spawn.ts); +13 GBRA-188 per-turn brain-first rule: user-prompt emission and its HookIo seam (rule and ledger read in core/setup/brain-first.ts)
+src/commands/hook.ts 1948 ratchet cathedral-5 heartbeat extraction offsets part of the BrainBench-seam growth; grown v0.46.26.0 megawave hooks-ipc (#4245); +108 monthly backup check: banner + gated session-start note + detached spawn (backup/status-file readers); +28 ship-review egress hardening: per-harness capture dispatch (capture-spec), memorable gate + receipt + relay block, fail-closed unscanned/newest-guess skips; +79 ambient-writeback WP4: hookStop bank step (gate -> bankWritebackTurn -> IPC flush; gate/bank logic live in core/facts + corpus-segments); +41 adversarial fix wave: wide-tail retry when the 128KB window misses the user turn, by-design heartbeat outcome classes, source-in-name banking; +11 #5413 session-end skips claude-cli self-transcripts; +11 #5701: hook lanes pass allowOversize so a long session reaches the bounded tail read; +1 #5371: the stop-hook dirty probe ignores physical-root ownership metadata (root-metadata.ts, engine-free); 2 core memory: user-prompt context-pressure notice wiring (logic in core/context/pressure.ts; session-start composition in core/context/session-start-output.ts); +3 fix wave 11 W2.1 #6091: PreCompact/SessionEnd capture-time consent record calls (logic in core/context/capture-consent.ts); +5 fix wave 11 W2.9 #6083: the three detached-push call sites skip a managed canonical worktree (push_managed_coordinator) + import; +2 fix wave 11 integration: W1 router help guard import beside the W2 managed-root import; +2 fix wave 13 P4.9 #6399: a header-only Codex rollout ends empty_session, not parser_drift; +3 W14 P4.16 (#5799): banner and SessionStart note read livePushStatuses (predicate in core/workspace-push.ts); +1 W15 P5.7 (#4992): gitChildEnv import for the hook git probes (launches moved onto core/spawn.ts); +13 GBRA-188 per-turn brain-first rule: user-prompt emission and its HookIo seam (rule and ledger read in core/setup/brain-first.ts); +3 GBRA-188 plugin lane: GBRAIN_HOOK_LANE=plugin yields to another gbrain lane wiring the event (import, comment and guard; detection in bootstrap/plugin-lanes.ts otherLaneWiresHook)
src/core/chunkers/code.ts 1602 ratchet new row: crossed the 1500 unlisted cap in v0.46.26.0 megawave (decorated-python defs #3821, version-gate + timeout chunker fixes); grown wave-g (#4511): named defs never folded into merged chunks; grown #4669: skip WASM parse for languages without TOP_LEVEL_TYPES; +6 N13-1: CodeChunkMetadata.definesFunction field + merge-guard stamp (predicate lives in def-types.ts); +10 Lua grammar swap: GRAMMAR_REVISIONS + chunkerStamp() (per-language re-chunk gate); +4: CodeChunkOptions.timeoutMs (per-call parse cap; markdown fences parse under a short cap) and the "Parsing failed" → ChunkerTimeoutError mapping in parseWithTimeout
src/core/config.ts 2012 ratchet +2 W5: search.page_rank_cut / page_rank_cut_factor KNOWN_CONFIG_KEYS rows (read in search/page-rank-cut.ts); +3 W3 confidence-gated reranking: search.reranker.gate / gate_min_gap KNOWN_CONFIG_KEYS rows (values parsed in search/crag.ts); re-summed at the W3 merge onto master v0.60.169.0 (1951 measured); +1 budgeted delivery PR 1: the search.auto_packing KNOWN_CONFIG_KEYS row (values validated in search/evidence-packing.ts); +1 #6278: persistence.sync_preparation_ms/maintenance_preparation_ms/preparation_ceiling_ms/max_preparation_attempts/preparation_deadlines key row (logic in persistence/preparation-budget.ts, switches.ts); +22 fix wave 11 W6.2/W6.3 (#5989, #6132): search.cjk_keyword_deadline_ms and search.hnsw_iterative_scan type fields, KNOWN_CONFIG_KEYS rows and the mergeSearchScanKnobs helper that keeps loadConfigWithEngine under its function-size baseline (logic in search/cjk-keyword-deadline.ts, search/hnsw-iterative-scan.ts); +8 #5988: sync.holds/hold_cap/hold_escalate_count/hold_escalate_pct/parser_regression key registration (read by persistence/sync-holds.ts); +3 agent operator wave A4: GBrainConfig.consent file-plane slot + 2 consent.preapprove.* key rows (logic in core/consent.ts); +1 System One v1: decide.* key prefix (validated by ai/decide/config.ts); new row: crossed the 1500 unlisted cap in v0.46.26.0 megawave (spend-controls hint #3703, config-set validation); +3 wave G #3974: sync.include_working_tree key; grown wave-g (#4540 #4494 #4415): extractor caps + intent-pattern config keys; +1 chat-connectors: connectors. config prefix; wave-k: config-table snapshot serving the DB-plane reads (#3980 + #2119 merge); +8: loadConfig hook for ~/.gbrain/.env, loader lives in gbrain-env-file.ts (#3893); +17: litellm/together key-fold slots (#3904 reimpl: two GBrainConfig fields + KNOWN_CONFIG_KEYS rows); +1: link_resolution.cross_source key (#3908); +4 v0.47 gmail-loops: loops.extraction_enabled key; +1: pricing.overrides key (#4633 adoption); +7 #4667 adoption: sync.exclude key registration; +4: eval fix wave keys (quote_verify + 3 rescue knobs); +memorable file-plane key registration (integrations.memorable.enabled + consent-event doc); +33 ambient-writeback: memory.* + brain.audience key registration + GBrainConfig.memory mirror slot (resolvers live in facts/writeback-config.ts); +38 2026-08 wave: retrieval_reflex_volunteer key + env mapping (volunteer-arm kill switch) + E5a registration of the 10 adaptive_return*/autocut*/crag_* search (incl. adversarial batch isEnvDisabled dedup); ambient-writeback (master merge): facts/writeback-config.ts); new row: crossed the 1500 unlisted cap in v0.46.26.0 megawave; prior growth: sync/intent/chat-connectors/litellm/pricing/loops key folds; +34: #4702 content_sanity.disabled_patterns (type + DB-plane parse/merge + key registration); composition true-up (fix-wave multi-train) | merged v0.48.1.0: master #4788 writeback keys + wave #4702/#4748 keys; master: | merged v0.48.1.0 true-up; ranker wave v0.48.4.0: +4 KNOWN_CONFIG_KEYS rows (+8); +5 #4895: CWD_DOTENV_FILES gains the per-NODE_ENV .local variants Bun auto-loads; +2 #5003: sync.include_hidden key registration; +57 #4605: search.* registry reconciled to the keys mode.ts reads (+20 knob rows, +4 direct-read singletons) + GBrainConfig.search slot + adaptive_return* DB-plane merge; +2 pre-landing review: fts.reindex_in_progress key registration (#4795 marker escape hatch); +4 #4987: auto_timeline key registration (the documented off switch was rejected as unknown); lowered to 1793: GHSA wave v0.50.5.0 moved CWD_DOTENV_FILES + dotenvValuesForKey into core/env-trust.ts (-49, re-exported); re-summed to the merged line count after merging master v0.50.2.0 (#5122) with the v0.50.5.0 security wave; fix wave 3 x fix wave 2 (v0.60.5.0) composition: +1 at the merge; evidence delivery: 5 registered config keys + comment (+7); +2 #5691: embedding_query_prefix key registration; evidence delivery auto v2: search.return_budget_conversation key row (+1); +1 #5836: facts.entity_inference key row; +6 #5824: search.vector_legacy_guard key row + GBrainConfig.search slot + DB-plane merge; +3 wave 8 lane D1 #5885: takes.auto_embed key row; +3 #5232: GBrainConfig.persistence.write_wait_ms file-plane slot + key row (resolver in persistence/write-wait.ts); +2 F4b: planner.* and import.analyze_every_pages keys; +3 cat40 cost wave C1 (garrytan/gbrain-evals#57 follow-ups): mcp.result_rows GBrainConfig slot + key row (resolver in mcp/result-rows.ts); v0.60.46.0 merge: both waves' +3 compose (1824 + 3 = 1827 measured); +4 #5984: sync.bulk, sync.bulk_size, sync.bulk_max_txn_ms known keys; v0.60.48.0 merge: #5984 growth re-summed over v0.60.47.0 (1838 measured); +3 retrieval feedback: the feedback keys in KNOWN_CONFIG_KEYS; 2 engine graduation (GBRA-50 G3): GBrainConfig.migrate.graduation file-plane opt-out slot + key row (read by commands/migrate-graduation.ts); P3 x engine graduation composition: both deltas re-summed at the merge; 2 Lane D: facts.drain_budget_usd, facts.drain_daily_budget_usd, facts.drain_max_jobs key registration (validated in core/facts/drain.ts); +2 engine graduation (GBRA-50 G3): GBrainConfig.migrate.graduation file-plane opt-out slot + key row (read by commands/migrate-graduation.ts); P3 x foundations-2 composition: deltas re-summed at the merge; 2 Lane D: facts.drain_budget_usd, facts.drain_daily_budget_usd, facts.drain_max_jobs key registration (validated in core/facts/drain.ts); +2 engine graduation (GBRA-50 G3): GBrainConfig.migrate.graduation file-plane opt-out slot + key row (read by commands/migrate-graduation.ts); +1 GBRA-49: graph.* key prefix (graph.edge_validity, read by link-validity.ts); P3 x P1 (v0.60.57.0) composition: deltas re-summed at the merge; 2 Lane D: facts.drain_budget_usd, facts.drain_daily_budget_usd, facts.drain_max_jobs key registration (validated in core/facts/drain.ts); +2 engine graduation (GBRA-50 G3): GBrainConfig.migrate.graduation file-plane opt-out slot + key row (read by commands/migrate-graduation.ts); +1 GBRA-49: graph.* key prefix (graph.edge_validity, read by link-validity.ts); +3 P7 search.relational_planner / search.relational_orient_onehop key registration; +2 P7 search.relational_chain_slots key registration; P3 x P7 (v0.60.60.0) composition: deltas re-summed at the merge; 2 Lane D: facts.drain_budget_usd, facts.drain_daily_budget_usd, facts.drain_max_jobs key registration (validated in core/facts/drain.ts); +2 engine graduation (GBRA-50 G3): GBrainConfig.migrate.graduation file-plane opt-out slot + key row (read by commands/migrate-graduation.ts); +1 GBRA-49: graph.* key prefix (graph.edge_validity, read by link-validity.ts); +3 P7 search.relational_planner / search.relational_orient_onehop key registration; +2 P7 search.relational_chain_slots key registration; +3 agent operator follow-up Item 2: mcp.allow_session_widen (GBrainConfig.mcp slot + known key); P3 x aow-followup composition: deltas re-summed at the merge; 2 Lane D: facts.drain_budget_usd, facts.drain_daily_budget_usd, facts.drain_max_jobs key registration (validated in core/facts/drain.ts); +2 engine graduation (GBRA-50 G3): GBrainConfig.migrate.graduation file-plane opt-out slot + key row (read by commands/migrate-graduation.ts); +1 GBRA-49: graph.* key prefix (graph.edge_validity, read by link-validity.ts); +3 P7 search.relational_planner / search.relational_orient_onehop key registration; +2 P7 search.relational_chain_slots key registration; +3 agent operator follow-up Item 2: mcp.allow_session_widen (GBrainConfig.mcp slot + known key); +2 entity mention index: mentions.auto_link, mentions.entity_types, mentions.ignore key rows (resolver in core/mentions/policy.ts); cat40 entity wave merge with v0.60.61.0 (1853 measured); P3 x cat40-entity-wave composition: deltas re-summed at the merge; +6 fix wave lane B3: chat_fallback_on_refusal (GBrainConfig slot, GBRAIN_CHAT_FALLBACK_ON_REFUSAL env fold, known key); +2 W-B4: shared_skills.inventory.* known keys (logic in shared-skills/inventory-limits.ts); +2 fix wave 9 lane B #4921: ai.chat.per_turn_timeout_ms known key; +1 wave 9 lane W #5363: cycle.consolidate.cluster_threshold key row; +1 #5984 lanes: sync.lanes key registration; +2 P8: dream.quote_verify and think.quote_verify known keys; +2 P8: GBrainConfig.mcp.advertised_surface interface slot (resolver in mcp/surface.ts); +2 fix wave 10 lane L1 #4907: cycle.synthesize_concepts.budget_usd registered (validation in cycle/phase-config-values.ts); +2 #5958: dream.propose_takes.call_timeout_ms registered; 3 core memory: memory.core.* and memory.pressure.* known keys; +15 P5: wanted_pages.enabled/remote, line_grammar.enabled/allow_undeclared_types/effective_ranges and put_page.similar_pages key rows (logic in wanted-links.ts, line-grammar.ts, similar-pages.ts); +1 P2 extraction.date_grounding / facts.attribution keys; +1 #6188: fences.normalize registered in KNOWN_CONFIG_KEYS; +2 #6188: fences.repair.max_usd_per_page/per_day key rows; +1 fix wave 12 W2.3 #6231: facts.page_write_notability_filter key row (resolver in facts/notability-filter.ts); +1 #6317: persistence.single_consumer key row (logic in persistence/switches.ts, consumer-election.ts); +2 newer mentions on context_pack cards: mentions.newer_on_cards key row (logic in mentions/newer-mentions.ts); master v0.60.136.0 merge into #5575 memory trust (both sides kept); +1 #5329 (W14 PR3): chronicle.max_events_per_page registered in KNOWN_CONFIG_KEYS (validation in chronicle/config.ts); +2 C1/C2 memory proof wave: search.evidence_date_header + facts.candidate_fusion registry rows; +1 facts.supersession_thresholds registry row (per-model supersession calibration); +1 C4: models.standing_questions key row; +1 search.entity_anchoring key registration (default off; search/entity-anchor.ts); +1 search.query_facts_arm key registration (default off; search/facts-arm.ts); re-summed at the master 6ccf30c3e merge (1871 integration + 1868 master - 1865 base); +1 search.temporal_fact_reserve key registration (default off; search/facts-arm.ts); +1 fix wave 13 PR2: persistence.publication_ceiling_ms (P2.1/P2.3); v0.60.165.0 merge: W14 PR4 +7 and master +2 compose (1947 measured); +1 memory proof wave 2 W1: the recall.question_admission KNOWN_CONFIG_KEYS row (values validated in facts/question-recall.ts); +2 Cat 40 Hard fix wave (#6271) on top: mentions.alias_deny/multiword_aliases/sibling_merge and search.alias_fanout_max/demote_generated KNOWN_CONFIG_KEYS rows (1950 measured); +1 wave 15 P7.1 #5213: cycle.propose_takes.types KNOWN_CONFIG_KEYS row (parse + filter live in cycle/propose-takes.ts); +1 wave 15 P7.2 #6451: autopilot.git_pull KNOWN_CONFIG_KEYS row (read in persistence/automatic-sync-policy.ts); +1 wave 15 P7.3 #6369: cycle.lint.enabled KNOWN_CONFIG_KEYS row (read in cycle/lint-fix-setting.ts); +2 wave 15 P7.4 #5461: think.pages_budget_chars / think.excerpt_ceiling_chars KNOWN_CONFIG_KEYS rows (validation in think/pages-budget.ts); +6 wave 16 G5.1 (#6495): search.keyword_statement_timeout_ms type field, DB merge and KNOWN_CONFIG_KEYS row, toEngineConfig carries it (range + resolver live in postgres-engine/keyword-statement-timeout.ts); +1 GBRA-81 item 1: search.mode_source registered; +1 GBRA-60 S1: search.diverse_pool_depth in the known search keys; +3 #6643: sync.knock_on_refreeze_limit / sync.knock_on_run_limit KNOWN_CONFIG_KEYS rows (read by persistence/sync-run.ts knockOnLimits); +3 #6696: KNOWN_CONFIG_KEYS rows for persistence.maintenance.compaction_stale_hours and refusal_breaker_threshold; +1 wave 5 D5: context.proactive_brief KNOWN_CONFIG_KEYS row (read in context/proactive-brief.ts); +3 Cat 40 next wave part 1: KNOWN_CONFIG_KEYS rows for entity.names_references + entity.record_types + entity.row_page_status (one line), mcp.instructions_governing_rule and search.long_page_unit (re-summed at the 0.60.242.0 merge: master 1975 + 3); +1 wave 17 (#6667): cycle.consolidate.enabled KNOWN_CONFIG_KEYS row (read in cycle/phases/consolidate.ts); +2 Wave B PR 1: pages.segmented_storage and the segmented ceiling/retention keys (page-body/limits.ts); merge v0.60.249.0: Wave B PR 1 and master growth compose at 1981; +1 #6297: dream.patterns.min_interval_hours / child_read_budget_kb known keys; +1 #5012: loops.updates_require_reciprocity known key; +1 wave 18b lane 2 (#6495): search.keyword_timeout_negative_cache_seconds KNOWN_CONFIG_KEYS row; integrated at wave 18b: master 1981 + 4 (lanes 2, 3, 5 known keys); +1 #6948: sync.origin_twins.auto_resolve KNOWN_CONFIG_KEYS row (read in repair/origin-twins-heal.ts); +1 #6948 sweep C-9: facts.absorb_retry.max_resubmits KNOWN_CONFIG_KEYS row (read in facts/dead-absorb-retry.ts); +1 #6907: backup.remote_timeout_ms KNOWN_CONFIG_KEYS row (resolver in backup/repository.ts); +1 at the #6712 PR 4b merge onto master v0.60.310.0 (both sides added a key); +3 #7130: sync.max_deletes / sync.max_delete_ratio / purge.retention_hours KNOWN_CONFIG_KEYS rows and the two per-source cap prefixes (parsers live in core/sync-reconcile.ts); +2 GBRA-154: search.collapse / search.rank_priors KNOWN_CONFIG_KEYS rows (read in search/mode.ts); +1 GBRA-150: sync.metafile_pages KNOWN_CONFIG_KEYS row (read in core/sync.ts); +1 GBRA-159: visibility.honor_aliases KNOWN_CONFIG_KEYS row (read in search/private-visibility.ts); +4 GBRA-156 warm CLI socket: GBrainConfig.serve_cli_socket slot and the published-config.ts import/re-export (snapshot-only merge and MERGED_CONFIG_BY_ENGINE live in core/published-config.ts); re-summed at the GBRA-159 hotfix merge (2000 measured); +2 #7242 GBrainConfig.minions.terminal_hook (interface field); #7252 merge of master v0.60.343.0: both sides grew the file, re-summed (2002 measured); +1 GBRA-155: entity.name_variants KNOWN_CONFIG_KEYS row (read in verbs/entity-variants.ts); +2 GBRA-161: the generations.* KNOWN_CONFIG_KEYS rows and their comment (bounds and reader in generations/config.ts); +1 GBRA-156: search.evidence_tail_trim KNOWN_CONFIG_KEYS row (read in search/evidence-tail-trim.ts); +2 GBRA-175: self_upgrade.channel (the GBrainConfig field and its KNOWN_CONFIG_KEYS row; resolved in core/self-upgrade.ts); re-summed at the master 440eeef6 merge (2009 measured); +2 GBRA-156 vector prewarm: GBrainConfig.serve_vector_prewarm slot (snapshot merge lives in core/published-config.ts); +1 GBRA-95 G7a: storage.git_lfs KNOWN_CONFIG_KEYS row (read in persistence/git-declared.ts); re-summed at the v0.60.449.0 merge (2012 measured)
src/core/persistence/sync-run.ts 1686 ratchet new row: crossed the 1500 unlisted cap in #6643 (knock-on re-freeze, checkpoint revival, root cause and the truthful --retry-failed wait all drive the private cursor/gate machinery: holdUnderGate, freezeEntry, saveCursor); classification lives in sync-knock-on.ts, the checkpoint clause in checkpoint-validation.ts; peel the settle path (settleFailedRequest and its recoveries) into a sibling module next; +3 #6722: committed pages' size_state tallied into the cursor and the sync receipt size_states (logic in page-embedding-budget.ts addSizeState); merge v0.60.240.0: large pages and master growth compose at 1687; +2 #6694: the slug-mode checkpoint revival import and its doc line (predicate lives in persistence/sync-slug-mode.ts); +11 #6712 PR 3 (L7): a plain sync retries the recorded failure --retry-failed used to (retryRecordedFailure; the unchanged-refusal replay lives in persistence/sync-stop-class.ts replaysUnchangedRefusal), the moved-checkpoint and company content-refusal exceptions; #6712 PR 3 integration: lanes L7 (retryRecordedFailure, +19) and L8 (#6727 legacy-slug refusal line, #6735 timeout revival, +6) compose at 1762; +2 wave 18a integration: #6729 (lane 2, written against the 1745 ceiling) records identity downgrades in performManagedPass through noteIdentityDowngrades (logic in core/sync-identity-downgrades.ts), composed with master 1762; +14 Wave B PR 2: freezeEntry freezes a Markdown file over the read bound by reference (body_ref) and holdFailedFenceRequest holds a streamed refusal; both set freezeEntry/holdFailedFenceRequest locals (blob, oversize, rawHash) so they stay here, the hashing and preparation live in persistence/sync-streamed.ts and the hold in sync-screen.ts streamedRefusalHold; integrated at the master 4e29d0904 merge: master 1764 + Wave B PR 2 14 = 1778 measured; +4 #6948: freezeEntry holds an entry several live pages claim (hold in sync-screen.ts originConflictHold, verdict in persistence/origin-twins.ts); +1 #7167: managedDryRun reports the writer state (the import of persistence/sync-dry-run-writer.ts, where the read lives); +4 G3 git-canonical: freezeEntry reads a strict source's entry from its commit (pinnedBlob) and carries committedOnly to publication; both use freezeEntry locals (rule in persistence/sync-classify.ts)
@@ -47,4 +47,4 @@ src/commands/doctor/checks/extraction-sync.ts 1500 ratchet +7 GBRA-130 A-1: link
src/core/search/evidence-delivery.ts 1733 ratchet +5 W5: EvidencePlan.rankCut resolved with the plan (logic in search/page-rank-cut.ts); +20 W5 whole_pages: wholeCost prices a block as delivery would emit it whole (needs the private Block/enrichBlock internals) and the cut is wired before allocate (cutWholePages lives in search/page-rank-cut.ts); new row: crossed the 1500 unlisted cap at the #6367 merge (master 1479, its explicit-budget cap) by the C1 date header threaded through every block path, cap included; pagePlanHits (search/page-plan-hits.ts) and the header loader (evidence-date.ts blockDateHeaders) were peeled first; peel candidate: allocateCapped; +8 at the #6396 merge: page evidence text cut through the fence-chunk trust overlay and the caller minTrust floor (re-summed: our 1504 + master +8); +119 Cat 40 next wave F2: the search.long_page_unit policy (withLongPagePolicy, selectLongPages size preflight with page/byte/deadline limits) and the long-page fetch and fallback in deliverEvidence, kept in the shared seam the plan names (gbrain-evals docs/plans/2026-10-11-cat40-next-wave, F2); +17 F2 rework to the frozen-comparison policy: search.long_page_min_chars (rendered-body characters, default 20,000) read in withLongPagePolicy, a character count in the preflight, the rendered-body confirmation in deliverEvidence, and the long-page row exemption in capDeliveredSnippets (re-summed at the 0.60.225.0 merge: master 1537 + F2 136); +39 Wave B PR 2 lane 2b: planSegmentedBlock joins the windows search/segmented-evidence.ts reads around a segmented page's hits into one run-marked document (needs the private Doc/Piece/buildDoc/locateAnchor internals), planBlock's unit cut split into blockFromDoc for both, sections bounded by their run, selectionCost counts a gap between runs, and the fetch skips the whole-body fence overlay for a segmented page; +4 segmented pages read at once before planning (segmentedReads; the read is search/segmented-evidence.ts, the statements page-body/read-range.ts); +17 GBRA-156: tail trim plan flag, DeliverOptions.query, DeliveryMeta.tail_trim, the trim call and the frozen-hit score/query library fields (logic in search/evidence-tail-trim.ts; interface fields cannot move)
src/commands/config.ts 1524 ratchet new row: crossed the 1500 unlisted cap in wave 15 P7.4 #5461: set-time validation of think.pages_budget_chars / think.excerpt_ceiling_chars (range + parser live in core/think/pages-budget.ts), mirroring the cycle.consolidate.cluster_threshold hook; +1 wave 16 G5.1 (#6495): set-time refusal hook for search.keyword_statement_timeout_ms (check lives in commands/config/keyword-timeout-value.ts); +1 wave 18b lane 5 (#5012 item 6): search.contextual_retrieval prints the existing-pages hint after the write (text lives in commands/config/contextual-mode-hint.ts); +1 #6712 PR 2: retired/rollback sync key dispatch line (logic in core/sync-config-keys.ts handleSyncKeyConfig); +1 #6865: sync.slug_conflicts.auto_remove boolean validation at set time (refusal text in repair/slug-autoheal.ts); +1 #6948: sync.origin_twins.auto_resolve boolean validation at set time (refusal text in repair/origin-twins-heal.ts); +2 #6795: config set chat_model/expansion_model help line and the model-pin import (shadow report and file-pin unset live in commands/config/model-pin-shadow.ts); +1 #6712 PR 4b: sync.admission set-time hook (value logic in commands/config/sync-admission-value.ts); +4 #7130: set-time refusal hook for sync.max_deletes / sync.max_delete_ratio (and .source.<id>) / purge.retention_hours (check lives in core/sync-reconcile.ts deleteSafetyConfigRefusal); +1 GBRA-150: sync.metafile_pages set-time route (body in config/sync-metafile-pages-value.ts); re-summed at the v0.60.330.0 merge (1520 measured); +2 #7242 minions.terminal_hook file-plane key and its set branch (logic in minions/terminal-hook.ts); +1 GBRA-161: generations.* set-time route (refusal in commands/config/generations-values.ts); +1 GBRA-207 #7630: sync.repo_path set-time refusal hook (refusal in core/sync-config-keys.ts syncRepoPathRefusal)
src/commands/mcp-expose.ts 1512 ratchet hosted_option: Session carries the gbrain.io coaching notice on the first-receipt run and Tailscale/service friction exits (copy, refs and gating live in core/onboard/hosted-option.ts)
-src/core/behavior-change-notice.ts 1537 ratchet the BEHAVIOR_CHANGES table grows by one row per disclosed change: +5 the frozen-source wave comment and four rows (#7868, #7850, #7869/#7870, #7871), +2 the #7848 visibility_noncanonical hold row (since TBD until the merge slot), +2 the #7846 extract_atoms session-source row (re-summed at the 0.60.481.0 merge: master 1524 + 2), +2 the #7805 synthesize session-source and #7841 visibility_not_applied rows (re-summed at the 0.60.480.0 merge: master 1522 + 2), +2 strict door planned-state row (#7705, re-summed at the 0.60.470.0 merge: master 1514 + 2), +2 Bun floor 1.4.4 row (#7644), the GBRA-95 RLS backfill row (+2), +3 rows for #7596 pass_interrupted, #7599 read-only serve and the --access=read-only ceiling, +1 G5 lane C trust_release row, +1 #7619 cli_flag_equals, +3 GBRA-207 #7630 relative-anchor and stalled-write rows, +2 the #7632 function search_path disclosure row and +2 the #7679 orphaned worktree refresh row (re-summed at the 0.60.471.0 merge: master 1516 + 2), +2 the #7814 retired v0.13.1 grandfather row, +2 the #7618 conversion withhold/progress/push row (master 1520 + 2); the behavior-change table split (#7607) retires this row; +4 GBRA-188 #7489: the wave comment and three rows (brain-first instructions, starter surface default, per-turn rule; since TBD until the merge slot)
+src/core/behavior-change-notice.ts 1538 ratchet the BEHAVIOR_CHANGES table grows by one row per disclosed change: +5 the frozen-source wave comment and four rows (#7868, #7850, #7869/#7870, #7871), +2 the #7848 visibility_noncanonical hold row (since TBD until the merge slot), +2 the #7846 extract_atoms session-source row (re-summed at the 0.60.481.0 merge: master 1524 + 2), +2 the #7805 synthesize session-source and #7841 visibility_not_applied rows (re-summed at the 0.60.480.0 merge: master 1522 + 2), +2 strict door planned-state row (#7705, re-summed at the 0.60.470.0 merge: master 1514 + 2), +2 Bun floor 1.4.4 row (#7644), the GBRA-95 RLS backfill row (+2), +3 rows for #7596 pass_interrupted, #7599 read-only serve and the --access=read-only ceiling, +1 G5 lane C trust_release row, +1 #7619 cli_flag_equals, +3 GBRA-207 #7630 relative-anchor and stalled-write rows, +2 the #7632 function search_path disclosure row and +2 the #7679 orphaned worktree refresh row (re-summed at the 0.60.471.0 merge: master 1516 + 2), +2 the #7814 retired v0.13.1 grandfather row, +2 the #7618 conversion withhold/progress/push row (master 1520 + 2); the behavior-change table split (#7607) retires this row; +4 GBRA-188 #7489: the wave comment and three rows (brain-first instructions, starter surface default, per-turn rule; since TBD until the merge slot); +1 GBRA-188 plugin_turn_hook_gbra188 row
diff --git a/src/commands/doctor/checks/harness-wiring.ts b/src/commands/doctor/checks/harness-wiring.ts
index b092fd0aff..b53eaf5fd5 100644
--- a/src/commands/doctor/checks/harness-wiring.ts
+++ b/src/commands/doctor/checks/harness-wiring.ts
@@ -354,10 +354,10 @@ export interface InstructionBlockView {
/**
* The brain-first instruction block for every surface gbrain wrote or was
- * told to skip (the ledger), plus each registered harness with no record,
- * checked at that harness's default instruction file. Read-only.
+ * told to skip (the ledger), plus each registered or plugin-served harness
+ * with no record, checked at that harness's default instruction file. Read-only.
*/
-export function instructionBlockViews(regs: HarnessRegistration[]): InstructionBlockView[] {
+export function instructionBlockViews(regs: HarnessRegistration[], plugins = enabledPluginLanes('gbrain')): InstructionBlockView[] {
const state = (s: ReturnType<typeof inspectBrainFirst>['state']): InstructionBlockView['state'] =>
s === 'current' ? 'current' : s === 'stale' ? 'stale' : s === 'damaged' ? 'damaged' : 'missing';
const views: InstructionBlockView[] = readBrainFirstLedger().map((e) => {
@@ -368,11 +368,11 @@ export function instructionBlockViews(regs: HarnessRegistration[]): InstructionB
? { harness: e.harness, path, state: 'opted_out', from: 'ledger' }
: { harness: e.harness, path, state: state(inspectBrainFirst(path, renderBrainFirstBlock(e.harness, e.access)).state), from: 'ledger', access: e.access };
});
- for (const r of regs) {
- if (views.some((v) => v.harness === r.harness) || !isBrainFirstHarness(r.harness)) continue;
- const target = brainFirstTarget(r.harness);
+ for (const harness of [...regs, ...plugins].map((r) => r.harness)) {
+ if (views.some((v) => v.harness === harness) || !isBrainFirstHarness(harness)) continue;
+ const target = brainFirstTarget(harness);
if ('error' in target) continue;
- views.push({ harness: r.harness, path: target.path, state: state(inspectBrainFirst(target.path).state), from: 'default_path' });
+ views.push({ harness, path: target.path, state: state(inspectBrainFirst(target.path).state), from: 'default_path' });
}
return views;
}
@@ -427,6 +427,18 @@ function repairArgv(v: InstructionBlockView): Action {
return { argv, consent: ['persistent_install'], actor: 'agent', requires_exclusive: false, verify: doctorVerify(NAME), why };
}
+/**
+ * post-upgrade: one line per wired harness (registration, plugin or ledger)
+ * whose brain-first block is missing or out of date, with the setup command
+ * that writes only that block. Read-only; an opt-out prints nothing.
+ */
+export function instructionBlockUpgradeHints(): string[] {
+ return instructionBlockViews(readHarnessRegistrations()).filter((v): v is InstructionBlockView & { state: 'missing' | 'stale' } => v.state === 'missing' || v.state === 'stale').map((v) => {
+ const fix = repairArgv(v);
+ return fix.argv ? `Brain-first instructions: the ${v.harness} block in ${v.path} ${INSTRUCTION_PROBLEM[v.state]}. Run \`${fix.argv.join(' ')}\` to write only that block (\`--no-instructions\` opts out).` : fix.user_message!;
+ });
+}
+
/** Registration read (full run) or registration read + smoke (`--only harness_wiring`), plus the brain-first block. */
export async function harnessWiringCheck(opts: { smoke: boolean }): Promise<Check> {
const regs = readHarnessRegistrations();
diff --git a/src/commands/hook.ts b/src/commands/hook.ts
index dbdc833a09..39837aff2c 100644
--- a/src/commands/hook.ts
+++ b/src/commands/hook.ts
@@ -93,6 +93,7 @@ import {
type HookHeartbeatEntry,
} from '../core/context/hook-heartbeat.ts';
import { CLAUDE_HOOK_OUTPUT_CAP_CHARS } from '../core/bootstrap/host-specs.ts';
+import { otherLaneWiresHook } from '../core/bootstrap/plugin-lanes.ts';
import { composeSessionStartOutput } from '../core/context/session-start-output.ts';
import { claudeCodePressure } from '../core/context/pressure.ts';
import { readManifest, readReceipt, type InstallReceipt } from '../core/bootstrap/format.ts';
@@ -339,6 +340,8 @@ export async function runHook(args: string[], io: HookIo = {}): Promise<number>
/* fail-open */
}
}
+ // Plugin lane (the Claude Code and Codex plugin manifests): yields to any other gbrain lane wiring this event.
+ if (process.env.GBRAIN_HOOK_LANE === 'plugin' && otherLaneWiresHook(io.harness ?? 'claude-code', event, io.cwd ?? process.cwd())) return 0;
switch (event) {
case 'session-start':
diff --git a/src/commands/upgrade.ts b/src/commands/upgrade.ts
index 1f6c7afdc5..62e0d0b316 100644
--- a/src/commands/upgrade.ts
+++ b/src/commands/upgrade.ts
@@ -933,6 +933,7 @@ export async function runPostUpgrade(args: string[] = []): Promise<void> {
// Pitch printing is cosmetic — don't gate migrations on it.
}
+ (await import('../core/setup/brain-first-upgrade-notice.ts')).printBrainFirstUpgradeNotice(); // GBRA-188: the command that writes a missing brain-first block
(await import('../core/post-upgrade-notice.ts')).writePostUpgradeCliNotice(); // F7: safety notice ([AGENT] block for agents)
// Mechanical: run every outstanding migration. Idempotent; exits 0 quickly
// when nothing is pending. Stays inside the same process so a long Phase F
diff --git a/src/core/behavior-change-notice.ts b/src/core/behavior-change-notice.ts
index d6a06cf232..dfc3779eca 100644
--- a/src/core/behavior-change-notice.ts
+++ b/src/core/behavior-change-notice.ts
@@ -1339,6 +1339,7 @@ export const BEHAVIOR_CHANGES: ReadonlyArray<{ since: string; text: ChangeText;
{ since: 'TBD', id: 'brain_first_instructions_gbra188', text: 'Harness installs now write a short marked brain-first block into the harness\'s own instruction file by default (Claude Code ~/.claude/CLAUDE.md, Codex AGENTS.md or a non-empty AGENTS.override.md, opencode AGENTS.md, the OpenClaw workspace AGENTS.md, an existing Hermes SOUL.md, a Cursor project rule): `gbrain setup <harness>`, `gbrain connect --install`, `gbrain bootstrap harness` and the thin-client GBRAIN-INSTRUCTIONS.md. Text outside the markers is never touched and a re-run upgrades the block in place. `--no-instructions` or GBRAIN_AGENT_INSTRUCTIONS=0 removes it and is remembered; `--remove` strips it; `gbrain setup <harness> --instructions-only` manages only the block. doctor `harness_wiring` warns when a registered harness\'s block is missing, stale or damaged.' },
{ since: 'TBD', id: 'install_surface_starter_gbra188', text: 'New stdio registrations gbrain writes (`gbrain setup`, `gbrain bootstrap hooks`, the readiness and `gbrain init` registration lines) now pin `--surface starter`, the daily-driver tool list, instead of `--surface full` (Garry, 2026-10-24; gbrain-evals#191: reach and accuracy unchanged, 17-23% fewer input tokens). An existing registration keeps its surface and is never rewritten; the Codex and Claude Code plugins and a bare `gbrain serve` stay on full. `--surface full` is the opt-in for every operation, any parameter the starter list leaves out is still accepted, and `request_tools` returns full schemas or widens the session to a left-out tool. doctor `harness_wiring` notes a full registration as information only.' },
{ since: 'TBD', id: 'brain_first_turn_rule_gbra188', text: 'The brain-first rule now rides every turn, not only the system prompt (Garry, 2026-10-25). The block (v2) opens with "before answering any turn, check GBrain first"; while it is installed, the Claude Code and Codex UserPromptSubmit hook leads each turn with that one-line rule, with or without a context block; `gbrain setup openclaw` writes a hook-only plugin (gbrain-turn-rule, before_prompt_build prependContext) under the OpenClaw state dir and installs it with the openclaw CLI (install --link --accept-capabilities, enable, plugins.entries.gbrain-turn-rule.hooks.allowConversationAccess true), or prints those commands with no openclaw on PATH; and `gbrain setup hermes` adds a marked, self-contained `pre_llm_call` shell hook (`/bin/echo` of the rule) to $HERMES_HOME/config.yaml and approves that command in Hermes\'s shell-hooks-allowlist.json, or prints the entry when config.yaml already has a `hooks:` section. `--no-instructions` or GBRAIN_AGENT_INSTRUCTIONS=0 turns the rule off with the block.' },
+ { since: 'TBD', id: 'plugin_turn_hook_gbra188', text: 'The Claude Code and Codex plugins (gbrain, gbrain-coding, gbrain-daily) now declare the UserPromptSubmit hook `gbrain setup` writes, run through the plugin launcher with GBRAIN_HOOK_LANE=plugin (Claude Code `hook user-prompt`, 3 s; Codex `hook user-prompt --harness codex`, 15 s, skipped until trusted in /hooks). While a brain-first block is installed it adds the per-turn rule, and with a serve running the read-context block; it exits without output when setup, bootstrap or a workspace install already wires the event, so a turn gets it once. doctor `harness_wiring` and `gbrain post-upgrade` now name `gbrain setup <harness> --instructions-only` for a plugin-only install with no brain-first block.' },
];
/** The newest disclosed change's release: the notice id moves only when a release adds rows. */
diff --git a/src/core/bootstrap/plugin-lanes.ts b/src/core/bootstrap/plugin-lanes.ts
index c3c5d818a0..37bb623ef1 100644
--- a/src/core/bootstrap/plugin-lanes.ts
+++ b/src/core/bootstrap/plugin-lanes.ts
@@ -7,7 +7,9 @@
*/
import { existsSync, readFileSync } from 'node:fs';
import { join } from 'node:path';
-import { claudeUserSettingsPath, codexConfigPath } from './host-specs.ts';
+import { codexHookCensus } from './codex-hooks.ts';
+import { classifyHarnessHook } from './hooks.ts';
+import { CLAUDE_HOOK_SUBCOMMAND, claudeUserSettingsPath, codexConfigPath, codexHooksPath, GBRAIN_HOOK_MARKER_KEY } from './host-specs.ts';
// ── Plugin-lane detection (codex/claude plugins provide an MCP server) ─────
//
@@ -151,3 +153,33 @@ export function claudeAnyRegistrationExists(
}
return false;
}
+
+/**
+ * Plugin-lane defer: does another gbrain install lane (`gbrain setup`,
+ * `gbrain bootstrap harness`, a workspace bootstrap) already wire this hook
+ * subcommand for the harness? The plugin's own hook (GBRAIN_HOOK_LANE=plugin)
+ * then yields, so the event fires once. Claude Code: any gbrain-marked or
+ * harness-lane entry in the user settings or the cwd's .claude settings;
+ * Codex: a setup or bootstrap group in CODEX_HOME/hooks.json. Fail-open: an
+ * unreadable file counts as not wired.
+ */
+export function otherLaneWiresHook(harness: string, subcommand: string, cwd: string): boolean {
+ const event = Object.entries(CLAUDE_HOOK_SUBCOMMAND).find(([, s]) => s === subcommand)?.[0];
+ if (!event) return false;
+ if (harness === 'codex') {
+ try { return codexHookCensus(codexHooksPath()).some((g) => g.event === event && g.lane !== 'other'); } catch { return false; }
+ }
+ for (const path of [claudeUserSettingsPath(), join(cwd, '.claude', 'settings.json'), join(cwd, '.claude', 'settings.local.json')]) {
+ try {
+ if (!existsSync(path)) continue;
+ const groups = (JSON.parse(readFileSync(path, 'utf8')) as { hooks?: Record<string, unknown> }).hooks?.[event];
+ if (!Array.isArray(groups)) continue;
+ for (const g of groups) {
+ const entries = (g as { hooks?: unknown })?.hooks;
+ if (Array.isArray(entries) && entries.some((e) => typeof (e as Record<string, unknown> | null)?.[GBRAIN_HOOK_MARKER_KEY] === 'string' || classifyHarnessHook(e, event, 'any'))) return true;
+ }
+ } catch { /* fail-open */ }
+ }
+ return false;
+}
+
diff --git a/src/core/setup/brain-first-upgrade-notice.ts b/src/core/setup/brain-first-upgrade-notice.ts
new file mode 100644
index 0000000000..4c05caf85e
--- /dev/null
+++ b/src/core/setup/brain-first-upgrade-notice.ts
@@ -0,0 +1,11 @@
+/**
+ * post-upgrade: a harness wired before the brain-first block existed, or a
+ * plugin-only install (its per-turn hook adds the rule only with a block),
+ * gets one line naming the setup command that writes only that block.
+ * Read-only and best-effort; an opt-out prints nothing.
+ */
+import { instructionBlockUpgradeHints } from '../../commands/doctor/checks/harness-wiring.ts';
+
+export function printBrainFirstUpgradeNotice(log: (line: string) => void = console.log): void {
+ try { for (const line of instructionBlockUpgradeHints()) log(line); } catch { /* cosmetic; never block the upgrade */ }
+}
diff --git a/test/doctor-harness-wiring-plugin.test.ts b/test/doctor-harness-wiring-plugin.test.ts
index b1fa73523d..a8ce2592d3 100644
--- a/test/doctor-harness-wiring-plugin.test.ts
+++ b/test/doctor-harness-wiring-plugin.test.ts
@@ -39,6 +39,13 @@ function codexPlugin(b: Box): void {
writeFileSync(join(b.env.CODEX_HOME!, 'config.toml'), '[plugins."gbrain@gbrain"]\nenabled = true\n');
}
+/** The brain-first block is its own verdict (GBRA-188): record an opt-out so these tests read the plugin-lane wiring alone. */
+function blockOptedOut(b: Box, harness: string): void {
+ mkdirSync(join(b.env.GBRAIN_HOME!, '.gbrain'), { recursive: true });
+ writeFileSync(join(b.env.GBRAIN_HOME!, '.gbrain', 'agent-instructions.json'), JSON.stringify({ version: 1, entries: [{ harness, path: join(b.root, 'AGENTS.md'),
+ status: 'declined', block_version: 2, writer: 'test', created_file: false, updated_at: '2026-10-28T00:00:00.000Z' }] }));
+}
+
function claudePlugin(b: Box): void {
mkdirSync(b.env.CLAUDE_CONFIG_DIR!, { recursive: true });
writeFileSync(join(b.env.CLAUDE_CONFIG_DIR!, 'settings.json'), JSON.stringify({ enabledPlugins: { 'gbrain@gbrain': true } }));
@@ -48,6 +55,7 @@ describe('harness_wiring with an enabled plugin lane (#6082)', () => {
test('Codex plugin only → ok plugin_lane_enabled, and plugin_lane_collision agrees', async () => {
const b = box();
codexPlugin(b);
+ blockOptedOut(b, 'codex');
await withEnv(b.env, async () => {
const check = await harnessWiringCheck({ smoke: false });
expect(check.status).toBe('ok');
@@ -62,6 +70,7 @@ describe('harness_wiring with an enabled plugin lane (#6082)', () => {
test('Claude Code plugin under CLAUDE_CONFIG_DIR only → ok', async () => {
const b = box();
claudePlugin(b);
+ blockOptedOut(b, 'claude-code');
await withEnv(b.env, async () => {
const check = await harnessWiringCheck({ smoke: false });
expect(check.status).toBe('ok');
diff --git a/test/plugin-turn-hook.test.ts b/test/plugin-turn-hook.test.ts
new file mode 100644
index 0000000000..20260b743f
--- /dev/null
+++ b/test/plugin-turn-hook.test.ts
@@ -0,0 +1,148 @@
+/**
+ * GBRA-188 follow-up: the Claude Code and Codex plugins declare setup's own
+ * UserPromptSubmit hook (same subcommand and timeout, launched through the
+ * plugin's launcher with GBRAIN_HOOK_LANE=plugin). The plugin hook yields to
+ * any other gbrain lane wiring the event, so a machine with both fires once.
+ * The rule itself stays gated on an installed brain-first block, and doctor
+ * harness_wiring and post-upgrade point plugin-only installs at
+ * `gbrain setup <harness> --instructions-only`. Hermetic temp HOME, CODEX_HOME,
+ * CLAUDE_CONFIG_DIR and GBRAIN_HOME.
+ */
+import { afterAll, describe, expect, test } from 'bun:test';
+import { chmodSync, existsSync, mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from 'node:fs';
+import { tmpdir } from 'node:os';
+import { join, resolve } from 'node:path';
+import { buildClaudeHookCommand } from '../src/core/bootstrap/hooks.ts';
+import { codexSetupHookGroup } from '../src/core/bootstrap/codex-hooks.ts';
+import { CLAUDE_HOOK_DEFAULT_TIMEOUT_SECS } from '../src/core/bootstrap/host-specs.ts';
+import { otherLaneWiresHook } from '../src/core/bootstrap/plugin-lanes.ts';
+import { runHook } from '../src/commands/hook.ts';
+import { harnessWiringCheck, instructionBlockUpgradeHints } from '../src/commands/doctor/checks/harness-wiring.ts';
+import { renderBrainFirstTurnRule } from '../src/core/setup/brain-first.ts';
+import { printBrainFirstUpgradeNotice } from '../src/core/setup/brain-first-upgrade-notice.ts';
+import { runCli } from './helpers/cli-spawn.ts';
+import { withEnv } from './helpers/with-env.ts';
+
+const ROOT = resolve(import.meta.dir, '..');
+const CLI = join(ROOT, 'src', 'cli.ts');
+const roots: string[] = [];
+afterAll(() => { for (const r of roots) rmSync(r, { recursive: true, force: true }); });
+
+const json = (p: string) => JSON.parse(readFileSync(join(ROOT, p), 'utf8'));
+const tail = (command: string, bin: string) => command.slice(command.indexOf(bin) + bin.length + 1);
+
+describe('plugin manifests declare the hook setup installs', () => {
+ const claudeSetup = buildClaudeHookCommand('/x/gbrain', 'UserPromptSubmit', {});
+ const codexSetup = codexSetupHookGroup('/x/gbrain', 'UserPromptSubmit', {}).hooks[0]!;
+ for (const dir of ['.', 'plugin-variants/gbrain-coding', 'plugin-variants/gbrain-daily']) {
+ test(`${dir}: Claude Code and Codex UserPromptSubmit, setup's subcommand and timeout, through the launcher`, () => {
+ expect(existsSync(join(ROOT, dir, '.agents', 'gbrain-launcher'))).toBe(true);
+ expect(json(join(dir, '.claude-plugin', 'plugin.json')).hooks).toEqual({ UserPromptSubmit: [{ hooks: [{ type: 'command',
+ command: `env GBRAIN_HOOK_LANE=plugin "\${CLAUDE_PLUGIN_ROOT}/.agents/gbrain-launcher" ${tail(claudeSetup, '/x/gbrain')}`,
+ timeout: CLAUDE_HOOK_DEFAULT_TIMEOUT_SECS.UserPromptSubmit }] }] });
+ // Codex's inline form is a whole hooks.json document (the `hooks` wrapper); Claude Code's is the bare event map.
+ expect(json(join(dir, '.codex-plugin', 'plugin.json')).hooks).toEqual({ hooks: { UserPromptSubmit: [{ hooks: [{ type: 'command',
+ command: `env GBRAIN_HOOK_LANE=plugin "\${PLUGIN_ROOT}/.agents/gbrain-launcher" ${tail(codexSetup.command, '/x/gbrain')}`,
+ timeout: codexSetup.timeout }] }] } });
+ });
+ }
+});
+
+interface Box { root: string; home: string; env: Record<string, string | undefined> }
+
+function box(): Box {
+ const root = mkdtempSync(join(tmpdir(), 'gbrain-plugin-turn-'));
+ roots.push(root);
+ const home = join(root, 'home');
+ mkdirSync(home, { recursive: true });
+ return { root, home, env: {
+ HOME: home, GBRAIN_HOME: home, CODEX_HOME: join(root, 'codex'), CLAUDE_CONFIG_DIR: join(root, 'claude'), XDG_CONFIG_HOME: join(root, 'xdg'),
+ GBRAIN_HOOK_LANE: 'plugin', GBRAIN_AGENT_INSTRUCTIONS: undefined, GBRAIN_HOOKS: undefined, GBRAIN_SURFACE: undefined, GBRAIN_SOURCE: undefined,
+ CLAUDECODE: undefined, CLAUDE_CODE_ENTRYPOINT: undefined, CODEX_SANDBOX: undefined, CODEX_CI: undefined, OPENCODE: undefined, OPENCODE_PID: undefined,
+ } };
+}
+
+function claudeSettings(b: Box, extra: Record<string, unknown> = {}): void {
+ mkdirSync(b.env.CLAUDE_CONFIG_DIR!, { recursive: true });
+ writeFileSync(join(b.env.CLAUDE_CONFIG_DIR!, 'settings.json'), JSON.stringify({ enabledPlugins: { 'gbrain@gbrain': true }, ...extra }));
+}
+
+async function userPrompt(b: Box, harness: 'claude-code' | 'codex'): Promise<string> {
+ let out = '';
+ await withEnv(b.env, async () => {
+ const code = await runHook(['user-prompt', '--harness', harness], {
+ stdin: JSON.stringify({ prompt: 'what did alice-example decide about the launch?', session_id: 's1' }),
+ write: (s) => { out += s; }, cwd: b.root, configOverride: null, disablePushBanner: true, disableTelemetry: true,
+ });
+ expect(code).toBe(0);
+ });
+ return out;
+}
+
+const RULE = renderBrainFirstTurnRule({ kind: 'mcp', server: 'gbrain' });
+
+describe('plugin lane: one hook per event, rule only with a block', () => {
+ test('Claude Code plugin only: no block, no rule; doctor and post-upgrade name --instructions-only; after it, the plugin hook carries the rule', async () => {
+ const b = box();
+ claudeSettings(b);
+ expect(await userPrompt(b, 'claude-code')).not.toContain('check GBrain first');
+ await withEnv(b.env, async () => {
+ const check = await harnessWiringCheck({ smoke: false });
+ expect(check.status).toBe('warn');
+ expect(check.fix?.argv).toEqual(['gbrain', 'setup', 'claude-code', '--instructions-only']);
+ expect(check.details?.instructions).toEqual([expect.objectContaining({ harness: 'claude-code', state: 'missing', from: 'default_path' })]);
+ const hints = instructionBlockUpgradeHints();
+ expect(hints).toHaveLength(1);
+ expect(hints[0]).toContain('Run `gbrain setup claude-code --instructions-only` to write only that block');
+ const printed: string[] = [];
+ printBrainFirstUpgradeNotice((l) => printed.push(l));
+ expect(printed).toEqual(hints);
+ });
+
+ const bin = join(b.root, 'gbrain');
+ writeFileSync(bin, `#!/bin/sh\nexec '${process.execPath}' --no-env-file '${CLI}' "$@"\n`);
+ chmodSync(bin, 0o755);
+ const r = await runCli(['setup', 'claude-code', '--instructions-only', '--json'], { env: { ...b.env, GBRAIN_HOOK_LANE: undefined }, cwd: b.root });
+ expect(r.exitCode).toBe(0);
+
+ expect(JSON.parse((await userPrompt(b, 'claude-code')).trim()).hookSpecificOutput).toEqual({ hookEventName: 'UserPromptSubmit', additionalContext: RULE });
+ await withEnv(b.env, async () => {
+ expect(instructionBlockUpgradeHints()).toEqual([]);
+ expect((await harnessWiringCheck({ smoke: false })).status).toBe('ok');
+ });
+ });
+
+ test('Claude Code: the plugin hook yields to setup\'s own UserPromptSubmit entry, and to a workspace bootstrap entry in the cwd', async () => {
+ const b = box();
+ const setupEntry = { type: 'command', command: 'env /opt/g hook user-prompt', timeout: 3, _gbrain: 'setup-v1' };
+ claudeSettings(b, { hooks: { UserPromptSubmit: [{ hooks: [setupEntry] }] } });
+ await withEnv(b.env, async () => {
+ expect(otherLaneWiresHook('claude-code', 'user-prompt', b.root)).toBe(true);
+ expect(otherLaneWiresHook('claude-code', 'session-start', b.root)).toBe(false);
+ });
+ mkdirSync(join(b.home, '.gbrain'), { recursive: true });
+ writeFileSync(join(b.home, '.gbrain', 'agent-instructions.json'), JSON.stringify({ version: 1, entries: [{ harness: 'claude-code', status: 'installed',
+ path: join(b.home, 'CLAUDE.md'), block_version: 2, access: { kind: 'mcp', server: 'gbrain' }, writer: 'test', created_file: false, updated_at: '2026-10-28T00:00:00.000Z' }] }));
+ expect(await userPrompt(b, 'claude-code')).toBe('');
+
+ const ws = box();
+ claudeSettings(ws, { hooks: { UserPromptSubmit: [{ hooks: [{ type: 'command', command: 'echo unrelated' }] }] } });
+ await withEnv(ws.env, async () => { expect(otherLaneWiresHook('claude-code', 'user-prompt', ws.root)).toBe(false); });
+ mkdirSync(join(ws.root, '.claude'), { recursive: true });
+ writeFileSync(join(ws.root, '.claude', 'settings.local.json'), JSON.stringify({ hooks: { UserPromptSubmit: [{ hooks: [{ type: 'command', command: 'gbrain hook user-prompt', _gbrain: 'bootstrap-v1' }] }] } }));
+ await withEnv(ws.env, async () => { expect(otherLaneWiresHook('claude-code', 'user-prompt', ws.root)).toBe(true); });
+ });
+
+ test('Codex: the plugin hook yields to setup\'s hooks.json group, and runs when hooks.json holds none', async () => {
+ const b = box();
+ mkdirSync(b.env.CODEX_HOME!, { recursive: true });
+ mkdirSync(join(b.home, '.gbrain'), { recursive: true });
+ writeFileSync(join(b.home, '.gbrain', 'agent-instructions.json'), JSON.stringify({ version: 1, entries: [{ harness: 'codex', status: 'installed',
+ path: join(b.home, 'AGENTS.md'), block_version: 2, access: { kind: 'mcp', server: 'gbrain' }, writer: 'test', created_file: false, updated_at: '2026-10-28T00:00:00.000Z' }] }));
+ expect(JSON.parse((await userPrompt(b, 'codex')).trim()).hookSpecificOutput.additionalContext).toBe(RULE);
+ writeFileSync(join(b.env.CODEX_HOME!, 'hooks.json'), JSON.stringify({ hooks: { UserPromptSubmit: [codexSetupHookGroup('/opt/g', 'UserPromptSubmit', {})] } }));
+ expect(await userPrompt(b, 'codex')).toBe('');
+ writeFileSync(join(b.env.CODEX_HOME!, 'hooks.json'), '{ not json');
+ await withEnv(b.env, async () => { expect(otherLaneWiresHook('codex', 'user-prompt', b.root)).toBe(false); });
+ });
+});