Garry's Opinionated OpenClaw/Hermes Agent Brain
TypeScript
Per-turn brain-first rule through each harness's own hook: OpenClaw before_prompt_build plugin, self-contained Hermes pre_llm_call (GBRA-188)
garrytan10949a15110f
diff --git a/docs/guides/setup.md b/docs/guides/setup.mdindex b10fe10d24..6544724877 100644--- a/docs/guides/setup.md+++ b/docs/guides/setup.md@@ -182,10 +182,13 @@ missing, stale or damaged, with a fix that rewrites only the block.A rule in the system prompt is easy for a model to pass over, so the same rulealso rides each turn where the harness has a per-turn hook: Claude Code andCodex get it from setup's UserPromptSubmit hook while the block is installed,-OpenClaw from gbrain's context engine, and Hermes from a marked `pre_llm_call`-hook (`gbrain hook turn-rule`) that `gbrain setup hermes` adds to its config.yaml.-Cursor's rule is always applied; opencode reads its AGENTS.md on every request.-The opt-out turns the per-turn rule off with the block.+OpenClaw from a hook-only plugin (`gbrain-turn-rule`, `before_prompt_build`)+that `gbrain setup openclaw` installs with the openclaw CLI, and Hermes from a+marked, self-contained `pre_llm_call` hook that `gbrain setup hermes` adds to its+config.yaml. Cursor's rule is always applied; opencode reads its AGENTS.md on+every request. QM has no per-turn hook an install can set: its gateway's+`instructions` are per turn but belong to the surface that posts the turn. The+opt-out turns the per-turn rule off with the block.## Harness capability tablediff --git a/docs/mcp/HERMES.md b/docs/mcp/HERMES.mdindex 1201b80945..705eb94a67 100644--- a/docs/mcp/HERMES.md+++ b/docs/mcp/HERMES.md@@ -56,16 +56,19 @@ hook to `$HERMES_HOME/config.yaml` and records its approval in Hermes's```yamlhooks:pre_llm_call:- - command: "/absolute/path/to/gbrain hook turn-rule"+ - command: "/bin/echo '{\"context\":\"GBrain: before answering this turn, check GBrain first ...\"}'"+ timeout: 10```-Hermes appends the hook's `{"context": ...}` output to each user message, so the-rule reaches the model next to the turn instead of only in the system prompt.-Text outside the markers is never touched. When config.yaml already has a-`hooks:` section, or setup has no absolute gbrain path (`--gbrain-bin`), setup-prints the entry to add yourself instead; approve it when Hermes asks (or set-`HERMES_ACCEPT_HOOKS=1`). `--no-instructions` and `--remove` take the hook and its-approval out, and the hook prints nothing under `GBRAIN_AGENT_INSTRUCTIONS=0`.+The command is self-contained: it echoes the rule as Hermes's `{"context": ...}`+wire shape, starts no gbrain process and needs no path on the Hermes host but+`/bin/echo`. Hermes appends that context to each user message, so the rule+reaches the model next to the turn instead of only in the system prompt. Text+outside the markers is never touched, and a re-run after an upgrade rewrites the+command and moves its approval. When config.yaml already has a `hooks:` section,+setup prints the entry to add yourself instead; approve it when Hermes asks (or+set `HERMES_ACCEPT_HOOKS=1`). `hermes hooks doctor` checks it.+`--no-instructions` and `--remove` take the hook and its approval out.## Direct config (equally supported)diff --git a/docs/mcp/OPENCLAW.md b/docs/mcp/OPENCLAW.mdindex 30ca9f9a5b..6c2d818a6d 100644--- a/docs/mcp/OPENCLAW.md+++ b/docs/mcp/OPENCLAW.md@@ -86,9 +86,26 @@ workspace, else `agents.defaults.workspace`, else `~/.openclaw/workspace`; withseveral agents, pass `--workspace`). Text outside the markers is never touched,a re-run upgrades the block in place, `--no-instructions` opts out and isremembered, and `--remove` takes it out. A thin-client install puts the same-block at the top of `GBRAIN-INSTRUCTIONS.md`. With gbrain's context engine plugin, the-same rule also rides every turn in its per-turn addition (off after-`--no-instructions` or under `GBRAIN_AGENT_INSTRUCTIONS=0`).+block at the top of `GBRAIN-INSTRUCTIONS.md`.++A rule in `AGENTS.md` reaches the system prompt only, so setup also puts it next+to every user turn with a hook-only OpenClaw plugin, `gbrain-turn-rule`: its+`before_prompt_build` handler returns the rule as `prependContext`. The plugin is+self-contained (the rule text is in its code; it reads and calls nothing) and+lives in `<OpenClaw state dir>/gbrain/gbrain-turn-rule`. Setup installs it with+OpenClaw's own CLI:++```bash+openclaw plugins install --link <state dir>/gbrain/gbrain-turn-rule --force --accept-capabilities+openclaw plugins enable gbrain-turn-rule+openclaw config set plugins.entries.gbrain-turn-rule.hooks.allowConversationAccess true+```++OpenClaw requires `allowConversationAccess` before a non-bundled plugin's+`before_prompt_build` runs. With no `openclaw` on PATH, setup writes the plugin+and prints those commands to run on the OpenClaw host; restart a running gateway+afterwards. `--no-instructions` and `--remove` uninstall the plugin and delete+its directory. A re-run after an upgrade rewrites the plugin with the new text.## Scheduled jobs and workspace scriptsdiff --git a/scripts/module-size-limits.tsv b/scripts/module-size-limits.tsvindex 21964a7737..cc1ae74227 100644--- a/scripts/module-size-limits.tsv+++ b/scripts/module-size-limits.tsv@@ -34,7 +34,7 @@ src/commands/sources.ts 2086 ratchet +5 PR #5955 / fix wave 14 P2.7: sources setsrc/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 edgessrc/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 budgetsrc/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 1959 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); +27 GBRA-188 per-turn brain-first rule: user-prompt fallback emission, the turn-rule event (Hermes pre_llm_call), its HookIo seam and help (rule and ledger read in core/setup/brain-first.ts)+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/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 parseWithTimeoutsrc/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)diff --git a/scripts/structural-suites.tsv b/scripts/structural-suites.tsvindex 8c1400538b..0ef7af2377 100644--- a/scripts/structural-suites.tsv+++ b/scripts/structural-suites.tsv@@ -45,6 +45,7 @@ test/brain-durability-hook.serial.test.ts brain-commit-push.sh (D13 guarantee) 4test/brain-durability-hook.serial.test.ts durability push remote confirmation (#5138) 9 readFileSynctest/brain-durability-hook.serial.test.ts durability schedule (installCron:true) [D2/D12] 0 readFileSynctest/brain-durability-hook.serial.test.ts post-commit hook (D9 local, D7 self-contained) 4 readFileSync+test/brain-first-turn-rule.test.ts per-turn rule: OpenClaw before_prompt_build plugin 3 readFileSynctest/brain-repo-durability.serial.test.ts hardenBrainRepo 20 readFileSynctest/brain-score-breakdown.test.ts Bug 11 — BrainHealth type shape 1 bun-filetest/brain-score-breakdown.test.ts Bug 11 — doctor renders brain_score breakdown 1 doctor-source-helperdiff --git a/src/cli/subcommands.ts b/src/cli/subcommands.tsindex af8fd42a97..02ab3e38fc 100644--- a/src/cli/subcommands.ts+++ b/src/cli/subcommands.ts@@ -20,7 +20,7 @@export const PAGES_SUBCOMMANDS = ['purge-deleted', 'purges', 'unpurge', 'unsearchable', 'ghosts', 'status'] as const;export const CACHE_SUBCOMMANDS = ['stats', 'clear', 'prune'] as const;export const INTEGRITY_SUBCOMMANDS = ['check', 'auto', 'review', 'reset-progress'] as const;-export const HOOK_SUBCOMMANDS = ['session-start', 'user-prompt', 'stop', 'session-end', 'compact', 'turn-rule'] as const;+export const HOOK_SUBCOMMANDS = ['session-start', 'user-prompt', 'stop', 'session-end', 'compact'] as const;export const SEARCH_SUBCOMMANDS = ['modes', 'stats', 'tune', 'diagnose'] as const;export const EDGE_PROPOSALS_SUBCOMMANDS = ['list', 'show', 'accept', 'reject', 'undo', 'date', 'retry'] as const;export const CONFIG_SUBCOMMANDS = ['show', 'get', 'set', 'unset'] as const;diff --git a/src/commands/hook.ts b/src/commands/hook.tsindex 1b322b7797..dbdc833a09 100644--- a/src/commands/hook.ts+++ b/src/commands/hook.ts@@ -267,9 +267,6 @@ Events (wired into .claude/settings.local.json by gbrain bootstrap):compact (PreCompact) bank the window's standing entities into thesession cursor so the post-compaction session-start servesa warm context pack; emits nothing- turn-rule (Hermes pre_llm_call) print the per-turn brain-first rule as- {"context": ...}; nothing after --no-instructions or under- GBRAIN_AGENT_INSTRUCTIONS=0Env: GBRAIN_HOOKS=0 disables all events (immediate exit 0).All events fail open: errors exit 0 with empty stdout and a heartbeat entry at@@ -354,8 +351,6 @@ export async function runHook(args: string[], io: HookIo = {}): Promise<number>return hookSessionEnd(io);case 'compact':return hookCompact(io);- case 'turn-rule':- return hookTurnRule(io);default:return 1; // unreachable}@@ -1306,15 +1301,6 @@ async function hookUserPrompt(io: HookIo): Promise<number> {return 0;}-// ── turn-rule (Hermes pre_llm_call) ───────────────────────────────────────────--/** Hermes `hooks.pre_llm_call`: Hermes appends stdout `{"context": ...}` to each user message. File reads only. */-function hookTurnRule(io: HookIo): number {- const rule = io.turnRule !== undefined ? io.turnRule : brainFirstTurnRule('hermes', { kind: 'mcp', server: 'gbrain' });- if (rule) write(io, `${JSON.stringify({ context: rule })}\n`);- return 0;-}-// ── compact (PreCompact banking, v0.45.7 ambient recall) ─────────────────────/** Self-deadline for the compact event (harness timeout is 5s). */diff --git a/src/commands/setup.ts b/src/commands/setup.tsindex 397b86f62c..89eacb65c0 100644--- a/src/commands/setup.ts+++ b/src/commands/setup.ts@@ -25,6 +25,7 @@import { realpathSync } from 'node:fs';import { dirname } from 'node:path';import { removeHermesTurnHook, syncHermesTurnHook } from '../core/setup/hermes-turn-hook.ts';+import { removeOpenclawTurnPlugin, syncOpenclawTurnPlugin } from '../core/setup/openclaw-turn-plugin.ts';import { opError, OperationError } from '../core/ops/contract.ts';import { cliRenderContext, renderCliError, renderNotice, type Action, type Notice } from '../core/agent-output.ts';import { writeCliNotices } from '../core/interop-notices.ts';@@ -128,8 +129,8 @@ Flags:existing block is removed and the opt-out is remembered.GBRAIN_AGENT_INSTRUCTIONS=0 does the same.--instructions Opt back in after an earlier --no-instructions.- --instructions-only Manage only the brain-first block (on Hermes, with its per-turn- hook): no brain, MCP or other hook changes.+ --instructions-only Manage only the brain-first block (on OpenClaw and Hermes, with+ its per-turn hook): no brain, MCP or other hook changes.Works for a hosted connection too, and for any harness below.--workspace DIR OpenClaw: the agent workspace whose AGENTS.md gets the block(default: agents.defaults.workspace, then ~/.openclaw/workspace).@@ -141,8 +142,9 @@ first, read the hit, fill gaps with other tools, apply your own access rules,finish the task). Text outside the markers is never touched; a re-run upgradesthe block in place. The same rule rides each turn where the harness has a per-turnhook: Claude Code and Codex get it from setup's UserPromptSubmit hook, OpenClaw-from gbrain's context engine, Hermes from a marked pre_llm_call hook setup adds-to $HERMES_HOME/config.yaml (gbrain hook turn-rule); Cursor's rule is always applied.+from a hook-only plugin (before_prompt_build) setup installs with the openclaw+CLI, Hermes from a marked pre_llm_call hook setup adds to $HERMES_HOME/config.yaml;+Cursor's rule is always applied.claude-code ~/.claude/CLAUDE.md (project scope: ./CLAUDE.local.md)codex $CODEX_HOME/AGENTS.md (a non-empty AGENTS.override.md instead)opencode ~/.config/opencode/AGENTS.md@@ -726,17 +728,19 @@ async function runInstructionsOnly(flags: SetupFlags, out: Out): Promise<number>const decision = resolveBrainFirstDecision(flags.instructions, priorBrainFirst(harness, target.path));instructions = syncBrainFirst({ target, access, decision, writer: `gbrain setup ${harness}`, dryRun: flags.dryRun });}- const hermesHome = harness === 'hermes' ? dirname(target.path) : null;- const turnHook = !hermesHome ? null : flags.remove || instructions?.decision.value === 'declined'- ? removeHermesTurnHook({ hermesHome, dryRun: flags.dryRun })- : syncHermesTurnHook({ hermesHome, launcher: flags.gbrainBin ?? resolveGbrainBin(), dryRun: flags.dryRun });+ const off = flags.remove || instructions?.decision.value === 'declined';+ const turnHook = harness === 'hermes'+ ? (off ? removeHermesTurnHook({ hermesHome: dirname(target.path), dryRun: flags.dryRun }) : syncHermesTurnHook({ hermesHome: dirname(target.path), access, dryRun: flags.dryRun }))+ : harness === 'openclaw'+ ? (off ? removeOpenclawTurnPlugin({ dryRun: flags.dryRun }) : syncOpenclawTurnPlugin({ access, dryRun: flags.dryRun }))+ : null;const code = instructions?.action === 'preserve' ? 1 : 0;if (out.json) {await writeJsonDocument(`${JSON.stringify({ harness, dry_run: flags.dryRun, remove: flags.remove, instructions_only: true, instructions, ...(turnHook ? { turn_hook: turnHook } : {}), mcp }, null, 2)}\n`, (t) => process.stdout.write(t));return code;}if (instructions) say(out, flags.remove ? describeBrainFirstOutcome(instructions, flags.dryRun) : describeInstructions(instructions, flags.dryRun));- if (turnHook) say(out, ` ${(flags.dryRun && (turnHook.action === 'write' || turnHook.action === 'remove') ? `would ${turnHook.action}` : turnHook.action).padEnd(8)} ${'turn hook'.padEnd(7)} ${turnHook.detail}${turnHook.snippet ? `:\n${turnHook.snippet.replace(/^/gm, ' ')}` : ''}`);+ if (turnHook) say(out, ` ${(flags.dryRun && (turnHook.action === 'write' || turnHook.action === 'remove') ? `would ${turnHook.action}` : turnHook.action).padEnd(8)} ${'turn hook'.padEnd(7)} ${turnHook.detail}${'snippet' in turnHook && turnHook.snippet ? `:\n${turnHook.snippet.replace(/^/gm, ' ')}` : ''}${'commands' in turnHook && turnHook.commands ? `:\n${turnHook.commands.map((c) => ` ${c}`).join('\n')}` : ''}`);if (mcp.setup === 'manual' && !flags.remove) say(out, `MCP: setup does not register ${adapter.label}'s MCP server. Follow ${adapter.guide} (one command), then start a new session.`);if (!flags.remove && instructions?.decision.value === 'accepted') say(out, 'Next: start a new session; the harness reads its instruction file at session start.');return code;diff --git a/src/core/behavior-change-notice.ts b/src/core/behavior-change-notice.tsindex f4dfaeed4a..32fd175b96 100644--- a/src/core/behavior-change-notice.ts+++ b/src/core/behavior-change-notice.ts@@ -1300,7 +1300,7 @@ export const BEHAVIOR_CHANGES: ReadonlyArray<{ since: string; text: ChangeText;// GBRA-188. since: 'TBD' is stamped at the merge slot.{ 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\'s OpenClaw context engine adds it to its per-turn addition; and `gbrain setup hermes` adds a marked `pre_llm_call` shell hook (`gbrain hook turn-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: '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.' },];/** The newest disclosed change's release: the notice id moves only when a release adds rows. */diff --git a/src/core/cli-flag-registry.generated.ts b/src/core/cli-flag-registry.generated.tsindex f099da945f..76f87109cd 100644--- a/src/core/cli-flag-registry.generated.ts+++ b/src/core/cli-flag-registry.generated.ts@@ -50,7 +50,7 @@ export const CLI_FLAG_REGISTRY: Record<string, readonly string[]> = {'db-repair': ['--accept-pending', '--apply', '--apply-rewrites', '--background', '--brain', '--break-lock', '--db-url', '--dry-run', '--explain', '--filter', '--follow', '--force', '--force-retry', '--format', '--help', '--http', '--json', '--legacy-lock', '--locks', '--name', '--no-accept-pending', '--path', '--prefer-postgres', '--probe', '--progress-interval', '--progress-json', '--quiet', '--remediate', '--restart', '--skip-verify', '--source', '--statement-timeout', '--supabase', '--timeout', '--timings', '--undo-last-rewrite', '--url', '--version', '--wait', '--yes'],'decide': ['--accept-all', '--all', '--all-from', '--apply', '--brain', '--call-site', '--dataset', '--dry-run', '--egress', '--embedding-dimensions', '--embedding-model', '--expect', '--from', '--help', '--include-withdrawals', '--input', '--items-out', '--json', '--kind', '--limit', '--max-cost', '--max-usd', '--min', '--non-interactive', '--out', '--provenance', '--provider', '--query', '--rate', '--reason', '--reason-family', '--recommended', '--remove', '--shadow', '--since', '--slot', '--source', '--status', '--suite', '--target', '--threshold', '--trust', '--undo', '--uri-prefix', '--version', '--what-if-threshold', '--yes'],'diag': ['--access', '--add', '--all', '--allowed-operations', '--apply', '--asof', '--body', '--bound-slug-prefixes', '--brain', '--budget-ms', '--client', '--count', '--cursor', '--date', '--dated-since', '--days', '--detach', '--entities', '--expect', '--expected-revision', '--federated-read', '--format', '--from-index', '--full', '--fuzzy', '--group-by', '--held', '--help', '--http', '--id', '--include-ambiguous', '--include-deleted', '--json', '--kind', '--limit', '--max-usd', '--model', '--multimodal', '--no-autopilot-install', '--no-pull', '--no-walk', '--only', '--page', '--params', '--path', '--phase', '--prefer', '--preview', '--purge', '--query', '--recent', '--refresh-operations', '--replace', '--restart-only', '--reverse', '--row', '--scopes', '--session', '--side', '--since', '--slug', '--slugs', '--source', '--source-id', '--sources', '--stale', '--state', '--surface', '--to', '--updated-after', '--url', '--yes'],- 'doctor': ['--abandon', '--abbrev-ref', '--accept-pending', '--access', '--account', '--acknowledge-managed', '--add', '--admin-intent', '--adopt', '--adopt-columns', '--adopt-permissions', '--after', '--aggressive', '--aliases', '--all', '--all-drifted', '--all-from', '--allow-old-serve', '--allow-outside-source-root', '--allow-shell-jobs', '--allow-unverified-remote', '--allowed-operations', '--applied', '--apply', '--apply-rewrites', '--assign-corpus', '--audit', '--auto', '--auto-additive', '--auto-fix', '--autostash', '--background', '--batch', '--batch-check', '--bound-brain', '--bound-max-concurrent', '--bound-slug-prefixes', '--bound-source', '--bound-tools', '--brain', '--branch', '--break-lock', '--budget-ms', '--budget-policy', '--budget-tokens', '--budget-usd', '--by-mention', '--cached', '--cacheinfo', '--call-site', '--catch-up', '--channel', '--check', '--cherry-mark', '--class', '--clear', '--clear-never-installed', '--cli-socket', '--client', '--close', '--concurrency', '--confidence', '--confirm', '--confirm-quiesced', '--confirm-relocated-root', '--conflicts', '--contacts-dir', '--content-audit', '--content-root', '--continue', '--conversation', '--count', '--cursor', '--dataset', '--day', '--db-url', '--deadline', '--delegated-namespace', '--delegated-slug-prefixes', '--delete-brain', '--dest', '--detach', '--detail', '--diff-filter', '--dim', '--dimensions', '--dir', '--disable', '--drain', '--drain-timeout', '--dry-run', '--egress', '--embedding-dimensions', '--embedding-model', '--enable', '--enable-dcr', '--end-of-options', '--entity', '--env', '--error-unmatch', '--exclude', '--exclude-standard', '--exit-code', '--expand', '--expect', '--expect-local', '--expect-remote', '--expect-upstream', '--expected-epoch', '--expected-revision', '--expected-state', '--explain', '--facts', '--fast', '--federated', '--federated-read', '--fetch-timeout-ms', '--ff-only', '--file', '--first-parent', '--fix', '--follow', '--force', '--force-break-lock', '--force-rechunk', '--force-remove', '--force-retry', '--force-schema', '--format', '--fresh', '--fresh-token', '--from', '--from-meetings', '--from-pages', '--full', '--full-tree', '--fuzzy', '--generation', '--get', '--get-all', '--get-url', '--git-common-dir', '--git-dir', '--git-path', '--grammar', '--group', '--group-by', '--hard', '--hard-deadline', '--harness', '--held', '--help', '--hold-state', '--holds', '--home', '--http', '--id', '--if-version', '--ignore-env-override', '--images', '--include-ambiguous', '--include-cross-entity', '--include-deleted', '--include-failures', '--include-flagged', '--include-frontmatter', '--include-gitignored', '--include-hidden', '--include-pseudo', '--include-repairs', '--include-withdrawals', '--index-audit', '--index-info', '--infer-dates', '--init', '--input', '--install', '--instructions-only', '--is-ancestor', '--is-inside-work-tree', '--items-out', '--job-isolation', '--jq', '--json', '--keep', '--keep-checkout', '--key', '--kind', '--lanes', '--lang', '--left-right', '--legacy-lock', '--limit', '--link-source', '--link-type', '--list', '--literal-pathspecs', '--local', '--local-env-vars', '--locks', '--log-noop', '--manifest', '--markdown', '--max-cost', '--max-cost-usd', '--max-count', '--max-facts', '--max-jobs', '--max-requests', '--max-rss', '--max-runtime', '--max-usd', '--max-waiting', '--mcp-only', '--merge-base', '--migrate-legacy', '--migrate-only', '--migration', '--min', '--min-n', '--mode', '--model', '--multimodal', '--name', '--name-only', '--name-status', '--nice', '--no-accept-pending', '--no-autopilot-install', '--no-autostash', '--no-capture', '--no-commit-id', '--no-confirm', '--no-cron', '--no-delegate', '--no-edit', '--no-embed', '--no-embed-cache', '--no-embedding', '--no-expand', '--no-extract', '--no-federated', '--no-filters', '--no-gpg-sign', '--no-hooks', '--no-instructions', '--no-lanes', '--no-llm', '--no-merges', '--no-migrate', '--no-probe', '--no-pull', '--no-renames', '--no-repair', '--no-restart', '--no-schema-pack', '--no-seat', '--no-tags', '--no-verify', '--no-walk', '--no-write-fetch-head', '--non-interactive', '--not', '--now', '--older-than', '--once', '--only', '--operations', '--others', '--out', '--output', '--oversized', '--overwrite', '--page', '--parallel', '--params', '--parents', '--parked-code', '--parked-pushes', '--pat-file', '--path', '--path-format', '--pending', '--pglite', '--phase', '--pid-file', '--plan', '--porcelain', '--port', '--prefer', '--prefer-postgres', '--preset', '--preview', '--probe', '--probe-pglite', '--profile', '--progress-interval', '--progress-json', '--project', '--provenance', '--provider', '--providers', '--prune-orphans', '--public-url', '--pull', '--pure', '--purge', '--push', '--push-only', '--query', '--question', '--queue', '--quiet', '--rate', '--reader-mode', '--reauth', '--rebase', '--rebuild', '--recommended', '--redact-paths', '--reference-date', '--refresh', '--refresh-operations', '--refresh-skills', '--regenerate', '--reissue', '--relative', '--relower', '--remediate', '--remediation-plan', '--remove', '--remove-core', '--repair', '--repair-unknown-markers', '--replace', '--repo', '--request', '--request-id', '--require-clean', '--reranker', '--reset', '--reset-checkpoint', '--reset-default', '--resolve', '--restart-only', '--restore-only', '--resume', '--retry-failed', '--retry-global', '--retry-held', '--retry-parked', '--reverse', '--review-lower', '--revision', '--right-only', '--rollback-to-source', '--root', '--run', '--sample', '--save', '--scope', '--scopes', '--search-mode', '--seat', '--section', '--segmented', '--select', '--self-transfer', '--semantic', '--session', '--session-id', '--set', '--set-upstream-to', '--shadow', '--short', '--show-current', '--show-object-format', '--show-prefix', '--show-token', '--show-toplevel', '--side', '--since', '--since-last-run', '--skills-dir', '--skip', '--skip-bare-tweet', '--skip-failed', '--skip-urls', '--skip-verify', '--slot', '--slot-a-model', '--slot-b-model', '--slot-c-model', '--slug', '--slugs', '--source', '--source-id', '--source-ids', '--sources', '--src-subpath', '--staged', '--stale', '--stat', '--state', '--statement-timeout', '--status', '--stdin', '--stop-mcp', '--strategy', '--strict', '--suite', '--supabase', '--surface', '--swap-only', '--symbol-kind', '--symbolic-full-name', '--takes-holders', '--target', '--target-score', '--threshold', '--tier', '--timeout', '--timings', '--to', '--token', '--token-ttl', '--top-k', '--topo-order', '--trust', '--type', '--unindexed', '--uninstall', '--unsafe-bypass-dream-guard', '--unset-all', '--untracked-files', '--url', '--url-env', '--user', '--vacuum', '--vectors', '--verbose', '--verify', '--version', '--wait', '--wait-drain', '--warn-only', '--watch', '--what-if-threshold', '--window', '--workers', '--working-tree', '--workspace', '--write-tree', '--yes'],+ 'doctor': ['--abandon', '--abbrev-ref', '--accept-capabilities', '--accept-pending', '--access', '--account', '--acknowledge-managed', '--add', '--admin-intent', '--adopt', '--adopt-columns', '--adopt-permissions', '--after', '--aggressive', '--aliases', '--all', '--all-drifted', '--all-from', '--allow-old-serve', '--allow-outside-source-root', '--allow-shell-jobs', '--allow-unverified-remote', '--allowed-operations', '--applied', '--apply', '--apply-rewrites', '--assign-corpus', '--audit', '--auto', '--auto-additive', '--auto-fix', '--autostash', '--background', '--batch', '--batch-check', '--bound-brain', '--bound-max-concurrent', '--bound-slug-prefixes', '--bound-source', '--bound-tools', '--brain', '--branch', '--break-lock', '--budget-ms', '--budget-policy', '--budget-tokens', '--budget-usd', '--by-mention', '--cached', '--cacheinfo', '--call-site', '--catch-up', '--channel', '--check', '--cherry-mark', '--class', '--clear', '--clear-never-installed', '--cli-socket', '--client', '--close', '--concurrency', '--confidence', '--confirm', '--confirm-quiesced', '--confirm-relocated-root', '--conflicts', '--contacts-dir', '--content-audit', '--content-root', '--continue', '--conversation', '--count', '--cursor', '--dataset', '--day', '--db-url', '--deadline', '--delegated-namespace', '--delegated-slug-prefixes', '--delete-brain', '--dest', '--detach', '--detail', '--diff-filter', '--dim', '--dimensions', '--dir', '--disable', '--drain', '--drain-timeout', '--dry-run', '--egress', '--embedding-dimensions', '--embedding-model', '--enable', '--enable-dcr', '--end-of-options', '--entity', '--env', '--error-unmatch', '--exclude', '--exclude-standard', '--exit-code', '--expand', '--expect', '--expect-local', '--expect-remote', '--expect-upstream', '--expected-epoch', '--expected-revision', '--expected-state', '--explain', '--facts', '--fast', '--federated', '--federated-read', '--fetch-timeout-ms', '--ff-only', '--file', '--first-parent', '--fix', '--follow', '--force', '--force-break-lock', '--force-rechunk', '--force-remove', '--force-retry', '--force-schema', '--format', '--fresh', '--fresh-token', '--from', '--from-meetings', '--from-pages', '--full', '--full-tree', '--fuzzy', '--generation', '--get', '--get-all', '--get-url', '--git-common-dir', '--git-dir', '--git-path', '--grammar', '--group', '--group-by', '--hard', '--hard-deadline', '--harness', '--held', '--help', '--hold-state', '--holds', '--home', '--http', '--id', '--if-version', '--ignore-env-override', '--images', '--include-ambiguous', '--include-cross-entity', '--include-deleted', '--include-failures', '--include-flagged', '--include-frontmatter', '--include-gitignored', '--include-hidden', '--include-pseudo', '--include-repairs', '--include-withdrawals', '--index-audit', '--index-info', '--infer-dates', '--init', '--input', '--install', '--instructions-only', '--is-ancestor', '--is-inside-work-tree', '--items-out', '--job-isolation', '--jq', '--json', '--keep', '--keep-checkout', '--key', '--kind', '--lanes', '--lang', '--left-right', '--legacy-lock', '--limit', '--link', '--link-source', '--link-type', '--list', '--literal-pathspecs', '--local', '--local-env-vars', '--locks', '--log-noop', '--manifest', '--markdown', '--max-cost', '--max-cost-usd', '--max-count', '--max-facts', '--max-jobs', '--max-requests', '--max-rss', '--max-runtime', '--max-usd', '--max-waiting', '--mcp-only', '--merge-base', '--migrate-legacy', '--migrate-only', '--migration', '--min', '--min-n', '--mode', '--model', '--multimodal', '--name', '--name-only', '--name-status', '--nice', '--no-accept-pending', '--no-autopilot-install', '--no-autostash', '--no-capture', '--no-commit-id', '--no-confirm', '--no-cron', '--no-delegate', '--no-edit', '--no-embed', '--no-embed-cache', '--no-embedding', '--no-expand', '--no-extract', '--no-federated', '--no-filters', '--no-gpg-sign', '--no-hooks', '--no-instructions', '--no-lanes', '--no-llm', '--no-merges', '--no-migrate', '--no-probe', '--no-pull', '--no-renames', '--no-repair', '--no-restart', '--no-schema-pack', '--no-seat', '--no-tags', '--no-verify', '--no-walk', '--no-write-fetch-head', '--non-interactive', '--not', '--now', '--older-than', '--once', '--only', '--operations', '--others', '--out', '--output', '--oversized', '--overwrite', '--page', '--parallel', '--params', '--parents', '--parked-code', '--parked-pushes', '--pat-file', '--path', '--path-format', '--pending', '--pglite', '--phase', '--pid-file', '--plan', '--porcelain', '--port', '--prefer', '--prefer-postgres', '--preset', '--preview', '--probe', '--probe-pglite', '--profile', '--progress-interval', '--progress-json', '--project', '--provenance', '--provider', '--providers', '--prune-orphans', '--public-url', '--pull', '--pure', '--purge', '--push', '--push-only', '--query', '--question', '--queue', '--quiet', '--rate', '--reader-mode', '--reauth', '--rebase', '--rebuild', '--recommended', '--redact-paths', '--reference-date', '--refresh', '--refresh-operations', '--refresh-skills', '--regenerate', '--reissue', '--relative', '--relower', '--remediate', '--remediation-plan', '--remove', '--remove-core', '--repair', '--repair-unknown-markers', '--replace', '--repo', '--request', '--request-id', '--require-clean', '--reranker', '--reset', '--reset-checkpoint', '--reset-default', '--resolve', '--restart-only', '--restore-only', '--resume', '--retry-failed', '--retry-global', '--retry-held', '--retry-parked', '--reverse', '--review-lower', '--revision', '--right-only', '--rollback-to-source', '--root', '--run', '--sample', '--save', '--scope', '--scopes', '--search-mode', '--seat', '--section', '--segmented', '--select', '--self-transfer', '--semantic', '--session', '--session-id', '--set', '--set-upstream-to', '--shadow', '--short', '--show-current', '--show-object-format', '--show-prefix', '--show-token', '--show-toplevel', '--side', '--since', '--since-last-run', '--skills-dir', '--skip', '--skip-bare-tweet', '--skip-failed', '--skip-urls', '--skip-verify', '--slot', '--slot-a-model', '--slot-b-model', '--slot-c-model', '--slug', '--slugs', '--source', '--source-id', '--source-ids', '--sources', '--src-subpath', '--staged', '--stale', '--stat', '--state', '--statement-timeout', '--status', '--stdin', '--stop-mcp', '--strategy', '--strict', '--suite', '--supabase', '--surface', '--swap-only', '--symbol-kind', '--symbolic-full-name', '--takes-holders', '--target', '--target-score', '--threshold', '--tier', '--timeout', '--timings', '--to', '--token', '--token-ttl', '--top-k', '--topo-order', '--trust', '--type', '--unindexed', '--uninstall', '--unsafe-bypass-dream-guard', '--unset-all', '--untracked-files', '--url', '--url-env', '--user', '--vacuum', '--vectors', '--verbose', '--verify', '--version', '--wait', '--wait-drain', '--warn-only', '--watch', '--what-if-threshold', '--window', '--workers', '--working-tree', '--workspace', '--write-tree', '--yes'],'dream': ['--audit-rejects', '--brain', '--cancel-unmatched', '--date', '--dir', '--drain', '--dry-run', '--eval-run', '--force', '--from', '--help', '--input', '--install', '--json', '--limit', '--list', '--max-usd', '--once', '--path', '--phase', '--probe', '--pull', '--reconcile-queue', '--since', '--source', '--source-id', '--threshold', '--to', '--unsafe-bypass-dream-guard', '--window', '--yes'],'edge-proposals': ['--access', '--add', '--all', '--all-applied', '--all-held', '--allowed-operations', '--asof', '--body', '--bound-slug-prefixes', '--brain', '--client', '--cursor', '--date', '--dated-since', '--days', '--entities', '--federated-read', '--from-index', '--full', '--fuzzy', '--group-by', '--help', '--http', '--id', '--include-deleted', '--json', '--kind', '--limit', '--max-usd', '--model', '--multimodal', '--no-autopilot-install', '--page', '--params', '--path', '--phase', '--prefer', '--purge', '--recent', '--refresh-operations', '--row', '--scopes', '--session', '--since', '--slugs', '--source', '--sources', '--stale', '--status', '--surface', '--to', '--updated-after', '--url', '--yes'],'edges-backfill': ['--all-sources', '--brain', '--concurrency', '--help', '--json', '--max-chunks', '--source', '--workers'],@@ -76,7 +76,7 @@ export const CLI_FLAG_REGISTRY: Record<string, readonly string[]> = {'graph-query': ['--brain', '--depth', '--direction', '--help', '--hop', '--include-foreign', '--json', '--mcp-only', '--request-id', '--source', '--type'],'hook': ['--allow-unverified-remote', '--auto', '--batch-check', '--brain', '--branch', '--cached', '--count', '--diff-filter', '--enable', '--end-of-options', '--env', '--get', '--harness', '--help', '--instructions-only', '--jq', '--json', '--limit', '--name-only', '--no-instructions', '--others', '--pat-file', '--path', '--porcelain', '--pure', '--quiet', '--remove', '--seat', '--session', '--show-current', '--show-toplevel', '--since', '--source', '--source-ids', '--workspace', '--yes'],'import': ['--accept-pending', '--admin-intent', '--allow-empty', '--allow-noncanonical-root', '--apply', '--background', '--batch-check', '--brain', '--cached', '--confirm-relocated-root', '--diff-filter', '--dim', '--embedding-dimensions', '--embedding-model', '--empty', '--exclude', '--exclude-standard', '--expected-epoch', '--expected-state', '--explain', '--follow', '--force', '--force-rechunk', '--format', '--fresh', '--help', '--include-gitignored', '--is-shallow-repository', '--json', '--literal-pathspecs', '--log-noop', '--manifest', '--name-only', '--no-accept-pending', '--no-embed', '--no-embedding', '--no-gpg-sign', '--no-pull', '--no-renames', '--no-verify', '--only', '--others', '--path', '--probe', '--progress-interval', '--progress-json', '--quiet', '--self-transfer', '--show-toplevel', '--skip-failed', '--slugs', '--source', '--source-id', '--stale', '--status', '--supabase', '--timeout', '--timings', '--to', '--url', '--verify', '--wait', '--workers'],- 'init': ['--access', '--acknowledge-managed', '--adopt', '--after', '--aliases', '--all', '--all-drifted', '--allow-create-db', '--allow-docker', '--allow-outside-source-root', '--applied', '--apply', '--assign-corpus', '--audit', '--auto', '--auto-additive', '--background', '--batch', '--bound-slug-prefixes', '--brain', '--branch', '--break-lock', '--budget-ms', '--budget-policy', '--budget-tokens', '--budget-usd', '--by-mention', '--catch-up', '--channel', '--chat-model', '--check', '--class', '--clear-never-installed', '--cli-socket', '--client', '--close', '--confirm-relocated-root', '--conflicts', '--content-root', '--continue', '--conversation', '--cursor', '--db-only', '--deadline', '--dest', '--detach', '--detail', '--dim', '--disable', '--drain', '--embedding-dimensions', '--embedding-model', '--enable', '--entity', '--exclude', '--expand', '--expansion-model', '--expect', '--expect-local', '--expect-remote', '--expect-upstream', '--explain', '--facts', '--fast', '--federated', '--file', '--fix', '--force', '--force-retry', '--format', '--fresh-token', '--from', '--from-meetings', '--full', '--git', '--grammar', '--grant-types', '--group-by', '--harness', '--held', '--help', '--hold-state', '--holds', '--http', '--id', '--images', '--include-ambiguous', '--include-cross-entity', '--include-frontmatter', '--include-gitignored', '--include-hidden', '--infer-dates', '--input', '--install', '--instructions-only', '--issuer-url', '--job-isolation', '--json', '--keep', '--keep-checkout', '--key', '--kind', '--lanes', '--legacy-lock', '--limit', '--list', '--local-postgres', '--markdown', '--max-cost-usd', '--max-facts', '--max-requests', '--max-rss', '--max-usd', '--mcp-only', '--mcp-url', '--migrate-only', '--migration', '--min-n', '--mode', '--model', '--no-autopilot-install', '--no-autostash', '--no-delegate', '--no-embed', '--no-embedding', '--no-expand', '--no-extract', '--no-federated', '--no-filters', '--no-git', '--no-instructions', '--no-lanes', '--no-llm', '--no-probe', '--no-pull', '--no-renames', '--no-repair', '--no-restart', '--no-schema-pack', '--no-verify', '--non-interactive', '--oauth-client-id', '--oauth-client-secret', '--older-than', '--once', '--only', '--output', '--oversized', '--page', '--params', '--parked-code', '--parked-pushes', '--pat-file', '--path', '--pending', '--pglite', '--phase', '--plan', '--prefer', '--prefer-postgres', '--preview', '--probe', '--profile', '--provenance', '--providers', '--pull', '--purge', '--push-only', '--query', '--question', '--quiet', '--rebase', '--rebuild', '--redact-paths', '--reference-date', '--remediate', '--remove', '--repair', '--repair-unknown-markers', '--repo', '--request', '--request-id', '--require-clean', '--reset', '--resolve', '--restart-only', '--resume', '--retry-failed', '--retry-parked', '--save', '--schema-pack', '--scope', '--scopes', '--search-mode', '--section', '--segmented', '--self-transfer', '--semantic', '--session', '--session-id', '--show-toplevel', '--side', '--since', '--since-last-run', '--skip', '--skip-embed-check', '--skip-failed', '--slug', '--slugs', '--source', '--source-id', '--sources', '--src-subpath', '--stale', '--state', '--status', '--stdin', '--stop-mcp', '--strategy', '--supabase', '--surface', '--swap-only', '--tier', '--timeout', '--to', '--token', '--touchpoint', '--type', '--url', '--url-env', '--user', '--vacuum', '--verbose', '--version', '--wait', '--warn-only', '--watch', '--working-tree', '--workspace', '--yes'],+ 'init': ['--accept-capabilities', '--access', '--acknowledge-managed', '--adopt', '--after', '--aliases', '--all', '--all-drifted', '--allow-create-db', '--allow-docker', '--allow-outside-source-root', '--applied', '--apply', '--assign-corpus', '--audit', '--auto', '--auto-additive', '--background', '--batch', '--bound-slug-prefixes', '--brain', '--branch', '--break-lock', '--budget-ms', '--budget-policy', '--budget-tokens', '--budget-usd', '--by-mention', '--catch-up', '--channel', '--chat-model', '--check', '--class', '--clear-never-installed', '--cli-socket', '--client', '--close', '--confirm-relocated-root', '--conflicts', '--content-root', '--continue', '--conversation', '--cursor', '--db-only', '--deadline', '--dest', '--detach', '--detail', '--dim', '--disable', '--drain', '--embedding-dimensions', '--embedding-model', '--enable', '--entity', '--exclude', '--expand', '--expansion-model', '--expect', '--expect-local', '--expect-remote', '--expect-upstream', '--explain', '--facts', '--fast', '--federated', '--file', '--fix', '--force', '--force-retry', '--format', '--fresh-token', '--from', '--from-meetings', '--full', '--git', '--grammar', '--grant-types', '--group-by', '--harness', '--held', '--help', '--hold-state', '--holds', '--http', '--id', '--images', '--include-ambiguous', '--include-cross-entity', '--include-frontmatter', '--include-gitignored', '--include-hidden', '--infer-dates', '--input', '--install', '--instructions-only', '--issuer-url', '--job-isolation', '--json', '--keep', '--keep-checkout', '--key', '--kind', '--lanes', '--legacy-lock', '--limit', '--link', '--list', '--local-postgres', '--markdown', '--max-cost-usd', '--max-facts', '--max-requests', '--max-rss', '--max-usd', '--mcp-only', '--mcp-url', '--migrate-only', '--migration', '--min-n', '--mode', '--model', '--no-autopilot-install', '--no-autostash', '--no-delegate', '--no-embed', '--no-embedding', '--no-expand', '--no-extract', '--no-federated', '--no-filters', '--no-git', '--no-instructions', '--no-lanes', '--no-llm', '--no-probe', '--no-pull', '--no-renames', '--no-repair', '--no-restart', '--no-schema-pack', '--no-verify', '--non-interactive', '--oauth-client-id', '--oauth-client-secret', '--older-than', '--once', '--only', '--output', '--oversized', '--page', '--params', '--parked-code', '--parked-pushes', '--pat-file', '--path', '--pending', '--pglite', '--phase', '--plan', '--prefer', '--prefer-postgres', '--preview', '--probe', '--profile', '--provenance', '--providers', '--pull', '--purge', '--push-only', '--query', '--question', '--quiet', '--rebase', '--rebuild', '--redact-paths', '--reference-date', '--remediate', '--remove', '--repair', '--repair-unknown-markers', '--repo', '--request', '--request-id', '--require-clean', '--reset', '--resolve', '--restart-only', '--resume', '--retry-failed', '--retry-parked', '--save', '--schema-pack', '--scope', '--scopes', '--search-mode', '--section', '--segmented', '--self-transfer', '--semantic', '--session', '--session-id', '--show-toplevel', '--side', '--since', '--since-last-run', '--skip', '--skip-embed-check', '--skip-failed', '--slug', '--slugs', '--source', '--source-id', '--sources', '--src-subpath', '--stale', '--state', '--status', '--stdin', '--stop-mcp', '--strategy', '--supabase', '--surface', '--swap-only', '--tier', '--timeout', '--to', '--token', '--touchpoint', '--type', '--url', '--url-env', '--user', '--vacuum', '--verbose', '--version', '--wait', '--warn-only', '--watch', '--working-tree', '--workspace', '--yes'],'integrations': ['--auto', '--brain', '--dry-run', '--help', '--json', '--overwrite', '--refresh', '--source', '--target'],'integrity': ['--accept-pending', '--auto', '--backend', '--background', '--body', '--brain', '--check', '--confidence', '--cost', '--dry-run', '--explain', '--follow', '--fresh', '--help', '--json', '--limit', '--no-accept-pending', '--progress-interval', '--progress-json', '--quiet', '--review-lower', '--skip-bare-tweet', '--skip-urls', '--source', '--timeout', '--timings', '--type', '--wait'],'jobs': ['--abbrev-ref', '--access', '--account', '--acknowledge-managed', '--add', '--admin-intent', '--adopt-slug-path', '--aliases', '--all', '--all-sources', '--allow-empty', '--allow-shell-jobs', '--allowed-operations', '--apply', '--asof', '--auto', '--background', '--backoff-delay', '--backoff-jitter', '--backoff-type', '--batch-size', '--body', '--bound-slug-prefixes', '--brain', '--break-lock', '--budget-ms', '--by-mention', '--cached', '--catch-up', '--channel', '--check', '--cli-path', '--client', '--close', '--cluster-errors', '--concurrency', '--confidence', '--confirm-destructive', '--confirm-relocated-root', '--cost-estimate', '--cursor', '--date', '--dated-since', '--days', '--delay', '--detach', '--detail', '--diff-filter', '--dir', '--drain', '--drain-timeout', '--dry-run', '--embedding-dimensions', '--embedding-model', '--empty', '--enable', '--entities', '--exclude', '--exclude-standard', '--expect', '--expect-local', '--expect-upstream', '--expected-state', '--explain', '--facts', '--federated-read', '--ff-only', '--file', '--filters', '--finished-since', '--fix', '--follow', '--force', '--force-break-lock', '--force-retry', '--format', '--fresh', '--from-index', '--from-meetings', '--full', '--full-history', '--fuzzy', '--git', '--grammar', '--grammar-diagnostics', '--group', '--group-by', '--hard-deadline', '--health-interval', '--held', '--help', '--hold-state', '--http', '--id', '--idempotency-key', '--ids', '--images', '--include-ambiguous', '--include-deleted', '--include-frontmatter', '--include-gitignored', '--include-hidden', '--include-null-signature', '--infer-dates', '--inject-bootstrap', '--inline', '--input', '--install', '--interval', '--is-ancestor', '--is-shallow-repository', '--job-id', '--job-isolation', '--json', '--keep', '--kind', '--lanes', '--legacy-lock', '--limit', '--list', '--local', '--lock-duration-ms', '--log-noop', '--markdown', '--max-age', '--max-attempts', '--max-cost', '--max-cost-usd', '--max-crashes', '--max-rss', '--max-sources', '--max-stalled', '--max-usd', '--max-waiting', '--mcp-only', '--migration', '--min-context', '--missing-path', '--mode', '--model', '--multimodal', '--name', '--name-only', '--ner', '--nice', '--no-auto-embed', '--no-autopilot-install', '--no-bulk', '--no-confirm', '--no-delegate', '--no-embed', '--no-embedding', '--no-extract', '--no-gpg-sign', '--no-hard-deadline', '--no-inject', '--no-lanes', '--no-llm', '--no-pull', '--no-renames', '--no-repair', '--no-restart', '--no-schema-pack', '--no-verify', '--no-worker', '--non-interactive', '--now', '--older-than', '--once', '--only', '--order', '--others', '--output', '--override-disabled', '--oversized', '--pace', '--pace-max-concurrency', '--pack', '--page', '--parallel', '--params', '--parked-code', '--pat-file', '--path', '--pause', '--pglite', '--phase', '--pid-file', '--plan', '--port', '--prefer', '--preview', '--priority', '--probe', '--prune-orphans', '--pull', '--purge', '--question', '--queue', '--queue-only', '--quiet', '--rate', '--reason', '--rebuild', '--recent', '--record', '--redact-paths', '--redact-secrets', '--reenrich-after', '--refresh-ms', '--refresh-operations', '--remediate', '--repo', '--request-id', '--reset-checkpoint', '--restart-only', '--resume', '--retry-failed', '--retry-global', '--retry-held', '--retry-parked', '--review-lower', '--row', '--scope', '--scopes', '--section', '--segment-limit', '--segmented', '--select', '--self-transfer', '--serial', '--session', '--show-toplevel', '--side', '--sigkill-rescue', '--since', '--skip', '--skip-bare-tweet', '--skip-failed', '--skip-urls', '--sleep', '--slug', '--slugs', '--source', '--source-guard', '--source-id', '--sources', '--src-subpath', '--stale', '--state', '--statement-timeout', '--status', '--stop-mcp', '--strategy', '--suites', '--surface', '--swap-only', '--target', '--thin', '--thin-threshold', '--tier', '--timeout', '--timeout-ms', '--to', '--token', '--trust', '--type', '--types', '--uninstall', '--updated-after', '--url', '--user', '--vectors', '--verbose', '--verify', '--version', '--watch', '--wedge-rescue', '--workers', '--working-tree', '--yes'],@@ -121,7 +121,7 @@ export const CLI_FLAG_REGISTRY: Record<string, readonly string[]> = {'schema': ['--alias', '--apply', '--as-filing-rules', '--brain', '--dims', '--expert', '--expert-routing', '--extractable', '--fields', '--force', '--help', '--inverse', '--json', '--kind', '--no-prefix', '--pack', '--page-type', '--path', '--prefix', '--primitive', '--schema-pack', '--since', '--source', '--source-id', '--target-type', '--to', '--with-db'],'self-upgrade': ['--apply', '--brain', '--channel', '--check-only', '--clear-never-installed', '--exit-code', '--ff-only', '--force', '--force-retry', '--help', '--is-ancestor', '--json', '--markdown', '--migrate-only', '--no-autopilot-install', '--no-bun-floor-check', '--no-restart', '--non-interactive', '--quiet', '--refresh-cache', '--refs', '--remediation-plan', '--restart-only', '--source', '--stop-mcp', '--swap-only', '--tags', '--version', '--yes'],'serve': ['--access', '--add', '--adopt-columns', '--adopt-permissions', '--all-new', '--apply-rewrites', '--bind', '--bound-brain', '--bound-max-concurrent', '--bound-slug-prefixes', '--bound-source', '--bound-tools', '--brain', '--budget-usd-per-day', '--cli-socket', '--client', '--days', '--delegated-namespace', '--delegated-slug-prefixes', '--enable-dcr', '--enable-dcr-insecure', '--expect', '--fail-fast', '--federated-read', '--grant-types', '--harness', '--help', '--http', '--id', '--if-version', '--json', '--log-full-params', '--migrate-legacy', '--min-trust', '--no-embedding', '--no-pull', '--oauth-request', '--only', '--operations', '--path', '--pglite', '--port', '--prefer-postgres', '--print-admin-token', '--profile', '--provenance', '--public-url', '--read-sources', '--redirect-uri', '--refresh-operations', '--repair', '--reset-default', '--retry-failed', '--scopes', '--source', '--source-guard', '--source-id', '--sources', '--stale', '--stdio-idle-timeout', '--suppress-bootstrap-token', '--surface', '--takes-holders', '--token', '--token-endpoint-auth-method', '--token-ttl', '--tools-json', '--url', '--usage', '--yes'],- 'setup': ['--agent', '--auto', '--bearer-token-env-var', '--brain', '--break-lock', '--capture', '--dry-run', '--env', '--gbrain-bin', '--harness', '--header', '--help', '--http', '--install', '--instructions', '--instructions-only', '--issuer-url', '--json', '--legacy-lock', '--mcp-only', '--mcp-url', '--name', '--no-capture', '--no-embedding', '--no-hooks', '--no-instructions', '--no-providers', '--oauth-client-id', '--oauth-client-secret', '--only', '--path', '--pglite', '--probe', '--providers', '--pure', '--remove', '--save', '--scope', '--source', '--source-ids', '--surface', '--token', '--url', '--workspace', '--yes'],+ 'setup': ['--accept-capabilities', '--agent', '--auto', '--bearer-token-env-var', '--brain', '--break-lock', '--capture', '--dry-run', '--env', '--force', '--gbrain-bin', '--harness', '--header', '--help', '--http', '--install', '--instructions', '--instructions-only', '--issuer-url', '--json', '--legacy-lock', '--link', '--mcp-only', '--mcp-url', '--name', '--no-capture', '--no-embedding', '--no-hooks', '--no-instructions', '--no-providers', '--oauth-client-id', '--oauth-client-secret', '--only', '--path', '--pglite', '--probe', '--providers', '--pure', '--remove', '--save', '--scope', '--source', '--source-ids', '--surface', '--token', '--url', '--workspace', '--yes'],'skillify': ['--brain', '--description', '--dry-run', '--force', '--help', '--json', '--mutating', '--recent', '--skills-dir', '--source', '--strict', '--triggers', '--writes-pages', '--writes-to'],'skillopt': ['--all', '--allow-mutate-bundled', '--background', '--batch-size', '--benchmark', '--bootstrap-from-routing', '--bootstrap-from-skill', '--bootstrap-reviewed', '--bootstrap-tasks', '--brain', '--brain-wide-max-cost-usd', '--dry-run', '--epochs', '--follow', '--force', '--held-out', '--help', '--json', '--judge-model', '--lr', '--lr-schedule', '--max-cost-usd', '--max-runtime-min', '--max-usd', '--models-strict', '--no-max-cost', '--no-mutate', '--optimizer-model', '--patch', '--reflect-max-tokens', '--resume', '--rewrite', '--skills-dir', '--source', '--split', '--status', '--target-model', '--target-models'],'skillpack': ['--all', '--apply-clean-hunks', '--author', '--auto', '--brain', '--dest', '--dry-run', '--env', '--exit-code', '--fast', '--fix', '--force-unlock', '--format', '--from', '--full', '--harness', '--help', '--homepage', '--json', '--license', '--list', '--minimal', '--name-only', '--no-cache', '--no-lint', '--note', '--out', '--overwrite-local', '--persona', '--probe', '--pure', '--push', '--quick', '--quiet', '--refresh', '--repo', '--schema-pack', '--scope', '--short', '--since', '--skill', '--skills', '--skills-dir', '--skip-doctor', '--source', '--strict', '--stub', '--supabase', '--target', '--tier', '--trust', '--url', '--verify', '--version', '--workspace', '--yes'],diff --git a/src/core/context-engine.ts b/src/core/context-engine.tsindex c24ed8e2b2..528dfc7e48 100644--- a/src/core/context-engine.ts+++ b/src/core/context-engine.ts@@ -22,7 +22,6 @@ import { backupNagReadOnlyConsult, backupNoticeText, loadBackupStatus } from './import { estimateMessageTokens, openClawCoreLane } from './context/openclaw-core.ts';import { TURN_CONTEXT_ENVELOPE } from './context/turn-context-envelope.ts';import { loadContextModule } from './context/load-warning.ts';-import { brainFirstTurnRule } from './setup/brain-first.ts';// Types inlined from openclaw/plugin-sdk to avoid hard dependency during development.// At runtime inside OpenClaw, the real SDK is available; these types ensure build compat.@@ -1384,13 +1383,6 @@ export function createGBrainContextEngine(ctx: {const parts = [contextBlock, ...await openClawCoreLane(workspaceDir, CHECKPOINT_POLL_TIMEOUT_MS).additions({sessionId: sanitizeEngineSessionId(sessionId ?? sessionKey ?? null), messages: msgs, tokenBudget, availableTools })];if (checkpointBlock) parts.push(checkpointBlock);- // The per-turn brain-first rule (brain-first.ts): on unless the block was declined for OpenClaw.- try {- const turnRule = brainFirstTurnRule('openclaw', { kind: 'mcp', server: 'gbrain' });- if (turnRule) parts.push(turnRule);- } catch {- /* a rule must never break context assembly */- }if (memoryAddition) parts.push(memoryAddition);if (reflexAddition) parts.push(reflexAddition);diff --git a/src/core/setup/brain-first.ts b/src/core/setup/brain-first.tsindex 51b46aaf1a..1ec617a0a1 100644--- a/src/core/setup/brain-first.ts+++ b/src/core/setup/brain-first.ts@@ -79,9 +79,10 @@ export function renderBrainFirstSnippet(harness: string, access: BrainFirstAcces/*** The per-turn rule: one line a harness's per-turn hook puts beside every user- * turn (Claude Code and Codex UserPromptSubmit, Hermes pre_llm_call, OpenClaw's- * context engine). An instruction in the system prompt alone left agents- * mostly answering without the brain; the same rule next to the turn did not.+ * turn (Claude Code and Codex UserPromptSubmit, Hermes pre_llm_call, OpenClaw+ * before_prompt_build). The block in the system prompt or identity file alone+ * left chat bots answering without the brain (harness-evals: 0 of 80 on+ * OpenClaw and Hermes); the same rule next to the turn was followed.*/export function renderBrainFirstTurnRule(access: BrainFirstAccess): string {const how = access.kind === 'cli' ? `\`${access.launcher} search "<names>"\` or \`${access.launcher} query "<question>"\``@@ -91,18 +92,15 @@ export function renderBrainFirstTurnRule(access: BrainFirstAccess): string {}/**- * The per-turn rule for one harness, or null. Off under GBRAIN_AGENT_INSTRUCTIONS=0- * and after a recorded decline; an installed block's access names the tools.- * `fallback` is the access for a lane that turns the rule on without a ledger- * entry (OpenClaw's context engine, Hermes's hook); without one, only a- * recorded install turns it on.+ * The per-turn rule the Claude Code and Codex user-prompt hook adds, or null:+ * on only while a block is recorded as installed for that harness (its access+ * names the tools), off under GBRAIN_AGENT_INSTRUCTIONS=0.*/-export function brainFirstTurnRule(harness: string, fallback?: BrainFirstAccess): string | null {+export function brainFirstTurnRule(harness: string): string | null {if (process.env[BRAIN_FIRST_OPT_OUT_ENV] === '0') return null;- const entries = readBrainFirstLedger().filter((e) => e.harness === harness);- const installed = entries.filter((e) => e.status === 'installed' && e.access).sort((a, b) => (a.updated_at < b.updated_at ? 1 : -1))[0];- if (installed) return renderBrainFirstTurnRule(installed.access);- return entries.length === 0 && fallback ? renderBrainFirstTurnRule(fallback) : null;+ const installed = readBrainFirstLedger().filter((e) => e.harness === harness && e.status === 'installed' && e.access)+ .sort((a, b) => (a.updated_at < b.updated_at ? 1 : -1))[0];+ return installed ? renderBrainFirstTurnRule(installed.access) : null;}export const CURSOR_HEAD = '---\ndescription: GBrain memory, managed by gbrain\nalwaysApply: true\n---\n';@@ -132,7 +130,7 @@ export function codexInstructionFile(overridePath: string, agentsPath: string):}/** OpenClaw's state directory: OPENCLAW_STATE_DIR, else ~/.openclaw (or ~/.openclaw-<profile>). */-function openclawStateDir(): string {+export function openclawStateDir(): string {const explicit = process.env.OPENCLAW_STATE_DIR?.trim();if (explicit) return expandHome(explicit);const profile = process.env.OPENCLAW_PROFILE?.trim();diff --git a/src/core/setup/hermes-turn-hook.ts b/src/core/setup/hermes-turn-hook.tsindex d2a893a6e0..c4b778fec5 100644--- a/src/core/setup/hermes-turn-hook.ts+++ b/src/core/setup/hermes-turn-hook.ts@@ -1,9 +1,11 @@/*** hermes-turn-hook.ts — Hermes's native per-turn hook for the brain-first* rule: a marked `hooks.pre_llm_call` shell hook in $HERMES_HOME/config.yaml- * running `<gbrain> hook turn-rule`, whose `{"context": ...}` output Hermes- * appends to every user message. The block in SOUL.md reaches the system- * prompt only; this puts the same rule next to each turn.+ * that echoes `{"context": <rule>}`, which Hermes appends to every user+ * message. The block in SOUL.md reaches the system prompt only, and bots read+ * it as identity; this puts the same rule next to each turn. The command is+ * self-contained (no gbrain process per turn, no path that must exist on the+ * Hermes host), so a re-run after an upgrade rewrites it with the new text.** Ownership is by YAML comment markers; text outside them is never touched.* gbrain appends its block only when config.yaml has no top-level `hooks:`@@ -13,12 +15,12 @@* way `gbrain setup codex` writes its hook trust entries. Removal strips the* block and that approval.*/-import { existsSync, readFileSync, statSync } from 'node:fs';-import { isAbsolute, join } from 'node:path';+import { existsSync, readFileSync } from 'node:fs';+import { join } from 'node:path';import { load } from 'js-yaml';import { atomicWriteTextFile } from '../bootstrap/atomic-write.ts';import { probeBlock, removeBlock, spliceBlock, type BlockMarkers } from '../managed-block.ts';-import { writeUnlessChanged } from './brain-first.ts';+import { renderBrainFirstTurnRule, writeUnlessChanged, type BrainFirstAccess } from './brain-first.ts';const MARKERS: BlockMarkers = { begin: '# gbrain:turn-rule:begin', end: '# gbrain:turn-rule:end', label: 'turn-rule', rerun: 'gbrain setup hermes --instructions-only' };const EVENT = 'pre_llm_call';@@ -26,7 +28,15 @@ const ALLOWLIST = 'shell-hooks-allowlist.json';export interface HermesTurnHookOutcome { action: 'write' | 'keep' | 'print' | 'remove' | 'skip'; path: string; detail: string; snippet?: string }-export const hermesTurnHookCommand = (launcher: string): string => `${launcher} hook turn-rule`;+/** `/bin/echo '<json>'`: Hermes splits the command without a shell (and checks the first path, /bin/echo, exists), and a quote in the rule is a JSON escape. */+export function hermesTurnHookCommand(access: BrainFirstAccess): string {+ return `/bin/echo '${JSON.stringify({ context: renderBrainFirstTurnRule(access) }).replace(/'/g, '\\u0027')}'`;+}++const commandIn = (interior: string | undefined): string | null => {+ const quoted = /command: (".*")/.exec(interior ?? '')?.[1];+ return quoted ? (JSON.parse(quoted) as string) : null;+};function hookYaml(command: string): string {return `hooks:\n ${EVENT}:\n - command: ${JSON.stringify(command)}\n timeout: 10\n`;@@ -49,9 +59,7 @@ function approve(hermesHome: string, command: string): void {const path = join(hermesHome, ALLOWLIST);const list = readAllowlist(path);if (list.approvals.some((e) => approves(e, command))) return;- let mtime: string | null = null;- try { mtime = statSync(command.split(' ')[0]!).mtime.toISOString(); } catch { /* Hermes records null for a missing script too */ }- list.approvals.push({ event: EVENT, command, approved_at: new Date().toISOString(), script_mtime_at_approval: mtime });+ list.approvals.push({ event: EVENT, command, approved_at: new Date().toISOString(), script_mtime_at_approval: null });atomicWriteTextFile(path, `${JSON.stringify(list, null, 2)}\n`, { freshMode: 0o600 });}@@ -64,11 +72,10 @@ function revoke(hermesHome: string, command: string): void {}/** Write or update the hook (accepted decision). Never throws: anything gbrain cannot edit safely is printed to add by hand. */-export function syncHermesTurnHook(opts: { hermesHome: string; launcher: string | null; dryRun: boolean }): HermesTurnHookOutcome {+export function syncHermesTurnHook(opts: { hermesHome: string; access: BrainFirstAccess; dryRun: boolean }): HermesTurnHookOutcome {const path = join(opts.hermesHome, 'config.yaml');- const command = hermesTurnHookCommand(opts.launcher ?? 'gbrain');+ const command = hermesTurnHookCommand(opts.access);const print = (why: string): HermesTurnHookOutcome => ({ action: 'print', path, detail: `${why}; add this to ${path} and approve it when Hermes asks (non-interactive runs: HERMES_ACCEPT_HOOKS=1)`, snippet: hookYaml(command) });- if (!opts.launcher || !isAbsolute(opts.launcher)) return print('no absolute gbrain launcher (pass --gbrain-bin)');if (!existsSync(opts.hermesHome)) return print(`${opts.hermesHome} does not exist yet`);try {const missing = !existsSync(path);@@ -87,6 +94,8 @@ export function syncHermesTurnHook(opts: { hermesHome: string; launcher: string}if (!opts.dryRun) {writeUnlessChanged(path, text, missing, next);+ const previous = commandIn(probe.interior);+ if (previous && previous !== command) revoke(opts.hermesHome, previous);approve(opts.hermesHome, command);}return { action: 'write', path, detail: `per-turn rule hook (${EVENT}) in ${path}, approved in ${ALLOWLIST}` };@@ -103,10 +112,10 @@ export function removeHermesTurnHook(opts: { hermesHome: string; dryRun: booleanconst text = readFileSync(path, 'utf8');const probe = probeBlock(MARKERS, text);if (probe.state !== 'present') return { action: 'skip', path, detail: `no per-turn rule hook in ${path}` };- const quoted = /command: (".*")/.exec(probe.interior ?? '')?.[1];+ const command = commandIn(probe.interior);if (!opts.dryRun) {writeUnlessChanged(path, text, false, removeBlock(MARKERS, text).text);- if (quoted) revoke(opts.hermesHome, JSON.parse(quoted) as string);+ if (command) revoke(opts.hermesHome, command);}return { action: 'remove', path, detail: `per-turn rule hook removed from ${path}` };} catch (e) {diff --git a/src/core/setup/openclaw-turn-plugin.ts b/src/core/setup/openclaw-turn-plugin.tsnew file mode 100644index 0000000000..b125e485b5--- /dev/null+++ b/src/core/setup/openclaw-turn-plugin.ts@@ -0,0 +1,114 @@+/**+ * openclaw-turn-plugin.ts — OpenClaw's native per-turn hook for the+ * brain-first rule: a hook-only OpenClaw plugin whose `before_prompt_build`+ * handler returns the rule as `prependContext`, so it reaches the model next+ * to each user turn. The workspace AGENTS.md block reaches the system prompt+ * only, and bots read it as identity, not as an instruction to call a tool.+ *+ * The plugin is self-contained (the rule text is written into its code; it+ * reads nothing and calls nothing) and lives in <OpenClaw state dir>/gbrain/.+ * Setup installs it with OpenClaw's own CLI, the supported path: a linked+ * install with capability consent, enabled, and+ * `plugins.entries.gbrain-turn-rule.hooks.allowConversationAccess`, which+ * OpenClaw requires of a non-bundled plugin's `before_prompt_build`. With no+ * `openclaw` on PATH, setup writes the plugin and prints those commands.+ */+import { existsSync, mkdirSync, readdirSync, readFileSync, rmdirSync, rmSync } from 'node:fs';+import { dirname, join } from 'node:path';+import { atomicWriteTextFile } from '../bootstrap/atomic-write.ts';+import { bunSpawnSync } from '../spawn.ts';+import { openclawStateDir, renderBrainFirstTurnRule, type BrainFirstAccess } from './brain-first.ts';++export const OPENCLAW_TURN_PLUGIN_ID = 'gbrain-turn-rule';++export interface OpenclawTurnPluginOutcome { action: 'write' | 'keep' | 'print' | 'remove' | 'skip'; path: string; detail: string; commands?: string[] }++export function openclawTurnPluginDir(): string {+ return join(openclawStateDir(), 'gbrain', OPENCLAW_TURN_PLUGIN_ID);+}++const DESCRIPTION = 'Puts the GBrain brain-first rule next to every user turn (managed by gbrain setup openclaw).';++export function openclawTurnPluginFiles(access: BrainFirstAccess): Record<string, string> {+ const rule = renderBrainFirstTurnRule(access);+ return {+ 'package.json': `${JSON.stringify({ name: OPENCLAW_TURN_PLUGIN_ID, version: '1.0.0', private: true, type: 'module', openclaw: { extensions: ['./index.js'] } }, null, 2)}\n`,+ 'openclaw.plugin.json': `${JSON.stringify({ id: OPENCLAW_TURN_PLUGIN_ID, name: 'GBrain turn rule', description: DESCRIPTION, configSchema: { type: 'object', additionalProperties: false } }, null, 2)}\n`,+ 'index.js': [+ '// Managed by gbrain setup openclaw; a re-run rewrites this file. Remove: gbrain setup openclaw --remove',+ `const RULE = ${JSON.stringify(rule)};`,+ 'export default {',+ ` id: ${JSON.stringify(OPENCLAW_TURN_PLUGIN_ID)},`,+ " name: 'GBrain turn rule',",+ ` description: ${JSON.stringify(DESCRIPTION)},`,+ ' register(api) {',+ " api.on('before_prompt_build', () => ({ prependContext: RULE }));",+ ' },',+ '};',+ '',+ ].join('\n'),+ };+}++type Run = (argv: string[]) => { ok: boolean; output: string };++function defaultRun(argv: string[]): { ok: boolean; output: string } {+ const r = bunSpawnSync(argv, { stdin: 'ignore', stdout: 'pipe', stderr: 'pipe', env: process.env, timeout: 120_000 });+ return { ok: r.exitCode === 0, output: `${r.stdout.toString()}${r.stderr.toString()}`.trim() };+}++function findOpenclaw(): string | null {+ try { return Bun.which('openclaw', { PATH: process.env.PATH ?? '' }); } catch { return null; }+}++const installArgv = (bin: string, dir: string): string[][] => [+ [bin, 'plugins', 'install', '--link', dir, '--force', '--accept-capabilities'],+ [bin, 'plugins', 'enable', OPENCLAW_TURN_PLUGIN_ID],+ [bin, 'config', 'set', `plugins.entries.${OPENCLAW_TURN_PLUGIN_ID}.hooks.allowConversationAccess`, 'true'],+];++const shown = (argv: string[]) => argv.map((a) => (/^[\w./:=@-]+$/.test(a) ? a : `'${a.replace(/'/g, `'\\''`)}'`)).join(' ');++/** Write the plugin and install it with OpenClaw's CLI (accepted decision). Never throws. */+export function syncOpenclawTurnPlugin(opts: { access: BrainFirstAccess; dryRun: boolean; openclawBin?: string | null; run?: Run }): OpenclawTurnPluginOutcome {+ const dir = openclawTurnPluginDir();+ const files = openclawTurnPluginFiles(opts.access);+ const bin = opts.openclawBin !== undefined ? opts.openclawBin : findOpenclaw();+ const commands = installArgv(bin ?? 'openclaw', dir);+ const changed = Object.entries(files).some(([name, text]) => {+ try { return readFileSync(join(dir, name), 'utf8') !== text; } catch { return true; }+ });+ if (opts.dryRun) return { action: changed ? 'write' : 'keep', path: dir, detail: `per-turn rule plugin ${OPENCLAW_TURN_PLUGIN_ID} (before_prompt_build) at ${dir}${bin ? ', installed with the openclaw CLI' : ''}` };+ try {+ if (changed) {+ mkdirSync(dir, { recursive: true });+ for (const [name, text] of Object.entries(files)) atomicWriteTextFile(join(dir, name), text, { freshMode: 0o644 });+ }+ } catch (e) {+ return { action: 'print', path: dir, detail: `the plugin could not be written to ${dir} (${(e as Error).message})` };+ }+ if (!bin) return { action: 'print', path: dir, detail: `plugin written to ${dir}; no openclaw on PATH, so run these on the OpenClaw host, then restart the gateway`, commands: commands.map(shown) };+ const run = opts.run ?? defaultRun;+ for (const [i, argv] of commands.entries()) {+ const r = run(argv);+ if (!r.ok) return { action: 'print', path: dir, detail: `\`${shown(argv)}\` failed (${r.output.split('\n').at(-1) ?? 'no output'}); run the rest yourself`, commands: commands.slice(i).map(shown) };+ }+ return { action: changed ? 'write' : 'keep', path: dir, detail: `per-turn rule plugin ${OPENCLAW_TURN_PLUGIN_ID} (before_prompt_build) at ${dir}, installed and enabled; restart the gateway if it is running` };+}++/** Uninstall the plugin and delete its directory (decline or --remove). Never throws. */+export function removeOpenclawTurnPlugin(opts: { dryRun: boolean; openclawBin?: string | null; run?: Run }): OpenclawTurnPluginOutcome {+ const dir = openclawTurnPluginDir();+ if (!existsSync(dir)) return { action: 'skip', path: dir, detail: `no per-turn rule plugin at ${dir}` };+ if (opts.dryRun) return { action: 'remove', path: dir, detail: `per-turn rule plugin ${OPENCLAW_TURN_PLUGIN_ID} at ${dir}` };+ const bin = opts.openclawBin !== undefined ? opts.openclawBin : findOpenclaw();+ const uninstall = [bin ?? 'openclaw', 'plugins', 'uninstall', OPENCLAW_TURN_PLUGIN_ID, '--force'];+ const r = bin ? (opts.run ?? defaultRun)(uninstall) : { ok: false, output: 'no openclaw on PATH' };+ try {+ rmSync(dir, { recursive: true, force: true });+ if (readdirSync(dirname(dir)).length === 0) rmdirSync(dirname(dir));+ } catch { /* the uninstall outcome below is what matters */ }+ return r.ok+ ? { action: 'remove', path: dir, detail: `per-turn rule plugin ${OPENCLAW_TURN_PLUGIN_ID} uninstalled and ${dir} removed` }+ : { action: 'print', path: dir, detail: `${dir} removed; ${r.output.split('\n').at(-1)}, so run this on the OpenClaw host`, commands: [shown(uninstall)] };+}diff --git a/test/brain-first-turn-rule.test.ts b/test/brain-first-turn-rule.test.tsindex baae08b811..9ff383af6d 100644--- a/test/brain-first-turn-rule.test.ts+++ b/test/brain-first-turn-rule.test.ts@@ -2,9 +2,9 @@* The per-turn brain-first rule (src/core/setup/brain-first.ts): one line a* harness's per-turn hook puts beside every user turn. Pins who gets it and* when it is off: Claude Code / Codex UserPromptSubmit (only while a block is- * installed for that harness), Hermes `gbrain hook turn-rule` and the- * config.yaml hook setup writes for it, OpenClaw's context engine (on unless- * declined), and the opt-out for all of them.+ * installed for that harness), the self-contained Hermes pre_llm_call hook+ * setup writes into config.yaml, the hook-only OpenClaw plugin setup installs+ * with OpenClaw's CLI, and the opt-out.*/import { afterAll, describe, expect, test } from 'bun:test';import { existsSync, mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from 'node:fs';@@ -14,8 +14,8 @@ import { load } from 'js-yaml';import { withEnv } from './helpers/with-env.ts';import { brainFirstTurnRule, renderBrainFirstTurnRule, type BrainFirstAccess } from '../src/core/setup/brain-first.ts';import { runHook } from '../src/commands/hook.ts';-import { createGBrainContextEngine } from '../src/core/context-engine.ts';-import { removeHermesTurnHook, syncHermesTurnHook } from '../src/core/setup/hermes-turn-hook.ts';+import { hermesTurnHookCommand, removeHermesTurnHook, syncHermesTurnHook } from '../src/core/setup/hermes-turn-hook.ts';+import { OPENCLAW_TURN_PLUGIN_ID, openclawTurnPluginDir, removeOpenclawTurnPlugin, syncOpenclawTurnPlugin } from '../src/core/setup/openclaw-turn-plugin.ts';const roots: string[] = [];afterAll(() => { for (const r of roots) rmSync(r, { recursive: true, force: true }); });@@ -54,22 +54,19 @@ describe('per-turn rule: text and decision', () => {expect(renderBrainFirstTurnRule({ kind: 'cli', launcher: '/opt/gbrain' })).toContain('`/opt/gbrain search "<names>"`');});- test('a recorded install turns it on with its access; a decline or the opt-out turns it off, fallback or not', async () => {- const fallback: BrainFirstAccess = { kind: 'mcp', server: 'gbrain' };+ test('a recorded install turns it on with its access; no record, a decline or the opt-out turns it off', async () => {await withEnv(env(home(null)), async () => {expect(brainFirstTurnRule('claude-code')).toBeNull();- expect(brainFirstTurnRule('openclaw', fallback)).toBe(renderBrainFirstTurnRule(fallback));});await withEnv(env(home([{ harness: 'claude-code', status: 'installed', access: { kind: 'mcp', server: 'brain', surface: 'verbs' } }])), async () => {expect(brainFirstTurnRule('claude-code')).toBe(renderBrainFirstTurnRule({ kind: 'mcp', server: 'brain', surface: 'verbs' }));expect(brainFirstTurnRule('codex')).toBeNull();});await withEnv(env(home([{ harness: 'openclaw', status: 'declined' }])), async () => {- expect(brainFirstTurnRule('openclaw', fallback)).toBeNull();+ expect(brainFirstTurnRule('openclaw')).toBeNull();});await withEnv(env(home([{ harness: 'claude-code', status: 'installed' }]), { GBRAIN_AGENT_INSTRUCTIONS: '0' }), async () => {expect(brainFirstTurnRule('claude-code')).toBeNull();- expect(brainFirstTurnRule('openclaw', fallback)).toBeNull();});});});@@ -100,50 +97,9 @@ describe('per-turn rule: Claude Code and Codex user-prompt hook', () => {});});-describe('per-turn rule: Hermes turn-rule hook', () => {- async function turnRule(root: string, extra: Record<string, string | undefined> = {}): Promise<string> {- let out = '';- await withEnv(env(root, extra), async () => {- expect(await runHook(['turn-rule'], { write: (s) => { out += s; } })).toBe(0);- });- return out;- }-- test('prints Hermes\'s {"context": ...} wire shape by default and with an installed block', async () => {- expect(JSON.parse(await turnRule(home(null)))).toEqual({ context: renderBrainFirstTurnRule({ kind: 'mcp', server: 'gbrain' }) });- expect(JSON.parse(await turnRule(home([{ harness: 'hermes', status: 'installed', access: { kind: 'mcp', server: 'brain' } }])))).toEqual({ context: renderBrainFirstTurnRule({ kind: 'mcp', server: 'brain' }) });- });-- test('prints nothing after a decline, under the opt-out or with hooks off', async () => {- expect(await turnRule(home([{ harness: 'hermes', status: 'declined' }]))).toBe('');- expect(await turnRule(home(null), { GBRAIN_AGENT_INSTRUCTIONS: '0' })).toBe('');- expect(await turnRule(home(null), { GBRAIN_HOOKS: '0' })).toBe('');- });-});--describe('per-turn rule: OpenClaw context engine', () => {- async function addition(root: string, extra: Record<string, string | undefined> = {}): Promise<string> {- const ws = mkdtempSync(join(tmpdir(), 'gbrain-turn-rule-ws-'));- roots.push(ws);- let text = '';- await withEnv(env(root, extra), async () => {- const result = await createGBrainContextEngine({ workspaceDir: ws }).assemble({ sessionId: 's1', messages: [], tokenBudget: 100000 });- text = result.systemPromptAddition ?? '';- });- return text;- }-- test('every assemble carries the rule unless OpenClaw\'s block was declined or the opt-out is set', async () => {- const rule = renderBrainFirstTurnRule({ kind: 'mcp', server: 'gbrain' });- expect(await addition(home(null))).toContain(rule);- expect(await addition(home([{ harness: 'openclaw', status: 'declined' }]))).not.toContain('check GBrain first');- expect(await addition(home(null), { GBRAIN_AGENT_INSTRUCTIONS: '0' })).not.toContain('check GBrain first');- });-});-describe('per-turn rule: Hermes pre_llm_call hook in config.yaml', () => {- const launcher = '/opt/gbrain/bin/gbrain';- const cmd = `${launcher} hook turn-rule`;+ const access: BrainFirstAccess = { kind: 'mcp', server: 'gbrain' };+ const cmd = hermesTurnHookCommand(access);function hermes(config?: string, approvals: unknown[] = []): string {const dir = mkdtempSync(join(tmpdir(), 'gbrain-hermes-home-'));roots.push(dir);@@ -154,16 +110,27 @@ describe('per-turn rule: Hermes pre_llm_call hook in config.yaml', () => {const cfg = (d: string) => readFileSync(join(d, 'config.yaml'), 'utf8');const approvals = (d: string) => JSON.parse(readFileSync(join(d, 'shell-hooks-allowlist.json'), 'utf8')).approvals as Array<Record<string, unknown>>;+ test('the command echoes Hermes\'s {"context": ...} wire shape on its own: no shell, no gbrain process', () => {+ const quoted: BrainFirstAccess = { kind: 'cli', launcher: "/opt/it's/gbrain" };+ const c = hermesTurnHookCommand(quoted);+ expect(c.startsWith("/bin/echo '")).toBe(true);+ expect(c.endsWith("'")).toBe(true);+ const inner = c.slice("/bin/echo '".length, -1);+ expect(inner).not.toContain("'");+ expect(JSON.parse(inner)).toEqual({ context: renderBrainFirstTurnRule(quoted) });+ expect(JSON.parse(cmd.slice("/bin/echo '".length, -1))).toEqual({ context: renderBrainFirstTurnRule(access) });+ });+test('appends a marked hook after the user\'s text, approves exactly that command, keeps on a re-run, and removal undoes both', () => {const mine = '# my config\nmodel:\n default: alice-example-model\n';const other = { event: 'pre_tool_call', command: '/usr/bin/true', approved_at: 'x', script_mtime_at_approval: null };const d = hermes(mine, [other]);- expect(syncHermesTurnHook({ hermesHome: d, launcher, dryRun: false }).action).toBe('write');+ expect(syncHermesTurnHook({ hermesHome: d, access, dryRun: false }).action).toBe('write');const text = cfg(d);expect(text.startsWith(mine)).toBe(true);expect(load(text)).toEqual({ model: { default: 'alice-example-model' }, hooks: { pre_llm_call: [{ command: cmd, timeout: 10 }] } });- expect(approvals(d)).toEqual([other, expect.objectContaining({ event: 'pre_llm_call', command: cmd })]);- expect(syncHermesTurnHook({ hermesHome: d, launcher, dryRun: false }).action).toBe('keep');+ expect(approvals(d)).toEqual([other, expect.objectContaining({ event: 'pre_llm_call', command: cmd, script_mtime_at_approval: null })]);+ expect(syncHermesTurnHook({ hermesHome: d, access, dryRun: false }).action).toBe('keep');expect(cfg(d)).toBe(text);expect(approvals(d)).toHaveLength(2);expect(removeHermesTurnHook({ hermesHome: d, dryRun: false }).action).toBe('remove');@@ -171,33 +138,99 @@ describe('per-turn rule: Hermes pre_llm_call hook in config.yaml', () => {expect(approvals(d)).toEqual([other]);});- test('a new launcher path rewrites the block in place', () => {+ test('new rule text rewrites the block in place and moves the approval to the new command', () => {const d = hermes('');- syncHermesTurnHook({ hermesHome: d, launcher, dryRun: false });- expect(syncHermesTurnHook({ hermesHome: d, launcher: '/usr/local/bin/gbrain', dryRun: false }).action).toBe('write');- expect(load(cfg(d))).toEqual({ hooks: { pre_llm_call: [{ command: '/usr/local/bin/gbrain hook turn-rule', timeout: 10 }] } });+ syncHermesTurnHook({ hermesHome: d, access, dryRun: false });+ const next: BrainFirstAccess = { kind: 'mcp', server: 'brain', surface: 'verbs' };+ expect(syncHermesTurnHook({ hermesHome: d, access: next, dryRun: false }).action).toBe('write');+ expect(load(cfg(d))).toEqual({ hooks: { pre_llm_call: [{ command: hermesTurnHookCommand(next), timeout: 10 }] } });+ expect(approvals(d).map((a) => a.command)).toEqual([hermesTurnHookCommand(next)]);});- test('prints the entry instead of editing: a hooks: section of the user\'s, no absolute launcher, no Hermes home, damaged markers', () => {+ test('prints the entry instead of editing: a hooks: section of the user\'s, no Hermes home, damaged markers', () => {const theirs = 'hooks:\n pre_tool_call:\n - command: /usr/bin/true\n';const d = hermes(theirs);- const o = syncHermesTurnHook({ hermesHome: d, launcher, dryRun: false });+ const o = syncHermesTurnHook({ hermesHome: d, access, dryRun: false });expect(o.action).toBe('print');- expect(o.snippet).toContain(`- command: "${cmd}"`);+ expect(o.snippet).toContain(`- command: ${JSON.stringify(cmd)}`);expect(cfg(d)).toBe(theirs);expect(existsSync(join(d, 'shell-hooks-allowlist.json'))).toBe(false);- expect(syncHermesTurnHook({ hermesHome: hermes(''), launcher: null, dryRun: false }).action).toBe('print');- expect(syncHermesTurnHook({ hermesHome: hermes(''), launcher: 'gbrain', dryRun: false }).action).toBe('print');- expect(syncHermesTurnHook({ hermesHome: join(tmpdir(), 'gbrain-no-such-hermes-home'), launcher, dryRun: false }).action).toBe('print');+ expect(syncHermesTurnHook({ hermesHome: join(tmpdir(), 'gbrain-no-such-hermes-home'), access, dryRun: false }).action).toBe('print');const damaged = hermes('# gbrain:turn-rule:begin\nmodel: x\n');- expect(syncHermesTurnHook({ hermesHome: damaged, launcher, dryRun: false }).action).toBe('print');+ expect(syncHermesTurnHook({ hermesHome: damaged, access, dryRun: false }).action).toBe('print');expect(cfg(damaged)).toBe('# gbrain:turn-rule:begin\nmodel: x\n');});test('dry-run writes nothing', () => {const d = hermes('model: x\n');- expect(syncHermesTurnHook({ hermesHome: d, launcher, dryRun: true }).action).toBe('write');+ expect(syncHermesTurnHook({ hermesHome: d, access, dryRun: true }).action).toBe('write');expect(cfg(d)).toBe('model: x\n');expect(existsSync(join(d, 'shell-hooks-allowlist.json'))).toBe(false);});});++describe('per-turn rule: OpenClaw before_prompt_build plugin', () => {+ const access: BrainFirstAccess = { kind: 'mcp', server: 'gbrain' };+ function state(): string {+ const dir = mkdtempSync(join(tmpdir(), 'gbrain-openclaw-state-'));+ roots.push(dir);+ return dir;+ }+ function recorder(fail?: string) {+ const calls: string[][] = [];+ return { calls, run: (argv: string[]) => { calls.push(argv); return argv.includes(fail ?? '\0') ? { ok: false, output: 'boom' } : { ok: true, output: '' }; } };+ }++ test('writes a self-contained hook-only plugin and installs it with the openclaw CLI; a re-run keeps it', async () => {+ const st = state();+ await withEnv({ OPENCLAW_STATE_DIR: st, OPENCLAW_PROFILE: undefined }, async () => {+ const dir = openclawTurnPluginDir();+ expect(dir).toBe(join(st, 'gbrain', OPENCLAW_TURN_PLUGIN_ID));+ const rec = recorder();+ const o = syncOpenclawTurnPlugin({ access, dryRun: false, openclawBin: '/bin/openclaw', run: rec.run });+ expect(o.action).toBe('write');+ expect(rec.calls).toEqual([+ ['/bin/openclaw', 'plugins', 'install', '--link', dir, '--force', '--accept-capabilities'],+ ['/bin/openclaw', 'plugins', 'enable', OPENCLAW_TURN_PLUGIN_ID],+ ['/bin/openclaw', 'config', 'set', `plugins.entries.${OPENCLAW_TURN_PLUGIN_ID}.hooks.allowConversationAccess`, 'true'],+ ]);+ expect(JSON.parse(readFileSync(join(dir, 'openclaw.plugin.json'), 'utf8'))).toMatchObject({ id: OPENCLAW_TURN_PLUGIN_ID, configSchema: { type: 'object' } });+ expect(JSON.parse(readFileSync(join(dir, 'package.json'), 'utf8')).openclaw).toEqual({ extensions: ['./index.js'] });+ const mod = await import(join(dir, 'index.js'));+ const handlers: Record<string, () => unknown> = {};+ mod.default.register({ on: (event: string, fn: () => unknown) => { handlers[event] = fn; } });+ expect(Object.keys(handlers)).toEqual(['before_prompt_build']);+ expect(handlers.before_prompt_build()).toEqual({ prependContext: renderBrainFirstTurnRule(access) });+ expect(syncOpenclawTurnPlugin({ access, dryRun: false, openclawBin: '/bin/openclaw', run: recorder().run }).action).toBe('keep');+ });+ });++ test('no openclaw on PATH or a failed command: the plugin is written and the remaining commands are printed', async () => {+ await withEnv({ OPENCLAW_STATE_DIR: state(), OPENCLAW_PROFILE: undefined }, async () => {+ const o = syncOpenclawTurnPlugin({ access, dryRun: false, openclawBin: null });+ expect(o.action).toBe('print');+ expect(o.commands?.[0]).toBe(`openclaw plugins install --link ${openclawTurnPluginDir()} --force --accept-capabilities`);+ expect(o.commands).toHaveLength(3);+ expect(existsSync(join(openclawTurnPluginDir(), 'index.js'))).toBe(true);+ const failed = syncOpenclawTurnPlugin({ access, dryRun: false, openclawBin: '/bin/openclaw', run: recorder('enable').run });+ expect(failed.action).toBe('print');+ expect(failed.commands).toEqual([`/bin/openclaw plugins enable ${OPENCLAW_TURN_PLUGIN_ID}`, `/bin/openclaw config set plugins.entries.${OPENCLAW_TURN_PLUGIN_ID}.hooks.allowConversationAccess true`]);+ });+ });++ test('dry-run writes and runs nothing; removal uninstalls and deletes the directory and its empty parent', async () => {+ const st = state();+ await withEnv({ OPENCLAW_STATE_DIR: st, OPENCLAW_PROFILE: undefined }, async () => {+ const rec = recorder();+ expect(syncOpenclawTurnPlugin({ access, dryRun: true, openclawBin: '/bin/openclaw', run: rec.run }).action).toBe('write');+ expect(rec.calls).toEqual([]);+ expect(existsSync(openclawTurnPluginDir())).toBe(false);+ expect(removeOpenclawTurnPlugin({ dryRun: false, openclawBin: '/bin/openclaw', run: rec.run }).action).toBe('skip');+ syncOpenclawTurnPlugin({ access, dryRun: false, openclawBin: '/bin/openclaw', run: rec.run });+ const gone = recorder();+ expect(removeOpenclawTurnPlugin({ dryRun: false, openclawBin: '/bin/openclaw', run: gone.run }).action).toBe('remove');+ expect(gone.calls).toEqual([['/bin/openclaw', 'plugins', 'uninstall', OPENCLAW_TURN_PLUGIN_ID, '--force']]);+ expect(existsSync(join(st, 'gbrain'))).toBe(false);+ });+ });+});diff --git a/test/setup-brain-first.test.ts b/test/setup-brain-first.test.tsindex c980f1fa26..046c92382c 100644--- a/test/setup-brain-first.test.ts+++ b/test/setup-brain-first.test.ts@@ -16,6 +16,7 @@ import { afterAll, describe, expect, test } from 'bun:test';import { chmodSync, existsSync, lstatSync, mkdirSync, mkdtempSync, readFileSync, rmSync, symlinkSync, writeFileSync } from 'node:fs';import { tmpdir } from 'node:os';import { dirname, join, resolve } from 'node:path';+import { load } from 'js-yaml';import { runCli } from './helpers/cli-spawn.ts';import { withEnv } from './helpers/with-env.ts';import {@@ -239,7 +240,9 @@ describe('brain-first block: placement rules', () => {const config = () => read(join(b.home, '.hermes', 'config.yaml'));const first = await setup(b, ['hermes', '--gbrain-bin', b.bin]);expect(first.doc.turn_hook).toMatchObject({ action: 'write', path: join(b.home, '.hermes', 'config.yaml') });- expect(config()).toContain(` pre_llm_call:\n - command: ${JSON.stringify(`${b.bin} hook turn-rule`)}`);+ const hook = (load(config()) as any).hooks.pre_llm_call[0];+ expect(hook.command.startsWith("/bin/echo '")).toBe(true);+ expect(JSON.parse(hook.command.slice("/bin/echo '".length, -1)).context).toContain('check GBrain first');expect(read(join(b.home, '.hermes', 'SOUL.md'))).toContain(BRAIN_FIRST_BEGIN);const declined = await setup(b, ['hermes', '--no-instructions']);expect(declined.doc.turn_hook.action).toBe('remove');@@ -250,6 +253,32 @@ describe('brain-first block: placement rules', () => {expect(config()).toBe('model:\n default: x\n');});+ test('openclaw: setup writes the before_prompt_build plugin and installs it with the openclaw CLI; the opt-out and --remove uninstall it', async () => {+ const b = box();+ mkdirSync(join(b.home, '.openclaw', 'workspace'), { recursive: true });+ const log = join(b.root, 'openclaw.log');+ writeFileSync(join(b.root, 'bin', 'openclaw'), `#!/bin/sh\necho "$*" >> '${log}'\n`);+ chmodSync(join(b.root, 'bin', 'openclaw'), 0o755);+ const path = { PATH: `${join(b.root, 'bin')}:${process.env.PATH ?? ''}` };+ const dir = join(b.home, '.openclaw', 'gbrain', 'gbrain-turn-rule');+ const first = await setup(b, ['openclaw'], path);+ expect(first.doc.turn_hook).toMatchObject({ action: 'write', path: dir });+ expect(read(join(dir, 'index.js'))).toContain('before_prompt_build');+ expect(read(log).trim().split('\n')).toEqual([+ `plugins install --link ${dir} --force --accept-capabilities`,+ 'plugins enable gbrain-turn-rule',+ 'config set plugins.entries.gbrain-turn-rule.hooks.allowConversationAccess true',+ ]);+ const declined = await setup(b, ['openclaw', '--no-instructions'], path);+ expect(declined.doc.turn_hook.action).toBe('remove');+ expect(existsSync(dir)).toBe(false);+ expect(read(log).trim().split('\n').at(-1)).toBe('plugins uninstall gbrain-turn-rule --force');+ await setup(b, ['openclaw', '--instructions'], path);+ expect(existsSync(dir)).toBe(true);+ expect((await setup(b, ['openclaw', '--remove'], path)).doc.turn_hook.action).toBe('remove');+ expect(existsSync(join(b.home, '.openclaw', 'gbrain'))).toBe(false);+ });+test('a damaged block is preserved and reported, never guessed through', async () => {const b = box();const path = join(b.home, '.claude', 'CLAUDE.md');