Skip to content

Garry's Opinionated OpenClaw/Hermes Agent Brain

TypeScript

Merge remote-tracking branch 'origin/master' into capy/gbra151-7193-false-success

garrytan7fb919a1ca4f
diff --cc docs/architecture/key-files/commands-4.md
index b3cd32d853,ffe0f6b9d5..95b5615fcc
--- a/docs/architecture/key-files/commands-4.md
+++ b/docs/architecture/key-files/commands-4.md
@@@ -35,9 -35,8 +35,8 @@@ Current behavior and load-bearing invar
- `src/commands/models.ts` — `gbrain models [--json]` read-only routing dashboard: prints tier defaults (`utility`/`reasoning`/`deep`/`subagent`), the resolved value for each (re-walking the resolution chain), every per-task override (14 `PER_TASK_KEYS`, including provider-neutral `models.contextual_synopsis` with legacy-key/env attribution and `models.dream.extract_atoms` which reports via its own caller-specific resolver — `resolveExtractAtomsModelWithSource()` in `extract-atoms.ts`: its own key, then `models.tier.utility`, then the key-aware utility default, never `models.default` or `GBRAIN_MODEL` (#6675) — rather than the generic chain, so the report can't diverge from what the phase actually calls), the alias map, and a source-of-truth column (`default` / `config: <key>` / `env: <VAR>`) derived from `resolveModelDetailed`, so a tier key is attributed before `models.default`. A `Nightly quality probe` block (JSON `nightly_probe`; `schema_version` stays 1) shows the probe's routes from `resolveNightlyProbeModelRoutes`: reader and extractor with their source, and each judge slot labelled `config: models.eval.cross_modal.slot_<x>`, `panel default` or `substitute for <default> (no usable provider)` — the #4636 substitution run with a silent log against this process's gateway. Its `environment_note` says availability, substitutes and key-aware defaults are judged from this process's environment, so a key only in the daemon's `~/.gbrain/env` reads as unavailable. A resolved Anthropic haiku/sonnet/opus id older (by major, minor) than the anthropic recipe's newest priced same-family id gets an advisory `[newer <family> available: <id>] (gbrain config set ...)` hint (JSON: `newer_available`); version parsing lives in `src/core/ai/anthropic-model-ids.ts` (8-digit segment is a date, so dated and undated forms compare equal; fable, non-Anthropic, newer-than-recipe and unparseable ids get no hint). The hint never changes a default. `gbrain models doctor [--skip=<provider>] [--json]` fires a 1-token `gateway.chat()` probe against each configured chat + expansion model and classifies failures into `{model_not_found, auth, rate_limit, network, unknown}`. The probe timeout resolves per model via `resolveChatProbeTimeoutMs` — the recipe touchpoint's `default_timeout_ms` when declared, else the flat 5000ms default (mirrors the reranker probe's recipe-default fallback; `claude-cli` declares 30s because its `claude -p` subprocess cold start routinely outruns 5s and would false-fail every run as `unknown`). The reranker reachability probe sends one question with a relevant and an unrelated passage and reports `ok` only when the relevant one scores higher by more than 0.1; equal, inverted or missing scores are `config` with a fix naming `docs/ai-providers/llama-server-reranker.md` step 2 (a broken GGUF conversion answers but ranks at random). Wired into `cli.ts` dispatch + `CLI_ONLY` set. A zero-token `embedding_config` probe runs FIRST, before any chat/expansion probes spend money: `probeEmbeddingConfig()` reads `getEmbeddingModel()` + `getEmbeddingDimensions()` and (for Voyage flexible-dim models) checks `isValidVoyageOutputDim(dims)` against `VOYAGE_VALID_OUTPUT_DIMS`. `ProbeStatus` variant `'config'` + optional `fix?: string` on `ProbeResult` surface a paste-ready `gbrain config set ...` line in human + JSON output; touchpoint label `'embedding_config'` joins `'chat'` and `'expansion'`.
- `src/commands/pricing.ts` — `gbrain pricing set <model> --input <usd/1M> --output <usd/1M> | --rate <usd/1M> [--source <url>]`, `pricing list [--json]`, `pricing unset <model>`. Each write reads `pricing.overrides`, changes one entry (keyed by the lowercased model; case variants replaced) and writes it back, so other entries survive; an unreadable stored value is refused, never overwritten. Rates must be non-negative finite numbers; $0 is accepted with a stderr warning. Entries keep the parser schema (`{input, output}` or `pricePerMTok`) with `source` and `set_at` beside them. Trust boundary: CLI-only (never an operation, so MCP cannot reach it) and `thinClient: 'refuse'` in the command table. Pinned by `test/budget/no-pricing-registration.test.ts`.
- - `src/commands/orphans.ts` — `gbrain orphans` and MCP `find_orphans` share islanded (no live inbound or outbound links) and legacy inbound-only modes. Read policy scopes candidates and excludes private candidates, endpoints and independent origin pages before counting. Cross-source public links still establish reachability by the documented orphan definition. Reporting exclusions (`shouldExcludeFromOrphanReporting`) stay centralized; the scoped live-page denominator excludes the same private/reporting rows. `--source` remains explicit; no new remote privacy parameter. Connector renders (an `email`/`meeting` page whose source `config.kind` is a connector kind) are islanded by construction, so they leave both totals and are reported as `connector_renders_excluded` (`--include-pseudo` keeps them); doctor `orphan_ratio` carries that count in `details` and prints `gbrain extract links --by-mention --source db` (plus `--source-id` when scoped). Pinned by `test/orphan-ratio-connector-renders.test.ts`.
+ - `src/commands/orphans.ts` — `gbrain orphans` and MCP `find_orphans` share islanded (no live inbound or outbound links) and legacy inbound-only modes. Read policy scopes candidates and excludes private candidates, endpoints and independent origin pages before counting. Cross-source public links still establish reachability by the documented orphan definition. Reporting exclusions (`shouldExcludeFromOrphanReporting`) stay centralized; the scoped live-page denominator excludes the same private/reporting rows. `--source` remains explicit; no new remote privacy parameter. Connector renders (an `email`/`meeting` page whose source `config.kind` is a connector kind) are islanded by construction, so they leave both totals and are reported as `connector_renders_excluded` (`--include-pseudo` keeps them); doctor `orphan_ratio` carries that count in `details` and prints `gbrain extract links --by-mention --source db` (plus `--source-id` when scoped). Pinned by `test/orphan-ratio-connector-renders.test.ts`. Pages of 100 (`--limit`/`--cursor`/`--all`; [bounded listings](core-utilities-2.md)); one-page results keep the old shape.
- - `src/commands/pages.ts` — `gbrain pages purge-deleted [--older-than HOURS|Nh|Nd] [--retry-parked] [--dry-run] [--json] [--yes]` operator escape hatch. Mirror of `gbrain sources purge` for the page-level lifecycle. Hard-deletes pages whose `deleted_at` is older than the cutoff in every source (per-source purge is not supported); cascades to content_chunks/page_links/chunk_relations. `parsePurgeArgs` is strict (the `pages purge-deleted` row of `src/cli/strict-args.ts`): `--older-than N` and `--older-than=N` both work, and any other token throws `invalid_params` before the engine is touched. The real purge first previews the count and, when anything would be purged, goes through `consentGate` (destructive): a TTY prompt, `--yes`, or exit 3 with the consent payload whose fix is the exact `--yes` argv and whose preview is `--dry-run --json`. `--retry-parked` retries parked tombstones once within `--older-than` and rename holds; the dry run lists `parked`, `retried` and `blocked`, and the consent names the parked count. The autopilot purge phase calls `purgeDeletedPagesCoordinated` directly and never asks. `pages ghosts [--source <id>] [--json]` (#6696 B5, `pages-ghosts.ts`) lists ghost pages read-only through `scanGhostSource`. Exports `SUBCOMMANDS` and `printUsage` for the help route. Pinned by `test/pages-purge-deleted-args.test.ts` and the `pages purge-deleted` consent-table row. Its help points soft-delete and restore at `gbrain delete|restore <slug> --force` (page writes are revisioned).
+ - `src/commands/pages.ts` — `gbrain pages purge-deleted [--older-than HOURS|Nh|Nd] [--retry-parked] [--dry-run] [--json] [--yes]` operator escape hatch. Mirror of `gbrain sources purge` for the page-level lifecycle. Hard-deletes pages whose `deleted_at` is older than the cutoff in every source (per-source purge is not supported); cascades to content_chunks/page_links/chunk_relations. `parsePurgeArgs` is strict (the `pages purge-deleted` row of `src/cli/strict-args.ts`): `--older-than N` and `--older-than=N` both work, and any other token throws `invalid_params` before the engine is touched. The real purge first previews the count and, when anything would be purged, goes through `consentGate` (destructive): a TTY prompt, `--yes`, or exit 3 with the consent payload whose fix is the exact `--yes` argv and whose preview is `--dry-run --json`. `--retry-parked` retries parked tombstones once within `--older-than` and rename holds; the dry run lists `parked`, `retried` and `blocked`, and the consent names the parked count. The autopilot purge phase calls `purgeDeletedPagesCoordinated` directly and never asks. `pages ghosts [--source <id>] [--json]` (#6696 B5, `pages-ghosts.ts`) lists ghost pages read-only through `scanGhostSource`. `pages status <slug...>` (#7179) lives in `pages-status.ts`. Exports `SUBCOMMANDS` and `printUsage` for the help route. Pinned by `test/pages-purge-deleted-args.test.ts` and the `pages purge-deleted` consent-table row. Its help points soft-delete and restore at `gbrain delete|restore <slug> --force` (page writes are revisioned).
-- `src/commands/pages-unsearchable.ts` — `gbrain pages unsearchable --source <id> [--state <state>] [--limit N] [--json]` (#6696 B3, read-only): one row per (page, embedding state) from `listEmbeddingStateRows` with reason, chunks, bytes and the state's rendered fix; every state but `embedded` unless `--state` names one; `--limit` 1-1000 (default 50) with `complete`; an unknown `--state` or bad `--limit` throws `invalid_params` naming the valid values. Test: `test/pages-unsearchable.test.ts`.
+- `src/commands/pages-unsearchable.ts` — `gbrain pages unsearchable --source <id> [--state <state>] [--limit N] [--json]` (#6696 B3, read-only): one row per (page, embedding state) from `listEmbeddingStateRows` with reason, chunks, bytes and the state's rendered fix; every state but `embedded` unless `--state` names one; `--limit` 1-1000 (default 50) with `complete`; an unknown `--state` or bad `--limit` throws `invalid_params` naming the valid values; adds `semantic_unsearchable` (+keyword_only) and `awaiting_sync` (held files) (#7193). Test: `test/pages-unsearchable.test.ts`.
-
- - `src/commands/persistence-admin.ts` + `src/core/persistence/{admin-contract,administration,transfer-administration}.ts` — trusted local `sources writer status|failures|claim|transfer` (failures: [Managed sync bookkeeping](managed-sync-bookkeeping.md)) and `auth local-writer list|register|revoke`. Parse and resolve the brain before opening PGLite; an existing owner receives a separate private administration envelope verified against the current CLI registration. These names never enter the public MCP operation registry; stdio, hook credentials, forged trust fields and revoked CLI registrations cannot administer. Transfer requires exact manifest and owner epoch; status `--probe` acquires/releases a real native lock. Explicit credential replacement commits old revocation and new registration together before atomically publishing the private file, preserving old credentials for recovery without keeping their authority. No credential/hash appears in output. `test/persistence-administration.test.ts` covers database rollback, parallel rotations, transfer conflicts, real sockets and real CLI subprocesses. `retry-effects <source> --request-id <original-uuid> --dry-run --json` previews a failed embedding effect without work; applying the same reviewed request requires original/current authority, selected-brain config, source/page/owner CAS and one additional allowance. For a request with parked Git or withdrawal effects the same command previews the parked targets (`--dry-run`) or authorizes one more attempt per parked target, reporting each effect's state and whether it is terminal. It never claims ownership or rewrites canonical receipts. `transfer-administration.ts` owns `transfer prepare|accept|cancel`: `cancel <source> --expected-epoch <n>` (intent `writer_transfer_cancel`, `--dry-run` previews) runs `cancelWriterTransfer` in `ownership.ts` on the owner host under the coordination lock and `FOR UPDATE`, requires `draining` at that epoch, returns the worktree to `active` and clears the prepared manifest while keeping the epoch, so an accept bound to it refuses `writer_transfer_conflict`. Prepare stamps `prepared_at`. Test: `test/pathological/c5-writer-transfer-cancel.test.ts` (both engines).
+ - `src/commands/pages-status.ts` — `gbrain pages status <slug...> [--source <id>] [--json]` (#7179, read-only, CLI only): one `PageStatus` per slug (at most 200) in the `sources resolve-path` state vocabulary (`searchable`, `pending_embedding`, `chunkless`, `keyword_only`, `quarantined`, `empty`, `missing`, `page_deleted`) with `searchable` true/'keyword'/false, the page's chunks and `unembedded` (no vector in the active column), `embedding_hold` (a held or capped budget row that applies per `budgetRowAppliesFilter`), `hold` (the Git sync hold on its file from `readGitHold`, keyed by the source-root path under the source's slug mode), `source_path`, `in_synced_commit` (the file is in `sources.last_commit`; null without a Git checkout here) and `why` + `fix`; top level `last_commit`, `head`, `at_head`, `embeddings_enabled`. The state is the worst classifier row from `listEmbeddingStateRows` narrowed by `slugs` (quarantined > chunkless > pending > keyword_only > empty > embedded); a held large page's vector-less chunks read `pending_embedding`, not keyword_only, and its fix is `heldApproveAction` (ask_user, preview first, never a spend). A sync hold's `gitHoldFix` wins over every other fix; otherwise `embeddingStateFix`, none for `searchable`, `missing`, `page_deleted` or pending on a brain keyless by choice. Strict arguments (`invalid_params`, exit 2); a page that is not searchable exits 0. Test: `test/pages-status-7179.test.ts`.
diff --cc src/core/behavior-change-notice.ts
index 76c5221865,2a5325aca3..893e4a76aa
--- a/src/core/behavior-change-notice.ts
+++ b/src/core/behavior-change-notice.ts
@@@ -1019,10 -1019,9 +1019,11 @@@ export const BEHAVIOR_CHANGES: Readonly
// #7112 (Postgres 15 SQL compatibility, owner-exception error text). `since` is restamped at the merge slot.
{ since: '0.60.326.0', text: 'Managed sync, put_page, source config updates, archive and restore, and the dream-breaker reset work again on Postgres 15: they used the Postgres 16+ `IS JSON` predicate (and doctor jsonb_integrity and `gbrain repair-jsonb` used `pg_input_is_valid`), a syntax error (42601) on Postgres 15 that failed every managed sync checkpoint. They now use a new `gbrain_try_jsonb(text)` function (migration v263) on every server. The same guard no longer fails a config merge or a dream-breaker reset whose stored text is JSON but not jsonb (a \\u0000 escape); that value now reads as an empty object, like other unparseable text.' },
{ 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.' },
+ // #7193 (GBRA-151). `since` is restamped at the merge slot.
+ { since: '0.60.331.0', text: '`gbrain embed --stale --images` now exits 1 (`status: nothing_rebuilt`, with a `reason` counting missing files, files the importer left unchanged, pages that need a fresh OCR pass and failures) whenever it rebuilds none of its candidate image pages; before, only a sweep where every source file was missing failed. `gbrain pages unsearchable` adds `semantic_unsearchable` (unsearchable plus keyword_only, which vector search cannot reach) and `awaiting_sync` (files sync still holds, which no embedding state counts), and its headline leads with what vector search cannot reach. An incomplete embed-backfill job now counts chunks on large pages held for approval or at their spend cap in its remaining total and names them. An unknown `--source` names the source it most likely meant.' },
// #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.339.0', text: 'A managed sync of a source with pages from before managed persistence (legacy pages) now screens at most 500 of them per pass, then imports the pass\'s real changes, and the next full round resumes the screen where the last one stopped (#7189). Before, the first full round screened every legacy page before importing anything, a page whose body no longer matched its file was never recorded, and a pass stopped by its deadline started over from the top, so a source with thousands of such pages stopped advancing. The pass row keeps the position in `obligations.legacy_sweep.cursor`.' },
{ 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.' },
diff --cc src/core/source-resolver.ts
index 6c34995daa,5c9b6167ea..5fd264fce9
--- a/src/core/source-resolver.ts
+++ b/src/core/source-resolver.ts
@@@ -617,12 -661,18 +661,19 @@@ export async function assessUnscopedDef
}
async function assertSourceExists(engine: BrainEngine, id: string): Promise<void> {
- const rows = await engine.executeRaw<{ id: string }>(
- `SELECT id FROM sources WHERE id = $1 AND archived = false`,
- [id],
- );
+ // GBRA-133: inside a CLI sync's routing scope the source's routing row answers this (sync-dispatch-read.ts).
+ const routing = await syncDispatchRow(engine, id);
+ // GBRA-156: inside a request snapshot the request's source rows answer it.
+ const pending = routing ? undefined : requestSourceRows(engine);
+ const request = pending && await pending;
+ const rows = routing ? (routing.id !== null && routing.archived === false ? [routing] : [])
+ : request ? request.filter(row => row.id === id && row.archived === false)
+ : await engine.executeRaw<{ id: string }>(
+ `SELECT id FROM sources WHERE id = $1 AND archived = false`,
+ [id],
+ );
if (rows.length === 0) {
+ const nearest = await nearestSourceId(engine, id);
throw new SourceTargetError(
`Source "${id}" not found or is archived. Available active sources: ` +
`run \`gbrain sources list\` to see registered sources, ` +