Garry's Opinionated OpenClaw/Hermes Agent Brain
TypeScript
fix(mcp): say when an unscoped read reaches no readable page; warn on non-federated sources add (GBRA-156)
garrytan97f51eccfe27
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex 5ba43d3de0..95116866fc 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -26,11 +26,14 @@ identifiers and attribution are available in the pre-removal Git revision| `request_tools {tools: [names]}` on a server whose ceiling is `starter` | returned the starter schema, so the left-out params could not be discovered | returns each tool's full schema with every optional parameter || Memory verb descriptions | began with `MEMORY VERB (v1):` | the prefix is gone; tool names and the protocol are unchanged || verbs and full surfaces | | list every parameter as before (verbs 8,573 bytes, was 8,757) |+| A token with no source grant searches a brain whose pages all sit in sources that are not federated | `[]` with an `empty_retrieval` notice calling it a clean miss | `[]` with a `sources_not_readable` notice (kind degraded): the pages are in sources this connection cannot read, and the fix is `gbrain sources federate <source>` on the brain host, or a grant for the token. It never names a hidden source. Same for `query`, `recall` and `list_pages` |+| `gbrain sources add` without `--federated` or `--no-federated` | printed `federated: false` | also warns on stderr that a token or agent connection with no source grant cannot read the new source, and names the two commands that change that. The stored default is still non-federated |### What to watch for after you upgrade- For a bot acting for several members, give each member a token granted only that member's sources (`gbrain auth rescope --token <name> --sources <ids>`, or `--client <client_id>`); `source_ids` narrows inside a grant and is not a separation between members. See [multi-source brains](docs/guides/multi-source-brains.md#a-bot-acting-for-many-members).- A schema-validating client on the starter surface with `mcp.strict_params reject` only sends parameters it was shown; fetch the full schema with `request_tools {tools: [name]}` or serve the full surface when an agent needs a left-out parameter.+- A token the operator granted sources, and every OAuth client (which always carries at least its bound source), never gets `sources_not_readable`: its scope is deliberate. A real miss inside a scope that holds pages gets no notice either.- Nothing is rewritten on upgrade, and there is no schema migration.## [0.60.442.0] - 2026-10-25diff --git a/docs/architecture/key-files/agent-contract.md b/docs/architecture/key-files/agent-contract.mdindex 349654c111..d161240d0d 100644--- a/docs/architecture/key-files/agent-contract.md+++ b/docs/architecture/key-files/agent-contract.md@@ -5,11 +5,11 @@ Current behavior and load-bearing invariants; history belongs in Git and CHANGELSpec: `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` and the command's source flag (`--source`; `--source-id` for a record declaring `routes_source: '--source-id'`, extract, whose `--source` is a mode selector and never blocks the pin) 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`; the escalation flag `ask_user: true` marks a refusal whose every way out is the user's decision) and `RenderedAction`, `Notice`/`RenderedNotice`, `AgentEnvelope`, `RenderContext`. `deriveNext` is the published decision table (a stored `ask_user: true` → `ask_user`; 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/agent-output.ts` — the contract v1 types and renderers every surface shares: `Action` (stored; never carries `next` or `command`; the escalation flag `ask_user: true` marks a refusal whose every way out is the user's decision) and `RenderedAction`, `Notice`/`RenderedNotice`, `AgentEnvelope`, `RenderContext`. `deriveNext` is the published decision table (a stored `ask_user: true` → `ask_user`; 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... (line truncated to 2000 chars)- `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`, and `reason_overrides`: a reason whose class and exit replace the code's on the envelope and the CLI exit); `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, plus an `Override:` line per reason override) 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`). #6758: every event carries `version` (defaults to the writing build's `VERSION`); on a warn the check adds `details.builds` (`this_build`, `other_builds`, `unknown_build` for older unversioned lines, `versions`) and `details.incident` (`historical` when no counted event came from this build, `since` the oldest), and the message names the events another build recorded. Test: `test/doctor-status-set.test.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). 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. A notice's unrendered `Notice.escalation` (`{key, level}`; the coverage notices: `held_files` and a projection-only `degraded_recall`) shows once per session per key for `COVERAGE_NOTICE_WINDOW_MS` (30 min), per-call code or not, and again at once when `coverageWorsened` (level up 10%, at least 1, from the lowest level seen since it showed); HTTP applies it only with a transport-resolved session id. `admitAcrossCliCalls(key, level)` is the same window across one-shot CLI calls (`<GBRAIN_HOME>/notices/coverage.json`, 200 marks, unwritable shows); the CLI op channel and the startup update check (one line per version per window) use it. `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. A notice's unrendered `Notic... (line truncated to 2000 chars)- `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; a `pglite_busy` with reason `legacy_owner_unverified` renders its own ask_user fix, `retryable: false`, exit 3). 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`.@@ -22,12 +22,13 @@ Spec: `docs/designs/AGENT_OPERATOR_WAVE.md`; wire goldens: `test/fixtures/agent-- `test/cli-contract.test.ts` — D5: `--help` contract for every command-table record (exit 0, non-stub, curated flags only, `--yes` shown where parsed) against the shrink-only `test/fixtures/cli-contract/help-baseline.json`, and one success + one failure row per `json`-declared record.- `src/cli/json-guard.ts` — picks the `--json` guard mode for an invocation: on only when `jsonRequested(argv)` and the command-table record declares `json: 'document' | 'ndjson'`; wires the E11 `json_document_missing` hook (document mode, exit 0; the event records `command`, `version`, `guard: 'document'` and `exit_code: 0`, never argv values; `outcome` keeps its value, #6629/D26). The guard itself is `installStdoutPipeDelivery({ json })` in `src/core/cli-force-exit.ts`: stdout writes and console.log/info/debug go to stderr, only `writeStdoutFinal`/`writeNdjsonLine` reach fd 1, a non-zero exit with no document writes the fallback document, `spawnCliChild` pipes child stdout to stderr. Test: `test/cli-json-guard.test.ts`. A record whose subcommands differ in shape declares `jsonSubcommands` (keyed by the first positional after the command; `eval`). `writeCliError` adds `status:'error'` to the envelope under the ndjson guard; `writeCliRefusal` (cli-error.ts) keeps a site's pre-v1 stderr line and writes the envelope under `--json`. D5 (`test/cli-contract.test.ts`) has one row per declaration, `<command> <sub>` included.- `scripts/check-agent-contract.ts` — syntax-only AST scanner (≈2 s) in `bun run verify` and `guards-manifest.tsv` (fixtures `test/fixtures/guards/check-agent-contract.ts/`). Rules: suggestion-less `OperationError`, `throw new Error` in ops/mcp/handlers, hand-built `fix`/`next_action` command strings, legacy advice keys, raw interactive stdin/readline/raw-mode outside `interaction.ts`/`consent.ts`, raw "re-run with --yes" strings outside `consent.ts`, `stdio: 'inherit'` outside `spawnCliChild`, marker literals outside `agent-output.ts`/`agent-markers.ts`, `verify.argv` naming a non-read-only command (read_only command-table records + a static read-only list), plus unregistered codes and code naming (never baselined). Two more never-baselined rules keep every refusal's next step site-specific: `defaulted-suggestion` (a function that builds an error through `opError`, `new OperationError`, `usageError`, `invalidParam` or `hostOnlyError` from a `*suggestion`/`*hint` parameter with a default, an optional marker or a `??` fallback) and `generic-suggestion` (a suggestion whose whole text is a denylisted phrase such as "see --help", "check your input" or "try again", at a constructor or at a call site of a file-local funnel). `funnelSites(files?)` lists every funnel call site (`invalid`, `fail`, `usage`, `deny`, …) with its literal suggestion texts, resolving file-level string constants; `test/helpers/agent-envelope.ts` (`expectFunnelSuggestions`, `envelopeFor`, `caught`) drives the per-funnel table tests in each module's owner test. Per-rule shrink-only baselines in `scripts/agent-contract-baselines/<rule>.tsv`; `--update` lowers them and refuses growth.-- `src/core/interop-notices.ts` — Lane F notice producers (pure; callers emit). `DEGRADED_STAGE_GUIDANCE` (closed, typed exhaustive over recall-affecting stages + the verbs' markers) → one `degraded_recall` notice (kind degraded: names the stages, says a thin result is not proof of absence; fix = the embeddings enablement or a doctor diagnostic; a `rerank_failed` stage names its reason, the `fused_order` fallback and the session's reranker-degraded call count, and when no other stage needs a fix its fix follows the reason: `timeout`/`rate_limited` repeat the same call after 5/20 s (`actor: provider`, `next: wait`), `auth` is the user's key (credentials), the rest run doctor verified by `reranker_health` (`test/rerank-degraded-notice.serial.test.ts`); none on a brain keyless by choice, whose why says no query text was sent and that `gbrain doctor --json` names the enable command). `embeddingOptedOutFor` reads the opt-out markers (search/query degraded reason `embedding_disabled`, recall `keyword_only_embedding_disabled` in `search_degraded` or `facts_degraded.reason`, think `QUESTION_EMBED_SKIPPED_EMBEDDING_DISABLED`); `factEmbeddingDisabled` (src/core/embedding-disabled.ts) gates every query and fact embed. With the call's `_meta.retrieval.coverage`, `degradedRecallNotice` leaves `projection_pending` out when no pending page could match the query, otherwise names the count in its why, and escalates when it is the only stage. `sourceBindingNarrowedNotice` (per-call info: a GBRAIN_SOURCE/.gbrain-source bound stdio read that came back empty while other sources are readable; fix = the explicit `source_id` read). `recallStagesFor` maps recall's `search_degraded` and `facts_degraded.reason` (question ranking) to stages. `recallInteropNotices` is dispatch's one producer call. `chatKeyFix` (credentials + paid, both providers, free fallback, never a key on a command line), `keylessThinkNotice`, `thinkNotSavedNotice`, `degradedDedupNotice`, `privateFactNotice` (#6606: a local `remember --visibility private` save is recall-only and never pushed into a session; names the world re-save and the private copy to forget), `writeCliNotices` (terminal lines / `[AGENT]` block for non-interactive callers). Test: `test/mcp-notice-channels.test.ts`. D2: `hiddenTakesNotice(hidden, route, fix)` → `hidden_tool_content` (info, per-call): a get_page/search/query result left out takes (counts and the result's own slugs, never take text); the fix is the hidden-tool route's next step.-- `src/mcp/status-mode.ts` + `src/commands/serve-status.ts` + `src/commands/serve-http-status.ts` + `src/core/serve-http-status-marker.ts` — F4 status-only serve, stdio and `--http`. cli.ts hands over a host-brain `serve` (not `--fail-fast`/`GBRAIN_SERVE_FAIL_FAST=1`) with no config, an unreadable config, a missing or repair-failed brain, or a PGLite lock held by a live holder; `runStatusModeServe` is the one entry point for both transports and logs `serve_status_mode_enter` / `serve_status_mode_recovered` (`reason`, `transport`, `elapsed_ms`) as one-line JSON on stderr. `probeStatus` reads config + `peekLock` only; `reprobe(state, connect)` is the one re-probe (no lock attempt while blocked, `resetReadinessMemo()` before the throw-only connect from `src/core/engine-connect.ts`); a check that must run on every re-probe hooks the `probeAgain` wrapper in `runStatusModeServe`. stdio: a gated lazy engine (`createDegradedEngine` with the configured `kind`, reconnect `statusReconnect`, ≤1 attempt / 5 s inside tool calls) marked with `StatusModeState`; `statusPayload` → `{status, reason, why (lock owner PID/transport, brain path, config path), fix, user_message, decisions, share_http_plan}`. `--http`: `runHttpStatusServe` binds one `node:http` listener with a mutable handler (`/health` 503 + `Retry-After: 5` + `instance`; `/mcp` stateless SDK server with only `gbrain_status`; every other route a 503 `serve_status_only` envelope), each response built from the allowlist in `httpStatusPayload`/`httpStatusEnvelope` with `reason` collapsed to `unavailable`; a single-flight chained 5 s tick runs the re-probe, and on a connect `runServe(..., { adoptServer })` builds the full app and swaps the handler on the same listener; a failed build disconnects the engine and stays status-only (`brain_unopenable`); SIGINT/SIGTERM during a recovery waits for it, then closes once. The marker `GBRAIN_HOME/serve-http-status-<port>.json` `{pid, instance_nonce, brain_id, bind, port, reason, since}` is removed only by its own instance; live = PID alive and written after the last boot (readiness), plus `/health` 503 with the nonce within 500 ms (`verifiedStatusMarkers`, doctor, which deletes dead markers). `statusFix(state, transport)` words the fix for how the server re-checks. A recovered HTTP server answers authenticated `gbrain_status` (read scope, never listed) with `status: recovered`. Tests: `test/serve-status-mode.serial.test.ts` (stdio recover → recall; shared `serve --http`; no brain → init; `--fail-fast`; stdio transition lines; Postgres `--http` keeps the degraded path), `test/serve-http-status-mode.serial.test.ts` (HTTP journey, doctor, thin client, recovery with re-auth, `serve_port_in_use`, no-config recovery, stale marker, single-flight tick, failed build, shutdown during recovery, two-port markers).+- `src/core/interop-notices.ts` — Lane F notice producers (pure; callers emit). `DEGRADED_STAGE_GUIDANCE` (closed, typed exhaustive over recall-affecting stages + the verbs' markers) → one `degraded_recall` notice (kind degraded: names the stages, says a thin result is not proof of absence; fix = the embeddings enablement or a doctor diagnostic; a `rerank_failed` stage names its reason, the `fused_order` fallback and the session's reranker-degraded call count, and when no other stage needs a fix its fix follows the reason: `timeout`/`rate_limited` repeat the same call after 5/20 s (`actor: provider`, `next: wait`), `auth` is the user's key (credentials), the rest run doctor verified by `reranker_health` (`test/rerank-degraded-notice.serial.test.ts`); none on a brain keyless by choice, whose why says no query text was sent and that `gbrain doctor --json` names the enable command). `embeddingOptedOutFor` reads the opt-out markers (search/query degraded reason `embedding_disabled`, recall `keyword_only_embedding_disabled` in `search_degraded` or `facts_degraded.reason`, think `QUESTION_EMBED_SKIPPED_EMBEDDING_DISABLED`); `factEmbeddingDisabled` (src/core/embedding-disabled.ts) gates every query and fact embed. With the call's `_meta.retrieval.coverage`, `degradedRecallNotice` leaves `projection_pending` out when no pending page could match the query, otherwise names the count in its why, and escalates when it is the only stage. `sourceBindingNarrowedNotice` (per-call info: a GBRAIN_SOURCE/.gbrain-source bound stdio read that came back empty while other sources are readable; fix = the explicit `source_id` read). `recallStagesFor` maps recall's `search_degraded` and `facts_degraded.reason` (question ranking) to stages. `recallInteropNotices` is dispatch's one producer call. `chatKeyFix` (credentials + paid, both providers, free fallback, never a key on a command line), `keylessThinkNotice`, `thinkNotSavedNotice`, `degradedDedupNotice`, `privateFactNotice` (#6606: a local... (line truncated to 2000 chars)+- `src/core/unreadable-sources-notice.ts` — `unreadableSourcesNotice`, dispatch's producer of the per-call `sources_not_readable` notice (kind degraded): an unscoped `search`/`query`/`recall`/`list_pages` from a connection with no source grant (no `allowedSources`, `hasSourceGrant` not true, no stdio binding; OAuth clients always carry a grant) that came back empty while its `federatedSearchScope` holds no live page and another live source does. The why says the result is not proof of absence and never names a hidden source; the fix is the host's `gbrain sources federate <source>` (input `source`), with the token grant named in the why. Never throws (`test/mcp-unreadable-sources-notice.test.ts`).+- `src/mcp/status-mode.ts` + `src/commands/serve-status.ts` + `src/commands/serve-http-status.ts` + `src/core/serve-http-status-marker.ts` — F4 status-only serve, stdio and `--http`. cli.ts hands over a host-brain `serve` (not `--fail-fast`/`GBRAIN_SERVE_FAIL_FAST=1`) with no config, an unreadable config, a missing or repair-failed brain, or a PGLite lock held by a live holder; `runStatusModeServe` is the one entry point for both transports and logs `serve_status_mode_enter` / `serve_status_mode_recovered` (`reason`, `transport`, `elapsed_ms`) as one-line JSON on stderr. `probeStatus` reads config + `peekLock` only; `reprobe(state, connect)` is the one re-probe (no lock attempt while blocked, `resetReadinessMemo()` before the throw-only connect from `src/core/engine-connect.ts`); a check that must run on every re-probe hooks the `probeAgain` wrapper in `runStatusModeServe`. stdio: a gated lazy engine (`createDegradedEngine` with the configured `kind`, reconnect `statusReconnect`, ≤1 attempt / 5 s inside tool calls) marked with `StatusModeState`; `statusPayload` → `{status, reason, why (lock owner PID/transport, brain path, config path), fix, user_message, decisions, share_http_plan}`. `--http`: `runHttpStatusServe` binds one `node:http` listener with a mutable handler (`/health` 503 + `Retry-After: 5` + `instance`; `/mcp` stateless SDK server with only `gbrain_status`; every other route a 503 `serve_status_only` envelope), each response built from the allowlist in `httpStatusPayload`/`httpStatusEnvelope` with `reason` collapsed to `unavailable`; a single-flight chained 5 s tick runs the re-probe, and on a connect `runServe(..., { adoptServer })` builds the full app and swaps the handler on the same listener; a failed build disconnects the engine and stays status-only (`brain_unopenable`); SIGINT/SIGTERM during a recovery waits for it, then closes once. The marker `GBRAIN_HOME/serve-http-status-<port>.json` `{pid, instance_nonce, brain_id, bind, port, reason, since}`... (line truncated to 2000 chars)- `src/mcp/initialize-context.ts` — per-initialize inputs for the generated instructions (`httpInstructionTools`: the tools/list filters with publish gates read on initialize; `instructionReadiness`: config plane + probed tier within 250 ms, HTTP view redacted) and `stdioCapabilityReadiness` (F2). Test: `test/mcp-capabilities-readiness.test.ts`.- `src/mcp/hidden-tool-hint.ts` + `src/core/ops/cli-equivalent.ts` — F6: on the owner's stdio pipe a real tool outside the surface/read-only access gets `unknown_tool` naming itself and its CLI equivalent (`cliEquivalent`: `cliOnly` argv, curated overrides, `cliHints.name`, else `gbrain call`). Where `request_tools` is callable and session widening is on, the fix is `request_tools {surface:'full'}` (`next: run`, argv kept); otherwise the CLI equivalent with actor `user` and a `user_message`; `why` names the lasting route (`GBRAIN_SURFACE=full` in the harness's per-server env, or a `--surface full` re-registration) and that an inherited `GBRAIN_SURFACE` overrides a pinned `--surface`. Read-only access never offers a widen. HTTP stays opaque. `scripts/generate-plugin-tree.ts` appends the same map as a per-skill note to generated starter-gap skills. Test: `test/hidden-tool-hint.test.ts`. D2: `hiddenToolRoute(op, ToolConnection)` is the one decision for every transport (`callable` | `widen {surface}` | `host {read_only|surface|grant}`): a widen is offered only when the widened connection could call the tool (read-only access, `GBRAIN_MCP_FORCE_SURFACE`, the grant's snapshot/scopes and an operator pin all hold); dispatch builds the connection with `toolConnection(opts)`. `hiddenToolNext` turns a route into the D2 fix (the call itself; request_tools; on HTTP the D4 grant repair; on stdio the CLI equivalent with the call's arguments as flags).- `Operation.cliOnly` + `cliOnlyRefusal` (`src/core/ops/callable.ts`) — F5: owner-only ops (they refuse every MCP caller) are never listed on MCP; a call gets `trusted_local_only` (error `permission_denied`) with the exact CLI command.-- `src/core/behavior-change-notice.ts` — the one-time `behavior_changes` safety notice: a live `chat_fallback_chain` (local view: entries, providers, refusal behavior, removal fix; HTTP view: only that a chain is configured), managed-brain lint repairs (`cycle.lint_fix`), smaller transcript parts re-embedded once (`TRANSCRIPT_REINGEST_MULTIPLIER`), a mention-linker rescan (v0.60.68.0), and fix wave 9's six upgrade-visible changes (v0.60.74.0). `BEHAVIOR_CHANGES` is the one table of disclosed changes, each with the release that introduced it (`FENCE_REPAIR_MEASURED` is the automatic fence repair row's measurement sentence, replaced by the Tier 3 eval's measured rates); `BEHAVIOR_NOTICE_SINCE` is the newest row's release (never `VERSION`), so the notice id `behavior_changes@<since>` moves only when a release appends rows. Content: the rows newer than the last notice release this brain × channel (× HTTP client) was shown, or than its baseline when never shown. Baseline: the brain's baseline under `GBRAIN_HOME/notices/behavior-changes/<brainKey>.baseline` (`gbrain init` stamps a database it creates; otherwise the first look records `0` when `upgrade-state.json` shows an upgrade from an older release or the oldest `sources.created_at` is past `FRESH_BRAIN_GRACE_MS`). Markers: CLI and stdio claim a `wx` file per notice × brain × channel (an unwritable home still delivers, once per process); the newest marker names the last release shown; HTTP keeps up to `HTTP_SHOWN_CAP` client ids, each with the release it was shown, in the `notices.behavior_changes.http` config row (a row from an older build counts its clients as shown its id's release) (no migration; a failed write still delivers). Delivery: `completeEngineStartup` in `src/cli.ts` (stderr; not `serve` or `doctor`), and `sessionSafetyNotices` in `src/mcp/dispatch.ts` on success and failure results. `gbrain doctor --only behavior_changes` reads every row newer than the baseline without writing. Pinned by `test/behavior-change-notice.test.ts` (both engines, plus upgrade steps in processes pinned to a `VERSION`) and `test/behavior-change-notice-cli.test.ts`.+- `src/core/behavior-change-notice.ts` — the one-time `behavior_changes` safety notice: a live `chat_fallback_chain` (local view: entries, providers, refusal behavior, removal fix; HTTP view: only that a chain is configured), managed-brain lint repairs (`cycle.lint_fix`), smaller transcript parts re-embedded once (`TRANSCRIPT_REINGEST_MULTIPLIER`), a mention-linker rescan (v0.60.68.0), and fix wave 9's six upgrade-visible changes (v0.60.74.0). `BEHAVIOR_CHANGES` is the one table of disclosed changes, each with the release that introduced it (`FENCE_REPAIR_MEASURED` is the automatic fence repair row's measurement sentence, replaced by the Tier 3 eval's measured rates); `BEHAVIOR_NOTICE_SINCE` is the newest row's release (never `VERSION`), so the notice id `behavior_changes@<since>` moves only when a release appends rows. Content: the rows newer than the last notice release this brain × channel (× HTTP client) was shown, or than its baseline when never shown. Baseline: the brain's baseline under `GBRAIN_HOME/notices/behavior-changes/<brainKey>.baseline` (`gbrain init` stamps a database it creates; otherwise the first look records `0` when `upgrade-state.json` shows an upgrade from an older release or the oldest `sources.created_at` is past `FRESH_BRAIN_GRACE_MS`). Markers: CLI and stdio claim a `wx` file per notice × brain × channel (an unwritable home still delivers, once per process); the newest marker names the last release shown; HTTP keeps up to `HTTP_SHOWN_CAP` client ids, each with the release it was shown, in the `notices.behavior_changes.http` config row (a row from an older build counts its clients as shown its id's release) (no migration; a failed write still delivers). Delivery: `completeEngineStartup` in `src/cli.ts` (stderr; not `serve` or `doctor`), and `sessionSafetyNotices` in `src/mcp/dispatch.ts` on success and failure results. `gbrain doctor --only behavior_changes` reads every row newer than the baseline without writing. Pinned by `test/behavior-c... (line truncated to 2000 chars)- `src/core/post-upgrade-notice.ts` — F7 `post_upgrade` safety notice (contract_version + behavior-table URL): `gbrain post-upgrade` writes it once; the first stdio MCP session per upgraded version gets it (persisted under GBRAIN_HOME). `src/cli/op-notices.ts` (also `retrievalIncompleteLine`, search/query's `Retrieval incomplete:` line: `projection_pending` only when `coverage` says some pending page could match, with the count, once per window across calls) renders op notices on the local CLI (`--json` objects gain `notices`; human output on stderr).- `src/core/ops/op-fix.ts` — Lane B builders for filled, surface-correct op errors (type-only agent-output import: ops sit in the snapshot-schema closure). `opTransport(ctx)` (cli/stdio/http from `remote`+`transport`), `paramUse(ctx, param, value?)` (`--no-pull` vs `no_pull: true`), `readFix` (diagnostic step, `mcp` + `argv`), `hostFix`/`hostOnlyError` (B6: host-only command, actor agent on CLI / user on stdio / host_admin on http with relay `user_message`), `invalidParam` (B2/B3: param, choices or type+description, one example; never echoes the raw value), `scopeDeniedError` (B5: `insufficient_scope`, frozen `error` via `legacy_error`, client id + current scopes in `why`, the exact `gbrain auth rescope`/`rescope-token` command, consent `credentials`). Test: `test/op-fix.test.ts`, `test/scope-denial-contract.test.ts`.- `src/core/persistence/page-identity.ts` — B4: `pageIdentityError(present, msg)` (a deleted page throws canonical `page_not_found` with the frozen wire/journal `error` `page_identity_changed`; a replaced page keeps `page_identity_changed`), `isMissingPageMessage` (replays recover the distinction from the stored message; no schema change), `yamlLocator` (content-free ` at line L, column C`). Replays (`writeResponse` in `persistence/service.ts`) set `OperationError.receiptFields` (never serialized); `toAgentError` fills the registry fix template (`{slug}`/`{source_id}`/`{request_id}`/`{operation}`, strict per-field patterns, unfillable → dropped) and applies the principal-aware receipt rule (CLI principal → `gbrain write-request`; same-principal MCP → `get_write_request` when callable; otherwise host inspection, actor host_admin). Test: `test/write-receipt-remediation.test.ts`.diff --git a/docs/architecture/key-files/commands-5.md b/docs/architecture/key-files/commands-5.mdindex 5cd602e8d0..eb6dfe99ae 100644--- a/docs/architecture/key-files/commands-5.md+++ b/docs/architecture/key-files/commands-5.md@@ -42,7 +42,7 @@ Current behavior and load-bearing invariants; history belongs in Git and CHANGEL- `src/commands/sources-strategy.ts` — `gbrain sources set-strategy <id> <markdown|code|auto>` (#4899, PR #5955): writes `sources.config.strategy` through `updateSourceConfig` (single-key merge; every other config key survives), the value `sync --all`, autopilot, the dream cycle and the MCP `sync` op pass to the per-source sync when the caller names no `--strategy`; unset means `markdown`. The one writer of that key (no `sources add --strategy`, no op param). Connector kinds refuse it. [R26]: refuses with `sync_run_unfinished` (exit 1) while the source has an unfinished `managed-sync` cursor, naming the resume and the orphan repair, because the frozen manifest was classified under the old strategy; re-stating the current value is allowed. `sources list --json` and `listSources` report `strategy` (`null` when unset). Pinned by `test/sources-strategy.test.ts`.-- `src/commands/sources.ts` — `gbrain sources {list,add,remove,archive,restore,archived,purge,current,status,audit,refresh,set-calendar}`; `set-calendar` dispatches to `src/commands/sources-set-calendar.ts`, and `set-cr-mode` prints `contextualModeHint` after the write. `refresh` dispatches to `src/commands/sources-refresh.ts` (argument parsing, stdout text or `--json` result/refusal objects, exit 1 on refusal or an unfinished sync; protocol in `src/core/persistence/worktree-refresh.ts`). `current [--json]` calls `resolveSourceWithTier()` and prints `source_id`, `tier` (`flag | env | dotfile | local_path | brain_default | seed_default`), and optional `detail` (decision table in `skills/conventions/brain-routing.md`). `status [--json]` — read-only per-source dashboard (last sync, staleness, page count, embedding coverage, unacked failures); thin wrapper around `buildSyncStatusReport` + `printSyncStatusReport` from `src/commands/sync.ts`; `--json` emits stable `{schema_version: 1, sources, ...}` on stdout; filters input to `local_path IS NOT NULL AND archived IS NOT TRUE`. `audit <id> [--json]` — read-only dry-run disk scan for size distribution + would-blocks + junk-pattern hits WITHOUT touching the DB; walks `sources.local_path`, reads each markdown file, runs `assessContent()` from `src/core/content-sanity.ts`, aggregates by verdict (`ok | warn_oversize | hard_block_junk_pattern`). The live `runStatus` health table gains a `BACKFILL` column between `EMBED` and `FAILS` (`active(N)` beats `queued(N)` beats `idle`, from `SourceMetrics.backfill_active` / `backfill_queued` in `src/core/source-health.ts`) so operators see deferred `embed-backfill` minion work after `sync --all` exits 0; `jobCountsBySource` in `source-health.ts` widens its `minion_jobs` SQL with two `COUNT(*) FILTER (WHERE name = 'embed-backfill' AND ...)` aggregates (best-effort, all-0 on pre-minions brains). `remove` pre-checks OAuth-client referents (guided refusal via `formatClientReferentsBlock` — the raw FK violation never reaches the operator), then commits the row DELETE atomically with an in-tx referents re-check (a registration racing the pre-check maps to the same guided refusal); durability-scaffolding teardown (`unhardenBrainRepo`: hook/cron/credential) runs only AFTER the commit, so a refused delete leaves the scaffolding intact. `purge` runs the same referents pre-check before its hard DELETE. Pinned by `test/content-sanity.test.ts`, `test/import-file-content-sanity.test.ts`, `test/source-health.test.ts`.+- `src/commands/sources.ts` — `gbrain sources {list,add,remove,archive,restore,archived,purge,current,status,audit,refresh,set-calendar}`; `set-calendar` dispatches to `src/commands/sources-set-calendar.ts`, and `set-cr-mode` prints `contextualModeHint` after the write. `refresh` dispatches to `src/commands/sources-refresh.ts` (argument parsing, stdout text or `--json` result/refusal objects, exit 1 on refusal or an unfinished sync; protocol in `src/core/persistence/worktree-refresh.ts`). `current [--json]` calls `resolveSourceWithTier()` and prints `source_id`, `tier` (`flag | env | dotfile | local_path | brain_default | seed_default`), and optional `detail` (decision table in `skills/conventions/brain-routing.md`). `status [--json]` — read-only per-source dashboard (last sync, staleness, page count, embedding coverage, unacked failures); thin wrapper around `buildSyncStatusReport` + `printSyncStatusReport` from `src/commands/sync.ts`; `--json` emits stable `{schema_version: 1, sources, ...}` on stdout; filters input to `local_path IS NOT NULL AND archived IS NOT TRUE`. `audit <id> [--json]` — read-only dry-run disk scan for size distribution + would-blocks + junk-pattern hits WITHOUT touching the DB; walks `sources.local_path`, reads each markdown file, runs `assessContent()` from `src/core/content-sanity.ts`, aggregates by verdict (`ok | warn_oversize | hard_block_junk_pattern`). The live `runStatus` health table gains a `BACKFILL` column between `EMBED` and `FAILS` (`active(N)` beats `queued(N)` beats `idle`, from `SourceMetrics.backfill_active` / `backfill_queued` in `src/core/source-health.ts`) so operators see deferred `embed-backfill` minion work after `sync --all` exits 0; `jobCountsBySource` in `source-health.ts` widens its `minion_jobs` SQL with two `COUNT(*) FILTER (WHERE name = 'embed-backfill' AND ...)` aggregates (best-effort, all-0 on pre-minions brains). `remove` pre-checks OAuth-client referents (guided refusal via `formatClientReferentsBlock` — the raw FK violation never reaches the operator), then commits the row DELETE atomically with an in-tx referents re-check (a registration racing the pre-check maps to the same guided refusal); durability-scaffolding teardown (`unhardenBrainRepo`: hook/cron/credential) runs only AFTER the commit, so a refused delete leaves the scaffolding intact. `purge` runs the same referents pre-check before its hard DELETE. `add` without `--federated` or `--no-federated` stores the source non-federated and warns on stderr that a remote token or agent connection with no source grant cannot read it, naming `gbrain sources federate <id>` and `gbrain auth rescope --token <name> --sources <id>` (`test/sources-add-federation-warning.test.ts`). Pinned by `test/content-sanity.test.ts`, `test/import-file-content-sanity.test.ts`, `test/source-health.test.ts`.- `src/commands/status-funnel.ts` — `gbrain status --funnel [--json] [--enable | --delete]` (D8 adoption funnel): engine-free, dispatched from `src/cli/main.ts` before any connect so it works before `gbrain init` and on a thin client; reads and writes only the local record through `src/core/funnel.ts`. Guide: `docs/guides/adoption-funnel.md`. Tests: `test/funnel.test.ts`, `test/funnel-cli.test.ts`.diff --git a/scripts/module-size-limits.tsv b/scripts/module-size-limits.tsvindex 552ff45c07..035edcf27b 100644--- a/scripts/module-size-limits.tsv+++ b/scripts/module-size-limits.tsv@@ -30,7 +30,7 @@ src/commands/integrations.ts 1739 ratchet grown v0.46.26.0 megawave (#4039 connesrc/core/minions/handlers/subagent.ts 1925 ratchet merged: master v131 settle rework + dream-wave C5 peel + C6 accounting + C7 lease heartbeats/lost-lease aborts + C9 oneshot dispatch + adversarial fix batches; grown by #4078 subagent-loop capability fix; +6 lines (reasoning-item replay: adaptContentBlocksToChatBlocks handles 'reasoning' blocks); +3 wave G #4514: Anthropic-via-OpenRouter allowed on the subagent loop; +36 lines (code review, same PR): isPromptTooLongError walks a bounded .cause chain so it still matches post-normalizeAIError() wrapping, plus extractPromptTooLongDetail so the dead-lettered job's error carries the matched provider detail instead of the generic normalizeAIError() wrapper text; master integration: harness support: boundary wiring to shared grants, isolated setup, withdrawal and delegated guards; #5105: +13 call-site wiring to shared tool-write-identity helper across fresh and replay dispatch; +7 fix wave 9 lane B #4921: ai.chat.per_turn_timeout_ms read once and passed to the oneshot and gateway-loop paths (resolver lives in minions/handler-timeouts.ts)src/commands/bootstrap.ts 2147 ratchet grandfathered at merge (grew past the 1500 cap on master); raised for #4066 HOME_WORKSPACE_GUARD_EXEMPT (status/uninstall/harness); +5 for the harnessDetect test seam (bulk lives in core/bootstrap/harness.ts); +23 for the contract subcommand dispatcher glue (#4105 absorb — bulk lives in core/bootstrap/contract.ts); +codex hooks-consent gate + mcp+hooks receipt registration + uninstall arm; +42 ambient-writeback WP8: interview-time SURFACE_MULTIUSER audience apply (pre-init ordering) + applyDeclaredAudienceFromInterview; +3 #4897 harness usage clause documenting --source ID semantics; +5 #5878: --refresh-skills dispatch and usage lines (logic in core/bootstrap/harness-skills.ts); +11 #5488: SUBCOMMAND_HELP harness entry (gate on --help / -h / help) — CLI help line, cannot move; +11 #4618 seat: --seat/--no-seat help lines and the runHooks parse (parse + notes live in core/bootstrap/hooks.ts parseSeatFlags); +13 #4082: runAdoptHooks (the --adopt branch of the hooks subcommand, kept out of runHooks for the function-size ratchet) and its two help lines (adoption logic lives in core/bootstrap/adopt-connection.ts + adopted-connections.ts)src/core/minions/worker.ts 1795 ratchet grandfathered at merge (grew past the 1500 cap on master, #4170); grown v0.46.11.0 five-issue wave; security: durable queued authority and confined filesystem dispatch; typed readiness, configuration-blocked lifecycle and bounded release; post-validation readiness publication and confirmed isolated-execution stop evidence; latch typed lock-renewal faults before generic retry; +9 Lane D: JobDeferredError routing (deferJob helper); +1 spend authorization: runWithJobSpend import (both handler seams call it in place of the bare handler); +3 watchdog: gracefulShutdown records its reason and launchJob aborts a claim committed before it fired; +5 GBRA-130 A-30: watchdog-attribution import, InFlightJob.shared (interface field), the suspect-alone claim gate and option, and the watchdog settle call in the executeJob catch (logic in minions/watchdog-attribution.ts); +6 GBRA-133 2a.4 sync-queue wake: IdleWaiter import and field, claimStarted before each claim, the idle poll through it, and stop/requestShutdown ending its wait (logic in minions/idle-wait.ts); +1 GBRA-158 #7239: refusal.ts import (a deterministic refusal ends the job at once; classification in minions/refusal.ts); +3 #7242 lane reservation: lanes import and the longJobNames/shortJobReservedSlots defaults (the claim passes claimExclusions; policy in minions/lanes.ts); +2 #7242 terminal hook: onJobSettled default and the settle call (logic in terminal-hook.ts); #7252 x #7249 merge: both sides grew the file, re-summed (1794 measured); GBRA-151 #7183/#7187/#7188 re-summed at the v0.60.402.0 merge (1795 measured)-src/commands/sources.ts 2081 ratchet +5 PR #5955 / fix wave 14 P2.7: sources set-strategy dispatch and help row, the strategy field of sources list --json (body in sources-strategy.ts); +5 #5988: sources status/retry-held help rows describe Git holds (help lines cannot move); +2 #5988: sources status <id> filter and Git held files (view in persistence/connector-status.ts); +5 F0: sources refresh dispatch and help rows (command body in sources-refresh.ts, protocol in persistence/worktree-refresh.ts); +6 fix wave 5 #5409: mirror-readonly/mirror-writable dispatch, help rows and the list --json mirror_read_only field (body in sources-mirror.ts); grown v0.46.22.0 phone wave: github source kind (#4104); +129 v0.47 gmail-loops: google source-kind flags + vault preflight + duplicate-account warn + access-mode validation; +8 set-path dispatch + help rows (#4739 — command body peeled to sources-set-path.ts); +29 #4698 adoption: --calendar-id flag + duplicate-account warn scoped to overlapping services; #5105: trusted writer administration route; company handlers and receipt status wiring; parsing stays in dedicated modules; canonical reconciliation: +5 engine-free sibling-command dispatch and help row, implementation remains in source-reconcile.ts; +4 fix wave 3 lane A: sources status connector recovery state and run counts (view lives in persistence/connector-status.ts); +3 fix wave 4 lane B: sources retry-held dispatch and help row (command body in sources-retry-held.ts) and the connector first-sync note on add; bodies in source-delete.ts and sources-set-path.ts); +4 #5984: sources status shows the managed sync backlog (logic in persistence/sync-drain.ts); v0.60.48.0 merge: #5984 growth re-summed over v0.60.47.0 (2031 measured); +11 W-B4: sources shared-skills dispatch, its --help guard and help rows, and the shared_skills field/lines in sources status (body in sources-shared-skills.ts, view in shared-skills/source-opt-out.ts); +4 #6188: uncommitted legacy fence-repair notices in sources status (logic in fence-repair/uncommitted.ts); +7 #6317: data_moving/movement_state on sources status and its human line (reader in persistence/sync-movement.ts), writer movement help row; +1 GBRA-133: sources reset-upstream help row (body in sources-reset-upstream.ts); fix wave 20 integration: lane 3 (#6827) and master growth compose at 2062 measured; +3 GBRA-150: sources resolve-path dispatch and help rows (body in sources-resolve-path.ts); +10 #7326: sources status parses --holds/--limit/--cursor and passes the git_holds listing mode, plus 4 help lines (bounding logic in persistence/connector-status.ts gitHoldStatusJson); +2 GBRA-133 Q1: sources set-sync dispatch and help row (body in sources-sync-enabled.ts); +4 G1 git-canonical: sources git-gap dispatch, doc line and help rows (body in sources-git-gap.ts)+src/commands/sources.ts 2082 ratchet +1 GBRA-156: the sources add non-federated warning line; +5 PR #5955 / fix wave 14 P2.7: sources set-strategy dispatch and help row, the strategy field of sources list --json (body in sources-strategy.ts); +5 #5988: sources status/retry-held help rows describe Git holds (help lines cannot move); +2 #5988: sources status <id> filter and Git held files (view in persistence/connector-status.ts); +5 F0: sources refresh dispatch and help rows (command body in sources-refresh.ts, protocol in persistence/worktree-refresh.ts); +6 fix wave 5 #5409: mirror-readonly/mirror-writable dispatch, help rows and the list --json mirror_read_only field (body in sources-mirror.ts); grown v0.46.22.0 phone wave: github source kind (#4104); +129 v0.47 gmail-loops: google source-kind flags + vault preflight + duplicate-account warn + access-mode validation; +8 set-path dispatch + help rows (#4739 — command body peeled to sources-set-path.ts); +29 #4698 adoption: --calendar-id flag + duplicate-account warn scoped to overlapping services; #5105: trusted writer administration route; company handlers and receipt status wiring; parsing stays in dedicated modules; canonical reconciliation: +5 engine-free sibling-command dispatch and help row, implementation remains in source-reconcile.ts; +4 fix wave 3 lane A: sources status connector recovery state and run counts (view lives in persistence/connector-status.ts); +3 fix wave 4 lane B: sources retry-held dispatch and help row (command body in sources-retry-held.ts) and the connector first-sync note on add; bodies in source-delete.ts and sources-set-path.ts); +4 #5984: sources status shows the managed sync backlog (logic in persistence/sync-drain.ts); v0.60.48.0 merge: #5984 growth re-summed over v0.60.47.0 (2031 measured); +11 W-B4: sources shared-skills dispatch, its --help guard and help rows, and the shared_skills field/lines in sources status (body in sources-shared-skills.ts, view in shared-skills/source-opt-out.ts); +4 #6188: uncommitted legacy fence-repair notices in sources status (logic in fence-repair/uncommitted.ts); +7 #6317: data_moving/movement_state on sources status and its human line (reader in persistence/sync-movement.ts), writer movement help row; +1 GBRA-133: sources reset-upstream help row (body in sources-reset-upstream.ts); fix wave 20 integration: lane 3 (#6827) and master growth compose at 2062 measured; +3 GBRA-150: sources resolve-path dispatch and help rows (body in sources-resolve-path.ts); +10 #7326: sources status parses --holds/--limit/--cursor and passes the git_holds listing mode, plus 4 help lines (bounding logic in persistence/connector-status.ts gitHoldStatusJson); +2 GBRA-133 Q1: sources set-sync dispatch and help row (body in sources-sync-enabled.ts); +4 G1 git-canonical: sources git-gap dispatch, doc line and help rows (body in sources-git-gap.ts)src/core/link-extraction.ts 2424 ratchet grown v0.46.26.0 megawave: link-aware timeline split + delimiter-outside-links (#3957 #4062 #3737); +37 wave-k #3908 reimpl: isCrossSourceLinksEnabled config ladder; +10 wave #4277: parseTimelineEntries skips generated backlink receipts; +17 #4855: latin-fold in normalizeBasename + dir-hint step tries both slug grammars; +17: #4855 Latin stroke-letter fold; +5: #4873 ./-relative markdown links kept as live references; +34 wave review: `../y.md` sibling links resolve on the DB path + folded bare-wikilink grammar (#4873 class); +62 #4977: role-prior suppression in machine-list sections (rolePriorSuppressedRanges, EntityRef.index); +3 composed with #4985 (variation-selector strip) in the same wave; +4 #4995: markdown-link anchor strip + lowercase-candidate rationale comments; +6 pre-landing review: #4977 suppression on code-stripped content + truthful watermark/section-list comments; T2: source-qualified inference and atomic origin-scoped derived links; canonical attendance evidence, source-qualified orientation, strict attendee resolution, and relocated filesystem link scanner (command export preserved); +4: pack-owned fallback and ambiguous attendee guards Display-label attendance exclusion, indexed evidence membership, and bounded strict resolver caching; attendance-boundary review.; complete attendance resolution and fence-safe evidence traversal; frontmatter discovery, canonical basename admission and code-aware attendance comment masking; exclude inline HTML comment spans from admitted attendance ranges; +17 write-path wave: same-name rule for entity fuzzy matches + rename-alias fallback in makeResolver; +1 #5567: materialized marker ends bullet detail; +30 #5749: unique global-basename step before fuzzy and live keyword resolution (ResolveOptions, watermark note); #5765: bold **Attendees:** label accepted + LINK_EXTRACTOR_VERSION_TS bump note; +10 eval-wave N9-2/N9-3/N12-7: pack frontmatter mappings inherit FRONTMATTER_LINK_MAP direction, page-type-bound pack attended follows canonical attendance, LINK_EXTRACTOR_VERSION_TS bump note; +1 #5623: normalizeBasename collapses hyphen runs like slugifySegment (extractor watermark note); +11 #5562: parseTimelineEntries accepts dated ### headings (FS-extractor parity); +3 eval-wave N12-6: Participants accepted as attendance evidence + LINK_EXTRACTOR_VERSION_TS bump note; +22 P5 wanted pages: AuthoredRef on body link candidates; -33 lowered: P5 moved machine-section ranges to core/machine-sections.ts and stated relation types to core/line-grammar.ts; +7 P5: ExtractPageLinksOptions interface + wikilinkAuthoredRef helper (keeps extractPageLinks under the function-size limit); +32 P5: per-edge verb attachment (attachedVerb, VERB_RULES) + joined-as works_at + extractor watermark note; P5 x temporal-edges merge: verb attachment reads the verb at the link's own position in the window (excerptAnchor) and the within-page dedup (now dedupeCandidates) drops a mention of a target the page also links with a typed edge; links joined only by commas/conjunctions share the verb before the first (coordinated); board roles (BOARD_RE, BOARD_AFTER_RE) resolve to invested_in for an investor page and advises otherwise, never works_at; +1 fix wave 11 #6191: imports targetTakesVerb (role-verb target guard lives in link-target-roles.ts); v0.60.105.0 merge: #5984 Phase 5 link preparation (+6) re-summed over wave 11 at 2211; +109 Q2 Track C: stable verb-rule ids, traceLinkType/explainLinkType (reasons for every typing decision), per-occurrence typer hoisted out of extractPageLinks (makeTypeFor); unit logic lives in core/link-typing-units.ts; +25 Q2 Track C: typing-unit verb rules and vetoes in attachedVerb/traceLinkType, validity stints in explainLinkType; +4 U3: board-seat rule split out of INVESTED_RE (same verb and precedence) and investor-prior/link offsets passed to unit vetoes; +11 U2: locateLink shared by attachedVerb and the U2 post-pass in traceLinkType; -11 lowered: Q2 verdict reverted U2 (locateLink and the post-pass); +21 fix wave 13 P4.10 #6266: resolveSameDirSlug + exported resolveMarkdownLinkSlug, shared with the link validator; +41 Wave B PR 2 lane 2e: extractPageLinks split into extractBodyLinks (window-scoped, offset-shifted, pass-tagged candidates) and frontmatterLinks, plus entityRefPasses, candidateKey, rolePriorPhrases and the roleText/regexBudget/window options, so a segmented page streams through the same extractor (window and merge logic in core/page-body/segment-links.ts); +1 at the #6869 gate-ahead merge: the #6803 wave EXTRACTOR_BUMP_NOTES comment composed with lane 2e (2420 + 1); +3 G5 (GBRA-60): extractBodyLinks masks the ## Links fence (links-fence.ts), whose rows are projected as their own edgessrc/core/embedding-migration.ts 1587 ratchet new row: crossed 1500 in v0.46.25.0 fix waves (#4305 #4306 chunk-model truth helpers); retired provider integration removed; safety wave: canonical projection readiness and fact-aware completion; file configuration publication retains lease-row locks; +8 transactional retained-vector rebuildability checks before destructive migration boundaries; archived eligibility: source-locked reconciliation and live/current smoke revalidation; +2 #5680: authorization_generation field and its carry-forward on same-target re-apply (settle idempotency); +10 #5226: plan carries chunks_to_restamp beside chunks_to_embed; +9 #5088: schema transition defers HNSW builds into the marker (deferred_ann_indexes), carry-forward on re-apply, verify blocks on pending/INVALID ANN indexes (build phase in embedding-ann-build.ts); +10 #5088: dim-pinned tables (query_cache, facts, and any later entry of TEXT_EMBEDDING_DIM_PINNED_TABLES) defer their HNSW through the same worklist (DEFERRED_ANN_TABLES, recordDeferredAnnIndexes); +25 wave 8 lane D1 #5885: takes in the dim-pinned column list, plan (takes_to_embed), status (takes_pending) and completion verify; +17 #5334: smoke check samples one representative chunk per distinct page (bounded index-ordered batch walk, longest chunk re-read under the page lock, title-prefixed bounded query); +1 #5334: the smoke-query length limits are shared with the worst-case budgetsrc/core/github-source.ts 1530 ratchet new row: crossed the 1500 unlisted cap in v0.46.23.0 review fix wave (scope-state gating, client hardening, symlink containment); merged reliability/shared-skills source integration; managed sweep lease wrapper; fix wave 3 lane A: config parser peeled to github-source-config.ts (-47), +account pin wiring and pinned-installation refreshdiff --git a/src/commands/sources.ts b/src/commands/sources.tsindex 103dc22d13..08c7488e75 100644--- a/src/commands/sources.ts+++ b/src/commands/sources.ts@@ -453,6 +453,7 @@ async function runAdd(engine: BrainEngine, args: string[]): Promise<void> {console.log(` federated: ${fed}${fed ? ' — appears in cross-source default search' : ' — only searched when explicitly named via --source'}`,);+ if (!fed && federated === null) console.error(`Warning: source "${id}" is not federated. A remote token or agent connection with no source grant cannot read its pages, so its searches answer empty for them. Run \`gbrain sources federate ${id}\` to let every such connection read it, or grant one token with \`gbrain auth rescope --token <name> --sources ${id}\`.`);if (ghKind || gKind) {console.log(` sync: run \`gbrain sync --source ${id}\` once; after its first sync, autopilot keeps it synced on the autopilot interval.`);}diff --git a/src/core/behavior-change-notice.ts b/src/core/behavior-change-notice.tsindex 6ae36904e0..7ceb69ee66 100644--- a/src/core/behavior-change-notice.ts+++ b/src/core/behavior-change-notice.ts@@ -1251,6 +1251,8 @@ export const BEHAVIOR_CHANGES: ReadonlyArray<{ since: string; text: ChangeText;{ since: '0.60.441.0', text: 'On a managed brain, `remove_link` no longer deletes an edge that the page\'s own text creates (a link, wikilink or frontmatter field): it keeps it and returns `derived_from_text` with a message saying to edit the page text (`edit_page`) instead.' },{ since: '0.60.441.0', text: 'On a managed brain, `extract_entities` writes the entity\'s timeline bullet into the entity page\'s Markdown through the page door, and the backlink to the source page is the link inside that bullet rather than a database-only edge.' },{ since: '0.60.433.0', id: 'starter_tools_list_params_gbra156', text: 'The starter MCP tool list is about 27% smaller: it leaves out parameters MCP callers cannot use (local-only, server-set provenance) and rarely needed ones (legacy, admin, versioned skill catalog, image and code search, tuning and recovery knobs with safe defaults). Every left-out parameter is still accepted, and `request_tools {tools: [names]}` now returns each tool\'s full schema with every optional parameter, also on a server capped at starter. Memory verb descriptions no longer start with `MEMORY VERB (v1):`. The verbs and full surfaces list every parameter as before.' },+ { since: '0.60.433.0', id: 'sources_not_readable_gbra156', text: 'An unscoped `search`, `query`, `recall` or `list_pages` from a token or agent connection with no source grant that comes back empty, while every source it can read holds no page and other sources do, now carries a `sources_not_readable` notice (kind degraded). It says the empty result is not proof of absence, never names a hidden source, and its fix is `gbrain sources federate <source>` on the brain host, or a grant for the token. Granted tokens and OAuth clients never get it.' },+ { since: '0.60.433.0', id: 'sources_add_federation_warning_gbra156', text: '`gbrain sources add` without `--federated` or `--no-federated` now warns on stderr that the new source is not federated, so a remote token or agent connection with no source grant cannot read its pages, and names `gbrain sources federate <id>` and `gbrain auth rescope --token <name> --sources <id>`. The stored default is still non-federated.' },];/** The newest disclosed change's release: the notice id moves only when a release adds rows. */diff --git a/src/core/cli-flag-registry.generated.ts b/src/core/cli-flag-registry.generated.tsindex 8a53771a80..9f2308beab 100644--- a/src/core/cli-flag-registry.generated.ts+++ b/src/core/cli-flag-registry.generated.ts@@ -50,7 +50,7 @@ export const CLI_FLAG_REGISTRY: Record<string, readonly string[]> = {'db-repair': ['--accept-pending', '--apply', '--apply-rewrites', '--background', '--brain', '--break-lock', '--db-url', '--dry-run', '--explain', '--filter', '--follow', '--force', '--force-retry', '--format', '--help', '--http', '--json', '--legacy-lock', '--locks', '--name', '--no-accept-pending', '--path', '--prefer-postgres', '--probe', '--progress-interval', '--progress-json', '--quiet', '--remediate', '--restart', '--skip-verify', '--source', '--statement-timeout', '--supabase', '--timeout', '--timings', '--undo-last-rewrite', '--url', '--version', '--wait', '--yes'],'decide': ['--accept-all', '--all', '--all-from', '--apply', '--brain', '--call-site', '--dataset', '--dry-run', '--egress', '--embedding-dimensions', '--embedding-model', '--expect', '--from', '--help', '--include-withdrawals', '--input', '--items-out', '--json', '--kind', '--limit', '--max-cost', '--max-usd', '--min', '--non-interactive', '--out', '--provenance', '--provider', '--query', '--rate', '--reason', '--reason-family', '--recommended', '--remove', '--shadow', '--since', '--slot', '--source', '--status', '--suite', '--target', '--threshold', '--trust', '--undo', '--uri-prefix', '--version', '--what-if-threshold', '--yes'],'diag': ['--access', '--add', '--all', '--allowed-operations', '--apply', '--asof', '--body', '--bound-slug-prefixes', '--brain', '--budget-ms', '--client', '--count', '--cursor', '--date', '--dated-since', '--days', '--detach', '--entities', '--expect', '--expected-revision', '--federated-read', '--format', '--from-index', '--full', '--fuzzy', '--group-by', '--held', '--help', '--http', '--id', '--include-ambiguous', '--include-deleted', '--json', '--kind', '--limit', '--max-usd', '--model', '--multimodal', '--no-autopilot-install', '--no-pull', '--no-walk', '--only', '--page', '--params', '--path', '--phase', '--prefer', '--preview', '--purge', '--query', '--recent', '--refresh-operations', '--replace', '--restart-only', '--reverse', '--row', '--scopes', '--session', '--side', '--since', '--slug', '--slugs', '--source', '--source-id', '--sources', '--stale', '--state', '--surface', '--to', '--updated-after', '--url', '--yes'],- 'doctor': ['--abandon', '--abbrev-ref', '--accept-pending', '--access', '--account', '--acknowledge-managed', '--add', '--admin-intent', '--adopt', '--adopt-columns', '--adopt-permissions', '--after', '--aggressive', '--aliases', '--all', '--all-drifted', '--all-from', '--allow-old-serve', '--allow-outside-source-root', '--allow-shell-jobs', '--allow-unverified-remote', '--allowed-operations', '--applied', '--apply', '--apply-rewrites', '--assign-corpus', '--audit', '--auto', '--auto-additive', '--auto-fix', '--autostash', '--background', '--batch', '--batch-check', '--bound-brain', '--bound-max-concurrent', '--bound-slug-prefixes', '--bound-source', '--bound-tools', '--brain', '--branch', '--break-lock', '--budget-ms', '--budget-policy', '--budget-tokens', '--budget-usd', '--by-mention', '--cached', '--cacheinfo', '--call-site', '--catch-up', '--channel', '--check', '--cherry-mark', '--class', '--clear', '--clear-never-installed', '--cli-socket', '--client', '--close', '--concurrency', '--confidence', '--confirm', '--confirm-quiesced', '--confirm-relocated-root', '--conflicts', '--contacts-dir', '--content-audit', '--content-root', '--conversation', '--count', '--cursor', '--dataset', '--day', '--db-url', '--delegated-namespace', '--delegated-slug-prefixes', '--delete-brain', '--dest', '--detach', '--detail', '--diff-filter', '--dim', '--dimensions', '--dir', '--disable', '--drain', '--drain-timeout', '--dry-run', '--egress', '--embedding-dimensions', '--embedding-model', '--enable', '--enable-dcr', '--end-of-options', '--entity', '--env', '--error-unmatch', '--exclude', '--exclude-standard', '--exit-code', '--expand', '--expect', '--expect-local', '--expect-remote', '--expect-upstream', '--expected-epoch', '--expected-revision', '--expected-state', '--explain', '--facts', '--fast', '--federated-read', '--fetch-timeout-ms', '--ff-only', '--file', '--first-parent', '--fix', '--follow', '--force', '--force-break-lock', '--force-rechunk', '--force-remove', '--force-retry', '--force-schema', '--format', '--fresh', '--fresh-token', '--from', '--from-meetings', '--from-pages', '--full', '--full-tree', '--fuzzy', '--generation', '--get', '--get-all', '--get-url', '--git-common-dir', '--git-dir', '--git-path', '--group', '--group-by', '--hard', '--hard-deadline', '--harness', '--held', '--help', '--hold-state', '--holds', '--home', '--http', '--id', '--if-version', '--ignore-env-override', '--images', '--include-ambiguous', '--include-cross-entity', '--include-deleted', '--include-failures', '--include-flagged', '--include-frontmatter', '--include-gitignored', '--include-hidden', '--include-pseudo', '--include-repairs', '--include-withdrawals', '--index-audit', '--index-info', '--infer-dates', '--init', '--input', '--install', '--is-ancestor', '--is-inside-work-tree', '--items-out', '--job-isolation', '--jq', '--json', '--keep', '--keep-checkout', '--key', '--kind', '--lanes', '--lang', '--left-right', '--legacy-lock', '--limit', '--link-source', '--link-type', '--list', '--literal-pathspecs', '--local', '--local-env-vars', '--locks', '--log-noop', '--manifest', '--markdown', '--max-cost', '--max-cost-usd', '--max-count', '--max-facts', '--max-jobs', '--max-rss', '--max-runtime', '--max-usd', '--max-waiting', '--mcp-only', '--merge-base', '--migrate-legacy', '--migrate-only', '--migration', '--min', '--min-n', '--mode', '--model', '--multimodal', '--name', '--name-only', '--name-status', '--nice', '--no-accept-pending', '--no-autopilot-install', '--no-autostash', '--no-capture', '--no-commit-id', '--no-confirm', '--no-cron', '--no-delegate', '--no-edit', '--no-embed', '--no-embed-cache', '--no-embedding', '--no-expand', '--no-extract', '--no-filters', '--no-gpg-sign', '--no-hooks', '--no-lanes', '--no-llm', '--no-merges', '--no-migrate', '--no-probe', '--no-pull', '--no-renames', '--no-repair', '--no-restart', '--no-schema-pack', '--no-seat', '--no-tags', '--no-verify', '--no-walk', '--no-write-fetch-head', '--non-interactive', '--not', '--now', '--older-than', '--once', '--only', '--operations', '--others', '--out', '--output', '--oversized', '--overwrite', '--page', '--parallel', '--params', '--parents', '--parked-code', '--parked-pushes', '--pat-file', '--path', '--path-format', '--pending', '--pglite', '--phase', '--pid-file', '--plan', '--porcelain', '--port', '--prefer', '--prefer-postgres', '--preset', '--preview', '--probe', '--probe-pglite', '--profile', '--progress-interval', '--progress-json', '--project', '--provenance', '--provider', '--providers', '--prune-orphans', '--public-url', '--pull', '--pure', '--purge', '--push', '--push-only', '--query', '--question', '--queue', '--quiet', '--rate', '--reader-mode', '--reauth', '--rebase', '--rebuild', '--recommended', '--redact-paths', '--reference-date', '--refresh', '--refresh-operations', '--refresh-skills', '--regenerate', '--reissue', '--relative', '--relower', '--remediate', '--remediation-plan', '--remove', '--remove-core', '--repair', '--repair-unknown-markers', '--replace', '--repo', '--request', '--request-id', '--require-clean', '--reranker', '--reset', '--reset-checkpoint', '--reset-default', '--resolve', '--restart-only', '--restore-only', '--resume', '--retry-failed', '--retry-global', '--retry-held', '--retry-parked', '--reverse', '--review-lower', '--revision', '--right-only', '--rollback-to-source', '--root', '--run', '--sample', '--save', '--scope', '--scopes', '--search-mode', '--seat', '--section', '--select', '--self-transfer', '--semantic', '--session', '--session-id', '--set', '--set-upstream-to', '--shadow', '--short', '--show-current', '--show-object-format', '--show-prefix', '--show-token', '--show-toplevel', '--side', '--since', '--since-last-run', '--skills-dir', '--skip', '--skip-bare-tweet', '--skip-failed', '--skip-urls', '--skip-verify', '--slot', '--slot-a-model', '--slot-b-model', '--slot-c-model', '--slug', '--slugs', '--source', '--source-id', '--sources', '--src-subpath', '--staged', '--stale', '--stat', '--state', '--statement-timeout', '--status', '--stdin', '--stop-mcp', '--strategy', '--strict', '--suite', '--supabase', '--surface', '--swap-only', '--symbol-kind', '--symbolic-full-name', '--takes-holders', '--target', '--target-score', '--threshold', '--tier', '--timeout', '--timings', '--to', '--token', '--token-ttl', '--top-k', '--topo-order', '--trust', '--type', '--unindexed', '--uninstall', '--unsafe-bypass-dream-guard', '--unset-all', '--untracked-files', '--url', '--url-env', '--user', '--vacuum', '--vectors', '--verbose', '--verify', '--version', '--wait', '--wait-drain', '--warn-only', '--watch', '--what-if-threshold', '--window', '--workers', '--working-tree', '--workspace', '--write-tree', '--yes'],+ 'doctor': ['--abandon', '--abbrev-ref', '--accept-pending', '--access', '--account', '--acknowledge-managed', '--add', '--admin-intent', '--adopt', '--adopt-columns', '--adopt-permissions', '--after', '--aggressive', '--aliases', '--all', '--all-drifted', '--all-from', '--allow-old-serve', '--allow-outside-source-root', '--allow-shell-jobs', '--allow-unverified-remote', '--allowed-operations', '--applied', '--apply', '--apply-rewrites', '--assign-corpus', '--audit', '--auto', '--auto-additive', '--auto-fix', '--autostash', '--background', '--batch', '--batch-check', '--bound-brain', '--bound-max-concurrent', '--bound-slug-prefixes', '--bound-source', '--bound-tools', '--brain', '--branch', '--break-lock', '--budget-ms', '--budget-policy', '--budget-tokens', '--budget-usd', '--by-mention', '--cached', '--cacheinfo', '--call-site', '--catch-up', '--channel', '--check', '--cherry-mark', '--class', '--clear', '--clear-never-installed', '--cli-socket', '--client', '--close', '--concurrency', '--confidence', '--confirm', '--confirm-quiesced', '--confirm-relocated-root', '--conflicts', '--contacts-dir', '--content-audit', '--content-root', '--conversation', '--count', '--cursor', '--dataset', '--day', '--db-url', '--delegated-namespace', '--delegated-slug-prefixes', '--delete-brain', '--dest', '--detach', '--detail', '--diff-filter', '--dim', '--dimensions', '--dir', '--disable', '--drain', '--drain-timeout', '--dry-run', '--egress', '--embedding-dimensions', '--embedding-model', '--enable', '--enable-dcr', '--end-of-options', '--entity', '--env', '--error-unmatch', '--exclude', '--exclude-standard', '--exit-code', '--expand', '--expect', '--expect-local', '--expect-remote', '--expect-upstream', '--expected-epoch', '--expected-revision', '--expected-state', '--explain', '--facts', '--fast', '--federated', '--federated-read', '--fetch-timeout-ms', '--ff-only', '--file', '--first-parent', '--fix', '--follow', '--force', '--force-break-lock', '--force-rechunk', '--force-remove', '--force-retry', '--force-schema', '--format', '--fresh', '--fresh-token', '--from', '--from-meetings', '--from-pages', '--full', '--full-tree', '--fuzzy', '--generation', '--get', '--get-all', '--get-url', '--git-common-dir', '--git-dir', '--git-path', '--group', '--group-by', '--hard', '--hard-deadline', '--harness', '--held', '--help', '--hold-state', '--holds', '--home', '--http', '--id', '--if-version', '--ignore-env-override', '--images', '--include-ambiguous', '--include-cross-entity', '--include-deleted', '--include-failures', '--include-flagged', '--include-frontmatter', '--include-gitignored', '--include-hidden', '--include-pseudo', '--include-repairs', '--include-withdrawals', '--index-audit', '--index-info', '--infer-dates', '--init', '--input', '--install', '--is-ancestor', '--is-inside-work-tree', '--items-out', '--job-isolation', '--jq', '--json', '--keep', '--keep-checkout', '--key', '--kind', '--lanes', '--lang', '--left-right', '--legacy-lock', '--limit', '--link-source', '--link-type', '--list', '--literal-pathspecs', '--local', '--local-env-vars', '--locks', '--log-noop', '--manifest', '--markdown', '--max-cost', '--max-cost-usd', '--max-count', '--max-facts', '--max-jobs', '--max-rss', '--max-runtime', '--max-usd', '--max-waiting', '--mcp-only', '--merge-base', '--migrate-legacy', '--migrate-only', '--migration', '--min', '--min-n', '--mode', '--model', '--multimodal', '--name', '--name-only', '--name-status', '--nice', '--no-accept-pending', '--no-autopilot-install', '--no-autostash', '--no-capture', '--no-commit-id', '--no-confirm', '--no-cron', '--no-delegate', '--no-edit', '--no-embed', '--no-embed-cache', '--no-embedding', '--no-expand', '--no-extract', '--no-federated', '--no-filters', '--no-gpg-sign', '--no-hooks', '--no-lanes', '--no-llm', '--no-merges', '--no-migrate', '--no-probe', '--no-pull', '--no-renames', '--no-repair', '--no-restart', '--no-schema-pack', '--no-seat', '--no-tags', '--no-verify', '--no-walk', '--no-write-fetch-head', '--non-interactive', '--not', '--now', '--older-than', '--once', '--only', '--operations', '--others', '--out', '--output', '--oversized', '--overwrite', '--page', '--parallel', '--params', '--parents', '--parked-code', '--parked-pushes', '--pat-file', '--path', '--path-format', '--pending', '--pglite', '--phase', '--pid-file', '--plan', '--porcelain', '--port', '--prefer', '--prefer-postgres', '--preset', '--preview', '--probe', '--probe-pglite', '--profile', '--progress-interval', '--progress-json', '--project', '--provenance', '--provider', '--providers', '--prune-orphans', '--public-url', '--pull', '--pure', '--purge', '--push', '--push-only', '--query', '--question', '--queue', '--quiet', '--rate', '--reader-mode', '--reauth', '--rebase', '--rebuild', '--recommended', '--redact-paths', '--reference-date', '--refresh', '--refresh-operations', '--refresh-skills', '--regenerate', '--reissue', '--relative', '--relower', '--remediate', '--remediation-plan', '--remove', '--remove-core', '--repair', '--repair-unknown-markers', '--replace', '--repo', '--request', '--request-id', '--require-clean', '--reranker', '--reset', '--reset-checkpoint', '--reset-default', '--resolve', '--restart-only', '--restore-only', '--resume', '--retry-failed', '--retry-global', '--retry-held', '--retry-parked', '--reverse', '--review-lower', '--revision', '--right-only', '--rollback-to-source', '--root', '--run', '--sample', '--save', '--scope', '--scopes', '--search-mode', '--seat', '--section', '--select', '--self-transfer', '--semantic', '--session', '--session-id', '--set', '--set-upstream-to', '--shadow', '--short', '--show-current', '--show-object-format', '--show-prefix', '--show-token', '--show-toplevel', '--side', '--since', '--since-last-run', '--skills-dir', '--skip', '--skip-bare-tweet', '--skip-failed', '--skip-urls', '--skip-verify', '--slot', '--slot-a-model', '--slot-b-model', '--slot-c-model', '--slug', '--slugs', '--source', '--source-id', '--sources', '--src-subpath', '--staged', '--stale', '--stat', '--state', '--statement-timeout', '--status', '--stdin', '--stop-mcp', '--strategy', '--strict', '--suite', '--supabase', '--surface', '--swap-only', '--symbol-kind', '--symbolic-full-name', '--takes-holders', '--target', '--target-score', '--threshold', '--tier', '--timeout', '--timings', '--to', '--token', '--token-ttl', '--top-k', '--topo-order', '--trust', '--type', '--unindexed', '--uninstall', '--unsafe-bypass-dream-guard', '--unset-all', '--untracked-files', '--url', '--url-env', '--user', '--vacuum', '--vectors', '--verbose', '--verify', '--version', '--wait', '--wait-drain', '--warn-only', '--watch', '--what-if-threshold', '--window', '--workers', '--working-tree', '--workspace', '--write-tree', '--yes'],'dream': ['--audit-rejects', '--brain', '--cancel-unmatched', '--date', '--dir', '--drain', '--dry-run', '--eval-run', '--force', '--from', '--help', '--input', '--install', '--json', '--limit', '--list', '--max-usd', '--once', '--path', '--phase', '--probe', '--pull', '--reconcile-queue', '--since', '--source', '--source-id', '--threshold', '--to', '--unsafe-bypass-dream-guard', '--window', '--yes'],'edge-proposals': ['--access', '--add', '--all', '--all-applied', '--all-held', '--allowed-operations', '--asof', '--body', '--bound-slug-prefixes', '--brain', '--client', '--cursor', '--date', '--dated-since', '--days', '--entities', '--federated-read', '--from-index', '--full', '--fuzzy', '--group-by', '--help', '--http', '--id', '--include-deleted', '--json', '--kind', '--limit', '--max-usd', '--model', '--multimodal', '--no-autopilot-install', '--page', '--params', '--path', '--phase', '--prefer', '--purge', '--recent', '--refresh-operations', '--row', '--scopes', '--session', '--since', '--slugs', '--source', '--sources', '--stale', '--status', '--surface', '--to', '--updated-after', '--url', '--yes'],'edges-backfill': ['--all-sources', '--brain', '--concurrency', '--help', '--json', '--max-chunks', '--source', '--workers'],@@ -76,7 +76,7 @@ export const CLI_FLAG_REGISTRY: Record<string, readonly string[]> = {'graph-query': ['--brain', '--depth', '--direction', '--help', '--hop', '--include-foreign', '--json', '--mcp-only', '--request-id', '--source', '--type'],'hook': ['--allow-unverified-remote', '--auto', '--batch-check', '--brain', '--branch', '--cached', '--count', '--diff-filter', '--enable', '--end-of-options', '--env', '--get', '--harness', '--help', '--jq', '--json', '--limit', '--name-only', '--others', '--pat-file', '--path', '--porcelain', '--pure', '--quiet', '--remove', '--seat', '--session', '--show-current', '--show-toplevel', '--since', '--source', '--yes'],'import': ['--accept-pending', '--admin-intent', '--allow-empty', '--allow-noncanonical-root', '--apply', '--background', '--batch-check', '--brain', '--cached', '--confirm-relocated-root', '--diff-filter', '--dim', '--embedding-dimensions', '--embedding-model', '--empty', '--exclude', '--exclude-standard', '--expected-epoch', '--expected-state', '--explain', '--follow', '--force', '--force-rechunk', '--format', '--fresh', '--help', '--include-gitignored', '--is-shallow-repository', '--json', '--literal-pathspecs', '--log-noop', '--manifest', '--name-only', '--no-accept-pending', '--no-embed', '--no-embedding', '--no-gpg-sign', '--no-pull', '--no-renames', '--no-verify', '--only', '--others', '--path', '--probe', '--progress-interval', '--progress-json', '--quiet', '--self-transfer', '--show-toplevel', '--skip-failed', '--slugs', '--source', '--source-id', '--stale', '--status', '--supabase', '--timeout', '--timings', '--to', '--url', '--verify', '--wait', '--workers'],- 'init': ['--access', '--acknowledge-managed', '--adopt', '--after', '--aliases', '--all', '--all-drifted', '--allow-create-db', '--allow-docker', '--allow-outside-source-root', '--applied', '--apply', '--assign-corpus', '--audit', '--auto', '--auto-additive', '--background', '--batch', '--bound-slug-prefixes', '--brain', '--branch', '--break-lock', '--budget-ms', '--budget-policy', '--budget-tokens', '--budget-usd', '--by-mention', '--catch-up', '--channel', '--chat-model', '--check', '--class', '--clear-never-installed', '--cli-socket', '--client', '--close', '--confirm-relocated-root', '--conflicts', '--content-root', '--conversation', '--cursor', '--db-only', '--dest', '--detach', '--detail', '--dim', '--disable', '--drain', '--embedding-dimensions', '--embedding-model', '--enable', '--entity', '--exclude', '--expand', '--expansion-model', '--expect', '--expect-local', '--expect-remote', '--expect-upstream', '--explain', '--facts', '--fast', '--file', '--fix', '--force', '--force-retry', '--format', '--fresh-token', '--from', '--from-meetings', '--full', '--git', '--grant-types', '--group-by', '--harness', '--held', '--help', '--hold-state', '--holds', '--http', '--id', '--images', '--include-ambiguous', '--include-cross-entity', '--include-frontmatter', '--include-gitignored', '--include-hidden', '--infer-dates', '--install', '--issuer-url', '--job-isolation', '--json', '--keep', '--keep-checkout', '--key', '--kind', '--lanes', '--legacy-lock', '--limit', '--list', '--local-postgres', '--markdown', '--max-cost-usd', '--max-facts', '--max-rss', '--max-usd', '--mcp-only', '--mcp-url', '--migrate-only', '--migration', '--min-n', '--mode', '--model', '--no-autopilot-install', '--no-autostash', '--no-delegate', '--no-embed', '--no-embedding', '--no-expand', '--no-extract', '--no-filters', '--no-git', '--no-lanes', '--no-llm', '--no-probe', '--no-pull', '--no-renames', '--no-repair', '--no-restart', '--no-schema-pack', '--no-verify', '--non-interactive', '--oauth-client-id', '--oauth-client-secret', '--older-than', '--once', '--only', '--oversized', '--page', '--params', '--parked-code', '--parked-pushes', '--pat-file', '--path', '--pending', '--pglite', '--phase', '--plan', '--prefer', '--prefer-postgres', '--preview', '--probe', '--profile', '--provenance', '--providers', '--pull', '--purge', '--push-only', '--query', '--question', '--quiet', '--rebase', '--rebuild', '--redact-paths', '--reference-date', '--remediate', '--remove', '--repair', '--repair-unknown-markers', '--repo', '--request', '--reset', '--resolve', '--restart-only', '--resume', '--retry-failed', '--retry-parked', '--save', '--schema-pack', '--scope', '--scopes', '--search-mode', '--section', '--self-transfer', '--semantic', '--session', '--session-id', '--show-toplevel', '--side', '--since', '--since-last-run', '--skip', '--skip-embed-check', '--skip-failed', '--slug', '--slugs', '--source', '--source-id', '--src-subpath', '--stale', '--state', '--status', '--stdin', '--stop-mcp', '--strategy', '--supabase', '--surface', '--swap-only', '--tier', '--timeout', '--to', '--token', '--touchpoint', '--type', '--url', '--url-env', '--user', '--vacuum', '--verbose', '--version', '--wait', '--warn-only', '--watch', '--working-tree', '--workspace', '--yes'],+ 'init': ['--access', '--acknowledge-managed', '--adopt', '--after', '--aliases', '--all', '--all-drifted', '--allow-create-db', '--allow-docker', '--allow-outside-source-root', '--applied', '--apply', '--assign-corpus', '--audit', '--auto', '--auto-additive', '--background', '--batch', '--bound-slug-prefixes', '--brain', '--branch', '--break-lock', '--budget-ms', '--budget-policy', '--budget-tokens', '--budget-usd', '--by-mention', '--catch-up', '--channel', '--chat-model', '--check', '--class', '--clear-never-installed', '--cli-socket', '--client', '--close', '--confirm-relocated-root', '--conflicts', '--content-root', '--conversation', '--cursor', '--db-only', '--dest', '--detach', '--detail', '--dim', '--disable', '--drain', '--embedding-dimensions', '--embedding-model', '--enable', '--entity', '--exclude', '--expand', '--expansion-model', '--expect', '--expect-local', '--expect-remote', '--expect-upstream', '--explain', '--facts', '--fast', '--federated', '--file', '--fix', '--force', '--force-retry', '--format', '--fresh-token', '--from', '--from-meetings', '--full', '--git', '--grant-types', '--group-by', '--harness', '--held', '--help', '--hold-state', '--holds', '--http', '--id', '--images', '--include-ambiguous', '--include-cross-entity', '--include-frontmatter', '--include-gitignored', '--include-hidden', '--infer-dates', '--install', '--issuer-url', '--job-isolation', '--json', '--keep', '--keep-checkout', '--key', '--kind', '--lanes', '--legacy-lock', '--limit', '--list', '--local-postgres', '--markdown', '--max-cost-usd', '--max-facts', '--max-rss', '--max-usd', '--mcp-only', '--mcp-url', '--migrate-only', '--migration', '--min-n', '--mode', '--model', '--no-autopilot-install', '--no-autostash', '--no-delegate', '--no-embed', '--no-embedding', '--no-expand', '--no-extract', '--no-federated', '--no-filters', '--no-git', '--no-lanes', '--no-llm', '--no-probe', '--no-pull', '--no-renames', '--no-repair', '--no-restart', '--no-schema-pack', '--no-verify', '--non-interactive', '--oauth-client-id', '--oauth-client-secret', '--older-than', '--once', '--only', '--oversized', '--page', '--params', '--parked-code', '--parked-pushes', '--pat-file', '--path', '--pending', '--pglite', '--phase', '--plan', '--prefer', '--prefer-postgres', '--preview', '--probe', '--profile', '--provenance', '--providers', '--pull', '--purge', '--push-only', '--query', '--question', '--quiet', '--rebase', '--rebuild', '--redact-paths', '--reference-date', '--remediate', '--remove', '--repair', '--repair-unknown-markers', '--repo', '--request', '--reset', '--resolve', '--restart-only', '--resume', '--retry-failed', '--retry-parked', '--save', '--schema-pack', '--scope', '--scopes', '--search-mode', '--section', '--self-transfer', '--semantic', '--session', '--session-id', '--show-toplevel', '--side', '--since', '--since-last-run', '--skip', '--skip-embed-check', '--skip-failed', '--slug', '--slugs', '--source', '--source-id', '--sources', '--src-subpath', '--stale', '--state', '--status', '--stdin', '--stop-mcp', '--strategy', '--supabase', '--surface', '--swap-only', '--tier', '--timeout', '--to', '--token', '--touchpoint', '--type', '--url', '--url-env', '--user', '--vacuum', '--verbose', '--version', '--wait', '--warn-only', '--watch', '--working-tree', '--workspace', '--yes'],'integrations': ['--auto', '--brain', '--dry-run', '--help', '--json', '--overwrite', '--refresh', '--source', '--target'],'integrity': ['--accept-pending', '--auto', '--backend', '--background', '--body', '--brain', '--check', '--confidence', '--cost', '--dry-run', '--explain', '--follow', '--fresh', '--help', '--json', '--limit', '--no-accept-pending', '--progress-interval', '--progress-json', '--quiet', '--review-lower', '--skip-bare-tweet', '--skip-urls', '--source', '--timeout', '--timings', '--type', '--wait'],'jobs': ['--abbrev-ref', '--access', '--account', '--acknowledge-managed', '--add', '--admin-intent', '--adopt-slug-path', '--aliases', '--all', '--all-sources', '--allow-empty', '--allow-shell-jobs', '--allowed-operations', '--apply', '--asof', '--auto', '--background', '--backoff-delay', '--backoff-jitter', '--backoff-type', '--batch-size', '--body', '--bound-slug-prefixes', '--brain', '--break-lock', '--budget-ms', '--by-mention', '--cached', '--catch-up', '--channel', '--check', '--cli-path', '--client', '--close', '--cluster-errors', '--concurrency', '--confidence', '--confirm-destructive', '--confirm-relocated-root', '--cost-estimate', '--cursor', '--date', '--dated-since', '--days', '--delay', '--detach', '--detail', '--diff-filter', '--dir', '--drain', '--drain-timeout', '--dry-run', '--embedding-dimensions', '--embedding-model', '--empty', '--enable', '--entities', '--exclude', '--exclude-standard', '--expect', '--expect-local', '--expect-upstream', '--expected-state', '--explain', '--facts', '--federated-read', '--ff-only', '--file', '--filters', '--finished-since', '--fix', '--follow', '--force', '--force-break-lock', '--force-retry', '--format', '--fresh', '--from-index', '--from-meetings', '--full', '--full-history', '--fuzzy', '--git', '--grammar-diagnostics', '--group', '--group-by', '--hard-deadline', '--health-interval', '--held', '--help', '--hold-state', '--http', '--id', '--idempotency-key', '--ids', '--images', '--include-ambiguous', '--include-deleted', '--include-frontmatter', '--include-gitignored', '--include-hidden', '--include-null-signature', '--infer-dates', '--inject-bootstrap', '--inline', '--input', '--install', '--interval', '--is-ancestor', '--is-shallow-repository', '--job-id', '--job-isolation', '--json', '--keep', '--kind', '--lanes', '--legacy-lock', '--limit', '--list', '--lock-duration-ms', '--log-noop', '--markdown', '--max-age', '--max-attempts', '--max-cost', '--max-cost-usd', '--max-crashes', '--max-rss', '--max-sources', '--max-stalled', '--max-usd', '--max-waiting', '--mcp-only', '--migration', '--min-context', '--missing-path', '--mode', '--model', '--multimodal', '--name', '--name-only', '--ner', '--nice', '--no-auto-embed', '--no-autopilot-install', '--no-bulk', '--no-confirm', '--no-delegate', '--no-embed', '--no-embedding', '--no-extract', '--no-gpg-sign', '--no-hard-deadline', '--no-inject', '--no-lanes', '--no-llm', '--no-pull', '--no-renames', '--no-repair', '--no-restart', '--no-schema-pack', '--no-verify', '--no-worker', '--non-interactive', '--now', '--older-than', '--once', '--only', '--order', '--others', '--output', '--override-disabled', '--oversized', '--pace', '--pace-max-concurrency', '--pack', '--page', '--parallel', '--params', '--parked-code', '--pat-file', '--path', '--pause', '--pglite', '--phase', '--pid-file', '--plan', '--port', '--prefer', '--preview', '--priority', '--probe', '--prune-orphans', '--pull', '--purge', '--question', '--queue', '--queue-only', '--quiet', '--rate', '--reason', '--rebuild', '--recent', '--record', '--redact-paths', '--redact-secrets', '--reenrich-after', '--refresh-ms', '--refresh-operations', '--remediate', '--repo', '--request-id', '--reset-checkpoint', '--restart-only', '--resume', '--retry-failed', '--retry-global', '--retry-held', '--retry-parked', '--review-lower', '--row', '--scope', '--scopes', '--section', '--segment-limit', '--select', '--self-transfer', '--serial', '--session', '--show-toplevel', '--side', '--sigkill-rescue', '--since', '--skip', '--skip-bare-tweet', '--skip-failed', '--skip-urls', '--sleep', '--slug', '--slugs', '--source', '--source-guard', '--source-id', '--sources', '--src-subpath', '--stale', '--state', '--statement-timeout', '--status', '--stop-mcp', '--strategy', '--suites', '--surface', '--swap-only', '--target', '--thin', '--thin-threshold', '--tier', '--timeout', '--timeout-ms', '--to', '--token', '--trust', '--type', '--types', '--uninstall', '--updated-after', '--url', '--user', '--vectors', '--verbose', '--verify', '--version', '--watch', '--wedge-rescue', '--workers', '--working-tree', '--yes'],diff --git a/src/core/error-registry.ts b/src/core/error-registry.tsindex 5a7fc69010..06a7ebb1c4 100644--- a/src/core/error-registry.ts+++ b/src/core/error-registry.ts@@ -854,6 +854,7 @@ export const NOTICE_CODES = {mention_index: { kind: 'degraded', summary: 'The entity mention index is pending, off, failed or does not cover this page type, so references listed for an entity may be incomplete.' },degraded_recall: { kind: 'degraded', summary: 'A retrieval stage that affects recall did not run; an empty or thin result is not proof of absence. A failed rerank names its reason (timeout, budget, rate_limited, unreachable, auth, provider_error), the fused-order fallback and the session\'s count of reranker-degraded calls; timeout and rate_limited say to repeat the call after a delay, the rest point at doctor\'s reranker_health.' },source_binding_narrowed: { kind: 'info', summary: "A GBRAIN_SOURCE / .gbrain-source binding narrowed an unqualified read that came back empty; the fix reads another source explicitly." },+ sources_not_readable: { kind: 'degraded', summary: 'An unscoped search, query, recall or list_pages came back empty because every source this connection can read holds no page, while other sources on the brain hold pages it cannot read (not federated, and no source grant). The result is not proof of absence; the fix is the host command that federates a source or grants this connection the sources it should read. Hidden sources are never named.' },degraded_dedup: { kind: 'info', summary: 'remember ran without an embedding provider, so only exact duplicates are detected.' },facts_calibration_unmeasured: { kind: 'info', summary: 'recall --question ranked facts with semantic matching on an embedding model whose fact admission floors were never measured (`facts_calibration: {status: "unmeasured", model_key}`); a short facts list is weaker evidence of "nothing matched". Once per brain per session; the fix is the read-only `gbrain doctor --only fact_admission_floors --json`.' },private_fact_not_pushed: { kind: 'info', summary: 'remember saved a private fact: only local CLI recall reads it, and session hooks never push it into a new agent session.' },diff --git a/src/core/interop-notices.ts b/src/core/interop-notices.tsindex d2c97610b2..24b97dc23d 100644--- a/src/core/interop-notices.ts+++ b/src/core/interop-notices.ts@@ -205,7 +205,7 @@ export function degradedRecallNotice(const BINDING_READ_OPS: ReadonlySet<string> = new Set(['search', 'query', 'recall', 'list_pages']);-function emptyRead(op: string, result: unknown): boolean {+export function emptyRead(op: string, result: unknown): boolean {if (Array.isArray(result)) return result.length === 0;if (op !== 'recall' || !result || typeof result !== 'object') return false;const r = result as { facts?: unknown[]; results?: unknown[] };diff --git a/src/core/notice-ledger.ts b/src/core/notice-ledger.tsindex f332813b4b..fbcdd41f03 100644--- a/src/core/notice-ledger.ts+++ b/src/core/notice-ledger.ts@@ -34,7 +34,7 @@ export const COACHING_BUDGET_PER_SESSION = 2;/** 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']);/** 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', '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', 'references_unavailable', 'record_types_undeclared', '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', 'sources_not_readable', 'local_transcripts', 'held_files', 'relational_chain', 'mention_index', 'delta_incomplete', 'identity_siblings_capped', 'references_unavailable', 'record_types_undeclared', 'alias_fanout', 'facts_unembedded']);/** How long a shown coverage state (a notice's `escalation`) stays shown. */export const COVERAGE_NOTICE_WINDOW_MS = 30 * 60 * 1000;diff --git a/src/core/unreadable-sources-notice.ts b/src/core/unreadable-sources-notice.tsnew file mode 100644index 0000000000..43fae126aa--- /dev/null+++ b/src/core/unreadable-sources-notice.ts@@ -0,0 +1,61 @@+/**+ * GBRA-156: `sources_not_readable`, the notice on an unscoped remote read+ * that reached no source holding a page while other sources hold pages.+ *+ * A connection with no source grant (a token minted without --sources, or+ * an unbound agent stdio connection) reads the default source plus the+ * federated ones. A new source is not federated by default, so such a+ * connection can answer every search with an empty result that reads like a+ * clean miss. This notice says the pages are elsewhere and names the host+ * command that makes them readable, without naming any source the connection+ * cannot read. A connection whose operator granted it sources (every OAuth+ * client carries at least its bound source), or a read that names a source,+ * never gets it: that scope is deliberate.+ */+import type { Notice } from './agent-output.ts';+import { emptyRead } from './interop-notices.ts';+import type { OperationContext } from './ops/contract.ts';+import { federatedSearchScope } from './ops/context.ts';+import { hostFix } from './ops/op-fix.ts';++const UNSCOPED_READ_OPS: ReadonlySet<string> = new Set(['search', 'query', 'recall', 'list_pages']);++function namesSources(params: Record<string, unknown>): boolean {+ const ids = params.source_ids;+ return params.source_id !== undefined || (Array.isArray(ids) ? ids.length > 0 : typeof ids === 'string' && ids.trim() !== '');+}++/** The notice for one successful call, or null. Never throws. */+export async function unreadableSourcesNotice(+ op: string, params: Record<string, unknown>, result: unknown, ctx: OperationContext,+): Promise<Notice | null> {+ if (ctx.remote === false || !UNSCOPED_READ_OPS.has(op) || !emptyRead(op, result) || namesSources(params)) return null;+ if (ctx.explicitReadBinding || ctx.auth?.allowedSources !== undefined || ctx.auth?.hasSourceGrant === true) return null;+ try {+ const scope = federatedSearchScope(ctx);+ const readable = scope.sourceIds ?? (scope.sourceId !== undefined ? [scope.sourceId] : null);+ if (!readable) return null;+ const [row] = await ctx.engine.executeRaw<{ in_scope: boolean; elsewhere: boolean }>(+ `SELECT EXISTS (SELECT 1 FROM pages WHERE source_id = ANY($1::text[]) AND deleted_at IS NULL) AS in_scope,+ EXISTS (SELECT 1 FROM pages p JOIN sources s ON s.id = p.source_id+ WHERE p.deleted_at IS NULL AND s.archived IS NOT TRUE AND NOT (p.source_id = ANY($1::text[]))) AS elsewhere`,+ [readable],+ );+ if (!row || row.in_scope || !row.elsewhere) return null;+ return {+ code: 'sources_not_readable',+ kind: 'degraded',+ why: `This unscoped ${op} read every source this connection can read (the default source and any federated source), and none of them holds a page. `+ + 'Other sources on this brain hold pages, but they are not federated and this connection has no source grant, so it cannot read them. '+ + 'The empty result is not proof the brain has nothing on this. The brain host\'s operator can federate a source so every connection without a grant reads it (command in fix), '+ + 'or grant this connection the sources it should read (`gbrain auth rescope --token <name> --sources <ids>`).',+ fix: {+ ...hostFix(ctx, ['gbrain', 'sources', 'federate', '<source>'],+ 'Makes the source readable by every connection without a source grant; only the trusted CLI on the brain host changes federation.'),+ inputs: [{ name: 'source', how: 'Ask the user which source these connections should read (`gbrain sources list` on the brain host shows them).' }],+ },+ };+ } catch {+ return null;+ }+}diff --git a/src/mcp/dispatch.ts b/src/mcp/dispatch.tsindex 1cb0d43f48..8007d03b52 100644--- a/src/mcp/dispatch.ts+++ b/src/mcp/dispatch.ts@@ -25,6 +25,7 @@ import { logVerbUsage, recordsFiring, type RecordsFiring } from '../core/verbs/uimport { searchCountLine } from '../core/search/keyword-paging.ts';import { dateLabelLine } from '../core/search/date-labels.ts';import { hiddenTakesNotice, localTranscriptsNotice, recallInteropNotices, wantsTranscriptHint } from '../core/interop-notices.ts';+import { unreadableSourcesNotice } from '../core/unreadable-sources-notice.ts';import { hiddenToolHint, hiddenToolNext, hiddenToolRoute, type ToolConnection } from './hidden-tool-hint.ts';import { opAllowedForBoundClient } from '../core/ops/context.ts';import { takePostUpgradeMcpNotice } from '../core/post-upgrade-notice.ts';@@ -1128,6 +1129,8 @@ async function dispatchResolvedCall(const rerankDegradedCalls = recordRerankDegradation(responseMeta, opts);notices.push(...recallInteropNotices(name, result, responseMeta, safeParams,{ config: ctx.config, transport: dispatchRenderContext(opts).transport, binding: ctx.explicitReadBinding, rerankDegradedCalls }));+ const unreadable = await unreadableSourcesNotice(name, safeParams, result, ctx);+ if (unreadable) notices.push(unreadable);notices.push(...await hiddenContentNotices(engine, name, result, ctx, opts));// Monthly backup-coverage: one AGGREGATE notice per process (counts only —// never a local path or source id). The refresher runs on the stdiodiff --git a/test/e2e/serve-http-member-tokens.test.ts b/test/e2e/serve-http-member-tokens.test.tsindex 79d0528cf0..338f55a537 100644--- a/test/e2e/serve-http-member-tokens.test.ts+++ b/test/e2e/serve-http-member-tokens.test.ts@@ -1,14 +1,19 @@/*** Per-member tokens on one shared brain: two bearer tokens, one granted- * source-a and one granted source-b, call `search` and `query` concurrently- * from one process against one real `gbrain serve --http` on Postgres. Each- * token's results stay inside its own grant on every call, and `source_ids`- * cannot carry either token into the other member's source.+ * source-a and one granted source-b, call `search` (hybrid and+ * `match: "keyword"`), `query` and `recall` concurrently from one process+ * against one real `gbrain serve --http` on Postgres. Each token's results+ * stay inside its own grant on every call, and `source_ids` cannot carry+ * either token into the other member's source. Two more tokens carry the+ * multi-source grant `gbrain auth rescope --token <name> --sources` writes+ * (the member's own source plus a shared one): each reads its own and the+ * shared source, never the other member's.** 1. Protects: the multi-member bot pattern (one token per member, each* narrowed to that member's sources) over the real HTTP transport.* 2. Fails when: the server resolves a call's scope from anything but that- * call's own token, or `source_ids` widens a token past its grant.+ * call's own token, any of those read paths returns a row outside the+ * token's grant, or `source_ids` widens a token past its grant.* 3. Existing coverage (serve-http-source-grant) pins one token at a time.* 4. No production seam.*@@ -20,6 +25,7 @@ import { setupDB, teardownDB, getConn, hasDatabase } from './helpers.ts';import type { PostgresEngine } from '../../src/core/postgres-engine.ts';import { hashToken, generateToken } from '../../src/core/utils.ts';import { importFromContent } from '../../src/core/import-file.ts';+import { mintLegacyToken } from '../../src/core/token-mint.ts';const skip = !hasDatabase();const describeE2E = skip ? describe.skip : describe;@@ -28,12 +34,22 @@ if (skip) console.log('Skipping E2E serve-http-member-tokens tests (DATABASE_URLconst PORT = 19158;const BASE = `http://localhost:${PORT}`;const MEMBERS = { a: 'mt-source-a', b: 'mt-source-b' } as const;+const SHARED = 'mt-shared';const CANARY = { a: 'canaryalpha', b: 'canarybravo' } as const;+const SHARED_CANARY = 'canaryshared';+type Tool = 'search' | 'query' | 'recall';+const READS: Array<[Tool, Record<string, unknown>]> = [+ ['search', { fields: 'full' }],+ ['search', { match: 'keyword', fields: 'full' }],+ ['query', { expand: false, fields: 'full' }],+ ['recall', {}],+];describeE2E('/mcp per-member tokens on one shared brain', () => {let serverProcess: ReturnType<typeof import('child_process').spawn> | null = null;let engine: PostgresEngine;const tokens = { a: '', b: '' };+ const multi = { a: '', b: '' };async function insertToken(name: string, sourceId: string): Promise<string> {const token = generateToken('gbrain_');@@ -48,6 +64,10 @@ describeE2E('/mcp per-member tokens on one shared brain', () => {engine = await setupDB();const conn = getConn();await conn.unsafe(`DELETE FROM access_tokens WHERE name LIKE 'mt-e2e-%'`);+ await conn.unsafe(`INSERT INTO sources (id, name, config) VALUES ($1, $1, '{}'::jsonb)`, [SHARED]);+ const shared = await importFromContent(engine, 'notes/ledger-shared',+ `# Quarry ledger\nQuarry ledger notes for the whole team, ${SHARED_CANARY}.`, { sourceId: SHARED, noEmbed: true });+ expect(shared.status).toBe('imported');for (const member of ['a', 'b'] as const) {await conn.unsafe(`INSERT INTO sources (id, name, config) VALUES ($1, $1, '{}'::jsonb)`, [MEMBERS[member]]);const imported = await importFromContent(engine, `notes/ledger-${member}`,@@ -55,6 +75,9 @@ describeE2E('/mcp per-member tokens on one shared brain', () => {expect(imported.status).toBe('imported');tokens[member] = await insertToken(`mt-e2e-${member}`, MEMBERS[member]);}+ for (const member of ['a', 'b'] as const) {+ multi[member] = (await mintLegacyToken(engine, { name: `mt-e2e-multi-${member}`, takesHolders: ['world'], scopes: ['read'], sourceGrant: [MEMBERS[member], SHARED] })).token;+ }const { spawn } = await import('child_process');serverProcess = spawn('bun', ['run', 'src/cli.ts', 'serve', '--http', '--port', String(PORT), '--public-url', BASE], {cwd: process.cwd(), env: { ...process.env }, stdio: ['ignore', 'pipe', 'pipe'],@@ -77,15 +100,15 @@ describeE2E('/mcp per-member tokens on one shared brain', () => {try {const conn = getConn();await conn.unsafe(`DELETE FROM access_tokens WHERE name LIKE 'mt-e2e-%'`);- await conn.unsafe(`DELETE FROM pages WHERE source_id IN ($1, $2)`, [MEMBERS.a, MEMBERS.b]);- await conn.unsafe(`DELETE FROM sources WHERE id IN ($1, $2)`, [MEMBERS.a, MEMBERS.b]);+ await conn.unsafe(`DELETE FROM pages WHERE source_id IN ($1, $2, $3)`, [MEMBERS.a, MEMBERS.b, SHARED]);+ await conn.unsafe(`DELETE FROM sources WHERE id IN ($1, $2, $3)`, [MEMBERS.a, MEMBERS.b, SHARED]);} catch (e: any) {console.error(`[afterAll] fixture cleanup failed: ${e.message}`);}await teardownDB();}, 30_000);- async function call(token: string, tool: 'search' | 'query', args: Record<string, unknown>): Promise<{ isError?: boolean; text: string }> {+ async function call(token: string, tool: Tool, args: Record<string, unknown>): Promise<{ isError?: boolean; text: string }> {const res = await fetch(`${BASE}/mcp`, {method: 'POST',headers: { Authorization: `Bearer ${token}`, 'Content-Type': 'application/json', Accept: 'application/json, text/event-stream' },@@ -106,12 +129,12 @@ describeE2E('/mcp per-member tokens on one shared brain', () => {expect(out.text).not.toContain(MEMBERS[other]);}- test('interleaved concurrent search and query calls never cross between the two tokens', async () => {+ test('interleaved concurrent search, keyword search, query and recall calls never cross between the two tokens', async () => {const calls: Array<Promise<void>> = [];for (let round = 0; round < 8; round++) {for (const member of ['a', 'b'] as const) {- for (const tool of ['search', 'query'] as const) {- const args = { query: 'quarry ledger notes', fields: 'full', ...(tool === 'query' ? { expand: false } : {}), ...(round % 2 ? { source_ids: [MEMBERS[member]] } : {}) };+ for (const [tool, extra] of READS) {+ const args = { query: 'quarry ledger notes', ...extra, ...(round % 2 && tool !== 'recall' ? { source_ids: [MEMBERS[member]] } : {}) };calls.push(call(tokens[member], tool, args).then(out => expectOwnOnly(member, out)));}}@@ -119,6 +142,19 @@ describeE2E('/mcp per-member tokens on one shared brain', () => {await Promise.all(calls);}, 60_000);+ test('a multi-source member grant reads its own and the shared source on every read path, never the other member\'s', async () => {+ const calls: Array<Promise<void>> = [];+ for (const member of ['a', 'b'] as const) {+ for (const [tool, extra] of READS) {+ calls.push(call(multi[member], tool, { query: 'quarry ledger notes', ...extra }).then(out => {+ expectOwnOnly(member, out);+ expect(out.text).toContain(SHARED_CANARY);+ }));+ }+ }+ await Promise.all(calls);+ }, 60_000);+test("source_ids naming the other member's source is refused for both tokens", async () => {for (const [member, other] of [['a', 'b'], ['b', 'a']] as const) {for (const tool of ['search', 'query'] as const) {diff --git a/test/mcp-unreadable-sources-notice.test.ts b/test/mcp-unreadable-sources-notice.test.tsnew file mode 100644index 0000000000..d8fc327721--- /dev/null+++ b/test/mcp-unreadable-sources-notice.test.ts@@ -0,0 +1,117 @@+/**+ * GBRA-156: an unscoped remote read that reaches no source holding a page,+ * while pages sit in sources the connection cannot read, says so.+ *+ * 1. Protects: a token with no source grant reads the default source plus the+ * federated ones. A new source is not federated by default, so a brain+ * whose pages all live in such sources answered every search with `[]`+ * and an `empty_retrieval` notice calling it a clean miss. The read now+ * carries a `sources_not_readable` notice whose fix is the host command+ * that makes the pages readable (federate the source, or grant the+ * connection), without naming any source the connection cannot read.+ * 2. Fails when: the notice is missing on an empty unscoped read whose scope+ * holds no page, it names a hidden source, it fires on a real miss inside+ * a scope that holds pages, or it fires for a connection whose operator+ * granted it sources (a token granted sources, or an OAuth client).+ * 3. Existing coverage: `source_binding_narrowed` covers a bound stdio+ * connection only (mcp-notice-channels).+ * 4. No production seam: production serve-http app, real tokens.+ */+import { afterAll, beforeAll, describe, expect, test } from 'bun:test';+import type { BrainEngine } from '../src/core/engine.ts';+import { PGLiteEngine } from '../src/core/pglite-engine.ts';+import { importFromContent } from '../src/core/import-file.ts';+import { mintLegacyToken } from '../src/core/token-mint.ts';+import { callTool, clientCredentialsToken, legacyToken, ownerCookie, registerOAuthClient, startServeHttp, type LiveServeHttp, type ToolResultWire } from './helpers/live-mcp-servers.ts';+import { testBackends } from './helpers/test-backends.ts';+import { isolatedPersistencePostgres } from './helpers/persistence-postgres.ts';++const HIDDEN = 'source-hidden';+const CANARY = 'harbourcanary';+const QUERY = 'quillmarsh ledger';++function noticeBlock(result: ToolResultWire, code: string): string | undefined {+ return result.content.map(c => c.text).find(t => t.startsWith(`[gbrain notice ${code} `));+}++function rows(result: ToolResultWire): unknown {+ return JSON.parse(result.content[0]!.text);+}++for (const kind of testBackends()) {+ describe(`sources_not_readable notice (${kind})`, () => {+ let engine: BrainEngine;+ let close: () => Promise<void>;+ let serve: LiveServeHttp;+ let noGrant: string;+ let granted: string;+ let oauth: string;++ beforeAll(async () => {+ if (kind === 'postgres') ({ engine, close } = await isolatedPersistencePostgres(process.env.DATABASE_URL!));+ else { engine = new PGLiteEngine(); await engine.connect({ engine: 'pglite' } as never); await engine.initSchema(); close = () => engine.disconnect(); }+ await engine.executeRaw(`INSERT INTO sources (id, name) VALUES ($1, $1), ('source-empty', 'source-empty') ON CONFLICT (id) DO NOTHING`, [HIDDEN]);+ await importFromContent(engine, 'notes/quillmarsh-ledger', `# Ledger\nThe quillmarsh ledger for the harbour team, ${CANARY}.`, { sourceId: HIDDEN, noEmbed: true });+ serve = await startServeHttp(engine, { surface: 'full' });+ noGrant = await legacyToken(engine, ['read']);+ granted = (await mintLegacyToken(engine, { name: 'granted-empty', takesHolders: ['world'], scopes: ['read'], sourceGrant: ['source-empty'] })).token;+ const client = await registerOAuthClient(serve, await ownerCookie(serve), 'read');+ oauth = await clientCredentialsToken(serve, client.clientId, client.clientSecret, 'read');+ }, 180_000);++ afterAll(async () => {+ await serve?.close();+ await close?.();+ }, 60_000);++ for (const [tool, args] of [+ ['search', { query: QUERY }],+ ['search', { query: QUERY, match: 'keyword' }],+ ['query', { query: QUERY, expand: false }],+ ['list_pages', {}],+ ['recall', { query: QUERY }],+ ] as const) {+ test(`${tool} ${JSON.stringify(args)}: a no-grant token whose sources hold no page is told the pages are elsewhere`, async () => {+ const out = await callTool(serve.base, noGrant, tool, args);+ expect(out.isError).not.toBe(true);+ expect(JSON.stringify(out.content)).not.toContain(CANARY);+ const block = noticeBlock(out, 'sources_not_readable');+ expect(block).toBeDefined();+ expect(block).toContain('kind=degraded');+ expect(block).toContain('gbrain sources federate');+ expect(block).not.toContain(HIDDEN);+ }, 60_000);+ }++ test('an OAuth client always carries a grant (at least its bound source), so it gets no notice', async () => {+ const out = await callTool(serve.base, oauth, 'search', { query: QUERY });+ expect(rows(out)).toEqual([]);+ expect(noticeBlock(out, 'sources_not_readable')).toBeUndefined();+ }, 60_000);++ test('a token the operator granted a source gets no notice (its scope is deliberate)', async () => {+ const out = await callTool(serve.base, granted, 'search', { query: QUERY });+ expect(rows(out)).toEqual([]);+ expect(noticeBlock(out, 'sources_not_readable')).toBeUndefined();+ }, 60_000);++ test('naming a source explicitly gets no notice', async () => {+ const out = await callTool(serve.base, noGrant, 'search', { query: QUERY, source_id: 'default' });+ expect(rows(out)).toEqual([]);+ expect(noticeBlock(out, 'sources_not_readable')).toBeUndefined();+ }, 60_000);++ test('once the source is federated the same token reads the page, and a real miss carries no notice', async () => {+ await engine.executeRaw(`UPDATE sources SET config = COALESCE(config, '{}'::jsonb) || '{"federated": true}'::jsonb WHERE id = $1`, [HIDDEN]);+ try {+ const hit = await callTool(serve.base, noGrant, 'search', { query: QUERY });+ expect(JSON.stringify(rows(hit))).toContain('quillmarsh-ledger');+ const miss = await callTool(serve.base, noGrant, 'search', { query: 'zzyzx nothing matches this' });+ expect(rows(miss)).toEqual([]);+ expect(noticeBlock(miss, 'sources_not_readable')).toBeUndefined();+ } finally {+ await engine.executeRaw(`UPDATE sources SET config = config - 'federated' WHERE id = $1`, [HIDDEN]);+ }+ }, 60_000);+ });+}diff --git a/test/postgres-unit-arms.txt b/test/postgres-unit-arms.txtindex c5c9ac8234..a8100a1a57 100644--- a/test/postgres-unit-arms.txt+++ b/test/postgres-unit-arms.txt@@ -240,6 +240,7 @@ test/managed-sync-pinned-reads.test.tstest/managed-sync-preparation-stalled-holds.test.tstest/managed-sync-row-parity.test.tstest/managed-sync-stale-group-head.test.ts+test/mcp-unreadable-sources-notice.test.tstest/migration-persistence-request-id-index.test.tstest/migration-persistence-request-slug-index.test.tstest/on-commit-embedding.serial.test.tsdiff --git a/test/sources-add-federation-warning.test.ts b/test/sources-add-federation-warning.test.tsnew file mode 100644index 0000000000..bde50d65e5--- /dev/null+++ b/test/sources-add-federation-warning.test.ts@@ -0,0 +1,79 @@+/**+ * GBRA-156: `gbrain sources add` warns when the new source is not federated.+ *+ * 1. Protects: a new source is not federated unless --federated is passed, so+ * a remote token with no source grant (and an unbound agent connection)+ * never reads its pages, and its searches answer empty. The stored default+ * stays non-federated; the command now says what that means on stderr,+ * with the two commands that change it.+ * 2. Fails when: the default add prints no warning, the warning lacks the+ * federate or grant command, a --federated or explicit --no-federated add+ * warns, or the stored default flips to federated.+ * 3. Existing coverage: the stdout `federated: false` line only.+ * 4. No production seam: the real command on PGLite, console spies only.+ */+import { afterAll, beforeAll, describe, expect, spyOn, test } from 'bun:test';+import { mkdtempSync, rmSync } from 'node:fs';+import { tmpdir } from 'node:os';+import { join } from 'node:path';+import { PGLiteEngine } from '../src/core/pglite-engine.ts';+import { runSources } from '../src/commands/sources.ts';++let engine: PGLiteEngine;+const dirs: string[] = [];++async function add(args: string[]): Promise<{ stdout: string; stderr: string }> {+ const dir = mkdtempSync(join(tmpdir(), 'gbrain-sources-add-warn-'));+ dirs.push(dir);+ const out: string[] = [];+ const err: string[] = [];+ const log = spyOn(console, 'log').mockImplementation((...a: unknown[]) => { out.push(a.join(' ')); });+ const warn = spyOn(console, 'error').mockImplementation((...a: unknown[]) => { err.push(a.join(' ')); });+ try {+ await runSources(engine, ['add', args[0]!, '--path', dir, '--force', ...args.slice(1)]);+ } finally {+ log.mockRestore();+ warn.mockRestore();+ }+ return { stdout: out.join('\n'), stderr: err.join('\n') };+}++async function federated(id: string): Promise<unknown> {+ const rows = await engine.executeRaw<{ f: unknown }>(`SELECT config->'federated' AS f FROM sources WHERE id = $1`, [id]);+ return rows[0]?.f ?? null;+}++beforeAll(async () => {+ engine = new PGLiteEngine();+ await engine.connect({ engine: 'pglite' } as never);+ await engine.initSchema();+}, 60_000);++afterAll(async () => {+ await engine?.disconnect();+ for (const d of dirs) rmSync(d, { recursive: true, force: true });+});++describe('sources add federation warning', () => {+ test('the default add warns on stderr and names both remedies; the stored default stays non-federated', async () => {+ const { stdout, stderr } = await add(['source-a']);+ expect(stdout).toContain('federated: false');+ expect(stderr).toContain('source "source-a" is not federated');+ expect(stderr).toContain('no source grant');+ expect(stderr).toContain('gbrain sources federate source-a');+ expect(stderr).toContain('gbrain auth rescope --token <name> --sources source-a');+ expect(await federated('source-a')).not.toBe(true);+ });++ test('--federated adds without the warning', async () => {+ const { stderr } = await add(['source-b', '--federated']);+ expect(stderr).not.toContain('is not federated');+ expect(await federated('source-b')).toBe(true);+ });++ test('an explicit --no-federated add is the operator\'s stated choice and does not warn', async () => {+ const { stdout, stderr } = await add(['source-c', '--no-federated']);+ expect(stdout).toContain('federated: false');+ expect(stderr).not.toContain('is not federated');+ });+});diff --git a/test/thin-client-member-sources.test.ts b/test/thin-client-member-sources.test.tsnew file mode 100644index 0000000000..26b8e3d94f--- /dev/null+++ b/test/thin-client-member-sources.test.ts@@ -0,0 +1,85 @@+/**+ * Per-member OAuth clients through the thin client: two clients, each+ * granted a different source, call `search` through `callRemoteTool`+ * against one MCP URL from one process, interleaved and concurrent. Every+ * call's rows stay inside that client's own source.+ *+ * 1. Protects: the multi-member bot pattern on the client side (one process,+ * one server URL, one client per member, each narrowed to that member's+ * sources). The access token a call presents is the one minted for that+ * call's client, so one member's call never runs under another's grant.+ * 2. Fails when: the thin client presents one client's token for another+ * client's call at the same URL, in memory or through the on-disk cache.+ * 3. Existing coverage (thin-client-token-cache-7360) pins write scope across+ * two clients; this pins read sources under concurrency.+ * 4. No production seam: production serve-http app, real OAuth clients.+ */+import { afterAll, beforeAll, describe, expect, test } from 'bun:test';+import { mkdirSync, mkdtempSync, rmSync } from 'node:fs';+import { tmpdir } from 'node:os';+import { join } from 'node:path';+import { PGLiteEngine } from '../src/core/pglite-engine.ts';+import { importFromContent } from '../src/core/import-file.ts';+import { callRemoteTool, _clearMcpClientTokenCache } from '../src/core/mcp-client.ts';+import { ownerCookie, registerOAuthClient, startServeHttp, thinClientConfig, type LiveServeHttp } from './helpers/live-mcp-servers.ts';+import { withEnv } from './helpers/with-env.ts';+import type { GBrainConfig } from '../src/core/config.ts';++const MEMBERS = { a: 'tc-source-a', b: 'tc-source-b' } as const;+const CANARY = { a: 'canaryalpha', b: 'canarybravo' } as const;++let engine: PGLiteEngine;+let serve: LiveServeHttp;+const configs = {} as Record<'a' | 'b', GBrainConfig>;+const home = mkdtempSync(join(tmpdir(), 'gbrain-thin-client-members-'));+const inHome = (fn: () => Promise<void>) => () => withEnv({ GBRAIN_HOME: home }, fn);++beforeAll(inHome(async () => {+ mkdirSync(join(home, '.gbrain'), { recursive: true });+ engine = new PGLiteEngine();+ await engine.connect({});+ await engine.initSchema();+ serve = await startServeHttp(engine);+ const cookie = await ownerCookie(serve);+ for (const member of ['a', 'b'] as const) {+ await engine.executeRaw(`INSERT INTO sources (id, name) VALUES ($1, $1)`, [MEMBERS[member]]);+ await importFromContent(engine, `notes/ledger-${member}`, `# Quarry ledger\nQuarry ledger notes for member ${member}, ${CANARY[member]}.`, { sourceId: MEMBERS[member], noEmbed: true });+ const client = await registerOAuthClient(serve, cookie, 'read');+ await engine.executeRaw(`UPDATE oauth_clients SET source_id = $2, federated_read = ARRAY[$2] WHERE client_id = $1`, [client.clientId, MEMBERS[member]]);+ configs[member] = thinClientConfig(serve, client);+ }+}), 120_000);++afterAll(async () => {+ _clearMcpClientTokenCache();+ await serve?.close();+ await engine?.disconnect();+ rmSync(home, { recursive: true, force: true });+});++describe('per-member OAuth clients through callRemoteTool', () => {+ async function searchAs(member: 'a' | 'b'): Promise<void> {+ const other = member === 'a' ? 'b' : 'a';+ const text = JSON.stringify(await callRemoteTool(configs[member], 'search', { query: 'quarry ledger notes' }));+ expect(text).toContain(CANARY[member]);+ expect(text).not.toContain(CANARY[other]);+ expect(text).not.toContain(MEMBERS[other]);+ }++ test('one client after the other at one URL: each call runs under its own client', inHome(async () => {+ await searchAs('a');+ await searchAs('b');+ _clearMcpClientTokenCache({ keepDisk: true });+ await searchAs('b');+ await searchAs('a');+ }), 60_000);++ test('interleaved concurrent searches at one URL never cross between the two clients', inHome(async () => {+ await searchAs('a');+ const calls: Array<Promise<void>> = [];+ for (let round = 0; round < 6; round++) {+ for (const member of ['b', 'a'] as const) calls.push(searchAs(member));+ }+ await Promise.all(calls);+ }), 60_000);+});