Skip to content

Garry's Opinionated OpenClaw/Hermes Agent Brain

TypeScript

docs(key-files): pollCommand quoting, parseRepoBase normalization

time-attack1aa67709724d
diff --git a/docs/architecture/key-files/agent-contract.md b/docs/architecture/key-files/agent-contract.md
index 8c446885b1..8495f76044 100644
--- a/docs/architecture/key-files/agent-contract.md
+++ b/docs/architecture/key-files/agent-contract.md
@@ -5,7 +5,7 @@ Current behavior and load-bearing invariants; history belongs in Git and CHANGEL
Spec: `docs/designs/AGENT_OPERATOR_WAVE.md`; wire goldens: `test/fixtures/agent-contract/v1/`.
- `src/core/fix-routing.ts` — A1 render-time routing pin: `pinRouting(argv, routing)` appends `--brain`/`--source` before a bare `--` for commands that route them (shared ops registered by `operations.ts`; CLI-only commands from the generated `CLI_ROUTING_FLAGS`, built from the command table's `phase`/`routes_source` and each command's code). Holds the CLI process's routing provider (`installCliRouting`, installed by `src/cli/fix-routing-provider.ts`; never for `serve`) and the first source the invocation resolved (`noteResolvedSource`, called by the source resolver). Never imports the command table (its lazy loaders would bundle every command). Tests: `test/fix-routing.test.ts`; journey proof in `test/agent-journey-recovery.serial.test.ts`.
-- `src/core/agent-output.ts` — the contract v1 types and renderers every surface shares: `Action` (stored; never carries `next` or `command`) and `RenderedAction`, `Notice`/`RenderedNotice`, `AgentEnvelope`, `RenderContext`. `deriveNext` is the published decision table (no runnable step → `report`; provider → `wait`; user/host_admin or a CLI-only fix on MCP → `tell_user_to_run`; unpreapproved consent, and `destructive` always → `ask_user`; else `run`). `renderAction` drops `mcp` unless `ctx.isCallable` (an MCP-only fix on the CLI, a thin client's remote fix, is kept as relay data with actor `user` and `tell_user_to_run`), pins `ctx.routing` (`--brain`/`--source`) into every gbrain argv via `src/core/fix-routing.ts`, renders `command` only from argv via `shellQuote`, rewrites a CLI-only agent fix to actor `user` (stdio) / `host_admin` (http). `inertText` flattens newlines and breaks marker tokens in every interpolated value. `docsUrl` pins `v<VERSION>` for a published package, `master` for a source checkout, `LLMS_REPO_BASE` for forks when `src/core/repo-base.ts` `parseRepoBase` accepts it (W4.12: a plain `https://host/path`, no credentials, query, fragment or whitespace; an invalid value is ignored with one stderr warning, and the build scripts refuse it through `repoBaseOrThrow`). `redactForTransport` is the one HTTP redaction pass (paths, PIDs, key names, posture keys). `toAgentError` is total and table-driven (OperationError incl. F0 refresh refusals → `fix.argv`, StructuredAgentError, BudgetExhausted/no_pricing with `inputs`, RemoteMcpError, CredentialError, AIConfig/AITransient, GBrainError, legacy PhaseError objects, the `GBRAIN_DB_ACCESS` classifier, unknown throws → `internal_error` naming the op); it applies the safe-recovery rule (an unknown-outcome mutation points at its receipt; `retryable` only for `idempotent` ops), adds the registry's diagnostic default fix for server/unavailable classes, logs internal faults and suggestion-less envelopes to E11, and redacts on http. `renderCliError`, `toolResultWithNotices` (content[0] byte-identical; notices as prefixed extra blocks + `_meta.gbrain_notices`), `toolErrorResult` (exactly one block), `withAgentSiblings`/`legacyNestedErrorDocument` (nested legacy shapes gain `code`/`fix`), `fallbackJsonDocument`. Tests: `test/agent-output.test.ts`, `test/agent-error.test.ts`, `test/agent-contract-goldens.test.ts`. `PageProjectionConflictError` has its own row (`page_projection_conflict`, `detail` names the changed fields, re-run suggestion naming the CLI command, read-only `gbrain get` fix) ahead of the unknown-throw fallback.
+- `src/core/agent-output.ts` — the contract v1 types and renderers every surface shares: `Action` (stored; never carries `next` or `command`) and `RenderedAction`, `Notice`/`RenderedNotice`, `AgentEnvelope`, `RenderContext`. `deriveNext` is the published decision table (no runnable step → `report`; provider → `wait`; user/host_admin or a CLI-only fix on MCP → `tell_user_to_run`; unpreapproved consent, and `destructive` always → `ask_user`; else `run`). `renderAction` drops `mcp` unless `ctx.isCallable` (an MCP-only fix on the CLI, a thin client's remote fix, is kept as relay data with actor `user` and `tell_user_to_run`), pins `ctx.routing` (`--brain`/`--source`) into every gbrain argv via `src/core/fix-routing.ts`, renders `command` only from argv via `shellQuote`, rewrites a CLI-only agent fix to actor `user` (stdio) / `host_admin` (http). `inertText` flattens newlines and breaks marker tokens in every interpolated value. `docsUrl` pins `v<VERSION>` for a published package, `master` for a source checkout, `LLMS_REPO_BASE` for forks when `src/core/repo-base.ts` `parseRepoBase` accepts it (W4.12: a plain `https://host/path`, no credentials, query, fragment or whitespace, returned as the parser normalizes it (fix wave 13 P1.16); an invalid value is ignored with one stderr warning, and the build scripts refuse it through `repoBaseOrThrow`). `redactForTransport` is the one HTTP redaction pass (paths, PIDs, key names, posture keys). `toAgentError` is total and table-driven (OperationError incl. F0 refresh refusals → `fix.argv`, StructuredAgentError, BudgetExhausted/no_pricing with `inputs`, RemoteMcpError, CredentialError, AIConfig/AITransient, GBrainError, legacy PhaseError objects, the `GBRAIN_DB_ACCESS` classifier, unknown throws → `internal_error` naming the op); it applies the safe-recovery rule (an unknown-outcome mutation points at its receipt; `retryable` only for `idempotent` ops), adds the registry's diagnostic default fix for server/unavailable classes, logs internal faults and suggestion-less envelopes to E11, and redacts on http. `renderCliError`, `toolResultWithNotices` (content[0] byte-identical; notices as prefixed extra blocks + `_meta.gbrain_notices`), `toolErrorResult` (exactly one block), `withAgentSiblings`/`legacyNestedErrorDocument` (nested legacy shapes gain `code`/`fix`), `fallbackJsonDocument`. Tests: `test/agent-output.test.ts`, `test/agent-error.test.ts`, `test/agent-contract-goldens.test.ts`. `PageProjectionConflictError` has its own row (`page_projection_conflict`, `detail` names the changed fields, re-run suggestion naming the CLI command, read-only `gbrain get` fix) ahead of the unknown-throw fallback.
- `src/core/error-registry.ts` — `CODES`: one row per literal error code thrown in `src/` (class, summary, optional why/reasons/docs/suggestion/diagnostic-only fix/effects/actor/`legacy_error`/`renamed_from`/`exit`/`retryable`); `RegistryCode` is its key union. `NOTICE_CODES`: notice codes with their kind (mute accepts coaching/info only). New codes: add a row, then `bun run build:error-codes`. Completeness is AST-checked by `test/error-catalogue.test.ts` and `scripts/check-agent-contract.ts`.
- `src/core/error-docs.ts` — renders registry rows (meaning · why · next step · who acts/consent · verify · exit · retryable) for `docs/guides/error-codes.md` (`scripts/build-error-codes.ts`, `check:error-codes` in verify) and `gbrain errors` (`src/cli/commands/errors.ts`: `<code>`, `--changed`, list; `--json`; unknown code exits 2 with a did-you-mean).
- `src/core/agent-contract-log.ts` — E11 seam: `recordAgentContractEvent` appends `{ts, op|command, transport, code, has_suggestion | effects, outcome, fault}` (never params or messages) to `<GBRAIN_HOME>/agent-contract/events.jsonl`, bounded (halved past 1 MiB), synchronous, fail-open. `readAgentContractEvents` feeds doctor's `agent_contract` check (`src/commands/doctor/checks/agent-contract.ts`).
diff --git a/docs/architecture/key-files/core-persistence.md b/docs/architecture/key-files/core-persistence.md
index cf40cdac99..90c88ec2ea 100644
--- a/docs/architecture/key-files/core-persistence.md
+++ b/docs/architecture/key-files/core-persistence.md
@@ -41,7 +41,7 @@ Connector ingestion, item holds, checkpoint validation and the single-write fast
- `src/core/persistence/page-input.ts` — freezes scoped subagent type normalization at durable admission, after existing-request replay. An explicit undeclared model-authored type becomes `note` with `legacy_type` retained using the then-active schema pack; a replay keeps its original normalized payload when the pack changes. Caller intent remains unchanged for idempotency checks. Raw input size is checked before normalization and malformed Markdown is left to the importer’s sanitized error contract. `test/brain-allowlist.test.ts` pins changed-pack replay, raw-size refusal, and private parse-error redaction. `undeclaredPageTypeWarning` covers every other `put_page` (not managed file imports): a type the write source's pack neither declares nor aliases is stored as written and the committed result carries `type_warning` (`code: page_type_undeclared`, cause, fix, docs), also logged; pinned by `test/put-page-type-warning.test.ts`.
- `src/core/persistence/params.ts` — runtime-leaf mutation parameter and receipt schemas shared with the frozen verb registry. Its operation-contract import is type-only; runtime validators live in separate modules to avoid a registry initialization cycle. `preconditions.ts` validates UUID/revision/force syntax. `purge-params.ts` validates local-only purge shape/trust before admission and publication, keeping purge diagnostics out of generic precondition imports and unrelated command flag scans. `test/persistence-cold-import.test.ts` loads each validator/contract/registry entry in a fresh process and preserves schema and typed-error identity.
-- `src/core/persistence/write-wait.ts` — the CLI write-wait and exit contract (#5232). `resolveCliWriteWaitMs` (`--wait` seconds > `GBRAIN_WRITE_WAIT_MS` > file-plane `persistence.write_wait_ms` > 30 s; agents keep `AGENT_WRITE_WAIT_MS`); `writeExchangeBudget` (transport deadline = wait + 15 s admission headroom; an explicit `--timeout` shortens the requested owner wait instead); `replayWhilePending` (replays the identical request ID while an older owner, a remote server or a subagent tool's own bounded wait reports pending; the caller-supplied `sleep` decides how each pause ends, which is how subagent tool writes stop on abort); `writeErrorExitCode` keys on an admitted non-terminal receipt (`admittedPendingReceipt` in `types.ts`): pending → `PENDING_WRITE_EXIT_CODE` (0 with `--accept-pending`/`GBRAIN_ACCEPT_PENDING=1`), anything else → 1. Pinned by `test/pending-write-exit.serial.test.ts` and `test/pending-write-exit-owner.test.ts`. `pollCommand` (#6255) renders the envelope's receipt `fix.argv` (`gbrain write-request --brain <id> -- <request_id>`), else pins that argv to the CLI routing.
+- `src/core/persistence/write-wait.ts` — the CLI write-wait and exit contract (#5232). `resolveCliWriteWaitMs` (`--wait` seconds > `GBRAIN_WRITE_WAIT_MS` > file-plane `persistence.write_wait_ms` > 30 s; agents keep `AGENT_WRITE_WAIT_MS`); `writeExchangeBudget` (transport deadline = wait + 15 s admission headroom; an explicit `--timeout` shortens the requested owner wait instead); `replayWhilePending` (replays the identical request ID while an older owner, a remote server or a subagent tool's own bounded wait reports pending; the caller-supplied `sleep` decides how each pause ends, which is how subagent tool writes stop on abort); `writeErrorExitCode` keys on an admitted non-terminal receipt (`admittedPendingReceipt` in `types.ts`): pending → `PENDING_WRITE_EXIT_CODE` (0 with `--accept-pending`/`GBRAIN_ACCEPT_PENDING=1`), anything else → 1. Pinned by `test/pending-write-exit.serial.test.ts` and `test/pending-write-exit-owner.test.ts`. `pollCommand` (#6255) renders the envelope's receipt `fix.argv` (`gbrain write-request --brain <id> -- <request_id>`), else pins that argv to the CLI routing; each argument is shell-quoted (`src/core/shell-quote.ts`, fix wave 13 P1.15).
- `src/core/persistence/page-edit.ts` — `edit_page` (#5616): splits the canonical serialization into editable text and protected takes/facts segments whose remote view matches get_page's sanitized `content` byte for byte; `applyPageEdits` applies ordered exact-once replacements inside editable text only (typed `edit_no_match`/`edit_ambiguous_match`/`edit_protected_span`/`edit_invalid`), so canonical fences never move; `editDiff` caps the caller-view diff at 8 KB. Called at submission (`page-mutations.ts`, before admission) and again on the locked snapshot in `page-prepare.ts`, which gives edit_page put_page's revision-bound `editing` timeline semantics. Pinned by `test/edit-page.test.ts`.
- `src/core/persistence/suffixed-slug.ts` — `.md`/`.mdx`-suffixed slugs (#4807). `preparePageAdmission` refuses a new put_page/put_pages slug ending in `.md`/`.mdx` before any journal row (`invalid_params`, why, suggestion naming the bare slug, read-only `get_page` fix and verify); a live page with that exact (source_id, slug) still updates and the put_page response carries `slug_advisory` (put under the bare slug, then delete_page). `suffixedSlugDryRun` serves put_page dry runs; `suffixedFrontmatterSlugHold` holds a file import whose frontmatter `slug:` identity ends in `.md` as `frontmatter_slug_conflict`. `validateSlug` and path-derived import slugs are unchanged. Test: `test/ingestion/put-page-write-through.test.ts`.