Garry's Opinionated OpenClaw/Hermes Agent Brain
TypeScript
docs(key-files): name asAgentToolError for SkillOpt rollout reads
garrytan975ba9e36b1e
diff --git a/docs/architecture/key-files/mcp.md b/docs/architecture/key-files/mcp.mdindex d26bea8343..3bc1f23001 100644--- a/docs/architecture/key-files/mcp.md+++ b/docs/architecture/key-files/mcp.md@@ -3,7 +3,7 @@[Subsystem index](../KEY_FILES.md). Read only the entries relevant to your change.Current behavior and load-bearing invariants; history belongs in Git and CHANGELOG.-- `src/mcp/dispatch.ts` — shared tool-call dispatch consumed by both stdio (`server.ts`) and HTTP transports. Exports `dispatchToolCall(engine, name, params, opts)` (a read op (`mutating === false`) runs inside `withRequestConfigSnapshot`, a write op under `withoutRequestConfigSnapshot`; `src/core/config-snapshot.ts`), `buildOperationContext(engine, params, opts)`, and re-exports `normalizeOptionalParams`/`validateParams` from `src/mcp/validate-params.ts` (the validation module — call order normalize → validate → findUnknownParams is load-bearing). Single source of truth for `(ctx, params)` handler arg order and the `OperationContext` shape. Defaults `remote: true` (untrusted); local CLI callers pass `remote: false`. Deny layers, in order: `opts.allowedOps` surface enforcement (hidden op → `unknownToolEnvelope`, byte-identical to a nonexistent op; did-you-mean candidates drawn ONLY from the caller's visible surface minus localOnly minus gated names), unknown op, the localOnly transport backstop (`op.localOnly && transport !== 'stdio'` → same envelope; stdio IS the local surface), param validation, strict/warn unknown-arg handling (reject mode returns `invalid_params` with suggestions; warn mode attaches `_meta.warnings` + a model-visible notice block), then `enforceBoundClientOpAllowList` (the bound-client fence) inside the handler try. `_meta` assembly per docs/protocol/MCP_META_CHANNELS.md: handler-emitted keys via `ctx.emitResponseMeta` (retrieval, warnings) attach first and independently of the `metaHook` (`brain_hot_memory`, built by `src/core/facts/meta-hook.ts`; for a read op on a live engine it runs beside the handler instead of after it (GBRA-156), and reads its withdrawal watermark and trust generation in one round trip — its 30s cache is keyed by ENGINE IDENTITY + source + visibility tier + session + allow-list hash + eligibility + the `sessionOnly` scope (a session with no facts of its own falls back to the source's newest 24h facts unless the caller passes `sessionOnly`, which the IPC handlers do when `context.hot_memory.session_only` is on; MCP callers never pass it), so a process hosting multiple engines can never serve one brain's cached facts into another's envelope; each entry's deadline is additionally CLAMPED to the earliest retained `valid_until`, so a fact expiring inside the window never outlives its read-time TTL by cache staleness; every mutating op, successful or not, drops the engine's entries via `invalidateHotMemoryForEngine`, a build that raced it is not stored, each hit revalidates the source's `fact_withdrawals` watermark so a forget from any process is never served, the key folds the effective read eligibility and each hit revalidates the trust policy generation (`src/core/eligibility/generation.ts`, migration v230: deferred triggers bump `trust_policy_state` on tier changes, quarantine transitions, read floor and `trust.%` config changes, purges and `needs_rederive`), read before the rows; an unreadable generation delivers nothing; facts read through the `hot_memory` proactive eligibility and `partitionForActivation`, carry `trust_tier` and `origin`, and the payload's `suppressed` counts what activation control withheld), each producer isolated so one failure never drops another's key; A successful result's content[0] is compact `JSON.stringify(result)` (error envelopes stay indented); `opts.resultRows` threads the transport's row-shape choice into `OperationContext.resultRows`. empty retrieval results get a SECOND model-visible content block via `buildEmptyRetrievalBlock`. `retrievalNoticeBlocks` marks a saved fact that carries `corrected_by` with "corrected by a newer saved fact above" in its bracket and caps the saved-facts block at 1,500 characters and the other-names block at 400 (header included) with whole items only: the first item always shows, later items that would cross the ceiling are counted in a `(+N more…)` marker (pinned by `test/mcp-notice-ceilings.test.ts`). Exports `isListLevelDenialEnvelope(parsed)` — the honest-catalog metric classifier: true for op-level denials the tools/list filter should have prevented (`detail: 'config_key=...'` publish-gate backstop, `detail: 'fence=op'` fence op-level deny), false for argument-level denials; serve-http logs matches as `status='denied_after_list'`. Exports `requestLogStatusForResult(result)` — the ONE request-log status decision (`success` / `success_with_warnings` / `accepted_pending` (a `write_pending` with an admitted non-terminal receipt, kept out of the admin error rate; `acceptedPendingReceipt` returns its receipt so serve-http logs the opaque `write_request_id`) / `denied_after_list` / `error`); BOTH HTTP transports (serve-http.ts and the legacy-bearer http-transport.ts) route every tools/call row through it so the honest-catalog metric sees all HTTP traffic (pinned by test/denied-after-list.test.ts + test/http-transport.test.ts). Also exports `summarizeMcpParams(opName, params)` — privacy-preserving redactor for `mcp_request_log` and the admin SSE feed, returns `{redacted, kind, declared_keys, unknown_key_count, approx_bytes}`. Intersects submitted top-level keys against the operation's declared `params` allow-list (declared keys preserved sorted; unknown keys counted but never named, closing the attacker-controlled-key-name leak). Byte counts bucketed up to nearest 1KB so an attacker can't binary-search secret-content sizes by probing. Raw payload visibility is opt-in via `gbrain serve --http --log-full-params` (loud stderr warning). Logging paths route through this helper, not `JSON.stringify(params)`. Agent contract v1: every failure (unknown tool, source guard, validation, strict params, missing source scope, handler throws) goes through `errorResult` → `toAgentError` → exactly one content block; handlers emit advice through `ctx.emitNotice` and the empty-retrieval, unknown-param and backup-coverage blocks ride that channel (prefixed `[gbrain notice <code> kind=<kind>]` blocks + `_meta.gbrain_notices`), filtered by the notice ledger (`opts.noticeLedger` on HTTP). `dispatchRenderContext` binds `isCallable` for fixes; `unknownToolEnvelope(name, opts, 'unknown_operation')` keeps serve-http's frozen value; `localCallErrorEnvelope` is `gbrain call`'s envelope. `sessionSafetyNotices` adds the one-time `behavior_changes` disclosure (stdio: once per brain; HTTP: once per authenticated client, remote view) and, on stdio only, the queued `chat_fallback_hop` notice, on success and failure results alike. `requestMetaSessionId(request.params)` is the one reader of the request-level `_meta.session_id` (beside `arguments`); stdio (`server.ts`) and HTTP (`serve-http-mcp.ts`) both pass it as `opts.sessionId`, which wins over an arguments-level `_meta` and is clamped to `SESSION_ID_MAX_CHARS` (256). Caches keyed on it stay bounded: the hot-memory cache at `HOT_MEMORY_CACHE_MAX_ENTRIES` (1000) and the facts queue's per-session counter, deleted at zero. `retrievalNoticeBlocks` also appends the rate line for a rateable answer (`_meta.retrieval.answer_id` with `feedback.rateable`): `Rate after use: rate_answer { answer_id, rating: 1-5 }`, or the fuller wording when `how_to_rate` fired, capped at `RATE_LINE_MAX_CHARS` = 160 (#6192; `test/mcp-feedback-visible-answer-id.test.ts`). Large pages: after a read's result is assembled (notices and `_meta` included), `frameOverCap` measures the final encoded frame against the connection's cap and replaces an oversized read with `result_too_large` (writes are never replaced); `DispatchOpts.thinClient` (from `X-Gbrain-Client` on both HTTP transports) reaches `OperationContext.thinClient`, a default-body-mode hint, never authority. GBRA-156: `hotMemoryOffIn(params)` reads `_meta.hot_memory: "off"`. Both transports pass the request-level value as `opts.hotMemoryOff`, and dispatch also reads it from the arguments' `_meta`. Either one skips the `metaHook` for that call, so the response carries no `brain_hot_memory` (`test/mcp-hot-memory-opt-out.test.ts`). Caches keyed on it stay bounded: the hot-memory cache at `HOT_MEMORY_CACHE_MAX_ENTRIES` (1000) and the facts queue's per-session counter, deleted at zero. `retrievalNoticeBlocks` also appends the rate line for a rateable answer (`_meta.retrieval.answer_id` with `feedback.rateable`): `Rate after use: rate_answer { answer_id, rating: 1-5 }`, or the fuller wording when `how_to_rate` fired, capped at `RATE_LINE_MAX_CHARS` = 160 (#6192; `test/mcp-feedback-visible-answer-id.test.ts`). Large pages: after a read's result is assembled (notices and `_meta` included), `frameOverCap` measures the final encoded frame against the connection's cap and replaces an oversized read with `result_too_large` (writes are never replaced); `DispatchOpts.thinClient` (from `X-Gbrain-Client` on both HTTP transports) reaches `OperationContext.thinClient`, a default-body-mode hint, never authority. GBRA-156: a remote non-mutating op runs inside `withPrivateReadableSources(auth.privatePages.sources)`; writes, local calls and `context_pack` / `delta` (`WORLD_ONLY_PACK_OPS`) run with an empty set. GST-359 C1: `opts.actor` carries the `x-qm-actor` header from both HTTP transports (stdio never attests); `resolveAttestedActor` (`src/core/access/actor.ts`) decides before any work, and `actorRefusal` returns its refusals with `structuredContent.error` beside the JSON text block, the one seam where layer D's `memory_recall` will answer `actor_unlinked` as empty content plus `structuredContent {facts: [], truncated: false, code: 'actor_unlinked'}`. Every MCP server's `serverInfo.description` is `MCP_SERVER_DESCRIPTION` (`instructions.ts`, at most 120 characters); `instructions` are unchanged.+- `src/mcp/dispatch.ts` — shared tool-call dispatch consumed by both stdio (`server.ts`) and HTTP transports. Exports `dispatchToolCall(engine, name, params, opts)` (a read op (`mutating === false`) runs inside `withRequestConfigSnapshot`, a write op under `withoutRequestConfigSnapshot`; `src/core/config-snapshot.ts`), `buildOperationContext(engine, params, opts)`, and re-exports `normalizeOptionalParams`/`validateParams` from `src/mcp/validate-params.ts` (the validation module — call order normalize → validate → findUnknownParams is load-bearing). Single source of truth for `(ctx, params)` handler arg order and the `OperationContext` shape. Defaults `remote: true` (untrusted); local CLI callers pass `remote: false`. Deny layers, in order: `opts.allowedOps` surface enforcement (hidden op → `unknownToolEnvelope`, byte-identical to a nonexistent op; did-you-mean candidates drawn ONLY from the caller's visible surface minus localOnly minus gated names), unknown op, the localOnly transport backstop (`op.localOnly && transport !== 'stdio'` → same envelope; stdio IS the local surface), param validation, strict/warn unknown-arg handling (reject mode returns `invalid_params` with suggestions; warn mode attaches `_meta.warnings` + a model-visible notice block), then `enforceBoundClientOpAllowList` (the bound-client fence) inside the handler try. `_meta` assembly per docs/protocol/MCP_META_CHANNELS.md: handler-emitted keys via `ctx.emitResponseMeta` (retrieval, warnings) attach first and independently of the `metaHook` (`brain_hot_memory`, built by `src/core/facts/meta-hook.ts`; for a read op on a live engine it runs beside the handler instead of after it (GBRA-156), and reads its withdrawal watermark and trust generation in one round trip — its 30s cache is keyed by ENGINE IDENTITY + source + visibility tier + session + allow-list hash + eligibility + the `sessionOnly` scope (a session with no facts of its own falls back to the source's newest 24h facts unless the caller passes `sessionOnly`, which the IPC handlers do when `context.hot_memory.session_only` is on; MCP callers never pass it), so a process hosting multiple engines can never serve one brain's cached facts into another's envelope; each entry's deadline is additionally CLAMPED to the earliest retained `valid_until`, so a fact expiring inside the window never outlives its read-time TTL by cache staleness; every mutating op, successful or not, drops the engine's entries via `invalidateHotMemoryForEngine`, a build that raced it is not stored, each hit revalidates the source's `fact_withdrawals` watermark so a forget from any process is never served, the key folds the effective read eligibility and each hit revalidates the trust policy generation (`src/core/eligibility/generation.ts`, migration v230: deferred triggers bump `trust_policy_state` on tier changes, quarantine transitions, read floor and `trust.%` config changes, purges and `needs_rederive`), read before the rows; an unreadable generation delivers nothing; facts read through the `hot_memory` proactive eligibility and `partitionForActivation`, carry `trust_tier` and `origin`, and the payload's `suppressed` counts what activation control withheld), each producer isolated so one failure never drops another's key; A successful result's content[0] is compact `JSON.stringify(result)` (error envelopes stay indented); `opts.resultRows` threads the transport's row-shape choice into `OperationContext.resultRows`. empty retrieval results get a SECOND model-visible content block via `buildEmptyRetrievalBlock`. `retrievalNoticeBlocks` marks a saved fact that carries `corrected_by` with "corrected by a newer saved fact above" in its bracket and caps the saved-facts block at 1,500 characters and the other-names block at 400 (header included) with whole items only: the first item always shows, later items that would cross the ceiling are counted in a `(+N more…)` marker (pinned by `test/mcp-notice-ceilings.test.ts`). Exports `isListLevelDenialEnvelope(parsed)` — the honest-catalog metric classifier: true for op-level denials the tools/list filter should have prevented (`detail: 'config_key=...'` publish-gate backstop, `detail: 'fence=op'` fence op-level deny), false for argument-level denials; serve-http logs matches as `status='denied_after_list'`. Exports `requestLogStatusForResult(result)` — the ONE request-log status decision (`success` / `success_with_warnings` / `accepted_pending` (a `write_pending` with an admitted non-terminal receipt, kept out of the admin error rate; `acceptedPendingReceipt` returns its receipt so serve-http logs the opaque `write_request_id`) / `denied_after_list` / `error`); BOTH HTTP transports (serve-http.ts and the legacy-bearer http-transport.ts) route every tools/call row through it so the honest-catalog metric sees all HTTP traffic (pinned by test/denied-after-list.test.ts + test/http-transport.test.ts). Also exports `summarizeMcpParams(opName, params)` — privacy-preserving redactor for `mcp_request_log` and the admin SSE feed, returns `{redacted, kind, declared_keys, unknown_key_count, approx_bytes}`. Intersects submitted top-level keys against the operation's declared `params` allow-list (declared keys preserved sorted; unknown keys counted but never named, closing the attacker-controlled-key-name leak). Byte counts bucketed up to nearest 1KB so an attacker can't binary-search secret-content sizes by probing. Raw payload visibility is opt-in via `gbrain serve --http --log-full-params` (loud stderr warning). Logging paths route through this helper, not `JSON.stringify(params)`. Agent contract v1: every failure (unknown tool, source guard, validation, strict params, missing source scope, handler throws) goes through `errorResult` → `toAgentError` → exactly one content block; handlers emit advice through `ctx.emitNotice` and the empty-retrieval, unknown-param and backup-coverage blocks ride that channel (prefixed `[gbrain notice <code> kind=<kind>]` blocks + `_meta.gbrain_notices`), filtered by the notice ledger (`opts.noticeLedger` on HTTP). `dispatchRenderContext` binds `isCallable` for fixes; `unknownToolEnvelope(name, opts, 'unknown_operation')` keeps serve-http's frozen value; `localCallErrorEnvelope` is `gbrain call`'s envelope. `sessionSafetyNotices` adds the one-time `behavior_changes` disclosure (stdio: once per brain; HTTP: once per authenticated client, remote view) and, on stdio only, the queued `chat_fallback_hop` notice, on success and failure results alike. `requestMetaSessionId(request.params)` is the one reader of the request-level `_meta.session_id` (beside `arguments`); stdio (`server.ts`) and HTTP (`serve-http-mcp.ts`) both pass it as `opts.sessionId`, which wins over an arguments-level `_meta` and is clamped to `SESSION_ID_MAX_CHARS` (256). Caches keyed on it stay bounded: the hot-memory cache at `HOT_MEMORY_CACHE_MAX_ENTRIES` (1000) and the facts queue's per-session counter, deleted at zero. `retrievalNoticeBlocks` also appends the rate line for a rateable answer (`_meta.retrieval.answer_id` with `feedback.rateable`): `Rate after use: rate_answer { answer_id, rating: 1-5 }`, or the fuller wording when `how_to_rate` fired, capped at `RATE_LINE_MAX_CHARS` = 160 (#6192; `test/mcp-feedback-visible-answer-id.test.ts`). Large pages: after a read's result is assembled (notices and `_meta` included), `frameOverCap` measures the final encoded frame against the connection's cap and replaces an oversized read with `result_too_large` (writes are never replaced); `DispatchOpts.thinClient` (from `X-Gbrain-Client` on both HTTP transports) reaches `OperationContext.thinClient`, a default-body-mode hint, never authority. GBRA-156: `hotMemoryOffIn(params)` reads `_meta.hot_memory: "off"`. Both transports pass the request-level value as `opts.hotMemoryOff`, and dispatch also reads it from the arguments' `_meta`. Either one skips the `metaHook` for that call, so the response carries no `brain_hot_memory` (`test/mcp-hot-memory-opt-out.test.ts`). Caches keyed on it stay bounded: the hot-memory cache at `HOT_MEMORY_CACHE_MAX_ENTRIES` (1000) and the facts queue's per-session counter, deleted at zero. `retrievalNoticeBlocks` also appends the rate line for a rateable answer (`_meta.retrieval.answer_id` with `feedback.rateable`): `Rate after use: rate_answer { answer_id, rating: 1-5 }`, or the fuller wording when `how_to_rate` fired, capped at `RATE_LINE_MAX_CHARS` = 160 (#6192; `test/mcp-feedback-visible-answer-id.test.ts`). Large pages: after a read's result is assembled (notices and `_meta` included), `frameOverCap` measures the final encoded frame against the connection's cap and replaces an oversized read with `result_too_large` (writes are never replaced); `DispatchOpts.thinClient` (from `X-Gbrain-Client` on both HTTP transports) reaches `OperationContext.thinClient`, a default-body-mode hint, never authority. GBRA-156: a remote non-mutating op runs inside `withPrivateReadableSources(auth.privatePages.sources)`; writes, local calls and `context_pack` / `delta` (`WORLD_ONLY_PACK_OPS`) run with an empty set. GST-359 C1: `opts.actor` carries the `x-qm-actor` header from both HTTP transports (stdio never attests); `resolveAttestedActor` (`src/core/access/actor.ts`) decides before any work, and `actorRefusal` returns its refusals with `structuredContent.error` beside the JSON text block, the one seam where layer D's `memory_recall` will answer `actor_unlinked` as empty content plus `structuredContent {facts: [], truncated: false, code: 'actor_unlinked'}`. Every MCP server's `serverInfo.description` is `MCP_SERVER_DESCRIPTION` (`instructions.ts`, at most 120 characters); `instructions` are unchanged. `asAgentToolError(e, op, ctx, allowedOps)` renders a failed read as the error text an HTTP read-scope MCP caller gets for the same call (code, message, suggestion, `fix` limited to `allowedOps`) for SkillOpt's tool loops, which throw it with `code` kept; an AI invocation policy stop passes through unchanged.- `src/core/egress-budget.ts` — the per-connection result cap: `resultByteCap` (Infinity for the trusted local CLI; else `mcp.max_result_bytes_stdio` 4 MiB / `mcp.max_result_bytes_http` 1 MiB, DB plane then file plane, clamped to 256 KiB–9 MiB), `encodedFrameBytes` (the complete JSON-RPC frame plus a framing reserve), and the dispatcher backstop pair `frameOverCap` / `resultTooLargeError`.- `src/mcp/instructions.ts` — canonical MCP initialize-time agent operating contract, compile-time source text (no runtime filesystem dependency) shared by the stdio SDK server, the OAuth HTTP SDK server and the legacy raw HTTP initialize path. `buildMcpInstructions({writeback?, tools?})` GENERATES the contract from the caller's callable set (`tools.callable`, the tools/list predicate): a clause naming a tool (search/query/get_page, skills catalog, put_page, whoami, join/sync skills, put/delete skill, the memory loop's `context_pack`/`volunteer_context`/`remember`/`forget`) appears only when that tool is listed, so every tool named is in that surface's tools/list (`test/mcp-initialize-instructions.test.ts`). When callable tools are left out of the listed set (`hiddenCallable`) and `request_tools` is callable, the hidden-tool sentence leads the contract, inside the 2,048 characters capped harnesses read (D1). It always carries the error protocol (follow `fix.next`, then `fix.verify`) and the notice prefix, then the optional status-only line (F4), the opt-in ambient-writeback section (`src/core/facts/writeback-instructions.ts`) and the readiness tail (top two `missing`/`degraded` gaps among embeddings, chat_llm, migrations, worker — never a by-choice state). With no `tools` and no writeback it equals `GBRAIN_MCP_INSTRUCTIONS` (the every-tool rendering bootstrap writes to GBRAIN-INSTRUCTIONS.md). `resolveMcpInstructions(config, env?, opts)` appends the operator-set deployment identity LAST under `Deployment identity:` (`GBRAIN_MCP_INSTRUCTIONS` env when non-blank, else file-plane `mcp.instructions`). `installInstructionsResolver(server, compute)` swaps the SDK Server's initialize handler so the stdio and OAuth servers compute the contract (callable set + readiness tail via `src/mcp/initialize-context.ts`) when the client initializes; the constructor value stays the fallback on a throw. The legacy bearer transport builds it inline per initialize. Transport tests compare against the contract for that connection's own tools/list (`test/helpers/instructions-parity.ts`): `test/serve-stdio-roundtrip.test.ts`, `test/http-transport.test.ts`, `test/connect-bearer.test.ts`, `test/mcp-instructions-writeback.test.ts`; identity composition in `test/mcp-server-identity.test.ts` + `test/config-set-mcp-instructions.test.ts`. #6170: `contractClauses(c, writeback)` puts the short `Ambient writeback is ON (<mode>)` line (with `visibility "private"` under a private posture) in the memory clause when writeback is on, follows the data-not-instructions clause with the shortened error protocol and moves the forget caveat after the scope clause, so the writeback line, `Follow \`fix.next\``, `[gbrain notice`, `context_pack`, `put_page REPLACES` and `Writing:` end inside the first 2,048 characters on every surface (pinned per surface × mode × extract_facts × visibility in `test/mcp-initialize-instructions.test.ts`); the full writeback section stays appended last. Cat 40's measured "Answering from the brain" clause is verbatim; the change needs the D12 Cat 40 smoke before merge. The brief clause puts the `referenced_by` walk on the single-name `entity` card and names only the fields compact `names` rows carry on the brain (`references: {namesRow, records}`, read at every per-initialize call site by `readInstructionContent` from `src/core/entity-references-config.ts`; the static contract is the defaults rendering; `test/mcp-instructions-references.test.ts`). Instruction 7's governing rule (`mcp.instructions_governing_rule`: `in_effect` default, `newest` the earlier recency sentence) leads the answering clause so it ends inside the first 2,048 characters (`test/mcp-instructions-governing-rule.test.ts` records its offset per surface).diff --git a/docs/architecture/key-files/skills.md b/docs/architecture/key-files/skills.mdindex c1a5aaf7a5..163b71c357 100644--- a/docs/architecture/key-files/skills.md+++ b/docs/architecture/key-files/skills.md@@ -23,7 +23,7 @@ Current behavior and load-bearing invariants; history belongs in Git and CHANGEL- `src/core/skill-trigger-index.ts` — Shared loader that unions per-skill SKILL.md frontmatter `triggers:` with curated RESOLVER.md / AGENTS.md rows from `skillsDir` AND the parent dir (preserves the OpenClaw workspace-root layout). UNION semantics: explicit RESOLVER.md rows ADD to frontmatter triggers (don't replace). Dedup keyed on `(skillPath, trigger.trim().toLowerCase())`. Three consumers fold through this primitive — `checkResolvable`, `runRoutingEvalCli`, `mounts-cache.composeResolvers` — so fixing frontmatter reaches all of them. Exports `loadSkillTriggerIndex(skillsDir): SkillTriggerEntry[]`, `entriesToResolverContent(entries): string` (synthesizes a markdown-table resolver string for `runRoutingEval`'s string-content API), `findPrimaryResolverPath(skillsDir): string | null`, the `FRONTMATTER_SECTION` constant, and `_resetWarnedSkillsForTests`. Skip rules: non-directory entries (a symlink dirent is followed via `statSync` — `readdirSync` dirents report the link's OWN type without following, so skill dirs symlinked in from a shared store, e.g. `~/.agents/skills/<name>`, still load), `_*`/`.*` prefixes, `conventions/`+`migrations/` subdirs, skills with no `SKILL.md` (deprecated `install/` graceful-skipped), no `triggers:` array, or malformed YAML (warn-once + skip). Reuses `parseSkillFrontmatter` from `src/core/skill-frontmatter.ts`, including block and wrapped flow-sequence arrays. Pinned by `test/skill-trigger-index.test.ts` (18 hermetic cases). CI gate `bun run check:resolver` (= `bun src/cli.ts check-resolvable --strict --skills-dir skills/`) wired into `bun run verify`.-- `src/core/skillopt/` + `src/commands/skillopt.ts` + `skills/skill-optimizer/` — self-evolving skill optimization grounded in the SkillOpt paper (arXiv 2605.23904). `gbrain skillopt <skill>` treats `SKILL.md` as trainable parameters of a frozen agent: validation-gated (median-of-3 + epsilon=0.05), budget-capped (preflight estimator), per-skill DB-locked (`tryAcquireDbLock('skillopt:<name>', 60min)`), atomic-versioned (history-intent-first 5-step commit), body-only mutations (frontmatter forbidden). Rollouts use `gateway.toolLoop` directly with no-op persistence callbacks (zero `subagent_messages` pollution) + a read-only tool allowlist derived from `BRAIN_TOOL_ALLOWLIST` minus `put_page`/`submit_job`/`file_upload`. Default is one gated one-shot rewrite (`optimizerMode`); `--loop` runs two reflect calls per step; rejected-edit buffer LRU-bounded to 100; bundled-skill gate; bootstrap workflow (sentinel + `--bootstrap-reviewed`); D_sel floor (>=5 with `--split` override); audit JSONL via `audit-writer.ts`. Added to `ALL_PHASES` after `patterns` (default OFF; opt-in via `gbrain config set cycle.skillopt.enabled true`); cycle phase wrapper at `src/core/skillopt/cycle-phase.ts` walks stale skills with per-skill ($0.50) + brain-wide ($2.00) caps. Added to `PROTECTED_JOB_NAMES`. Surface: dream-cycle phase wrapper; `--all` batch mode (`src/core/skillopt/batch.ts:runBatchAll`); `--target-models` fleet (`runFleet` parallel per-model receipts under `skillopt/fleet/<slug>/`); MCP op `run_skillopt` (admin scope + per-skill `skillopt.allowed_skills` allowlist, NOT localOnly, validates `skill_name` kebab-only + confines caller-supplied benchmark/held-out paths to skillsDir for remote callers); Minion `skillopt` handler + `--background` with `allowProtectedSubmit: true`; write-flavored optimization via `src/core/skillopt/write-capture.ts:buildWriteCaptureRegistry` (virtual `put_page`/`submit_job`/`file_upload` captured in-memory; `--write-capture` flag; its read tools and the rollout registry in `rollout.ts` drop `""`/`null` optional arguments and validate against the op schema before the handler, like MCP dispatch); held-out real-user test set via `src/core/skillopt/held-out.ts` (capture infra at `~/.gbrain/skillopt-captures/<skill>/<run>.jsonl`, `--held-out <path>` flag, `runHeldOutGate` candidate >= baseline). Hermetic via DI seams (`opts.chatFn` for optimizer + judge; `opts.toolLoopFn` for rollouts; no `mock.module`). `--bootstrap-from-skill` → `runBootstrapFromSkill` in `src/core/skillopt/bootstrap-benchmark.ts`: reads `SKILL.md` directly (no `routing-eval.jsonl`), makes ONE LLM call emitting a full starter benchmark (tasks + rule judges) as JSONL, parsed line-by-line with skip-bad-line salvage and a min-2-valid-checks-per-task drop; provider/transport errors PROPAGATE (not collapsed to `bootstrap_empty`). `--bootstrap-tasks N` (default 15, capped 50); `maxTokens` scales `min(8000, max(4000, N*220))`. The stderr REVIEW line prints the literal `gbrain skillopt <name> --bootstrap-reviewed --split 1:1:1` — load-bearing because the default `4:1:5` split makes a 15-task starter's `D_sel = floor(15/10) = 1`, below the `>=5` floor, so a 15-task benchmark needs `--split 1:1:1`. Both bootstrap generators share `assertBenchmarkAbsent` + `readSkillBodyOrThrow`; `--bootstrap-from-skill` is mutually exclusive with `--bootstrap-from-routing`/`--benchmark`/`--all`/`--target-models`/`--resume`. Generated rule judges are explicitly WEAK DRAFTS to be strengthened during the review gate. The held-out gate is wired: `--held-out <path>` is parsed and threaded through every caller (CLI main + `--background` `held_out_path` + batch/fleet `heldOutPath` + the `run_skillopt` `held_out_path` param), running at CHECKPOINT ACCEPTANCE so no-mutate/fleet paths can't promote a held-out-failing candidate. `assertBundledMutationHeldOut` in bundled-skill-gate.ts: bundled + `--allow-mutate-bundled` requires a NON-EMPTY held-out (`MIN_HELD_OUT_SIZE = D_SEL_MIN_SIZE` = 5, derived so they can't desync) or hard-refuses (exit 2), for ALL callers (they funnel through `runSkillOpt`); held-out must be task_id-DISJOINT from the benchmark (overlap rejected — can't catch overfitting). `receipt.baseline_sel_score` populated + a real final-test eval (`test_score` + `baseline_test_score`) scoring best + baseline on `split.test`; shared `scoreSkillOnTasks` primitive (validate-gate.ts) backs baseline/final-test/held-out scoring. `--no-mutate` writes proposed.md via `writeProposed` in version-store.ts. `maxRuntimeMin` ENFORCED (wall-clock deadline between steps → `skillopt_runtime_exceeded` → outcome aborted). Two eval-internal ablation opts on `SkillOptOpts` (NOT on CLI): `reflectMode` (`'both'`/`'failure-only'`) and `disableValidationGate` (greedy-accept), recorded in `RunReceipt` + audit `run_start` for replayability; `optimizerMode` is a product setting, required on `SkillOptOpts` (`'one-shot-rewrite'` default, `'reflect'` = `--loop`; `optimizer_mode` on the `run_skillopt` op and job data) and recorded in the receipt; `ROLLOUT_SUCCESS_THRESHOLD = 0.5` named constant for the partition; one-shot fence-strip is anchored (`^```...```$`) so an embedded code sample isn't truncated. Claude Haiku 4.5's dateless canonical id `claude-haiku-4-5` is in `src/core/anthropic-pricing.ts` (a `BudgetTracker`-capped run on Haiku would otherwise throw `no_pricing` on the FIRST `chat()` of every rollout); `runValidationGate` (validate-gate.ts) scans settled results for `isMustAbortError(error)` (from `worker-pool.ts`; `BUDGET_EXHAUSTED` is in `MUST_ABORT_ERROR_TAGS`) and re-throws so the caller aborts loudly instead of recording a hollow `selScore:0` — ordinary non-abort rollout errors still fail-open to `score:0` (judge-hiccup posture preserved), but a 100%-failed gate (every task errored — e.g. a logged-out `claude-cli` child — or every rollout carrying a `judge_error`) throws `skillopt_all_rollouts_failed` / `skillopt_all_judge_errors` (constants exported from validate-gate.ts) so a dead provider ends the run `errored` with the first provider message as `abort_detail` instead of a plausible `no_improvement` at 0.000; the orchestrator's zero-candidate step (reflect produced/parsed no edits) logs audit reason `no_edits_proposed[: <first reflect error>]` + one stderr line, distinct from the apply-rejected `no_edits_applied`, and does not touch the rejected buffer. `GBRAIN_CLAUDE_CLI_HERMETIC_CONFIG=1` (empty config dir) logs the child out on every platform, macOS included — docs/comment make no keychain-survives claim (pinned by `test/skillopt/deadline-and-hermetic.test.ts`). Pinned by 152 tests across 18 files (foundation + adversarial + v2 surface + E2E PGLite serial), `test/skillopt/bootstrap-from-skill.test.ts` (20 cases), `test/skillopt/rollout.test.ts`, `test/skillopt/validate-gate-abort.test.ts` (7 cases), held-out ENFORCE + one-shot-rewrite unit cases, and e2e (held-out block/allow, bundled no-mutate, runtime deadline, receipt honesty, held-out disjointness, no-DB-pollution). Drives the Track B SkillOpt benchmark suite in the sibling `gbrain-evals` repo.+- `src/core/skillopt/` + `src/commands/skillopt.ts` + `skills/skill-optimizer/` — self-evolving skill optimization grounded in the SkillOpt paper (arXiv 2605.23904). `gbrain skillopt <skill>` treats `SKILL.md` as trainable parameters of a frozen agent: validation-gated (median-of-3 + epsilon=0.05), budget-capped (preflight estimator), per-skill DB-locked (`tryAcquireDbLock('skillopt:<name>', 60min)`), atomic-versioned (history-intent-first 5-step commit), body-only mutations (frontmatter forbidden). Rollouts use `gateway.toolLoop` directly with no-op persistence callbacks (zero `subagent_messages` pollution) + a read-only tool allowlist derived from `BRAIN_TOOL_ALLOWLIST` minus `put_page`/`submit_job`/`file_upload`. Default is one gated one-shot rewrite (`optimizerMode`); `--loop` runs two reflect calls per step; rejected-edit buffer LRU-bounded to 100; bundled-skill gate; bootstrap workflow (sentinel + `--bootstrap-reviewed`); D_sel floor (>=5 with `--split` override); audit JSONL via `audit-writer.ts`. Added to `ALL_PHASES` after `patterns` (default OFF; opt-in via `gbrain config set cycle.skillopt.enabled true`); cycle phase wrapper at `src/core/skillopt/cycle-phase.ts` walks stale skills with per-skill ($0.50) + brain-wide ($2.00) caps. Added to `PROTECTED_JOB_NAMES`. Surface: dream-cycle phase wrapper; `--all` batch mode (`src/core/skillopt/batch.ts:runBatchAll`); `--target-models` fleet (`runFleet` parallel per-model receipts under `skillopt/fleet/<slug>/`); MCP op `run_skillopt` (admin scope + per-skill `skillopt.allowed_skills` allowlist, NOT localOnly, validates `skill_name` kebab-only + confines caller-supplied benchmark/held-out paths to skillsDir for remote callers); Minion `skillopt` handler + `--background` with `allowProtectedSubmit: true`; write-flavored optimization via `src/core/skillopt/write-capture.ts:buildWriteCaptureRegistry` (virtual `put_page`/`submit_job`/`file_upload` captured in-memory; `--write-capture` flag; its read tools and the rollout registry in `rollout.ts` drop `""`/`null` optional arguments and validate against the op schema before the handler, like MCP dispatch, and throw a failed read as `asAgentToolError` (`src/mcp/dispatch.ts`) so the model reads the same code, message, suggestion and runnable `fix` a read-scope HTTP MCP caller gets, with a fix naming only tools the rollout offers); held-out real-user test set via `src/core/skillopt/held-out.ts` (capture infra at `~/.gbrain/skillopt-captures/<skill>/<run>.jsonl`, `--held-out <path>` flag, `runHeldOutGate` candidate >= baseline). Hermetic via DI seams (`opts.chatFn` for optimizer + judge; `opts.toolLoopFn` for rollouts; no `mock.module`). `--bootstrap-from-skill` → `runBootstrapFromSkill` in `src/core/skillopt/bootstrap-benchmark.ts`: reads `SKILL.md` directly (no `routing-eval.jsonl`), makes ONE LLM call emitting a full starter benchmark (tasks + rule judges) as JSONL, parsed line-by-line with skip-bad-line salvage and a min-2-valid-checks-per-task drop; provider/transport errors PROPAGATE (not collapsed to `bootstrap_empty`). `--bootstrap-tasks N` (default 15, capped 50); `maxTokens` scales `min(8000, max(4000, N*220))`. The stderr REVIEW line prints the literal `gbrain skillopt <name> --bootstrap-reviewed --split 1:1:1` — load-bearing because the default `4:1:5` split makes a 15-task starter's `D_sel = floor(15/10) = 1`, below the `>=5` floor, so a 15-task benchmark needs `--split 1:1:1`. Both bootstrap generators share `assertBenchmarkAbsent` + `readSkillBodyOrThrow`; `--bootstrap-from-skill` is mutually exclusive with `--bootstrap-from-routing`/`--benchmark`/`--all`/`--target-models`/`--resume`. Generated rule judges are explicitly WEAK DRAFTS to be strengthened during the review gate. The held-out gate is wired: `--held-out <path>` is parsed and threaded through every caller (CLI main + `--background` `held_out_path` + batch/fleet `heldOutPath` + the `run_skillopt` `held_out_path` param), running at CHECKPOINT ACCEPTANCE so no-mutate/fleet paths can't promote a held-out-failing candidate. `assertBundledMutationHeldOut` in bundled-skill-gate.ts: bundled + `--allow-mutate-bundled` requires a NON-EMPTY held-out (`MIN_HELD_OUT_SIZE = D_SEL_MIN_SIZE` = 5, derived so they can't desync) or hard-refuses (exit 2), for ALL callers (they funnel through `runSkillOpt`); held-out must be task_id-DISJOINT from the benchmark (overlap rejected — can't catch overfitting). `receipt.baseline_sel_score` populated + a real final-test eval (`test_score` + `baseline_test_score`) scoring best + baseline on `split.test`; shared `scoreSkillOnTasks` primitive (validate-gate.ts) backs baseline/final-test/held-out scoring. `--no-mutate` writes proposed.md via `writeProposed` in version-store.ts. `maxRuntimeMin` ENFORCED (wall-clock deadline between steps → `skillopt_runtime_exceeded` → outcome aborted). Two eval-internal ablation opts on `SkillOptOpts` (NOT on CLI): `reflectMode` (`'both'`/`'failure-only'`) and `disableValidationGate` (greedy-accept), recorded in `RunReceipt` + audit `run_start` for replayability; `optimizerMode` is a product setting, required on `SkillOptOpts` (`'one-shot-rewrite'` default, `'reflect'` = `--loop`; `optimizer_mode` on the `run_skillopt` op and job data) and recorded in the receipt; `ROLLOUT_SUCCESS_THRESHOLD = 0.5` named constant for the partition; one-shot fence-strip is anchored (`^```...```$`) so an embedded code sample isn't truncated. Claude Haiku 4.5's dateless canonical id `claude-haiku-4-5` is in `src/core/anthropic-pricing.ts` (a `BudgetTracker`-capped run on Haiku would otherwise throw `no_pricing` on the FIRST `chat()` of every rollout); `runValidationGate` (validate-gate.ts) scans settled results for `isMustAbortError(error)` (from `worker-pool.ts`; `BUDGET_EXHAUSTED` is in `MUST_ABORT_ERROR_TAGS`) and re-throws so the caller aborts loudly instead of recording a hollow `selScore:0` — ordinary non-abort rollout errors still fail-open to `score:0` (judge-hiccup posture preserved), but a 100%-failed gate (every task errored — e.g. a logged-out `claude-cli` child — or every rollout carrying a `judge_error`) throws `skillopt_all_rollouts_failed` / `skillopt_all_judge_errors` (constants exported from validate-gate.ts) so a dead provider ends the run `errored` with the first provider message as `abort_detail` instead of a plausible `no_improvement` at 0.000; the orchestrator's zero-candidate step (reflect produced/parsed no edits) logs audit reason `no_edits_proposed[: <first reflect error>]` + one stderr line, distinct from the apply-rejected `no_edits_applied`, and does not touch the rejected buffer. `GBRAIN_CLAUDE_CLI_HERMETIC_CONFIG=1` (empty config dir) logs the child out on every platform, macOS included — docs/comment make no keychain-survives claim (pinned by `test/skillopt/deadline-and-hermetic.test.ts`). Pinned by 152 tests across 18 files (foundation + adversarial + v2 surface + E2E PGLite serial), `test/skillopt/bootstrap-from-skill.test.ts` (20 cases), `test/skillopt/rollout.test.ts`, `test/skillopt/validate-gate-abort.test.ts` (7 cases), held-out ENFORCE + one-shot-rewrite unit cases, and e2e (held-out block/allow, bundled no-mutate, runtime deadline, receipt honesty, held-out disjointness, no-DB-pollution). Drives the Track B SkillOpt benchmark suite in the sibling `gbrain-evals` repo.- `src/core/skillopt/{reflect,output-cap,run-outcome,remediation,checkpoint,models-plan,job,bootstrap-run,must-abort,preflight}.ts` — skillopt run honesty and model provenance (user docs: `docs/guides/skillopt.md` "Optimizer output" + "Model provenance"). **Output caps** (`output-cap.ts`): one optimizer cap for every reflect call (patch + rewrite modes) and the default one-shot rewrite, precedence `--reflect-max-tokens` / MCP+job `reflect_max_tokens` (remote callers clamped to 256-32000) > `skillopt.reflect_max_tokens` (invalid warns once, valid honored exactly) > `defaultMaxOutputTokens(optimizer)` (32000 thinking, 4096 otherwise); `skilloptOutputCap(model, siteCap)` gives the judge (200) and bootstrap sites `max(siteCap, 8192)` on thinking models only — gateway `chat()` semantics are untouched. **Reply classification** (`reflect.ts`): at most one error per call, in precedence `reflect_<mode>_truncated` (length stop; partial edits dropped) > `_empty_reply` > `_no_parseable_edits` > `_invalid_edits`; a fenced or bare `{"edits": []}` is a deliberate, usable empty; partial invalid drops sum into `reflect_invalid_edits_dropped`; the skill body is sent whole when it fits `resolveChatContextTokens(optimizer)` minus output cap and bounded prompt overhead at 3 chars/token (unknown window → 120,000 chars), else truncated with an in-prompt disclosure + `skill_body_truncated`; prompt + cap over the window refuses the call (`_context_too_small`), provider length errors map to `_context_overflow`; the one-shot rewrite refuses on `one_shot_rewrite_output_cap_too_small` / `_body_truncated` and never promotes a `_truncated` reply. The judge records `judge_error: llm_truncated` and bootstrap rows skip as `truncated` on a length stop. **Must-abort** (`must-abort.ts`): budget exhaustion, AI spend-policy refusals, runtime deadline and SIGINT rethrow (the validation gate uses the same predicate) at every optimizer/judge/held-out/bootstrap site, so the run ends `aborted` with its real reason. **Outcome** (`run-outcome.ts`): `accepted` if any candidate was accepted (even after an early stop), `errored` with `abort_detail: optimizer_output_unusable: <first error>` when no optimizer reply in the whole run was usable, else `no_improvement`; 2 consecutive fully-unusable steps (any class) stop the loop (`stop_reason: early_stop_unusable_output`); `buildResumeCommand` rebuilds the exact resume command from the stored run spec plus the run's mode, cost cap, runtime cap, `--models-strict` and `--force` (only when the run used it; the dirty-tree gate admits a resume whose SKILL.md equals the checkpoint's best text); output-cap failures (from `abort_detail`, or the trailing reflect error of an early stop) double the reflect cap, contract failures put a quoted `'<other-model>'` in place of the optimizer model. An early-stopped run keeps its checkpoint and resume command even when it resolves `no_improvement`; a resume re-runs the trailing fully-unusable steps (`rewindCursor`) and restarts the early-stop streak, a kept checkpoint banks the final evaluation's spend and the rewound cursor is persisted before any save, the cycle's skillopt phase GCs kept checkpoints older than 7 days, and a legacy checkpoint whose best text moved past its baseline counts as already accepted. CLI exit map: accepted 0, no_improvement 1, aborted/errored 2. **Remediation** (`remediation.ts`): `SKILLOPT_REMEDIATION_CODES` → `{code, fix, docs}` receipt entries whose `docs` anchors into the guide's error-code table (pinned by `test/skillopt/error-code-docs.test.ts`); errors deduped, max 20 x 300 chars. **Checkpoint/resume** (`checkpoint.ts`): stores a `next_epoch`/`next_step` cursor (legacy checkpoints converted), the early-stop counter, the reflect tally, ledger rows and cost on completed steps and handled aborts (an abort saves the step-start tally, since resume re-runs that step), and a run spec; `--resume` refuses a changed benchmark/held-out/split or a no-mutate → mutate widening, and allows optimizer model, reflect cap and cost cap overrides; the receipt merges prior segments into `models_used` (`models_used_scope: full_run`, or `since_resume` for legacy checkpoints) plus `prior_segments_cost_usd`. **Models plan** (`models-plan.ts`): `resolveSkillOptModels` is the ONE role resolution (optimizer→tier deep, target→subagent, judge→reasoning; flag > config chain) used by the CLI, the `run_skillopt` op, the cycle phase and the job handler (four-path golden test); `buildModelsPlan` adds per-task judge overrides (benchmark + held-out; the default judge is inactive when no reachable LLM-judged task lacks its own `judge.model`), gateway expansion/chat with retained sources, the embedding model of the column search actually reads (file plane / `GBRAIN_EMBEDDING_MODEL`, never DB rows) and the reranker when enabled; the stderr banner prints before any spend and `models_plan` lands on the receipt + `run_start` audit. Strict mode (`--models-strict` / `skillopt.models_strict`; unrecognized values warn and count as on) aborts before spend when any active touchpoint came from `models_default`, `tier_default`, `fallback`, `unknown` or a capability substitution, listing a copy-paste fix per touchpoint (an unreadable `skillopt.models_strict` counts as on; an explicit `embedding_columns.embedding` override counts as configuration); it applies to batch, fleet, both bootstrap modes and background jobs. Echoed strings pass `sanitizeEcho` (control chars stripped, 200-char cap). **Jobs** (`job.ts`): job data records the model flags and strict setting; the handler re-resolves sources and re-runs the strict check at execution time, legacy jobs resolve as `unknown`. **Bootstrap** (`bootstrap-run.ts`): both bootstrap modes resolve the optimizer via the plan, print its banner row, honor strict and `--dry-run`, and run under a `--max-cost-usd` tracker. **Preflight** (`preflight.ts`): prices each role's per-call reservation with the tracker's `reservationCostUsd` at effective caps and aborts pre-spend with `reservation_exceeds_cap` naming the role; the heuristic expected-cost estimate is reported separately. The cycle phase forwards `abort_reason`/`abort_detail`/`run_id`/`remediation`, records `skipped_budget` (no calls; retried only after the admission fingerprint — optimizer/target/judge models, reflect cap, per-skill cap, `pricing.overrides`, gbrain version, benchmark content (unreadable benchmark re-admits) — changes) and gates `errored` retries 24h via `cycle.skillopt.last_error.<skill>` without banking `last_run`.