Garry's Opinionated OpenClaw/Hermes Agent Brain
Key files: Commands (5/6)
Subsystem index. Read only the entries relevant to your change. Current behavior and load-bearing invariants; history belongs in Git and CHANGELOG.
src/commands/repair.ts—gbrain repair [<kind>] [--apply] [--source <id>] [--limit <n>] [--no-embed] [--json]andgbrain repair --all. Kindstimeline(#5567 materialize),visibility(#5525 tighten-only backfill)safe-chunks(#5050/#5247 projection-only re-seal of pages of every kind below the safe-chunk fence;--no-embeddefers embedding toembed --stale),contextual-mode(#5621 projection-only stamp of the import-time contextual retrieval mode on pages that have none; honors--no-embed)connector-checkpoints(#5686 brain-wide cleanup of connector checkpoint rows no source can load),take-supersession(#5886 relinks takes supersession chains from journal, stored-pointer or forced fence-structure evidence; ambiguous pages are reported with the manual edit, never rewritten;src/core/repair/take-supersession.ts),orphan-bindings(#5732 brain-wide cleanup of persistence source bindings whose source or incarnation is gone) andembedding-effects(#5629/#5734 settlement of stale queued and failed embedding effects: reconciled, superseded, retry_queued or blocked, reported per item inoutcomes/outcome_items) andgoogle-file-modes(clears group/other bits on gbrain's own files under Google source dirs outside~/.gbrain; filesystem only); no kind previews every kind. Dry run unless--apply(no prompt;--yesrefused).gbrain repair fences [--only <path>]... [--skip <path>]... [--slug <slug>]... [--diff] [--no-llm] [--max-usd <n>] [--apply [--expect <hash>]]repairs malformed facts and takes fences (#6188,src/core/repair/fences.ts).parseRepairArgsis strict: any unknown option or a second positional refusesinvalid_paramsbefore anything runs; flags a kind does not take name the kinds that do (--only/--skip/--diff: frontmatter, fences;--slug: fences;--yes: frontmatter);--expectis accepted for explicit-only and preview-bound kinds,--include-ambiguousfor explicit-only kinds;--max-usd <n>and--no-llm... (line truncated to 2000 chars)src/commands/repair-content.ts—gbrain repair content [--source <id>] [--only <path>]... [--skip <path>]... [--no-llm] [--max-usd <n>] [--diff] [--apply [--expect <h1>[,<h2>]]] [--json](#6377): the content-repair lane as one command.contentis parsed byrepair.ts's strict flag grammar like a kind (CONTENT_LANE;--only/--skip/--diff,--no-llm,--max-usdand--expectare accepted for it,--slug,--yes,--include-ambiguousand--allrefuse) and dispatched before the kind check; it is a lane, not aRepairKind: no registry entry, no cursor of its own, listed under "Lanes:" inREPAIR_HELP.runRepairContentCommandresolves the scope, runsrunContentLaneand prints each kind's result throughrenderRepairResultplus a lane line (spend, allowance left, each kind's hash, every stop, the apply command);--jsonprints{ lane, scope, mode, kinds, results[] (withpaid), preview_hashes, cost, stopped, paid_kinds, apply_command }. A kind's stop sets exit verdict 1; a wrong--expectcount isinvalid_paramswith the preview as its fix. Test:test/repair-content.test.ts.src/commands/reindex.ts—gbrain reindex --markdown [--type PAGE_TYPE] [--limit N] [--workers N] [--dry-run] [--json] [--no-embed] [--yes] [--max-usd USD] [--repo PATH]. W4.5: re-embedding is paid, sorunReindex(engine, args, { authorized?, interactive? })callsrequireReindexConsent(src/core/reindex-consent.ts) after the dry-run return and before the managed dispatch for every caller unless--no-embedorauthorized(the upgrade path's TTY yes, the job handler's stored spend record);src/cli/commands/reindex.tsrenders the exit-3 consent refusal andcost_cap_exceeded. The approved finite cap runs the inline pass (and the managed dispatch) under aBudgetTrackerviawithBudgetTracker; once it is exhausted (an import swallows the refused embedding) the loop stops at the next page andreportBudgetStopexits 1 withbudget_exhaustedin--json.countPendingis exported forjobs submit reindexand the mode-switch prompt. The writer pool is sized once from the run's page target (pending, capped by--limit) throughresolveWorkersWithClamp, so Postgres runs over 100 pages default toDEFAULT_PARALLEL_WORKERSwhile PGLite stays at one;--workersoverrides and the used count is reported asworkersin the result and JSON (pinned bytest/e2e/reindex-auto-workers-5181.test.ts). Walks markdown pages with stalechunker_version(plus unstamped contextual-retrieval mode when embedding is enabled;--no-embedstill stamps the mode of every page it re-chunks) in 100-row id-keyset batches; a failed row cannot starve later batches in the same invocation.--typeadds a bound-parameterpages.type = $Nscope for focused backfills such as atom pages and is rejected by reindex modes that do not consume it. Current-version chunkless healing deliberately remains owned by the native, boundedembed --stalepath. Rows with non-nullsource_pathre-import viaimportFromFile; rows without fall back toimportFromContent. Both paths pass `force... (line truncated to 2000 chars)src/commands/repair-jsonb.ts—gbrain repair-jsonb [--dry-run] [--json]: rewritesjsonb_typeof='string'rows in place across 8 affected columns (pages.frontmatter, raw_data.data, ingest_log.pages_updated, files.metadata, page_versions.frontmatter, subagent_messages.content_blocks, subagent_tool_executions.input, subagent_tool_executions.output). The subagent targets arejsonPayloadOnly: those columns can legitimately hold jsonb string scalars (persistToolExec binds a tool's pre-serialized string payload as-is), so their damage predicate additionally requires container-shaped content (^\s*[\[{]) thatgbrain_try_jsonb(...)(jsonb or NULL; portable to Postgres 15, unlike thepg_input_is_validit replaced, #7112) actually parses — a plain-text value that merely starts with[or{is never flagged or corrupted. Targets whose table doesn't exist on the brain are skipped viato_regclass(brains without the subagent tables), and one target's failure is recorded on stderr while the run continues — earlier repairs are already committed and the v0_12_2 migration orchestrator JSON-parses stdout.runDoctor'sjsonb_integritycheck counts damage with the same predicate over the same target list. Repairs double-encoded rows on Postgres; PGLite no-ops. Idempotent. Pinned bytest/repair-jsonb.test.ts+test/doctor.test.ts.src/commands/report.ts— Structured report saver (audit trail for maintenance/enrichment). Pages carrytype: note+report_type: <name>(a type the default pack declares; the dream drift report uses the same shape)src/commands/routing-eval.ts+src/core/routing-eval.ts—gbrain routing-evalcatches user phrasings that route to the wrong skill. Readsskills/<name>/routing-eval.jsonlfixtures ({intent, expected_skill, ambiguous_with?}). Structural layer runs incheck-resolvableby default (zero API cost).--llmis a placeholder for a future LLM tie-break layer; today it emits a stderr notice and runs structural only. UsesautoDetectSkillsDirReadOnlyand the same multi-file resolver merge ascheck-resolvable, so on OpenClaw layouts (skills/RESOLVER.md+../AGENTS.md) all three commands see the same trigger index. RESOLVER.md rows carry the full frontmattertriggers:arrays so the structural matcher sees realistic phrasings; ambiguous-fixture annotations cover deliberate skill chains likeenrich → article-enrichment.src/commands/salience.ts—gbrain salience [--days N] [--limit N] [--kind PREFIX] [--json]: pages ranked by emotional + activity salience over a recency window. Mirrors orphans.ts shape (pure data fn + JSON formatter + human formatter). Callsengine.getRecentSalience(opts). Score formula:(emotional_weight × 5) + ln(1 + active_take_count) + 1/(1 + days_since_update).src/commands/search-diagnose.ts—gbrain search diagnose "<query>" --target <slug> [--json] [--source <id>]: Phase-0 retrieval diagnostic. Traces WHERE a target page surfaces (or fails to) across keyword / vector (per-page max-pool) / alias / hybrid layers and names the layer responsible for an incident, so an operator can pin whether the fix is max-pool/innerLimit (vector) vs title/alias. The verdict names the layer that DOES surface the target (or "none"). Pinned bytest/search/search-diagnose.test.ts.src/commands/search.ts:gbrain search stats—rerank_gatesection (eligible, graded, would_skip andwould_skip_rateover graded, provider_calls,by_reason,ineligibleby why), read from the reserved(date, 'rerank_gate', <counter>)rows ofsearch_telemetry(no DDL; diverted out oftotal_callslike the empty-result rows; written only whensearch.reranker.gateis notoff; cache hits add nothing); human output prints it when anything was graded.graph_signalssection (enabled/source/failures_count/failures_by_reason). JSON envelope adds agraph_signalssibling property;_meta.metric_glossaryaddsgraph_signals.enabled+graph_signals.failures_by_reason. Human output prints the section after the existing block. Readssearch.graph_signalsconfig first, falls back to the mode default. Pinned bytest/search/search-stats-graph-signals.test.ts. Bothgbrain search statsandgbrain search tunealso surface acoveragedisclosure (JSON:{cli_invocations: 'recorded_on_clean_exit', reason}; human: a one-line caveat) sourced fromtelemetryCoverage()/TELEMETRY_COVERAGE_CAVEATinsrc/core/search/telemetry.ts: a short-lived CLI call's buffer flushes during the bounded CLI teardown drain, so a CLEAN exit is recorded; hard kills, drains that exceed their bound, and anything buffered when an engine disconnects outside the CLI teardown path still drop — the disclosure is display-only and reads its truth from the telemetry module's single-source constants. Pinned by the coverage-disclosure tests intest/commands-search.test.ts.gbrain search tune --applywrites in order and stops at the first write that did not land; a thrown write is reconciled by re-reading its key (appliedwhen the target value is there,failedwhen not,outcome_unknownwhen the read fails too). JSON lists only landed changes inappliedandrevert_commands, adds per-itemresults,not_appliedandapply_error, and the command rethrows the write error (no... (line truncated to 2000 chars)src/commands/serve-http-grants.ts+admin/src/components/ClientGrant.tsx— typed admin grant request validation and shared profile/advanced permission editor. Register/rescope/TTL routes inserve-http-registration.ts,serve-http-grants.ts, andserve-http-admin-api.tsuse canonical grant validation and audit; legacy response shapes remain available. Registration and permission-edit failures add safe classifications, stage, outcome and inspection remedies; an unacknowledged mutation stays outcome-unknown, while read/preview failures and known refusals remain failed. New UI creation defaults to memory-writer and requires a preview, while edits carry the displayed revision and require a fresh preview after any field change or conflict. Detail/catalog endpoints expose non-secret grants and the shared harness registry. Operation authority snapshots, source sets, delegated tools/namespaces, spend, concurrency, and future TTL are independently reviewable; profile regrant is explicit.admin/src/pages/Agents.tsxpreviews machine/public PKCE/confidential PKCE registration and current permissions, and exposes versioned lifecycle actions. Explicit downloads select machineHarnessCredentialsor nativeOAuthClientSetup; mixed clients require a flow choice. Loading errors preserve stale rows with Retry and disable creation when required source metadata is missing. Browser downloads and native connection evidence remain distinct. Rebuild committedadmin/distandsrc/admin-embedded.tsafter SPA edits.src/commands/serve-http.ts— Express 5 HTTP MCP server with OAuth 2.1, admin dashboard, and SSE live activity feed. The legacyPOST /ingestqueue refuses operation-snapshot clients; they use approved MCP writes so execution stays inside the shared grant contract. Started viagbrain serve --http [--port N] [--token-ttl N] [--enable-dcr] [--public-url URL] [--bind HOST] [--log-full-params]. OAuth discovery'sscopes_supported(RFC 8414 AS metadata and both RFC 9728 protected-resource documents, one value through the SDK router) comes fromscopesSupportedForDiscovery({ enableDcr })insrc/core/scope.ts: with--enable-dcrit is exactly the self-registration ceiling (read write), so a client that copies discovery into its/registerrequest succeeds; without DCR it is every scope except operator-onlyagent. The DCR ceiling still rejects an explicit privileged request, and operator-registered clients are never narrowed by the advertisement. Combines MCP SDK'smcpAuthRouter(authorize/token/register/revoke), a customclient_credentialshandler running BEFORE the router (SDK's token endpoint throwsUnsupportedGrantTypeErrorfor CC; custom handler falls through forauth_code/refresh_token),requireBearerAuthmiddleware for/mcpwith scope enforcement +localOnlyrejection before op dispatch, and per-IPexpress-rate-limitbuckets: the MCP SDK's defaults on/authorize(100 / 15 min),/register(20 / hour) and/token(50 / 15 min) becauseauthRouterOptionspasses norateLimit: false, the customclient_credentialshandler'sccRateLimiter, and independent owner limits: 60 total authentication requests/min/IP, 10 failed authentications/min/IP (verified authority, independent of response status), and 60 consent requests/min/authenticated session inserve-http-admin-limits.ts. Admin no-store, no-referrer and framing headers precede login/link handlers. Explicit pending IDs survive fresh-browser links; invalid or restarted reque... (line truncated to 2000 chars) Layout:runServeHttpbinds throughlistenOrRefuse(serve-http-listen.ts:serve_port_in_useon a taken port; withoptions.adoptServerfrom status-only recovery it hands the app to the already-bound listener instead of binding).buildServeHttpAppbuilds one sharedServeHttpContext(sessions, nonce stores, limiters,requireAdmin, SSE fan-out, OAuth provider, resource verifier, non-localOnlyop list) and mounts in registration orderserve-http-oauth.ts(CORS gates, DCR TTL hook, confidential credentials, SDK router, discovery, owner login links, consent),serve-http-metrics.ts(/health,/metrics, probes),serve-http-admin-api.ts(requireAdmin,/admin/login,/admin/api/*,/admin/events),serve-http-spa.ts,serve-http-mcp.ts(/mcp; writes[gbrain-serve] dispatch op=<name> args_sha256=<16 hex>to stderr before each tool call so a stall's last line names its request, never the arguments) andserve-http-webhooks.ts(/ingest, which maps a legacy-authoritypermission_deniedfrom submission to 409{error, message, hint, docs_url}(test/serve-http-ingest-legacy.test.ts), answers 429ingest_backlog_fullwhen the 50-capture waiting cap hands back another job, and every other submission error to 500;legacyIngestJobanswers a retried POST /ingest recorded under the pre-v0.60.609.0 key (no slug) when that row's slug matches (test/serve-http-ingest-legacy-key-retry.test.ts,test/e2e/serve-http-ingest-legacy-key-retry-postgres.test.ts); the queue key dedupes only while the job row exists, and theingest_capturehandler (minions/handlers/ingest-capture.ts) applies a capture once per job idempotency key for 90 days throughingest_applied_captures(ingestion/applied-captures.ts, migration v296), even aftergbrain jobs prune: the row is inserted in the page write's transaction (importFromContent'sbeforeCommit; a run that loses the insert rolls its write back and returns the stored result) or after a committed m... (line truncated to 2000 chars)src/commands/serve.ts—gbrain servestdio MCP entrypoint with idempotent shutdown across every parent-disconnect signal. Surface: stdio resolvesGBRAIN_SURFACE>--surface> config > full (resolveStdioSurface; an invalid env value is ignored with a stderr line and handed tostartMcpServerasinvalidSurfaceEnv),--httpresolves--surface> config > full and says on stderr that it ignoresGBRAIN_SURFACE; both printsurface=<x> (source: …)at start.--http --token-ttlgoes throughparseTokenTtl(src/commands/auth.ts) and refuses anything outside 60 to 7,776,000 seconds before the server starts. Stdio EOF, SIGTERM, SIGINT, SIGHUP, and parent-process death (every reparent case — PID 1, launchd subreaper, systemd, tmux, or a parent shell withPR_SET_CHILD_SUBREAPER) all funnel into onecleanup(reason)that first awaitsshutdownDelegatedSync()(idempotent shared promise; a running delegated sync is aborted and settles its checkpoint against the live engine, with the cleanup deadline extended byGBRAIN_SERVE_SYNC_SETTLE_MSonly while a job runs) and then releases the engine and the PGLite write-lock dir within 5 seconds (otherwise the lock is held indefinitely after Claude Desktop / Cursor / launchd-managed gateways disconnect, forcing a 5-minute stale-lock wait on next start). Watchdog reparent check isgetParentPid() !== initialParentPid(the=== 1check missed the subreaper case under launchd/systemd). Bun'sprocess.ppidcache is stale across reparenting (oven-sh/bun#30305) sogetParentPid()runsspawnSync('ps', ['-o', 'ppid=', '-p', PID])per tick. Startup probe verifiespsis on PATH; if not (stripped containers, busybox), the watchdog skips installing AND emits a loud[gbrain serve] watchdog disabled: ps unavailable ...stderr line so operators see the degraded mode. The idle maintenance sweep skips ticks while a delegated sync runs and drains deferred embeds afterwards... (line truncated to 2000 chars)src/commands/skillify-check.ts—gbrain skillpack-checkagent-readable health report. Exit 0/1/2 for CI gating; JSON for debugging. Wrapscheck-resolvable --json,doctor --json, and migration ledger into one payload. Required item 12 (brain_first_compliance) callsanalyzeSkillBrainFirst()on the candidate SKILL.md; exits 1 when the verdict ismissing_brain_first(external-lookup pattern present, no callout, nobrain_first: exempt). The scaffold path insrc/core/skillify/templates.tspre-inserts the canonical Convention callout into new SKILL.md files so freshly-scaffolded skills pass item 12.src/commands/setup.ts+src/cli/commands/setup.ts—gbrain setup <harness>(D8), pre-connect and engine-free (thinClient: 'none',json: 'document'): an orchestrator over the existing wiring, not a new installation system. Target first: it resolves the brain (loadConfig; none → agbrain init --pglite --no-embedding --jsonchild,--providersdrops--no-embedding; setup printsBrain ready at <path>and never init's standalone quickstart or[AGENT]banners; on the brain it just created it runs the setup migrations init left pending (finishFreshSetupMigrations,src/commands/setup-migrations.ts: oneapply-migrations --yes --no-autopilot-install --jsonchild built bysetupMigrationsArgvinmigrations/fresh-install.ts, 60 s bound, offline; v0.11.0 is held back when its host phase would edit an existing~/.claude/AGENTS.md,~/.openclaw/AGENTS.mdor OpenClaw cron manifest (hostRewriteTargets)) and replaces init's[init] Migrations:line with[setup] Migrations: …(a failure keeps init's hand-off plus the error code; an existing brain is not touched), and renders aMemory:line namingremember(#6606: world facts are pushed, private ones are recall-only, capture writes a page) and thensetupFirstRunNoticesonce afterNext:in human output, or undernoticesin--json), the source (--source>GBRAIN_SOURCE> unpinned), the launcher (--gbrain-bin>resolveGbrainBin), the surface (--surface>GBRAIN_SURFACE> the receipt's >REGISTRATION_SURFACE) and the registration owner, prints them, then refuses before any write withsetup_hosted_connection(thin-client config, hosted connection receipt or remote entry: never a second, local brain) orsetup_owner_conflict(live_servefrompeekLockunless the live stdio serve is this registration's own,unowned_entry,other_installby receiptgbrain_home,harness_lanefor a bootstrap harness receipt that wired the configuration setup would write (a target in t... (line truncated to 2000 chars)src/commands/setup-brain-layout.ts—gbrain setup claude-code|codex --shape personal|company|both [--notes DIR] [--docs DIR] [--transcripts DIR] [--team|--solo](GST-2731; guidedocs/guides/brain-layout.md). Every page is written create-only throughgbrain getthengbrain putchildren, and only whengetreportspage_not_found(empty forms,status: stub, one "Example (delete me)" line each):me/facts,me/voice,me/how-i-decidein the run's source, andCOMPANY_PAGES(company/facts,company/decisions,company/pricing,company/customers,company/calls,company/playbooks) in thecompanysource. The company source is kept when it exists, else added withgbrain sources add company --path <dir>on a gbrain-owned folder beside the default source's content root (never the person's docs folder; a path there that is not an empty folder fails the company part with anask_userbrain_layout_pages_pendingand the block is written without company lines) with no federation flag, sosources addfederates it only on a one-person brain (#9396); when it reads back unfederated, setup returnssource_not_in_default_searchwithask_user.--notesand--docsimport read only with onegbrain import DIR --no-embed --jsonchild each (GBRAIN_SOURCE pins the source; overIMPORT_INLINE_MAX= 500 markdown files it returnsbrain_layout_import_pendinginstead), then check keyless search finds the first file's title in the top 5 (company docs through default search when federated).--teamcreates nothing for the company part and returnsbrain_layout_team_next. A<!-- gbrain:brain-layout:begin/end -->block (lines per part) goes into the brain-first target only when the brain-first decision is accepted;--no-instructionsremoves it,--shape noneremoves it and keeps pages and source. A brand-new brain set up without--shapeasks inline only whenisInteractive(), otherwisebrain_shapejoins thefirst_run_decisionsbundle (defa... (line truncated to 2000 chars)src/commands/import-calls.ts—gbrain import <dir> --calls [--prefix <slug prefix>] [--source <id>] [--json](GST-2731), dispatched fromrunImportonce the folder resolves (--callsalso implies--no-embed; a--prefixvalue is never read as the folder).listCallFileswalks .txt/.md files (dot entries and symlinks skipped), and a single file argument imports that file as an import of its folder would (any other kind of file is an error);callPageFornames each<prefix>/<date>-<title slug>(date: dated file name, else first line, else modified day; title: rest of a dated file name, else first line, both read after redaction so a credential in either never reaches the title or slug), redacts the whole text withredactSessionand the user's patterns (loadImportRedactionPatterns), redacts the relative path the same way (redactCallPath), neutralizes structure lines (neutralizeOutsideText) and writes frontmattertype: meeting,facts_backstop: falseandcall_import: {file (redacted), root, path, hash, redactions, embedding_hold: call_import}(root, path and hash JSON-quoted so they read back as strings), plusreadable_by(the owner and the attendees the call's header names, matched bysrc/core/meetings/attendees.ts) whensrc/core/access/call-scope.tsfinds a brain serving two or more people whose owner's connections can read scoped pages (GST-2904).--readers attendees|source(default attendees) chooses it; otherwise the import stays open and prints thecalls_not_scopednotice (reasons owner_unset, owner_inactive, unbound_readers, stdio_unbound), and each row addsscoped,reason,readers,readers_from,matched_byandunmatched.rootiscallRootId(dir)(a hash of the folder path),patha hash of the folder and the unredacted relative path (so two names a redaction pattern makes alike stay two files, and neither name is stored), and the hash covers title and body, not the date.call_importis one ofANY_SIZE_HOLD_REASONSinsrc/core/page-embedding-budget.ts, so embed paths skip the page at any size until the owner approves it.--prefixis slugified per segment. Each new page goes through theput_pagehandler (trusted local context); a rerun finds the earlier page bycall_import.pathunder the prefix, matching the path digest from any folder above the file that an import could have started from (callPathIds), or byrootandfilefor a page stored beforepathexisted, claimed by one file per run; a queuedput_pageof the same file is reportedpending, not written again (not the computed slug, which a new modified day can move) and reports itunchanged(same hash) orkept(never overwritten); a write still in flight (write_pending) is reportedpendingwith itsgbrain write-requestcommand, not as an error, and ... (line truncated to 2000 chars)src/commands/doctor/checks/facts-pages.ts—facts_undated_lines(GST-2731, brain category): eachtype: factspage with list lines carrying no YYYY-MM-DD date is a warn naming source, slug and line numbers (never the line text); the fix isgbrain get <slug> --source <id>withask_userfor the dates; segmented pages are skipped and counted. Read-only. Pinned bytest/doctor-facts-undated-lines.test.ts.src/core/setup/brain-first.ts+src/core/managed-block.ts— the brain-first instruction block every harness install writes by default (<!-- gbrain:brain-first:begin/end -->,BRAIN_FIRST_VERSION).brainFirstTargetnames each harness's own instruction file (Claude Code~/.claude/CLAUDE.mdor./CLAUDE.local.md, CodexAGENTS.mdor an existingAGENTS.override.md, opencode globalAGENTS.md, OpenClaw<workspace>/AGENTS.mdfrom JSON5agents.defaults.workspace(several agents need--workspace), HermesSOUL.mdafter the identity text, Cursor.cursor/rules/gbrain-brain-first.mdc); other clients get the block printed to paste.syncBrainFirstsplices only between the markers (idempotent, upgrades in place, preserves a damaged block and reports it), and the decision (--no-instructions/GBRAIN_AGENT_INSTRUCTIONS=0,--instructions, prior) is remembered in<configDir>/agent-instructions.jsonwith the writer (underInstructionLedgerLockholds one lock,<configDir>/agent-instructions.lock, shared withskill-loading.json, across the ledger read, the file and permission edits and the ledger write, re-reads a recorded decision under it, reports a lock it cannot take within 10 seconds aspreserve, and a dry run takes none;test/instruction-ledger-lock.test.ts,test/instruction-ledger-lock-timeout.slow.test.ts), so--removeon setup,connect --installandbootstrap harness(lane inbootstrap/harness-brain-first.ts) strips only its own blocks. Text varies by access: MCP search surface, verbs surface, or the thin-client CLI launcher (GBRAIN-INSTRUCTIONS.mdstarts with it). doctorharness_wiringreads the ledger plus each registered or plugin-served harness's default file and warns on a missing, stale or damaged block with a fix that rewrites only the block (instructionBlockViews,withInstructionBlocks);gbrain post-upgradeprints the same command (brain-first-upgrade-notice.ts,instructionBlockUpgradeHints). The Clau... (line truncated to 2000 chars)src/core/setup/turn-hook.ts+src/core/setup/turn-hook-check.ts— the per-turn rule hook for installs whose MCP came from a plainmcp addor another installer: aturn-rule-v1Claude Code UserPromptSubmit entry or a Codexhooks.jsongroup plus itsconfig.tomltrust entry, runningGBRAIN_HOOK_LANE=turn-rule <hook launcher> gbrain hook user-prompt(rule only, no local context; it yields to setup, bootstrap and plugin lanes). Written bysetup <claude-code|codex> --instructions-only,connect --install, the hostedharness connect --installandbootstrap harness(not in registrar mode); with no absolute binary the outcome isprintwith the one-line next step.inspectTurnHook(files only; it also reads Claude Code's managedmanaged-settings.jsonandmanaged-settings.d/*.json, andturnRuleHookYieldscounts a managed gbrain hook, #8057) feeds doctorharness_wiring(turnHookViews,withTurnHooks: untrusted, or missing beside a ledger block, warns with codeturn_hook_not_loaded);verifyTurnHookruns the hook (Claude Code, Codex),openclaw plugins inspect gbrain-turn-rule --runtime --jsonorhermes hooks doctor, and every install path exits non-zero withturn_hook_not_loadedwhen it fails (docs/guides/repair.md#turn-hook-not-loaded). OpenClaw and Hermes rules name the gbrain tools and thetool_searchroute (renderBrainFirstTurnRule(access, harness);test/brain-first-turn-rule.test.ts,test/setup-brain-first.test.ts).src/core/setup/hook-launcher.ts+src/core/setup/hook-launcher-refresh.ts— the trusted-directory hook launcher (#8424):<config dir>/hook-launcher/gbrain-hook, a POSIX sh script that records the session directory inGBRAIN_HOOK_CWD, changes into its own directory and execs gbrain there, so a script-mode install never lets the session directory'sbunfig.tomlpreload or.envload; it refuses (exit 1, one stderr line) when its directory holds anything else. A script-mode install's launcher also records the directory of the Bun that wrote it (launcherRuntimeDir, preferring the bun on PATH when it is the same file;hookLauncherScript(dir)) and puts it first on PATH, so a harness started without bun on PATH still starts gbrain (GST-2784); a compiled gbrain gets the plain launcher (isScriptRuntime, exported from cli-preflight.ts).hookLauncherStatecalls a launcherstalewhen it records no Bun that a script install needs, or a Bun that is gone, andensureHookLaunchermoves a launcher that records another Bun. Every setup-lane and turn-rule hook command names it (buildClaudeHookCommand(…, launcher),codexSetupHookGroup(…, launcher),buildCodexSessionEndCommand(bin, launcher));ensureHookLauncherwrites it before any hook that names it, andgbrain hookreads the session directory throughhookSessionCwd().hookLauncherProblem(turn-hook-check.ts) feeds doctorharness_wiring(withHookLaunchers, codehook_session_cwd, reasonssession_cwd|missing|stale|foreign);refreshHookLaunchersruns ingbrain post-upgrade, rewrites this install's stale launcher file in place (no entry changes, so no Codex trust moves) and moves the turn-rule entries and each installed user-scope setup receipt's hooks onto the launcher through their own writers. The stdio MCP entries (desiredMcpEntry,desiredCodexMcpEntry,registerClaudeMcp/registerCodexMcpwithhookLauncher) and the bootstrap, harness and Codex SessionEnd lanes use it too (#8426... (line truncated to 2000 chars)src/commands/skillify.ts+src/core/skillify/{generator,templates}.ts—gbrain skillify scaffold <name>creates all stubs for a new skill: SKILL.md, script, tests, routing-eval.jsonl, resolver entry, filing-rules pointer.gbrain skillify check <script>runs the 10-step checklist (LLM evals, routing evals, check-resolvable gate, filing audit) against a candidate skill before it lands.src/commands/skillpack.ts+src/core/skillpack/{bundle,scaffold,reference,migrate-fence,scrub-legacy,harvest,harvest-lint,copy,apply-hunks,diff-text,installer}.ts—install/uninstallare not supported (they exit non-zero with a hint to the replacement). Surface:scaffold(one-time additive copy viacopyArtifactsincopy.ts; refuses to overwrite; partial-state fills missing paired sources declared in SKILL.md frontmattersources:),reference(read-only diff lens +--apply-clean-hunkstwo-way auto-apply via pure-JS unified-diff parser/applier inapply-hunks.ts+diff-text.ts; strict arguments through theskillpack referencerow ofsrc/cli/strict-args.ts(#5491):--dry-run=true, a typo or an unknown flag exits 2 before any write, the per-skill and--allgrammars print separately, and--all --apply-clean-hunksrefuses with the three-command update path; pinned bytest/skillpack-reference-strict-args.test.ts),migrate-fence(one-shot strip of legacy fence; cumulative-slugs receipt → row-parsing fallback; preserves rows verbatim as user-owned routing),scrub-legacy-fence-rows(opt-in row cleanup with skill-present + non-empty-triggers gate),harvest(host→gbrain inverse with symlink-reject + canonical-path containment via avalidateUploadPath-style gate + default-on privacy linter inharvest-lint.tsagainst~/.gbrain/harvest-private-patterns.txtplus built-in a built-in fork-name pattern + email + Slack-channel patterns; rollback on match). Paired-source declarations live in each SKILL.md's frontmattersources:array (validated byloadSkillSourcesinbundle.ts).autoDetectSkillsDir(insrc/core/repo-root.ts) has acwd_walk_uptier ahead of~/.openclaw/workspace($OPENCLAW_WORKSPACEprecedence preserved).gbrain skillpack check --strictexits non-zero on drift (CI gate); top-levelgbrain skillpack-checkkeeps exit-1-on-issues for cron. Companion editorial skillskills/skillpack-harvest/SKILL.mddrives ... (line truncated to 2000 chars)