Skip to content

Garry's Opinionated OpenClaw/Hermes Agent Brain

TypeScript

Merge remote-tracking branch 'origin/master' into capy/gbra151-notices-get-slices

garrytanab59c2aecc9c
diff --cc docs/architecture/key-files/entrypoints-and-docs.md
index 13f4a7f29d,3a3520f3cb..eb4399add7
--- a/docs/architecture/key-files/entrypoints-and-docs.md
+++ b/docs/architecture/key-files/entrypoints-and-docs.md
@@@ -117,8 -117,8 +117,8 @@@ Current behavior and load-bearing invar
- `src/assets/wasm/` — 37 tree-sitter grammar WASMs + tree-sitter runtime. Committed to the repo so `bun --compile` embeds them deterministically via `import path from ... with { type: 'file' }`. The CI guard `scripts/check-wasm-embedded.sh` requires semantic TypeScript and Bash case-statement symbols in the compiled binary. Bash uses the official tree-sitter-bash v0.23.3 ABI-14 release asset, pinned by checksum in `scripts/vendor-bash-wasm.sh`; `src/assets/wasm/README.md` records provenance. Code chunker version 7 invalidates old content hashes; `gbrain sync --source <id> --full` revisits affected history in active repositories. `tree-sitter-sql.wasm` (DerekStride/tree-sitter-sql @ c2e1e08db1ea20dc23bdb8d228a81a8756e9c450, built with [email protected] --abi 14) adds SQL coverage at 11 MB — larger than peers because the grammar covers PostgreSQL + MySQL + SQLite + T-SQL basics (40 MB generated parser.c); the compiled binary grows ~6%.
- `src/cli.ts` — the entry point (`bun src/cli.ts`, the `gbrain` bin, the compiled binary): Bun floor, signal handlers and stdout delivery, then either the engine-free fast path (`cliFastPath`: `--version`, `version`, bare `gbrain`, `--help`, `-h`, after global-flag parsing and `runCliPreflight`) or a dynamic import of the dispatcher, `src/cli/main.ts` `runCli()`. Its static imports are paid by every invocation and stay light: the dispatcher's graph (every operation and command module) loads only for real commands, so `--version` and top-level help skip it. The top-level help text is `src/cli/top-help.ts`, shared by both paths. Pinned by `test/cli-fast-path.test.ts` (fast-path branches, output parity, and import-graph bounds for the entry and the dispatcher).
-- `src/cli/main.ts` — the dispatcher (moved out of `src/cli.ts`; tests import its helpers from here). It keeps three graphs off every command: `completeEngineStartup` asks `migrate-pending.ts` (generated latest version) before loading `migrate.ts` and its ~220 migration modules, `thin-client-upgrade-prompt.ts` takes `compareVersions` from `migration-ledger.ts` instead of the upgrade orchestrator registry, and `mcp-client.ts` loads the MCP HTTP client SDK on the first remote call. Generic thin-client mutation failures use the shared persistence reporter, retaining request IDs and typed JSON receipts while preserving SIGINT exit 130. `test/thin-client-write-errors.serial.test.ts` exercises real CLI timeout, cancellation, pending and conflict paths against a loopback MCP fixture. No-DB fallbacks announce themselves on stderr instead of degrading silently. `dream` dispatch binds the caught engine-connect error and emits `[dream] WARNING: could not connect to DB (...)` before falling through to filesystem-only phases; the `runDream(null, ...)` no-DB fallback is preserved (pinned by `test/cli-dream-engine-warn.test.ts`, 2 subprocess cases against good + bad DATABASE_URL). `doctor` dispatch does the same: when `connectEngine` OR the DB-backed `runDoctor` run throws, it emits `[doctor] DB-backed doctor run failed (...) — falling back to filesystem-only checks`, scrubbing the error message through BOTH `url-redact.ts:redactUrlsInText` and `redact-connection-info.ts:redactConnectionInfo` first, because doctor output is exactly what users paste into issues and CI logs (pinned by the fallback case in `test/doctor-minions-check.test.ts`: stderr note present, credentials absent, stdout stays parseable `--json`). `main()` opens with `await runCliPreflight()` (core/cli-preflight.ts: cwd-.env quarantine -> `~/.gbrain/.env` -> guardrails loader) before `parseGlobalFlags`; the former inline #3688 guardrails block lives in the preflight module. `get_page` output renders through `src/cli/page-render.ts`: a partial response prints only what it carries plus a stderr note, and a thin-client `gbrain get` refused with `page_too_large_for_inline` pages the round-trip markdown to its end (`readWholePageMarkdown`, size + sha256 checked, restarts if the page changes) before printing.
+- `src/cli/main.ts` — the dispatcher (moved out of `src/cli.ts`; tests import its helpers from here). It keeps three graphs off every command: `completeEngineStartup` asks `migrate-pending.ts` (generated latest version) before loading `migrate.ts` and its ~220 migration modules, `thin-client-upgrade-prompt.ts` takes `compareVersions` from `migration-ledger.ts` instead of the upgrade orchestrator registry, and `mcp-client.ts` loads the MCP HTTP client SDK on the first remote call. Generic thin-client mutation failures use the shared persistence reporter, retaining request IDs and typed JSON receipts while preserving SIGINT exit 130. `test/thin-client-write-errors.serial.test.ts` exercises real CLI timeout, cancellation, pending and conflict paths against a loopback MCP fixture. No-DB fallbacks announce themselves on stderr instead of degrading silently. `dream` dispatch binds the caught engine-connect error and emits `[dream] WARNING: could not connect to DB (...)` before falling through to filesystem-only phases; the `runDream(null, ...)` no-DB fallback is preserved (pinned by `test/cli-dream-engine-warn.test.ts`, 2 subprocess cases against good + bad DATABASE_URL). `doctor` dispatch does the same: when `connectEngine` OR the DB-backed `runDoctor` run throws, it emits `[doctor] DB-backed doctor run failed (...) — falling back to filesystem-only checks`, scrubbing the error message through BOTH `url-redact.ts:redactUrlsInText` and `redact-connection-info.ts:redactConnectionInfo` first, because doctor output is exactly what users paste into issues and CI logs (pinned by the fallback case in `test/doctor-minions-check.test.ts`: stderr note present, credentials absent, stdout stays parseable `--json`). `main()` opens with `await runCliPreflight()` (core/cli-preflight.ts: cwd-.env quarantine -> `~/.gbrain/.env` -> guardrails loader) before `parseGlobalFlags`; the former inline #3688 guardrails block lives in the preflight module. `get_page` output renders through `src/cli/page-render.ts`: a partial response prints only what it carries plus a stderr note (a `--section` read prints the section text, a `--grep` read each block under `-- lines a-b (match at …)`, with the heading path or match counts on stderr), and a thin-client `gbrain get` refused with `page_too_large_for_inline` pages the round-trip markdown to its end (`readWholePageMarkdown`, size + sha256 checked, restarts if the page changes) before printing.
- `connectEngine` is the thin-client backstop: on a config with `remote_mcp` and no `database_url` it refuses the dispatched command through `refuseThinClient` instead of building an engine, so a command without its own route never dies with "No database URL" or reads an empty in-memory PGLite. Handlers that already route over MCP (salience, anomalies, graph-query, whoknows, founder, and every recall form except an in-process `--query`/`--budget-tokens` call) run engine-free from `prepareConnectedDispatch`. Pinned by `test/thin-client-connect-engine-guard.test.ts`. The host connect itself is `connectEngineForServe(hooks, {probeOnly})` in `src/core/engine-connect.ts`: throw-only (`no_brain`, `requires_local_engine`, repair refusals), it records the engine's config through `ENGINE_CONNECT_HOOKS` and disconnects an engine whose startup fails after the connect; `connectEngine` wraps it with the CLI exits (`exitOnRepairFailed`), and the status-only serve call sites pass it directly (`test/engine-connect.test.ts`).
+ `connectEngine` is the thin-client backstop: on a config with `remote_mcp` and no `database_url` it refuses the dispatched command through `refuseThinClient` instead of building an engine, so a command without its own route never dies with "No database URL" or reads an empty in-memory PGLite. Handlers that already route over MCP (salience, anomalies, graph-query, whoknows, founder, and every recall form except an in-process `--query`/`--budget-tokens` call) run engine-free from `prepareConnectedDispatch`. Pinned by `test/thin-client-connect-engine-guard.test.ts`. A read-scope op connects with `oneShotRead`: startup reads the config table once (`withRequestConfigSnapshot`; pending migrations run outside it), skips the retired-marker cleanup only filesystem-guarded writes need, and the context build and the operation share a second snapshot; a transaction pooler's prepared-statements banner prints once per database (`src/core/pooler-notice.ts`). Pinned by `test/e2e/cli-read-startup-round-trips.test.ts` (statement counts from the wire trace). The host connect itself is `connectEngineForServe(hooks, {probeOnly, oneShotRead})` in `src/core/engine-connect.ts`: throw-only (`no_brain`, `requires_local_engine`, repair refusals), it records the engine's config through `ENGINE_CONNECT_HOOKS` and disconnects an engine whose startup fails after the connect; `connectEngine` wraps it with the CLI exits (`exitOnRepairFailed`), and the status-only serve call sites pass it directly (`test/engine-connect.test.ts`).
Size ceiling (`src/cli/main.ts`): `scripts/module-size-limits.tsv` (per-change raise history: `git log -p` on that file). The ceiling covers `handleCliOnly`'s explicit ordered pipeline (`@cliPipelineStage` functions: thin-client guard, deferred-persistence routing, subcommand and help routes, read-only timeout path, sync watchdog and delegation, connectEngine terminator with degraded-serve recovery, teardown), thin-client routing and refusal, help and self-help text, strict flag parsing and process-exit teardown. Per-command dispatch (pre- and post-connect) lives in the command table (entry below), not in `src/cli/main.ts`.
- `src/cli/remember-format.ts` — the `remember` human formatter (`formatRememberResult`: status, entity with `(inferred from mention)`, expiry, degraded dedup, a `note: private` line when the call passed `visibility: private` (#6606; read from the params, so it prints when the write ran on a serve owner too), `warnings` + `hint`), kept out of `src/cli.ts`; `--json` prints the raw envelope. Pinned by `test/remember-entity-inference.test.ts`.
diff --cc src/core/behavior-change-notice.ts
index c872c3b24b,838cb9eac0..30c637c200
--- a/src/core/behavior-change-notice.ts
+++ b/src/core/behavior-change-notice.ts
@@@ -1021,10 -1021,10 +1021,13 @@@ export const BEHAVIOR_CHANGES: Readonly
{ since: '0.60.326.0', text: 'A write that ends `storage_error` on an unexpected database server error now keeps, owner-side in the receipt, the server message with any quoted value replaced by … (`error_text`; object names stay only in known catalog messages or when the statement names them), the failing statement with every literal, number and comment replaced and never its parameters (`statement`), and the error position; a PL/pgSQL RAISE or ASSERT keeps no text. On the brain host `gbrain write-request <id> --json` now prints the receipt\'s `error_detail`, and the persistence consumer log line adds `error_text=`, `statement=` and `position=`. Remote readers see no new field.' },
// #7125 and #7117 (GBRA-145). `since` is restamped at the merge slot.
{ since: '0.60.327.0', text: 'Fact extraction no longer rewrites the facts it stores: the prompt-injection filter used to delete words such as "System" before a parenthesis, so "Business System (ABS)" was saved as "Business [redacted](ABS)". Injection phrases are now neutralized only where stored facts are rendered into a model prompt (standing questions, turn context, proactive briefs). `gbrain doctor --only facts_redaction_marker` counts facts damaged earlier; `gbrain repair redacted-facts` previews what a source page can prove and changes nothing until you apply the printed `--apply --expect <hash>` command.' },
+ { since: '0.60.333.0', text: '`gbrain doctor --tier quick` is the health gate for agents on large brains: the ops sections plus schema version, sync failures, queue health and partial embeddings under a 10 s deadline, with every other check reported from its last known result and its age (same status; `details.last_known`, `last_known_sections`). A brain-wide `gbrain doctor` run now records each check it finishes in `op_checkpoints` (op `doctor-last-known`), and a check that runs out of its budget reports that result instead of unknown while it is under 24 h old. Checks with no result that recent are named in one `doctor_last_known` warning, and a Postgres brain queues one background `doctor-refresh` job per hour to measure them (it needs a running jobs worker). `--only` and `--source` runs neither read nor record these results.' },
+ { since: '0.60.333.0', text: '`gbrain doctor --only sync_failures` now connects the brain instead of reporting that durable sync state is unavailable. `sync_failures` ignores, and counts, local-ledger rows that no sync can retry or clear: rows on a source that is not registered, and rows whose file was deleted from its source after it failed. A process running under `bun test` (NODE_ENV=test) with neither GBRAIN_SYNC_FAILURES_DIR nor GBRAIN_HOME set writes a scratch sync-failure ledger instead of the real one.' },
+ { since: '0.60.333.0', text: 'Behind a transaction-mode pooler, the "Prepared statements and statement pipelining disabled" banner prints once per database per gbrain home instead of on every call (`gbrain engine status` and doctor\'s `pgbouncer_prepare` still report it). A one-shot read command reads the config table once for its startup and once for the operation, and skips the retired managed-marker cleanup that only writes need.' },
{ since: '0.60.327.0', text: 'The embed sweep that finds chunks whose text changed after they were embedded now runs in 5,000-chunk batches, keeps its place between runs (at most 60 seconds per run) and starts a new pass once a day (`embed.content_drift.pass_interval_hours`, default 24); before, one statement covered the whole brain and a large brain cancelled it on every run. `gbrain doctor --only content_drift_sweep` shows each pass and any error.' },
+ // #7165 and #7147 (GBRA-151 wave 2). `since` is restamped at the merge slot.
+ { since: '0.60.327.0', text: 'search and query responses carry `_meta.retrieval.coverage`: pending text projections, held files and pages held from embedding in scope, each with `could_affect` (how many could match this query; an empty result counts all). The `held_files` notice (which now also names embedding holds), the `projection_pending` part of `degraded_recall` and the CLI `Retrieval incomplete:` line appear only when some could, say how many, and show once per session (CLI: once per 30 minutes per GBRAIN_HOME) unless the count rises 10% or a new source or kind appears. `_meta.retrieval.degraded` still lists `projection_pending`.' },
+ { since: '0.60.327.0', text: 'The update check prints one line instead of two: agent harnesses (stderr not a terminal, or GBRAIN_FORCE_UPGRADE_MARKER=1) get only `UPGRADE_AVAILABLE <current> <latest>`, a terminal gets only the `gbrain <a> -> <b> available` sentence, and it shows once per 30 minutes per GBRAIN_HOME for a given version; a newer version shows at once.' },
{ since: '0.60.328.0', id: 'google_api_access_probe', text: 'A managed Google source whose enabled services cannot name the account (an API disabled for the OAuth project, a scope not granted) now resolves it through the OAuth userinfo endpoint: the account pins, the services that work keep syncing, the run is `partial`, and the disabled API is reported as `api_not_enabled` instead of failing the whole sync. `connector_account_changed` is raised only when an account resolved and differs from the pin; when nothing can name the account (userinfo also failing), the sync fails with the underlying error, a network failure included, instead of refusing as an account change. `gbrain google setup` now probes every requested service before registering a source and stops (exit 2, `status: api_access_blocked`) naming each disabled API with its Google Cloud project and enable link, or each scope not granted, in one report. `gbrain google status` adds `accounts[].api_access` and exits 1 while a problem remains, and doctor adds `google_api_access`, read from what the last sync recorded. A Google 403 for insufficient authentication scopes is now `scope_missing` (before: `upstream`, and a calendar read named it `calendar_unreadable`).' },
// #7130 (sync deleting pages whose file Git never committed; autopilot purge hard-deleting them). `since` is restamped at the merge slot.
{ since: '0.60.330.0', text: 'A managed sync no longer deletes a live page whose recorded file is missing when Git never committed that file (#7130): a page whose file no commit of the pinned history or the pass\'s baseline holds is held `file_drift` (side `deleted`, state `file_gone`, `meta.reason` `ignored` when `.gitignore` excludes the path, else `never_committed`) instead, in a normal pass, under `--full` and in the dry run. A file that was committed and then removed still deletes its page. When Git cannot answer (a failed or timed-out read), the page is held. `gbrain repair file-drift --prefer file` still applies the deletion after review, and committing the file again clears the hold. On a source without Git durability, a managed put_page or capture of a new page whose file would land under a path `.gitignore` excludes, now writes no file and records none: the page is database-only, so no later sync can read the missing file as a deletion.' },