Garry's Opinionated OpenClaw/Hermes Agent Brain
TypeScript
Merge remote-tracking branch 'origin/master' into capy/lhf-wave
garrytanee15c3669f08
diff --cc docs/architecture/key-files/agent-contract.mdindex fd283f5384,a717c99314..2b33b565f3--- a/docs/architecture/key-files/agent-contract.md+++ b/docs/architecture/key-files/agent-contract.md@@@ -9,7 -9,7 +9,7 @@@ Spec: `docs/designs/AGENT_OPERATOR_WAVE- `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`).- - `src/core/notice-ledger.ts` — notice dedupe/budget/mute. `NoticeLedger.tally(audience, key)` counts per-session events (dispatch counts reranker-degraded search/query calls with it and records `_meta.retrieval.rerank_degraded`). `NoticeLedger.admit(notices, {transport, principal, sessionId}, muted)`: stdio uses `processNoticeLedger()`; HTTP passes `ServeHttpContext.noticeLedger` (keyed by principal + transport-resolved session id, 10k keys, 24 h TTL). Per-call codes (`PER_CALL_NOTICE_CODES`: `degraded_recall`, `empty_retrieval`, `unknown_param`, `listing_truncated`, `source_binding_narrowed`, `local_transcripts`, `held_files`, `mention_index`, …) and, on HTTP, `degraded`/`safety` notices are never deduped, except that a notice's unrendered `Notice.dedupe_key` replaces its code as the dedupe identity and dedupes a per-call code once per session per key on stdio/CLI (`degradedRecallNotice` sets it only when every stage/reason pair is configuration-persistent: a keyless brain's `embed_unavailable`; HTTP ignores it for degraded notices; `renderNotice` never copies it); at most 2 coaching notices per session. Mutes apply to coaching/info notices and to `MUTEABLE_ASK_CODES` (only `first_run_decisions`). Mute store `<GBRAIN_HOME>/notices/muted.json`: owner list (global) + per-client lists; `mute_notice` op (`src/core/ops/notices.ts`, write scope; HTTP per client, stdio under the `stdio` audience that dispatch reads on stdio) and `gbrain notices mute|unmute|list` (`src/cli/commands/notices.ts`, owner; `unmuteNoticeForOwner` clears the global and the `stdio` lists, `list` shows both). Tests: `test/notice-ledger.test.ts`, `test/mcp-onboarding.test.ts` (stdio mute across a fresh process, MCP mute → CLI unmute).-- `src/core/notice-ledger.ts` — notice dedupe/budget/mute. `NoticeLedger.tally(audience, key)` counts per-session events (dispatch counts reranker-degraded search/query calls with it and records `_meta.retrieval.rerank_degraded`). `NoticeLedger.admit(notices, {transport, principal, sessionId}, muted)`: stdio uses `processNoticeLedger()`; HTTP passes `ServeHttpContext.noticeLedger` (keyed by principal + transport-resolved session id, 10k keys, 24 h TTL). Per-call codes (`PER_CALL_NOTICE_CODES`: `empty_retrieval`, `unknown_param`, `listing_truncated`, `source_binding_narrowed`, `local_transcripts`, `held_files`, `mention_index`) and, on HTTP, `degraded`/`safety` notices are never deduped; at most 2 coaching notices per session. Mutes apply to coaching/info notices and to `MUTEABLE_ASK_CODES` (only `first_run_decisions`). Mute store `<GBRAIN_HOME>/notices/muted.json`: owner list (global) + per-client lists; `mute_notice` op (`src/core/ops/notices.ts`, write scope; HTTP per client, stdio under the `stdio` audience that dispatch reads on stdio) and `gbrain notices mute|unmute|list` (`src/cli/commands/notices.ts`, owner; `unmuteNoticeForOwner` clears the global and the `stdio` lists, `list` shows both). Tests: `test/notice-ledger.test.ts`, `test/mcp-onboarding.test.ts` (stdio mute across a fresh process, MCP mute → CLI unmute). D4: `claim(key)` (true once per key) and `memoize(key, compute)` back the once-per-session `grant_blocked_operations` notice; codes in `SELF_DEDUPED_NOTICE_CODES` were deduped by their producer on its own key, so `admit` applies mute only. `hidden_tool_content` is per-call.++- `src/core/notice-ledger.ts` — notice dedupe/budget/mute. `NoticeLedger.tally(audience, key)` counts per-session events (dispatch counts reranker-degraded search/query calls with it and records `_meta.retrieval.rerank_degraded`). `NoticeLedger.admit(notices, {transport, principal, sessionId}, muted)`: stdio uses `processNoticeLedger()`; HTTP passes `ServeHttpContext.noticeLedger` (keyed by principal + transport-resolved session id, 10k keys, 24 h TTL). Per-call codes (`PER_CALL_NOTICE_CODES`: `degraded_recall`, `empty_retrieval`, `unknown_param`, `listing_truncated`, `source_binding_narrowed`, `local_transcripts`, `held_files`, `mention_index`, …) and, on HTTP, `degraded`/`safety` notices are never deduped, except that a notice's unrendered `Notice.dedupe_key` replaces its code as the dedupe identity and dedupes a per-call code once per session per key on stdio/CLI (`degradedRecallNotice` sets it only when every stage/reason pair is configuration-persistent: a keyless brain's `embed_unavailable`; HTTP ignores it for degraded notices; `renderNotice` never copies it); at most 2 coaching notices per session. Mutes apply to coaching/info notices and to `MUTEABLE_ASK_CODES` (only `first_run_decisions`). Mute store `<GBRAIN_HOME>/notices/muted.json`: owner list (global) + per-client lists; `mute_notice` op (`src/core/ops/notices.ts`, write scope; HTTP per client, stdio under the `stdio` audience that dispatch reads on stdio) and `gbrain notices mute|unmute|list` (`src/cli/commands/notices.ts`, owner; `unmuteNoticeForOwner` clears the global and the `stdio` lists, `list` shows both). Tests: `test/notice-ledger.test.ts`, `test/mcp-onboarding.test.ts` (stdio mute across a fresh process, MCP mute → CLI unmute). D4: `claim(key)` (true once per key) and `memoize(key, compute)` back the once-per-session `grant_blocked_operations` notice; codes in `SELF_DEDUPED_NOTICE_CODES` were deduped by their producer on its own key, so `admit` applies mute only. `hidden_tool_content` is per-call.- `src/core/ops/callable.ts` — `isCallable(op, {transport, surface, scopes, publishGates, allowedOps})`: the one predicate behind stdio `stdioVisibleTools`, serve-http `listMcpTools`, the legacy bearer transport's tools/list, and `dispatchRenderContext` (which tools a fix may name). `publishGatesFromDisabled` converts the gate resolver's disabled-op set. Test: `test/callable-predicate.test.ts` (list ⇔ pre-A2 filters; list ⇔ dispatch on surface/locality).- `src/cli/cli-error.ts` — the CLI's one error writer (D1): `writeCliError`/`exitCliError` render through `renderCliError` (human `Error [code]` / `Fix:` / `Why:` / `Docs:` on stderr; under `--json` one envelope on stdout plus the human lines on stderr) and record the code for the guard's fallback document; a `legacy` shape (unknown flag's `{status, reason:'invalid_flag', message}`, `pglite_busy`'s `next_action`) leads, keeps its values and stays one line. `usageError` (`invalid_params` / `unknown_flag` / `unknown_command`, exit 2), `unknownFlagError` (did-you-mean from the command's curated help flags, else the acceptance registry), `writeFatalCliError` (the `import.meta.main` seam; keeps the `GBRAIN_DB_ACCESS` marker + remediation on human output). Test: `test/cli-error-render.test.ts`.- `src/cli/help/<command>.ts` + `src/cli/help/render.ts` + `src/cli/help/validate.ts` — D3/D4 curated CLI help. Each spec module exports `help: CliHelpSpec` (`summary`, `usage`, `flags: [{name, type: boolean|string|number|enum, values?, desc, consent?}]`, 2–4 `examples`, `end_of_options?`) and is loaded lazily through its command-table record's `help: () => import('./help/<name>.ts')` (literal, so `bun build --compile` bundles it and `gbrain --version` loads none; pinned by `test/cli-command-table.test.ts` and `scripts/check-compile-autoload.sh`). Curated today: doctor, import, serve, apply-migrations, autopilot, status, onboard; every curated flag must be in the generated acceptance registry and `--yes` is listed wherever the handler parses it. `printCuratedHelp` answers `gbrain <cmd> --help`/`-h` first in main()'s help short-circuit, engine-free (human table with type/values/consent; `--help --json` one document `{command, …spec, contract_version}`). `curatedFlagError(command, args)` (called in main() after the unknown-flag check) refuses a missing/non-numeric `number` value or an out-of-set `enum` value with `invalid_params` (exit 2) via `flagValueError`, example value drawn from the spec's examples; `--flag=value` and `--flag value`, stops at a bare `--`; `string` flags (e.g. onboard's `--max-usd off`) are not checked. `unknownFlagError` draws did-you-mean candidates from the curated flags. Tests: `test/cli-help-curated.test.ts`, `test/cli-help-curated-cli.test.ts`.diff --cc src/core/behavior-change-notice.tsindex 69688207f9,d2857c001e..f730cbdde9--- a/src/core/behavior-change-notice.ts+++ b/src/core/behavior-change-notice.ts@@@ -479,12 -479,8 +479,14 @@@ export const BEHAVIOR_CHANGES: Readonly{ since: '0.60.185.0', text: 'gbrain\'s own brain-repo commits (page write-through, facts fences, takes, timeline, `lint --fix`, and `sources harden` scaffolding) now take the checkout\'s commit lock (write-through waits 2 seconds, then commits its one path without it), commit only their own paths, and include both sides of a staged `git mv` rename. Paths passed to the helper or `gbrain git commit-push` are literal: a quoted glob no longer expands and fails `commit_paths_invalid`; name the files.' },{ since: '0.60.185.0', text: 'The pull that `gbrain sources pull`, the pull cron, `sources harden` and the workspace push run no longer rebases: a branch whose local and remote sides diverged is merged in memory and the checkout fast-forwards to the merge, for `pull_strategy: rebase` as well as `merge` (`set-pull-strategy` is still accepted). `gbrain sync`\'s pull is now a fetch plus a fast-forward under the commit lock. `gbrain sources harden` sets `rebase.autoStash=false`, `merge.autoStash=false` and `pull.ff=only` in the checkout\'s local git config so a stray `git pull` refuses instead of autostashing. A conflict now stops with `integrate_conflict` (ask the user; resolve with `gbrain git commit-push --push-only --expect-remote <sha> --resolve <path>=ours|theirs`), and `put_page` reports an unresolved one for that checkout.' },{ since: '0.60.185.0', text: 'The committed `scripts/brain-commit-push.sh` written by `gbrain sources harden` needs a gbrain that knows `git commit-push` to integrate remote commits. Without one it does only a locked, path-scoped commit and a plain push, and a rejected push now fails loudly (exit 4, PUSH FAILED) instead of rebasing. A helper written by a newer gbrain (a higher `# gbrain-protocol:` line) is never downgraded by an older harden.' },+ // GBRA-60 D2/D4 in-band notices. `since` is provisional (current VERSION); restamped at the merge slot.+ { since: '0.60.186.0', text: 'Two new info notices on MCP results; nothing a connection can call changes. `grant_blocked_operations` tells an authenticated connection once per session (once per grant revision for stateless HTTP) that its grant\'s operation snapshot, stored client surface or the server surface keeps operations its scopes allow out of reach, with counts and no operation names, and gives the brain owner\'s preview-then-apply rescope command (a missing scope is named only on a refused call). `hidden_tool_content` on get_page, search and query says when the result left out takes that a tool outside the tool list serves, with the next step that connection can take: the takes_list call (stdio also lists it), one request_tools {surface} widen, or the owner\'s repair. Fixes no longer name an MCP tool outside the grant\'s operation snapshot, and the stdio unknown-tool hint no longer offers a widen that read-only access or GBRAIN_MCP_FORCE_SURFACE would refuse.' },+ // Low-hanging-fruit wave (GBRA-81 items 1 and 1b).+ { since: '0.60.186.0', text: '`query` now expands only when the search mode says so: on in `tokenmax`, off in `balanced` (the default) and `conservative`, so `query` on a `balanced` brain no longer makes an expansion LLM call before retrieval. `expand: true` (CLI `--expand`) expands one call in any mode, and `gbrain config set search.expansion true` restores expansion by default for the brain; `expand: false` (`--no-expand`) still skips it. A `search.expansion` value set earlier, which `query` used to ignore, now takes effect on `query`; `gbrain search modes` shows it. `search` never expands, as before. CRAG escalation now reads whether the first pass actually expanded (`expansion_applied`), and eval capture records the `expand` the caller sent (null when unset) so `gbrain eval replay` replays the mode default.' },+ { since: '0.60.186.0', text: '`gbrain init --search-mode <conservative|balanced|tokenmax>` records the operator\'s choice: no recommendation, no first-run `search_mode` question, and `search.mode_source: operator` (picker choices record `auto`, and `gbrain config set search.mode` records `operator`). On a brain that already has a different mode it refuses unless `--force`. Init now recommends `balanced` instead of `conservative` when a reranker is ready but no chat key exists, and provider keys saved in `~/.gbrain/config.json` count toward the recommendation. The install matrix now prices Haiku 5.5, Sonnet 5.5 and Opus 5.5 from gbrain\'s pricing table (about a 200x corner-to-corner spread), and switching modes no longer promises a cache refill while semantic result caching is off.' },+ // Low-hanging-fruit wave (GBRA-81 items 2 and 3).+ { since: '0.60.186.0', text: 'Lean `search` and `query` rows (remote callers) now carry `id`, the `fetch` key, only when the connection can call `fetch` at that moment: a `full` surface, a stdio session `request_tools` widened, or an HTTP client whose surface and scopes include it. On `starter` and `verbs` connections, `fetch` was never callable, so the row\'s `slug` and `source_id` identify the page; `fields: "full"` returns every field, `id` included, and the `mcp.result_rows: full` host setting does so for every remote caller. Lean-row `score` now prints 4 significant digits. The local CLI and gbrain\'s thin client keep full rows, unchanged. `fetch` called without an id now says to re-run `search` once `fetch` is callable, or to pass the row\'s slug.' },+ { since: '0.60.186.0', text: 'On stdio MCP and the CLI, the `degraded_recall` notice now shows on every call a transient degradation affects (`rerank_failed`, `embed_timeout`, a failed keyword or title arm, and every other per-call stage); it used to show once per session, so a rerank failure after an earlier embedding timeout returned fused-order results with no notice. A keyless brain whose only degradation is `embed_unavailable` still shows it once per session. HTTP is unchanged: every affected call. `_meta.retrieval.degraded` still records every call\'s stages.' },];/** The newest disclosed change's release: the notice id moves only when a release adds rows. */diff --cc src/core/notice-ledger.tsindex 8183fdc7d9,26eb32849f..649c7badda--- a/src/core/notice-ledger.ts+++ b/src/core/notice-ledger.ts@@@ -25,10 -20,13 +25,13 @@@ import type { Notice, Transport } fromconst MAX_KEYS = 10_000;const TTL_MS = 24 * 60 * 60 * 1000;export const COACHING_BUDGET_PER_SESSION = 2;-/** Notices that describe THIS call's result (never deduped): the diagnosis must ride every affected call. *//** The one muteable `ask`: an unanswered first-run bundle must stay dismissible. Every other ask always shows. */export const MUTEABLE_ASK_CODES: ReadonlySet<string> = new Set(['first_run_decisions']);-export const PER_CALL_NOTICE_CODES: ReadonlySet<string> = new Set(['hidden_tool_content', 'empty_retrieval', 'unknown_param', 'listing_truncated', 'former_relationships_hidden', 'source_binding_narrowed', 'local_transcripts', 'held_files', 'relational_chain', 'mention_index', 'delta_incomplete', 'identity_siblings_capped', 'alias_fanout', 'facts_unembedded']);+/** Notices that describe THIS call's result (never deduped unless the notice carries a `dedupe_key`): the diagnosis must ride every affected call. */- export const PER_CALL_NOTICE_CODES: ReadonlySet<string> = new Set(['degraded_recall', 'empty_retrieval', 'unknown_param', 'listing_truncated', 'former_relationships_hidden', 'source_binding_narrowed', 'local_transcripts', 'held_files', 'relational_chain', 'mention_index', 'delta_incomplete', 'identity_siblings_capped', 'alias_fanout', 'facts_unembedded']);++export const PER_CALL_NOTICE_CODES: ReadonlySet<string> = new Set(['degraded_recall', 'hidden_tool_content', 'empty_retrieval', 'unknown_param', 'listing_truncated', 'former_relationships_hidden', 'source_binding_narrowed', 'local_transcripts', 'held_files', 'relational_chain', 'mention_index', 'delta_incomplete', 'identity_siblings_capped', 'alias_fanout', 'facts_unembedded']);++ /** Notices whose producer already deduped them with `claim` on its own key; admit applies mute only. */+ export const SELF_DEDUPED_NOTICE_CODES: ReadonlySet<string> = new Set(['grant_blocked_operations']);export interface NoticeAudience {transport: Transport;@@@ -73,9 -91,9 +96,9 @@@ export class NoticeLedgerconst session = this.session(audience);for (const n of notices) {if ((n.kind === 'coaching' || n.kind === 'info' || MUTEABLE_ASK_CODES.has(n.code)) && muted.has(n.code)) continue;- const always = (PER_CALL_NOTICE_CODES.has(n.code) && n.dedupe_key === undefined)- const always = PER_CALL_NOTICE_CODES.has(n.code) || SELF_DEDUPED_NOTICE_CODES.has(n.code)++ const always = (PER_CALL_NOTICE_CODES.has(n.code) && n.dedupe_key === undefined) || SELF_DEDUPED_NOTICE_CODES.has(n.code)|| (audience.transport === 'http' && (n.kind === 'degraded' || n.kind === 'safety'));- const key = `${session}|${n.code}`;+ const key = n.dedupe_key === undefined ? `${session}|${n.code}` : `${session}|${n.code}|${n.dedupe_key}`;if (!always && this.seen.has(key)) continue;if (n.kind === 'coaching') {const used = this.coaching.get(session)?.count ?? 0;