Skip to content

Garry's Opinionated OpenClaw/Hermes Agent Brain

TypeScript
33.6 KB
Raw Blame

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] and gbrain repair --all. Kinds timeline (#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-embed defers embedding to embed --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) and embedding-effects (#5629/#5734 settlement of stale queued and failed embedding effects: reconciled, superseded, retry_queued or blocked, reported per item in outcomes / outcome_items) and google-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; --yes refused). 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). parseRepairArgs is strict: any unknown option or a second positional refuses invalid_params before anything runs; flags a kind does not take name the kinds that do (--only/--skip/--diff: frontmatter, fences; --slug: fences; --yes: frontmatter); --expect is accepted for explicit-only and preview-bound kinds, --include-ambiguous for 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. content is parsed by repair.ts's strict flag grammar like a kind (CONTENT_LANE; --only/--skip/--diff, --no-llm, --max-usd and --expect are accepted for it, --slug, --yes, --include-ambiguous and --all refuse) and dispatched before the kind check; it is a lane, not a RepairKind: no registry entry, no cursor of its own, listed under "Lanes:" in REPAIR_HELP. runRepairContentCommand resolves the scope, runs runContentLane and prints each kind's result through renderRepairResult plus a lane line (spend, allowance left, each kind's hash, every stop, the apply command); --json prints { lane, scope, mode, kinds, results[] (with paid), preview_hashes, cost, stopped, paid_kinds, apply_command }. A kind's stop sets exit verdict 1; a wrong --expect count is invalid_params with 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, so runReindex(engine, args, { authorized?, interactive? }) calls requireReindexConsent (src/core/reindex-consent.ts) after the dry-run return and before the managed dispatch for every caller unless --no-embed or authorized (the upgrade path's TTY yes, the job handler's stored spend record); src/cli/commands/reindex.ts renders the exit-3 consent refusal and cost_cap_exceeded. The approved finite cap runs the inline pass (and the managed dispatch) under a BudgetTracker via withBudgetTracker; once it is exhausted (an import swallows the refused embedding) the loop stops at the next page and reportBudgetStop exits 1 with budget_exhausted in --json. countPending is exported for jobs submit reindex and the mode-switch prompt. The writer pool is sized once from the run's page target (pending, capped by --limit) through resolveWorkersWithClamp, so Postgres runs over 100 pages default to DEFAULT_PARALLEL_WORKERS while PGLite stays at one; --workers overrides and the used count is reported as workers in the result and JSON (pinned by test/e2e/reindex-auto-workers-5181.test.ts). Walks markdown pages with stale chunker_version (plus unstamped contextual-retrieval mode when embedding is enabled; --no-embed still 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. --type adds a bound-parameter pages.type = $N scope 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, bounded embed --stale path. Rows with non-null source_path re-import via importFromFile; rows without fall back to importFromContent. Both paths pass `force... (line truncated to 2000 chars)

  • src/commands/repair-jsonb.ts — gbrain repair-jsonb [--dry-run] [--json]: rewrites jsonb_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 are jsonPayloadOnly: 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*[\[{]) that gbrain_try_jsonb(...) (jsonb or NULL; portable to Postgres 15, unlike the pg_input_is_valid it 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 via to_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's jsonb_integrity check counts damage with the same predicate over the same target list. Repairs double-encoded rows on Postgres; PGLite no-ops. Idempotent. Pinned by test/repair-jsonb.test.ts + test/doctor.test.ts.

  • src/commands/report.ts — Structured report saver (audit trail for maintenance/enrichment). Pages carry type: 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-eval catches user phrasings that route to the wrong skill. Reads skills/<name>/routing-eval.jsonl fixtures ({intent, expected_skill, ambiguous_with?}). Structural layer runs in check-resolvable by default (zero API cost). --llm is a placeholder for a future LLM tie-break layer; today it emits a stderr notice and runs structural only. Uses autoDetectSkillsDirReadOnly and the same multi-file resolver merge as check-resolvable, so on OpenClaw layouts (skills/RESOLVER.md + ../AGENTS.md) all three commands see the same trigger index. RESOLVER.md rows carry the full frontmatter triggers: arrays so the structural matcher sees realistic phrasings; ambiguous-fixture annotations cover deliberate skill chains like enrich → 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). Calls engine.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 by test/search/search-diagnose.test.ts.

  • src/commands/search.ts:gbrain search stats — rerank_gate section (eligible, graded, would_skip and would_skip_rate over graded, provider_calls, by_reason, ineligible by why), read from the reserved (date, 'rerank_gate', <counter>) rows of search_telemetry (no DDL; diverted out of total_calls like the empty-result rows; written only when search.reranker.gate is not off; cache hits add nothing); human output prints it when anything was graded. graph_signals section (enabled/source/failures_count/failures_by_reason). JSON envelope adds a graph_signals sibling property; _meta.metric_glossary adds graph_signals.enabled + graph_signals.failures_by_reason. Human output prints the section after the existing block. Reads search.graph_signals config first, falls back to the mode default. Pinned by test/search/search-stats-graph-signals.test.ts. Both gbrain search stats and gbrain search tune also surface a coverage disclosure (JSON: {cli_invocations: 'recorded_on_clean_exit', reason}; human: a one-line caveat) sourced from telemetryCoverage()/TELEMETRY_COVERAGE_CAVEAT in src/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 in test/commands-search.test.ts. gbrain search tune --apply writes in order and stops at the first write that did not land; a thrown write is reconciled by re-reading its key (applied when the target value is there, failed when not, outcome_unknown when the read fails too). JSON lists only landed changes in applied and revert_commands, adds per-item results, not_applied and apply_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 in serve-http-registration.ts, serve-http-grants.ts, and serve-http-admin-api.ts use 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.tsx previews machine/public PKCE/confidential PKCE registration and current permissions, and exposes versioned lifecycle actions. Explicit downloads select machine HarnessCredentials or native OAuthClientSetup; 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 committed admin/dist and src/admin-embedded.ts after SPA edits.

  • src/commands/serve-http.ts — Express 5 HTTP MCP server with OAuth 2.1, admin dashboard, and SSE live activity feed. The legacy POST /ingest queue refuses operation-snapshot clients; they use approved MCP writes so execution stays inside the shared grant contract. Started via gbrain serve --http [--port N] [--token-ttl N] [--enable-dcr] [--public-url URL] [--bind HOST] [--log-full-params]. OAuth discovery's scopes_supported (RFC 8414 AS metadata and both RFC 9728 protected-resource documents, one value through the SDK router) comes from scopesSupportedForDiscovery({ enableDcr }) in src/core/scope.ts: with --enable-dcr it is exactly the self-registration ceiling (read write), so a client that copies discovery into its /register request succeeds; without DCR it is every scope except operator-only agent. The DCR ceiling still rejects an explicit privileged request, and operator-registered clients are never narrowed by the advertisement. Combines MCP SDK's mcpAuthRouter (authorize/token/register/revoke), a custom client_credentials handler running BEFORE the router (SDK's token endpoint throws UnsupportedGrantTypeError for CC; custom handler falls through for auth_code / refresh_token), requireBearerAuth middleware for /mcp with scope enforcement + localOnly rejection before op dispatch, and per-IP express-rate-limit buckets: the MCP SDK's defaults on /authorize (100 / 15 min), /register (20 / hour) and /token (50 / 15 min) because authRouterOptions passes no rateLimit: false, the custom client_credentials handler's ccRateLimiter, 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 in serve-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: runServeHttp binds through listenOrRefuse (serve-http-listen.ts: serve_port_in_use on a taken port; with options.adoptServer from status-only recovery it hands the app to the already-bound listener instead of binding). buildServeHttpApp builds one shared ServeHttpContext (sessions, nonce stores, limiters, requireAdmin, SSE fan-out, OAuth provider, resource verifier, non-localOnly op list) and mounts in registration order serve-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) and serve-http-webhooks.ts (/ingest, which maps a legacy-authority permission_denied from submission to 409 {error, message, hint, docs_url} (test/serve-http-ingest-legacy.test.ts), answers 429 ingest_backlog_full when the 50-capture waiting cap hands back another job, and every other submission error to 500; legacyIngestJob answers 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 the ingest_capture handler (minions/handlers/ingest-capture.ts) applies a capture once per job idempotency key for 90 days through ingest_applied_captures (ingestion/applied-captures.ts, migration v296), even after gbrain jobs prune: the row is inserted in the page write's transaction (importFromContent's beforeCommit; 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 serve stdio MCP entrypoint with idempotent shutdown across every parent-disconnect signal. Surface: stdio resolves GBRAIN_SURFACE > --surface > config > full (resolveStdioSurface; an invalid env value is ignored with a stderr line and handed to startMcpServer as invalidSurfaceEnv), --http resolves --surface > config > full and says on stderr that it ignores GBRAIN_SURFACE; both print surface=<x> (source: …) at start. --http --token-ttl goes through parseTokenTtl (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 with PR_SET_CHILD_SUBREAPER) all funnel into one cleanup(reason) that first awaits shutdownDelegatedSync() (idempotent shared promise; a running delegated sync is aborted and settles its checkpoint against the live engine, with the cleanup deadline extended by GBRAIN_SERVE_SYNC_SETTLE_MS only 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 is getParentPid() !== initialParentPid (the === 1 check missed the subreaper case under launchd/systemd). Bun's process.ppid cache is stale across reparenting (oven-sh/bun#30305) so getParentPid() runs spawnSync('ps', ['-o', 'ppid=', '-p', PID]) per tick. Startup probe verifies ps is 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-check agent-readable health report. Exit 0/1/2 for CI gating; JSON for debugging. Wraps check-resolvable --json, doctor --json, and migration ledger into one payload. Required item 12 (brain_first_compliance) calls analyzeSkillBrainFirst() on the candidate SKILL.md; exits 1 when the verdict is missing_brain_first (external-lookup pattern present, no callout, no brain_first: exempt). The scaffold path in src/core/skillify/templates.ts pre-inserts the canonical Convention callout into new SKILL.md files so freshly-scaffolded skills pass item 12.

  • src/commands/setup.ts + src/cli/commands/setup.ts — gbrain setup <harness> (D8), pre-connect and engine-free (thinClient: 'none', json: 'document'): an orchestrator over the existing wiring, not a new installation system. Target first: it resolves the brain (loadConfig; none → a gbrain init --pglite --no-embedding --json child, --providers drops --no-embedding; setup prints Brain ready at <path> and never init's standalone quickstart or [AGENT] banners; on the brain it just created it runs the setup migrations init left pending (finishFreshSetupMigrations, src/commands/setup-migrations.ts: one apply-migrations --yes --no-autopilot-install --json child built by setupMigrationsArgv in migrations/fresh-install.ts, 60 s bound, offline; v0.11.0 is held back when its host phase would edit an existing ~/.claude/AGENTS.md, ~/.openclaw/AGENTS.md or OpenClaw cron manifest (hostRewriteTargets)) and replaces init's [init] Migrations: line with [setup] Migrations: … (a failure keeps init's hand-off plus the error code; an existing brain is not touched), and renders a Memory: line naming remember (#6606: world facts are pushed, private ones are recall-only, capture writes a page) and then setupFirstRunNotices once after Next: in human output, or under notices in --json), the source (--source > GBRAIN_SOURCE > unpinned), the launcher (--gbrain-bin > resolveGbrainBin), the surface (--surface > GBRAIN_SURFACE > the receipt's > REGISTRATION_SURFACE) and the registration owner, prints them, then refuses before any write with setup_hosted_connection (thin-client config, hosted connection receipt or remote entry: never a second, local brain) or setup_owner_conflict (live_serve from peekLock unless the live stdio serve is this registration's own, unowned_entry, other_install by receipt gbrain_home, harness_lane for a bootstrap harness receipt 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; guide docs/guides/brain-layout.md). Every page is written create-only through gbrain get then gbrain put children, and only when get reports page_not_found (empty forms, status: stub, one "Example (delete me)" line each): me/facts, me/voice, me/how-i-decide in the run's source, and COMPANY_PAGES (company/facts, company/decisions, company/pricing, company/customers, company/calls, company/playbooks) in the company source. The company source is kept when it exists, else added with gbrain 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 an ask_user brain_layout_pages_pending and the block is written without company lines) with no federation flag, so sources add federates it only on a one-person brain (#9396); when it reads back unfederated, setup returns source_not_in_default_search with ask_user. --notes and --docs import read only with one gbrain import DIR --no-embed --json child each (GBRAIN_SOURCE pins the source; over IMPORT_INLINE_MAX = 500 markdown files it returns brain_layout_import_pending instead), then check keyless search finds the first file's title in the top 5 (company docs through default search when federated). --team creates nothing for the company part and returns brain_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-instructions removes it, --shape none removes it and keeps pages and source. A brand-new brain set up without --shape asks inline only when isInteractive(), otherwise brain_shape joins the first_run_decisions bundle (defa... (line truncated to 2000 chars)

  • src/commands/import-calls.ts — gbrain import <dir> --calls [--prefix <slug prefix>] [--source <id>] [--json] (GST-2731), dispatched from runImport once the folder resolves (--calls also implies --no-embed; a --prefix value is never read as the folder). listCallFiles walks .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); callPageFor names 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 with redactSession and the user's patterns (loadImportRedactionPatterns), redacts the relative path the same way (redactCallPath), neutralizes structure lines (neutralizeOutsideText) and writes frontmatter type: meeting, facts_backstop: false and call_import: {file (redacted), root, path, hash, redactions, embedding_hold: call_import} (root, path and hash JSON-quoted so they read back as strings), plus readable_by (the owner and the attendees the call's header names, matched by src/core/meetings/attendees.ts) when src/core/access/call-scope.ts finds 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 the calls_not_scoped notice (reasons owner_unset, owner_inactive, unbound_readers, stdio_unbound), and each row adds scoped, reason, readers, readers_from, matched_by and unmatched. root is callRootId(dir) (a hash of the folder path), path a 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_import is one of ANY_SIZE_HOLD_REASONS in src/core/page-embedding-budget.ts, so embed paths skip the page at any size until the owner approves it. --prefix is slugified per segment. Each new page goes through the put_page handler (trusted local context); a rerun finds the earlier page by call_import.path under the prefix, matching the path digest from any folder above the file that an import could have started from (callPathIds), or by root and file for a page stored before path existed, claimed by one file per run; a queued put_page of the same file is reported pending, not written again (not the computed slug, which a new modified day can move) and reports it unchanged (same hash) or kept (never overwritten); a write still in flight (write_pending) is reported pending with its gbrain write-request command, not as an error, and ... (line truncated to 2000 chars)

  • src/commands/doctor/checks/facts-pages.ts — facts_undated_lines (GST-2731, brain category): each type: facts page with list lines carrying no YYYY-MM-DD date is a warn naming source, slug and line numbers (never the line text); the fix is gbrain get <slug> --source <id> with ask_user for the dates; segmented pages are skipped and counted. Read-only. Pinned by test/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). brainFirstTarget names each harness's own instruction file (Claude Code ~/.claude/CLAUDE.md or ./CLAUDE.local.md, Codex AGENTS.md or an existing AGENTS.override.md, opencode global AGENTS.md, OpenClaw <workspace>/AGENTS.md from JSON5 agents.defaults.workspace (several agents need --workspace), Hermes SOUL.md after the identity text, Cursor .cursor/rules/gbrain-brain-first.mdc); other clients get the block printed to paste. syncBrainFirst splices only between the markers (idempotent, upgrades in place, preserves a damaged block and reports it), and the decision (--no-instructions / GBRAIN_AGENT_INSTRUCTIONS=0, --instructions, prior) is remembered in <configDir>/agent-instructions.json with the writer (underInstructionLedgerLock holds one lock, <configDir>/agent-instructions.lock, shared with skill-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 as preserve, and a dry run takes none; test/instruction-ledger-lock.test.ts, test/instruction-ledger-lock-timeout.slow.test.ts), so --remove on setup, connect --install and bootstrap harness (lane in bootstrap/harness-brain-first.ts) strips only its own blocks. Text varies by access: MCP search surface, verbs surface, or the thin-client CLI launcher (GBRAIN-INSTRUCTIONS.md starts with it). doctor harness_wiring reads the ledger plus each registered or plugin-served harness's default file and warns on a missing, stale or damaged block with a fix that rewrites only the block (instructionBlockViews, withInstructionBlocks); gbrain post-upgrade prints the same command (brain-first-upgrade-notice.ts, instructionBlockUpgradeHints). The 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 plain mcp add or another installer: a turn-rule-v1 Claude Code UserPromptSubmit entry or a Codex hooks.json group plus its config.toml trust entry, running GBRAIN_HOOK_LANE=turn-rule <hook launcher> gbrain hook user-prompt (rule only, no local context; it yields to setup, bootstrap and plugin lanes). Written by setup <claude-code|codex> --instructions-only, connect --install, the hosted harness connect --install and bootstrap harness (not in registrar mode); with no absolute binary the outcome is print with the one-line next step. inspectTurnHook (files only; it also reads Claude Code's managed managed-settings.json and managed-settings.d/*.json, and turnRuleHookYields counts a managed gbrain hook, #8057) feeds doctor harness_wiring (turnHookViews, withTurnHooks: untrusted, or missing beside a ledger block, warns with code turn_hook_not_loaded); verifyTurnHook runs the hook (Claude Code, Codex), openclaw plugins inspect gbrain-turn-rule --runtime --json or hermes hooks doctor, and every install path exits non-zero with turn_hook_not_loaded when it fails (docs/guides/repair.md#turn-hook-not-loaded). OpenClaw and Hermes rules name the gbrain tools and the tool_search route (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 in GBRAIN_HOOK_CWD, changes into its own directory and execs gbrain there, so a script-mode install never lets the session directory's bunfig.toml preload or .env load; 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). hookLauncherState calls a launcher stale when it records no Bun that a script install needs, or a Bun that is gone, and ensureHookLauncher moves a launcher that records another Bun. Every setup-lane and turn-rule hook command names it (buildClaudeHookCommand(…, launcher), codexSetupHookGroup(…, launcher), buildCodexSessionEndCommand(bin, launcher)); ensureHookLauncher writes it before any hook that names it, and gbrain hook reads the session directory through hookSessionCwd(). hookLauncherProblem (turn-hook-check.ts) feeds doctor harness_wiring (withHookLaunchers, code hook_session_cwd, reasons session_cwd|missing|stale|foreign); refreshHookLaunchers runs in gbrain 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/registerCodexMcp with hookLauncher) 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/uninstall are not supported (they exit non-zero with a hint to the replacement). Surface: scaffold (one-time additive copy via copyArtifacts in copy.ts; refuses to overwrite; partial-state fills missing paired sources declared in SKILL.md frontmatter sources:), reference (read-only diff lens + --apply-clean-hunks two-way auto-apply via pure-JS unified-diff parser/applier in apply-hunks.ts + diff-text.ts; strict arguments through the skillpack reference row of src/cli/strict-args.ts (#5491): --dry-run=true, a typo or an unknown flag exits 2 before any write, the per-skill and --all grammars print separately, and --all --apply-clean-hunks refuses with the three-command update path; pinned by test/skillpack-reference-strict-args.test.ts), migrate-fence (one-shot strip of legacy fence; cumulative-slugs receipt → row-parsing fallback; preserves rows verbatim as user-owned routing), scrub-legacy-fence-rows (opt-in row cleanup with skill-present + non-empty-triggers gate), harvest (host→gbrain inverse with symlink-reject + canonical-path containment via a validateUploadPath-style gate + default-on privacy linter in harvest-lint.ts against ~/.gbrain/harvest-private-patterns.txt plus built-in a built-in fork-name pattern + email + Slack-channel patterns; rollback on match). Paired-source declarations live in each SKILL.md's frontmatter sources: array (validated by loadSkillSources in bundle.ts). autoDetectSkillsDir (in src/core/repo-root.ts) has a cwd_walk_up tier ahead of ~/.openclaw/workspace ($OPENCLAW_WORKSPACE precedence preserved). gbrain skillpack check --strict exits non-zero on drift (CI gate); top-level gbrain skillpack-check keeps exit-1-on-issues for cron. Companion editorial skill skills/skillpack-harvest/SKILL.md drives ... (line truncated to 2000 chars)