Garry's Opinionated OpenClaw/Hermes Agent Brain
TypeScript
feat(#7246): bounded whole-brain listings and serve log rotation/dedupe
garrytan9407c9c553bb
diff --git a/docs/architecture/key-files/commands-1.md b/docs/architecture/key-files/commands-1.mdindex 0887ef07a1..2051b17252 100644--- a/docs/architecture/key-files/commands-1.md+++ b/docs/architecture/key-files/commands-1.md@@ -13,7 +13,7 @@ Current behavior and load-bearing invariants; history belongs in Git and CHANGEL- `src/commands/agent.ts` — `gbrain agent run|logs|register` dispatcher. `run` submits `subagent` (or N children + 1 aggregator) under `{allowProtectedSubmit: true}`; single-entry `--fanout-manifest` short-circuits; children get `on_child_fail: 'continue'` + `max_stalled: 3`; `--follow` is the default on TTY (streams logs + polls `waitForCompletion` in parallel; Ctrl-C detaches, does not cancel). `logs` delegates to `agent-logs.ts`; `register` lazy-imports `agent-register.ts`. Subcommand-aware help is answered BEFORE any engine or queue work and STOPS at the `--` terminator (`agent run -- --help` submits the LITERAL prompt); on a brainless machine (null engine) help still prints while real `run`/`logs` invocations refuse with an init hint.-- `src/commands/anomalies.ts` — `gbrain anomalies [--since YYYY-MM-DD] [--lookback-days N] [--sigma N] [--json]`: cohort-level activity outliers. Calls `engine.findAnomalies(opts)`. Two cohort kinds: tag, type.+- `src/commands/anomalies.ts` — `gbrain anomalies [--since YYYY-MM-DD] [--lookback-days N] [--sigma N] [--json]`: cohort-level activity outliers. Calls `engine.findAnomalies(opts)`. Two cohort kinds: tag, type. `--json` (and MCP `find_anomalies`) lists at most 20 `page_slugs` per cohort and sets `page_slugs_complete: false` on a capped row; `count` covers the whole cohort. `--all` (CLI) or `slug_limit` (MCP, max 1000) lists more. Pinned by `test/anomalies-bounded-7246.test.ts`.- `src/commands/auth.ts` — token management. `gbrain auth create/list/revoke/test` for legacy bearer tokens (`revoke-client` runs an atomic `DELETE...RETURNING` on `oauth_clients`; FK `ON DELETE CASCADE` on `oauth_tokens.client_id` and `oauth_codes.client_id` purges every active token + auth code in one transaction; `process.exit(1)` on no-such-client (idempotent). Legacy tokens stored as SHA-256 hashes in `access_tokens`; OAuth clients in `oauth_clients`; legacy tokens with no scopes grant grandfather to `read+write+admin` on the OAuth HTTP server (no migration); scoped tokens are honored at exactly their grant. Every SQL site routes through `sqlQueryForEngine(engine)` from `src/core/sql-query.ts` (and `executeRawJsonb` for the takes-holders `permissions` JSONB column) so `gbrain auth` works against PGLite; the takes-holders write goes through `executeRawJsonb(engine, sql, [name, hash], [{takes_holders:[...]}])` which round-trips with `jsonb_typeof = 'object'`. `register-client` accepts `--source <id>` (write authority, scalar), `--federated-read <S1,S2,...>` (read scope, array), and `--token-ttl <seconds>` (per-client access-token TTL persisted to `oauth_clients.token_ttl`, bounds `TOKEN_TTL_MIN_SECONDS`=60 to `TOKEN_TTL_MAX_SECONDS`=7,776,000/90d) and prints the resolved `Write source` + `Federated reads`; clients without a `source_id` backfill to `'default'` via migration v60. The registration core is the exported `registerScopedClient(sql, engine, name, parsed, opts)` — exit-free, print-free, injected-handle (engine-bound callers like `agent register` pass the dispatcher's engine; a second `withConfiguredSql` engine self-deadlocks PGLite's single-writer lock), returns a `RegisteredClient` data object and throws on failure; the thin CLI wrapper owns exit/print. Its printer `formatRegisterClientOutput` is a BYTE-PINNED contract (connect.ts's `defaultRegisterOAuthClient` regex-scrapes `Client ID:`/`Client Secret:` from it in production) — pinned by `test/auth-register-client-output-pin.test.ts`. `preflightOauthClientColumns(sql)` probes `information_schema.columns` for the optional columns (`token_ttl`, `surface`, `federated_read`, `source_id`, `deleted_at`) so statement shapes are decided BEFORE any transaction — Postgres/PGLite abort the whole tx on any statement error (25P02) and SqlQuery has no savepoint seam, so "catch 42703 and continue" inside a tx is impossible; skipped optional writes surface as `RegisteredClient.skipped` with an apply-migrations hint. `gbrain auth clients [--usage] [--days N] [--json]` lists clients with scopes, per-client surface, write source (`source_id`), federated reads (`federated_read`) and the operation snapshot — one projection-widened SELECT with a degrade ladder for pre-migration brains (drops the newest columns first, never errors); `clientOperationsView` reports four distinct operation states (SQL NULL = `operations: "all"` with `includes_future_operations: true` and a re-pin `fix` naming `auth rescope --client <id> --operations <list>` or `--profile`; `[]` = deny-all; an explicit list; `unavailable` when the schema predates `allowed_operations`) and marks soft-revoked clients (`deleted_at`) `revoked` with no fix (`test/auth-clients-operations.test.ts`, both engines); `tokenLifetimeClampedClients` reads the migration's `clamp_token_ttl` / `shorten_access_tokens` audit rows so the listing marks clients whose access-token lifetime an upgrade brought inside 90 days (`token_lifetime_clamped` in `--json`); the `TOKEN_TTL_*` bounds are re-exported from `src/core/grants/model.ts`; `--usage` joins per-client op-call counts via `src/core/mcp-usage.ts`. The bare `gbrain auth create <name>` form (no `--takes-holders`) mints a token via the exported pure `parseAuthCreateArgs(rest)`. Pinned by `test/auth-create-args.test.ts` + `test/auth-register-client-args.test.ts`. F3: `gbrain auth rescope` (`runRescope`) is the one grant editor for tokens (`--token`/`--id`) and OAuth clients (`--client`), with a bare-name resolver, `--migrate-legacy [--dry-run]`, and refusals printed as JSON on stdout under `--json`; `rescope-token`, `rescope-client` and `permissions set-takes-holders` are aliases routed through it.diff --git a/docs/architecture/key-files/commands-4.md b/docs/architecture/key-files/commands-4.mdindex 58a3adf7eb..5d184cbdad 100644--- a/docs/architecture/key-files/commands-4.md+++ b/docs/architecture/key-files/commands-4.md@@ -35,7 +35,7 @@ Current behavior and load-bearing invariants; history belongs in Git and CHANGEL- `src/commands/models.ts` — `gbrain models [--json]` read-only routing dashboard: prints tier defaults (`utility`/`reasoning`/`deep`/`subagent`), the resolved value for each (re-walking the resolution chain), every per-task override (14 `PER_TASK_KEYS`, including provider-neutral `models.contextual_synopsis` with legacy-key/env attribution and `models.dream.extract_atoms` which reports via its own caller-specific resolver — `resolveExtractAtomsModelWithSource()` in `extract-atoms.ts`: its own key, then `models.tier.utility`, then the key-aware utility default, never `models.default` or `GBRAIN_MODEL` (#6675) — rather than the generic chain, so the report can't diverge from what the phase actually calls), the alias map, and a source-of-truth column (`default` / `config: <key>` / `env: <VAR>`) derived from `resolveModelDetailed`, so a tier key is attributed before `models.default`. A `Nightly quality probe` block (JSON `nightly_probe`; `schema_version` stays 1) shows the probe's routes from `resolveNightlyProbeModelRoutes`: reader and extractor with their source, and each judge slot labelled `config: models.eval.cross_modal.slot_<x>`, `panel default` or `substitute for <default> (no usable provider)` — the #4636 substitution run with a silent log against this process's gateway. Its `environment_note` says availability, substitutes and key-aware defaults are judged from this process's environment, so a key only in the daemon's `~/.gbrain/env` reads as unavailable. A resolved Anthropic haiku/sonnet/opus id older (by major, minor) than the anthropic recipe's newest priced same-family id gets an advisory `[newer <family> available: <id>] (gbrain config set ...)` hint (JSON: `newer_available`); version parsing lives in `src/core/ai/anthropic-model-ids.ts` (8-digit segment is a date, so dated and undated forms compare equal; fable, non-Anthropic, newer-than-recipe and unparseable ids get no hint). The hint never changes a default. `gbrain models doctor [--skip=<provider>] [--json]` fires a 1-token `gateway.chat()` probe against each configured chat + expansion model and classifies failures into `{model_not_found, auth, rate_limit, network, unknown}`. The probe timeout resolves per model via `resolveChatProbeTimeoutMs` — the recipe touchpoint's `default_timeout_ms` when declared, else the flat 5000ms default (mirrors the reranker probe's recipe-default fallback; `claude-cli` declares 30s because its `claude -p` subprocess cold start routinely outruns 5s and would false-fail every run as `unknown`). The reranker reachability probe sends one question with a relevant and an unrelated passage and reports `ok` only when the relevant one scores higher by more than 0.1; equal, inverted or missing scores are `config` with a fix naming `docs/ai-providers/llama-server-reranker.md` step 2 (a broken GGUF conversion answers but ranks at random). Wired into `cli.ts` dispatch + `CLI_ONLY` set. A zero-token `embedding_config` probe runs FIRST, before any chat/expansion probes spend money: `probeEmbeddingConfig()` reads `getEmbeddingModel()` + `getEmbeddingDimensions()` and (for Voyage flexible-dim models) checks `isValidVoyageOutputDim(dims)` against `VOYAGE_VALID_OUTPUT_DIMS`. `ProbeStatus` variant `'config'` + optional `fix?: string` on `ProbeResult` surface a paste-ready `gbrain config set ...` line in human + JSON output; touchpoint label `'embedding_config'` joins `'chat'` and `'expansion'`.- `src/commands/pricing.ts` — `gbrain pricing set <model> --input <usd/1M> --output <usd/1M> | --rate <usd/1M> [--source <url>]`, `pricing list [--json]`, `pricing unset <model>`. Each write reads `pricing.overrides`, changes one entry (keyed by the lowercased model; case variants replaced) and writes it back, so other entries survive; an unreadable stored value is refused, never overwritten. Rates must be non-negative finite numbers; $0 is accepted with a stderr warning. Entries keep the parser schema (`{input, output}` or `pricePerMTok`) with `source` and `set_at` beside them. Trust boundary: CLI-only (never an operation, so MCP cannot reach it) and `thinClient: 'refuse'` in the command table. Pinned by `test/budget/no-pricing-registration.test.ts`.-- `src/commands/orphans.ts` — `gbrain orphans` and MCP `find_orphans` share islanded (no live inbound or outbound links) and legacy inbound-only modes. Read policy scopes candidates and excludes private candidates, endpoints and independent origin pages before counting. Cross-source public links still establish reachability by the documented orphan definition. Reporting exclusions (`shouldExcludeFromOrphanReporting`) stay centralized; the scoped live-page denominator excludes the same private/reporting rows. `--source` remains explicit; no new remote privacy parameter. Connector renders (an `email`/`meeting` page whose source `config.kind` is a connector kind) are islanded by construction, so they leave both totals and are reported as `connector_renders_excluded` (`--include-pseudo` keeps them); doctor `orphan_ratio` carries that count in `details` and prints `gbrain extract links --by-mention --source db` (plus `--source-id` when scoped). Pinned by `test/orphan-ratio-connector-renders.test.ts`.+- `src/commands/orphans.ts` — `gbrain orphans` and MCP `find_orphans` share islanded (no live inbound or outbound links) and legacy inbound-only modes. Read policy scopes candidates and excludes private candidates, endpoints and independent origin pages before counting. Cross-source public links still establish reachability by the documented orphan definition. Reporting exclusions (`shouldExcludeFromOrphanReporting`) stay centralized; the scoped live-page denominator excludes the same private/reporting rows. `--source` remains explicit; no new remote privacy parameter. Connector renders (an `email`/`meeting` page whose source `config.kind` is a connector kind) are islanded by construction, so they leave both totals and are reported as `connector_renders_excluded` (`--include-pseudo` keeps them); doctor `orphan_ratio` carries that count in `details` and prints `gbrain extract links --by-mention --source db` (plus `--source-id` when scoped). Pinned by `test/orphan-ratio-connector-renders.test.ts`. Pages of 100 (`--limit`/`--cursor`/`--all`; [bounded listings](core-utilities-2.md)); one-page results keep the old shape.- `src/commands/pages.ts` — `gbrain pages purge-deleted [--older-than HOURS|Nh|Nd] [--retry-parked] [--dry-run] [--json] [--yes]` operator escape hatch. Mirror of `gbrain sources purge` for the page-level lifecycle. Hard-deletes pages whose `deleted_at` is older than the cutoff in every source (per-source purge is not supported); cascades to content_chunks/page_links/chunk_relations. `parsePurgeArgs` is strict (the `pages purge-deleted` row of `src/cli/strict-args.ts`): `--older-than N` and `--older-than=N` both work, and any other token throws `invalid_params` before the engine is touched. The real purge first previews the count and, when anything would be purged, goes through `consentGate` (destructive): a TTY prompt, `--yes`, or exit 3 with the consent payload whose fix is the exact `--yes` argv and whose preview is `--dry-run --json`. `--retry-parked` retries parked tombstones once within `--older-than` and rename holds; the dry run lists `parked`, `retried` and `blocked`, and the consent names the parked count. The autopilot purge phase calls `purgeDeletedPagesCoordinated` directly and never asks. `pages ghosts [--source <id>] [--json]` (#6696 B5, `pages-ghosts.ts`) lists ghost pages read-only through `scanGhostSource`. Exports `SUBCOMMANDS` and `printUsage` for the help route. Pinned by `test/pages-purge-deleted-args.test.ts` and the `pages purge-deleted` consent-table row. Its help points soft-delete and restore at `gbrain delete|restore <slug> --force` (page writes are revisioned).- `src/commands/pages-unsearchable.ts` — `gbrain pages unsearchable --source <id> [--state <state>] [--limit N] [--json]` (#6696 B3, read-only): one row per (page, embedding state) from `listEmbeddingStateRows` with reason, chunks, bytes and the state's rendered fix; every state but `embedded` unless `--state` names one; `--limit` 1-1000 (default 50) with `complete`; an unknown `--state` or bad `--limit` throws `invalid_params` naming the valid values. Test: `test/pages-unsearchable.test.ts`.diff --git a/docs/architecture/key-files/core-utilities-2.md b/docs/architecture/key-files/core-utilities-2.mdindex ffa83e1144..29c09b4bec 100644--- a/docs/architecture/key-files/core-utilities-2.md+++ b/docs/architecture/key-files/core-utilities-2.md@@ -4,6 +4,8 @@ Memory trust tiers and read eligibility (#5575, the trust and eligibility direct[Subsystem index](../KEY_FILES.md). Read only the entries relevant to your change.Current behavior and load-bearing invariants; history belongs in Git and CHANGELOG.+- `src/core/bounded-listing.ts` + `src/core/bounded-listing-cli.ts` — the bounded whole-brain listing contract (#7246). `pageSortedRows(rows, key, {limit, cursor}, kind)` sorts by a composite string key and returns one page with `returned`, `limit` (null for every row), `complete` and `next_cursor`; the cursor is base64url JSON `{v:1,k:kind,a:lastKey}`, a keyset position, so rows added or removed between pages never shift one, and a cursor of another kind (listing or filter set) is refused with `invalid_params`. `LISTING_DEFAULT_LIMIT` 100, `LISTING_MAX_LIMIT` 1000 (the remote cap). `topCounts` gives summary counts per key, `capRowList` caps a per-row list and marks the row `<field>_complete: false`. The CLI half parses `--limit`/`--cursor`/`--all` and builds `next_command` (it keeps `--limit`); it is a separate module so a command that only caps rows does not gain those flags in the generated flag registry. Used by `gbrain orphans`, `find_orphans` and `find_anomalies`. Tests: `test/bounded-listing-7246.test.ts`.+- `src/core/repair/` — `gbrain repair` core. `core.ts`: `resolveRepairScope` (default every active source; prints brain and source ids), `runRepair` (dry run unless `apply`; each item is one revision-bound `put_page` with a deterministic request id (replayed while pending, a new attempt id after a terminal failure), re-decided against current state just before it is applied; a cursor in `op_checkpoints` keyed by kind + scope resumes an interrupted or `--limit` run and is cleared when a scan completes; the same row carries the run id (written before the first applied item and passed to `apply` as `runId`), so a resumed run keeps the id that any authorization it granted is bound to; a kind may return a named per-item outcome (`RepairItemOutcome`), tallied in `outcomes` and `outcome_items`; a `spends: 'llm'` kind's plan reports `llm` (its paid-model estimate, null for an unpriced model under a user-set cap, and what is left under its own daily cap), and its result's `cost` adds `llm_usd` (the estimate on a dry run, the actual spend summed from each item's `llm_usd` on an apply) and `llm_cap_remaining_usd` (the smaller of the daily cap and the run allowance, less the spend), keys other kinds never carry; `maxLlmUsd` is the run's paid-model allowance: each item's `apply` gets what is left as `llmAllowanceUsd`, and once it is used up, or an item's own `llm_usd` estimate exceeds what is left, the run stops `budget_exhausted` before that item, naming spent and allowance, and rerunning the apply command resumes it (a dry run sums the per-item estimates of the items it would apply, so `--limit` lowers it); the core opens no budget tracker; `deadline` (epoch ms) stops the run with `time_budget` before the next item; an item outcome's `stop` ends the run after that item with its reason, message and fix; a kind's `report` hook adds `repaired`, `remaining`, `verification` (or refines `stopped`) once the run ends, and a plan's `scan` is copied to the result; stops before crossing 90% of the brain or principal lifetime-ID / receipt-byte caps with the `gbrain config set` value that finishes; a held writer stops with `gbrain sources writer status <source>`; other item failures go through one `ItemRun` (`repair.apply_items`): an accepted pending write is checked first, a run-scoped failure is thrown, an item-scoped one is a `failed[]` entry (`reason` its code, `retry: 'next_full_scan'`, `fix` the kind's preview) and the run goes on; the breaker stops it `item_failures_systemic`; a limited run with only item failures clears its cursor; a kind's `onItemFailures` gets the failed items unless the run stopped; `--expect` applies throw all but `REPAIR_ITEM_FAILURE_CODES`). `rotation.ts`: the bare-apply rotation fences and slug-conflicts share (keys joined with U+0001 for jsonb). `timeline.ts`: `scanTimelineHistory` (bounded id-order scan shared with the doctor; one stored-row read per page batch for the retraction check) and the materialize kind. `visibility.ts`: `planVisibilityRepair`, the tighten-only atom/concept backfill (atoms from `effectiveVisibility` of their origin, concepts from the strictest input over provenance edges and atoms' `concepts:`; no-lineage concepts are counted and left alone). `safe-chunks.ts`: a `publication: 'projection'` kind (no admission, zero lifetime-ID and receipt cost, no capacity stop) that re-seals markdown and code pages below the safe-chunk fence through `resealSafeChunks`, then embeds their NULL chunks unless `--no-embed`; code pages without a recorded path and other page kinds are residuals; a page whose re-seal throws item-scoped is `held` `projection_unbuildable` (code, message, retry `fix`), stays withheld and is retried next run; the plan also selects pages the v0.60.31 re-chunk held (`CREDENTIAL_RESEAL_HELD`, segmented pages excluded). The pending count is reported only by the doctor check `safe_index_pending`, which the post-upgrade recovery banner uses. `contextual-mode.ts`: a `publication: 'projection'` kind (#5621) that stamps `contextual_retrieval_mode` + `corpus_generation` on sealed live markdown pages with a NULL mode through `resolveImportContextualMode` (`src/core/import-contextual-mode.ts`, the resolver `importFromContent` also uses, strict source-row read), then under the page guard clears only vectors whose recorded embedding input the stamped convention no longer accepts (the #5553 rule) and re-embeds that page once unless `--no-embed`; unsealed pages are the `unsealed_projection` residual. `connector-checkpoints.ts`: a `publication: 'projection'` bookkeeping kind (#5686, `embeds: false`) that deletes connector checkpoint rows and retry pointers no registered source can load and that are older than 7 days, keeping rows a non-terminal request or recorded pending set references; brain-wide. `request-indexes.ts`: a `publication: 'projection'` brain-wide kind (#5762, `embeds: false`) that builds a missing online-built request index (`PERSISTENCE_REQUEST_ONLINE_INDEXES`: the managed sync checkpoint pair and the page purge's slug index) or drops an INVALID one and rebuilds it through `buildIndexOnline` (`src/core/schema-migrations/helpers.ts`: CONCURRENTLY on Postgres under the session's startup timeouts with no session SET, inline on PGLite, the result re-checked for validity, an index another session is still building is left alone); it clears `persistence_request_indexes`. `orphan-bindings.ts`: a projection bookkeeping kind (#5732) over `persistence/orphan-bindings.ts` that deletes persistence source bindings of a removed source or an earlier incarnation, brain-wide, keeping one a pending request of that incarnation references. `embedding-effects.ts`: a projection kind (#5629/#5734, `embeds: 'effect'`) over `persistence/embedding-settlement.ts`; each stale queued or failed embedding effect of a committed write is `reconciled` (the effect projection verifier passes), `superseded` (page deleted, or a newer revision of the same page owns its own effect), `retry_queued` (stale queued re-queued for the owner; failed granted the retry-effects allowance; an exhausted allowance gets one new bounded cycle under `embeddingGrantId(runId, effect)`, which a resumed run replays) or `blocked` with a reason; every change is a compare-and-set on state, attempts, execution token and recovery, and a changed candidate is `changed_since_preview`. Retry items count the whole retry budget in the embedding estimate. `registry.ts`: `REPAIR_REGISTRY` (one entry per `REPAIR_KINDS` name in `--all` order: handler, help summary, `embeds` — `effect` when the publication's embedding effect re-embeds each page outside the run, `inline` when the kind embeds in-process and honors `--no-embed`, `none` for bookkeeping kinds — `spends: 'llm'` for a kind that may call a paid chat model, and the doctor `checks` it clears), `repairMayEmbed` (embedding spend under the flags) and `repairMaySpend` (that or `spends: 'llm'`), `repairForCheck`, `repairApplyCommand` and `repairRunner`, the one trusted local runner that both `gbrain repair` and doctor remediation use (an applying runner resolves the CLI write wait once, before any kind runs, and puts it on the ctx as `writeWaitMs`, so every publication waits like other CLI writes and a malformed `GBRAIN_WRITE_WAIT_MS` refuses before a checkpoint; a preview never reads it) (its `run` takes `maxLlmUsd`; `repairRunner` and `repairSpec` take an optional `registry` of stub specs for tests, and production callers use the registered kinds); a new kind plugs in by adding its name to `REPAIR_KINDS` and one registry entry. A kind with `explicit_only` (`stale-atoms`, `extractor-facts`; the `extractor-facts.ts` stub refuses with `unavailable` until its fix wave 5 lane lands) runs only when named: `AUTO_REPAIR_REGISTRY` is the `--all`, no-kind and remediation set, `explicitRepairNotices` lists the rest as `explicit_kind_required` with `repairPreviewCommand`, and `runRepair` refuses an unnamed explicit-only kind (`explicitKindRequired`), so a supplied remediation step cannot run one. Explicit-only kinds and kinds with `preview_bound` (`fences`, which is not explicit-only and so also runs from `--all`, the remediation run and the maintenance cycle with a bare `--apply`) accept `--expect <hash>`; only explicit-only kinds accept `--include-ambiguous`; `--only`/`--skip`/`--slug` selections, `--no-llm` and `--max-usd` (only `spends: 'llm'` kinds; it only lowers their cap) are passed to `plan` as `RepairPlanOptions` and printed in the apply command; a plan's `preview_hash` is appended to its apply command, and its `listing` (every previewed item with its class) is printed by the dry run. `stale-atoms.ts` (#5770): live page-bound atoms (never `imported_from`, never `source_path`-only) whose source page is gone (`origin_gone`) or whose stripped 16-character `source_hash` differs from a source page whose extraction at its current hash produced atoms (`origin_changed`; evidence is a live atom at that hash, managed also the completed `managed-atoms` checkpoint via `managedAtomCompletedSql`, so zero yield replaces nothing). The preview saves the set with `saveApprovedSet`; `--apply --expect <hash>` loads it (`preview_changed` otherwise; `--apply` alone refuses with the filled commands), rechecks each atom (revision, class, origin, evidence) and reports `retired`, `changed_since_preview` or `file_conflict` (an uncoordinated atom-file edit; its attempt-aware `repairRequestId` lets a later apply retry once the file is fixed). An approved set applies only under the source selection it was previewed with, and the apply's resume cursor is keyed by its approval hash. Managed brains admit one `managed_maintenance_retire_stale_atoms` request per atom bound to its revision (`prepareStaleAtomRetirement`, rechecked under the atom and origin page locks, no live origin needed); unmanaged brains soft-delete in one locked transaction. Both stamp `retired_by: stale-atoms`/`retired_at` and bump the origin page's `managed-atoms-generation` (clearing its page state and completed checkpoints, keeping the current hash for `origin_changed`), so a restored page is extracted again and `publishManagedAtoms` restores the retired atoms. Tests: `test/repair-explicit-only.test.ts`, `test/repair-stale-atoms.test.ts` and `test/journey-atoms-sync-race.test.ts` (PGLite and Postgres). Tests: `test/repair-command.test.ts`, `test/derived-visibility-repair.test.ts`, `test/safe-chunk-reseal.test.ts` (PGLite and Postgres), `test/repair-contextual-mode-5621.serial.test.ts` (PGLite and Postgres), `test/repair-flags.test.ts`, `test/persistence-request-indexes.test.ts`. `attribution-backfill.ts` (Foundations 1, F1b): an automatic `publication: 'projection'` bookkeeping kind (`embeds: 'none'`, no doctor check) that fills NULL write attribution only where exactly one committed request proves it: `pages.revision_*` and `page_versions.write_*` from the page mutation (or fenced `remember`) whose `outcome.revision` is the row's `knowledge_revision` (skipped, duplicate and observe-only requests prove nothing), and `facts.write_*` from the `remember` whose `outcome.id` names the fact with status `inserted` or `superseded`. The preview proofs and each batch run inside a short transaction with `enable_nestloop` off (the journal join on the outcome key has no index, and fresh attribution columns have no statistics), restoring the caller's setting before it ends. Items are batches of up to 1,000 ids per table in (table, id) cursor order; each batch re-runs the proof under `lockPageKeys` for its pages and commits on its own, so an interrupted run resumes after the last committed batch. Unproven NULL rows are the `unrecorded_<table>` residuals. Test: `test/write-attribution-read.test.ts`. `google-file-modes.ts`: an explicit-only (`explicit_only: true`), `publication: 'projection'` filesystem-only kind (`embeds: false`, no admission, no request ids) that plans one item per loose entry from `scanGoogleFileModes` (cursor phase = source index; the item carries root, relative path, kind and old mode) and applies `tightenGoogleEntry` (outcomes `tightened`, `already_private`, `skipped` with a reason); symlink, foreign-owner and wrong-type entries are `skipped_*` residuals. It is last in `REPAIR_KINDS`, so `--all` runs it after `embedding-effects`; registry check `google_file_modes`. Every run re-scans, so a rerun after `--limit` picks up exactly what is still loose.- `src/core/rerank-audit.ts` — failure-only JSONL audit at `~/.gbrain/audit/rerank-failures-YYYY-Www.jsonl` (ISO-week rotation, mirrors `src/core/audit-slug-fallback.ts`). Exports `logRerankFailure({reason, model, query_hash, doc_count, error_summary})` + `readRecentRerankFailures(days)`. The `no_key` reason is written ONCE per process per model by the gateway itself (not per query by `applyReranker`): the provider key is absent, so calls are skipped without HTTP and results pass through unreranked; `auth` means key present but rejected; `unreachable` means no HTTP response at all (connection refused, DNS, reset; a stale `provider_base_urls` entry fails every call this way, Cat 40 R0), while `network` stays a provider 5xx. Deliberately no `logRerankSuccess`: writing once per tokenmax search is hot-path I/O churn AND success events leak query volume + timing into a local audit file. `gbrain doctor`'s `reranker_health` check (`doctor/checks/calibration.ts`) resolves enablement + model through `resolveSearchMode(loadSearchModeConfig)` — the plane search reranks with — and `rerankerReadiness` before reading the audit: readiness is evaluated against the DB-merged config plane (`loadConfigWithEngine`, so DB-plane provider keys and `provider_base_urls` self-host overrides count, exactly like the gateway the CLI configures): a brain with NO embedding provider (`isAvailable('embedding')` false on a configured gateway) is `ok` even when not ready — search runs keyword-only there and never reaches `applyReranker`, so there is nothing to fix; otherwise enabled-but-not-ready (key absent / unknown model) warns with the paste-ready fix; only audit rows for the RESOLVED model count (rows for any other model never make the live default warn or send the operator to verify the wrong key); `no_key` skip rows are informational once ready (those processes ran unreranked; a long-lived worker started before the key was added keeps skipping until restarted) and never outlive the fix as a warn; then the auth / payload / budget / unreachable (3+ rows: names the `provider_base_urls.<provider>` key) / transient / unknown ladders on the non-skip rows; disabled → ok (with an enable hint when the default is ready). Query text SHA-256-prefix-hashed (8 hex chars) for privacy. `GBRAIN_AUDIT_DIR` env override honored via the shared `resolveAuditDir()`.- `src/core/repair/extractor-facts.ts` — `gbrain repair extractor-facts` (#5731), explicit-only and preview-bound. `classifyExtractorFacts` (read-only; also the doctor check's count) takes conversation-extractor facts with `expired_at` set and `row_num` NULL and classes each: `excluded` (page missing or deleted, `superseded_by` set, withdrawn, an active same-text fact on the page, or an earlier same-text candidate), `ambiguous` (unmanaged brain; no committed request of the page with `completed_at = expired_at`, compared in SQL as microsecond UTC text, which only a same-transaction completion satisfies on Postgres; a consumer at or above v0.60.11.0; or the page has ever held fence-projected facts) or `evidenced`. The preview lists every candidate, hashes them with the selection (`--include-ambiguous`) and saves one approved item per page (with its request id) through `preview-approval.ts`; the apply loads only that set, replays a still-pending request with the ctx's CLI write wait, skips pages whose request already committed or whose facts are active again, and restores each still-identical fact with a fresh `row_num` above the page's facts and fence rows. Managed brains publish one database-only `managed_maintenance_restore_extractor_facts` request per page (`submitDatabaseMaintenanceIntent`, dispatched by `prepareMaintenanceMutation` to `prepareExtractorFactsRestore`, which reclassifies under the page lock); unmanaged brains run the same restore in one locked transaction. Previews warn, naming the host, when a consumer older than this release published after `writer_version_cutoff`. On PGLite `now()` has millisecond resolution, so the same-transaction rule is millisecond-exact there.diff --git a/docs/architecture/key-files/mcp.md b/docs/architecture/key-files/mcp.mdindex 11a648c181..fdd4228c9d 100644--- a/docs/architecture/key-files/mcp.md+++ b/docs/architecture/key-files/mcp.md@@ -21,6 +21,7 @@ Current behavior and load-bearing invariants; history belongs in Git and CHANGEL- `src/mcp/source-preflight.ts` — `assertStdioSourceBindable(engine, env?)`: stdio-lane boot preflight called first thing in `startMcpServer`, before any transport attaches. A well-formed `GBRAIN_SOURCE` that names no ACTIVE source row (`SELECT id FROM sources WHERE id = $1 AND archived = false`, the same predicate as `assertSourceExists` in `src/core/source-resolver.ts`) throws a message naming the value and the fix (`gbrain sources list`), so serve exits 1 instead of binding every call to a phantom scope where reads return `[]` and writes die on the sources FK while health stays green. An inherited `__all__` emits an engine-free stderr warning with a source-binding recovery action, without widening its fail-closed scope. Unset env and malformed values are left to the resolver; an engine error fail-opens (guards config, not connectivity); a degraded engine (`isEngineDegraded`) is never touched so the boot does not spend the proxy's reconnect attempt. HTTP is out of scope (tokens carry their own source grant). Pinned by `test/mcp-stdio-source-preflight.test.ts` and real PostgreSQL/PGLite processes in `test/e2e/mcp-search-transport-matrix.test.ts`.- `src/core/mcp-registration.ts` — `REGISTRATION_SURFACE` (`full` since S0, wave 0: callable and advertised; README, docs/mcp, INSTALL_FOR_AGENTS.md and the plugin manifests name the same value, which the S0 grep test in `test/mcp-registration.test.ts` keeps so), `stdioServeArgv(bin, surface = REGISTRATION_SURFACE)` (`null` → bare `serve`) and `registeredSurface(text)` (an existing entry's pinned surface, `null` for bare, `undefined` when no serve command is visible): every stdio registration gbrain writes builds from them (readiness `harness_wiring`, init's quickstart, `bootstrap hooks` for Claude Code / Codex / opencode, the plugin generator, which also refuses root plugin manifests pinned elsewhere). The OpenClaw manifest stays a bare `serve`. Also the HTTP+bearer wiring helpers `connect.ts` re-exports. Test: `test/mcp-registration.test.ts`.+- `src/core/serve-log.ts` — serve's own log hygiene (#7246), installed by `src/cli/commands/serve.ts` before `runServe`. For each of stderr, and stdout under `--http` only (stdio serve's stdout is the JSON-RPC channel), whose descriptor is a regular file, it routes console and stream writes through a `ServeLogFile`: `LineDeduper` writes the first occurrence of a line at once and counts repeats inside the window (a leading timestamp ignored), then writes one `[gbrain serve-log] repeated N more time(s) in the last Ws: <line>` line when the window ends or the process exits; rotation is copy-then-truncate on the inherited append-mode descriptor (`<log>.N-1` → `<log>.N`, `<log>` → `<log>.1`, truncate), each write placed at the file's current end, and only when the descriptor's path is known (`/proc/self/fd` or the `serveLogPath`/`serveErrPath` inode) and still names the same inode. TTYs, pipes and journald are untouched. `GBRAIN_SERVE_LOG_MAX_BYTES` (10 MiB; 0 off), `GBRAIN_SERVE_LOG_MAX_FILES` (5), `GBRAIN_SERVE_LOG_DEDUPE_SECONDS` (600; 0 off). Tests: `test/serve-log-7246.test.ts`.- `src/core/ops/request-tools.ts` — `request_tools`: catalog (no args), descriptors (`{tools}`; D1: an empty list or one with no caller-visible name returns the catalog plus `did_you_mean` drawn only from `visibleOpsForCaller`, never echoing the requested names, so an invisible existing op and a nonexistent one answer byte-identically), and `{surface}`: per OAuth client on HTTP (ceiling, operator lock, rate limit, audit), and on the owner's stdio pipe `widenStdioSession` widens `ctx.stdioSurface` for the session (refused with the persistent route when `mcp.allow_session_widen` is off; clamped by `GBRAIN_MCP_FORCE_SURFACE`; returns `persisted:false, scope:'session'` and the new tools' schemas). A widenable stdio session's catalog lists the full surface. Tests: `test/request-tools.test.ts`, `test/request-tools-stdio.test.ts`.- `src/mcp/surface.ts` — MCP tool-surface modes: `'verbs'` (exactly the ops marked `verb: true`) | `'starter'` (the ~27-op daily-driver set) | `'full'` (default — identity; existing installs unchanged). `STARTER_OPS` is composed PROGRAMMATICALLY: a spread of `VERB_NAMES` (never a hand-count) + the fallback daily slice (`BRAIN_TOOL_ALLOWLIST` + the agent lane `submit_agent`/`get_agent_job`) + `whoami` + `request_tools` + `capture` (a DIRECT literal, deliberately NOT via the allowlist); re-derived from production usage via `scripts/derive-starter-ops.ts` (paste-in proposal, never an auto-edit). `ALWAYS_INCLUDED_STARTER_OPS` (verbs + `whoami` + `request_tools` + the agent lane + `capture`) is the exported always-set consumed by BOTH `derive-starter-ops.ts` and the advisor starter-fit collector, so neither re-types the composition. `parseSurfaceFlag` (strict, loud reject), `resolveSurface`/`resolveSurfaceWithSource` (flag > config `mcp_surface` > full, the `serve --http` order), `resolveStdioSurface` (stdio: `GBRAIN_SURFACE` > flag > config > full; an invalid env value is returned as `invalidEnv`, never fatal; `surfaceEnvInvalidNotice` builds its notice), `SURFACE_SOURCE_LABEL`, `filterOpsForSurface`, `allowedOpNames`, `createStdioSurfaceState` (the stdio session's one mutable allow-set; `widen(to)` recomputes it, read-only stays read-only), `sessionWidenAllowed` (`mcp.allow_session_widen`, DB > file, default true). `STARTER_OPS` also carries `mute_notice`, the dismissal for the coaching notices starter sessions receive. Enforcement is TWO-layer and fail-closed: the advertised list AND `dispatchToolCall`'s `allowedOps` set (a hidden op returns `unknown_tool` even when called by name) — applied on stdio (server.ts) and BOTH HTTP paths (serve-http.ts after `!localOnly`, and the second transport http-transport.ts). Per-client ceiling machinery (OAuth transport only): `effectiveSurfaceForClient` is the pure composition `clamp(min(server ceiling, client row surface ?? mcp.default_surface_dcr ?? ceiling))`; the per-REQUEST application lives in serve-http.ts's `resolveEffectiveSurface`, which short-circuits a `verbs` ceiling (min() cannot go lower, so the config read is skipped) and, on a default-surface read failure, applies the LAST successfully read default (held per process, fail-closed) so a transient config outage cannot silently widen a NULL-surface client to the ceiling; `resolveClientRowSurface` ignores unknown row values with a bounded warn-once (the column's value space is documented OPEN for future tier names); `resolveDefaultClientSurface` reads the DCR default dual-plane (DB > file > null) and never throws; `clampSurface`/`readForceSurfaceEnv` fold in the `GBRAIN_MCP_FORCE_SURFACE` kill switch — NARROW-ONLY by construction (min(); can never widen past the ceiling). `minSurface`/`surfaceWiderThan` own the verbs < starter < full rank math. Pinned by test/mcp-surface.test.ts (membership, monotonicity verbs ⊆ starter ⊆ full, ceiling + force-narrow cases). `--access read-only` (`parseAccessFlag`, stdio only; HTTP refuses it) intersects the surface with `isReadOnlyOperation` (read scope, not mutating, no required capability scope); `src/mcp/server.ts` uses that one set for tools/list, the capabilities resource (`access`), skill resources and dispatch `allowedOps`. Pinned by `test/serve-stdio-read-only.test.ts`. `mcp.advertised_surface` (`resolveAdvertisedSurface`, DB plane > file plane) narrows only what `tools/list` shows (`advertisedOps`, never wider than the callable set); dispatch keeps the ceiling. Stdio lists the advertised set plus tools `request_tools` described in this session (`OperationContext.revealTools` → `tools/list_changed`); the OAuth HTTP server lists a client's own row surface in full and otherwise the advertised set; the simple bearer transport reads the file plane once at startup. Initialize instructions carry `hiddenCallable` and name `request_tools` when tools are unlisted. `NEW_INSTALL_ADVERTISED_SURFACE` is what a fresh `gbrain init` writes (`'full'` writes nothing; the held-out agent benchmark picks verbs or starter). Pinned by `test/mcp-advertised-surface.test.ts`. Once a session widens (`request_tools {surface}`), the whole widened surface is listed.diff --git a/docs/guides/remote-mcp.md b/docs/guides/remote-mcp.mdindex e20ceae449..996803c364 100644--- a/docs/guides/remote-mcp.md+++ b/docs/guides/remote-mcp.md@@ -456,7 +456,14 @@ port once the cause is fixed. `--fail-fast` (or `GBRAIN_SERVE_FAIL_FAST=1`)exits instead.`gbrain mcp expose --status` re-runs the probes; `--json` names the failing-check. Logs: `~/.gbrain/serve/serve.log` and `serve.err`.+check. Logs: `~/.gbrain/serve/serve.log` and `serve.err`. Serve rotates each+of them at 10 MiB and keeps 5 copies (`serve.log.1` to `serve.log.5`), and a+line repeated within 10 minutes is written once, followed by one+`[gbrain serve-log] repeated N more time(s)` line. The same applies to any+`gbrain serve` whose output you redirect to a file with `>>`. Tune it with+`GBRAIN_SERVE_LOG_MAX_BYTES` (0 turns rotation off),+`GBRAIN_SERVE_LOG_MAX_FILES` and `GBRAIN_SERVE_LOG_DEDUPE_SECONDS` (0 turns+dedupe off) in the serve wrapper's environment.<a id="remote-mcp-symptoms"></a>diff --git a/llms-full.txt b/llms-full.txtindex 085c0d3850..c62f603135 100644--- a/llms-full.txt+++ b/llms-full.txt@@ -469,7 +469,14 @@ port once the cause is fixed. `--fail-fast` (or `GBRAIN_SERVE_FAIL_FAST=1`)exits instead.`gbrain mcp expose --status` re-runs the probes; `--json` names the failing-check. Logs: `~/.gbrain/serve/serve.log` and `serve.err`.+check. Logs: `~/.gbrain/serve/serve.log` and `serve.err`. Serve rotates each+of them at 10 MiB and keeps 5 copies (`serve.log.1` to `serve.log.5`), and a+line repeated within 10 minutes is written once, followed by one+`[gbrain serve-log] repeated N more time(s)` line. The same applies to any+`gbrain serve` whose output you redirect to a file with `>>`. Tune it with+`GBRAIN_SERVE_LOG_MAX_BYTES` (0 turns rotation off),+`GBRAIN_SERVE_LOG_MAX_FILES` and `GBRAIN_SERVE_LOG_DEDUPE_SECONDS` (0 turns+dedupe off) in the serve wrapper's environment.<a id="remote-mcp-symptoms"></a>diff --git a/src/cli/commands/serve.ts b/src/cli/commands/serve.tsindex 75606c219c..60d66a727f 100644--- a/src/cli/commands/serve.ts+++ b/src/cli/commands/serve.ts@@ -7,6 +7,8 @@import type { BrainEngine } from '../../core/engine.ts';export async function run(engine: BrainEngine, args: string[]): Promise<void> {+ // #7246: rotate and dedupe serve's own log when its stdout/stderr is a file.+ (await import('../../core/serve-log.ts')).installServeLogSink({ http: args.includes('--http') });const { runServe } = await import('../../commands/serve.ts');await runServe(engine, args);// serve doesn't disconnectdiff --git a/src/cli/main.ts b/src/cli/main.tsindex cd39ec2996..87dac4e896 100755--- a/src/cli/main.ts+++ b/src/cli/main.ts@@ -2684,8 +2684,8 @@ async function connectCliOnlyEngine(command: string, args: string[]): Promise<Brreturn connectEngine();},});- const { runServe } = await import('../commands/serve.ts');- await runServe(degraded, args);+ (await import('../core/serve-log.ts')).installServeLogSink({ http: args.includes('--http') });+ await (await import('../commands/serve.ts')).runServe(degraded, args);return null; // serve doesn't disconnect}throw serveConnectError;diff --git a/src/commands/anomalies.ts b/src/commands/anomalies.tsindex 17c4cd5bf4..4c6979d8f9 100644--- a/src/commands/anomalies.ts+++ b/src/commands/anomalies.ts@@ -12,18 +12,22 @@* gbrain anomalies # since=today, lookback=30d, sigma=3* gbrain anomalies --since 2026-04-28* gbrain anomalies --sigma 2 --lookback-days 60- * gbrain anomalies --json+ * gbrain anomalies --json # up to 20 slugs per cohort+ * gbrain anomalies --json --all # every slug (local brain)*/import type { BrainEngine } from '../core/engine.ts';import { loadConfig, isThinClient } from '../core/config.ts';import { callRemoteTool, unpackToolResult } from '../core/mcp-client.ts';+import { capRowList, LISTING_MAX_LIMIT } from '../core/bounded-listing.ts';+import { ANOMALY_SLUG_DEFAULT_LIMIT } from '../core/ops/salience.ts';interface RunOpts {since?: string;lookbackDays?: number;sigma?: number;json?: boolean;+ all?: boolean;}function parseArgs(args: string[]): RunOpts | { help: true } {@@ -32,6 +36,7 @@ function parseArgs(args: string[]): RunOpts | { help: true } {const a = args[i];if (a === '--help' || a === '-h') return { help: true };if (a === '--json') { opts.json = true; continue; }+ if (a === '--all') { opts.all = true; continue; }if (a === '--since') {const v = args[++i];if (v && /^\d{4}-\d{2}-\d{2}$/.test(v)) opts.since = v;@@ -59,7 +64,9 @@ Options:--since YYYY-MM-DD Target day (default: today UTC)--lookback-days N Baseline window (default 30)--sigma N Threshold multiplier (default 3.0)- --json JSON output for agents+ --json JSON output for agents (up to ${ANOMALY_SLUG_DEFAULT_LIMIT} slugs per cohort;+ page_slugs_complete is false when slugs were left out)+ --all Every slug of each cohort (a remote brain caps at ${LISTING_MAX_LIMIT})--help, -h Show this help`;@@ -77,6 +84,7 @@ export async function runAnomalies(engine: BrainEngine, args: string[]): Promisesince: parsed.since,lookback_days: parsed.lookbackDays,sigma: parsed.sigma,+ slug_limit: parsed.all ? LISTING_MAX_LIMIT : ANOMALY_SLUG_DEFAULT_LIMIT,}, { timeoutMs: 30_000 });rows = unpackToolResult<Awaited<ReturnType<BrainEngine['findAnomalies']>>>(raw);} else {@@ -87,7 +95,7 @@ export async function runAnomalies(engine: BrainEngine, args: string[]): Promise});}if (parsed.json) {- console.log(JSON.stringify(rows, null, 2));+ console.log(JSON.stringify(rows.map(row => capRowList(row, 'page_slugs', parsed.all ? null : ANOMALY_SLUG_DEFAULT_LIMIT)), null, 2));return;}if (rows.length === 0) {diff --git a/src/commands/orphans.ts b/src/commands/orphans.tsindex 809c698291..e06e87b600 100644--- a/src/commands/orphans.ts+++ b/src/commands/orphans.ts@@ -13,7 +13,9 @@ import { pageReadFilter } from '../core/search/read-policy-sql.ts';* Usage:* gbrain orphans # list islanded pages grouped by domain* gbrain orphans --mode inbound # legacy: pages with no inbound links- * gbrain orphans --json # JSON output for agent consumption+ * gbrain orphans --json # JSON: totals first, then the first 100 orphans+ * gbrain orphans --cursor <c> # the next page (next_cursor / next_command)+ * gbrain orphans --all # every orphan (no page limit)* gbrain orphans --count # just the number* gbrain orphans --include-pseudo # include auto-generated/pseudo pages*/@@ -30,6 +32,8 @@ import {} from '../core/orphan-policy.ts';import { quarantineFilterFragment } from '../core/quarantine.ts';import { isConnectorSourceKind } from '../core/persistence/connector-identity.ts';+import { pageSortedRows, topCounts, type ListingPage } from '../core/bounded-listing.ts';+import { nextListingCommand, parseListingFlags } from '../core/bounded-listing-cli.ts';// --- Types ---@@ -221,7 +225,7 @@ export const getOrphansData = findOrphans;// --- Output formatters ----export function formatOrphansText(result: OrphanResult): string {+export function formatOrphansText(result: OrphanResult, page?: { complete: boolean; next_command: string[] | null }): string {const lines: string[] = [];const { orphans, total_orphans, total_linkable, total_pages, excluded, connector_renders_excluded } = result;@@ -254,9 +258,42 @@ export function formatOrphansText(result: OrphanResult): string {lines.push('');}+ if (page && !page.complete && page.next_command) {+ lines.push(`Showing ${orphans.length} of ${total_orphans} orphans. Next page: ${page.next_command.join(' ')} (--all lists every orphan).`);+ }+return lines.join('\n').trimEnd();}+/**+ * #7246: summary-first JSON. A listing whose one page holds every orphan prints+ * the findOrphans result unchanged (totals first). A paged listing (a first page+ * that left orphans out, or any page reached by --cursor) prints the totals and+ * counts per domain, then the page with returned/limit/complete/next_cursor/next_command.+ */+export function orphansJson(result: OrphanResult, page: ListingPage<OrphanPage>, nextCommand: string[] | null, paged: boolean) {+ const totals = {+ total_orphans: result.total_orphans,+ total_linkable: result.total_linkable,+ total_pages: result.total_pages,+ excluded: result.excluded,+ ...(result.connector_renders_excluded !== undefined ? { connector_renders_excluded: result.connector_renders_excluded } : {}),+ };+ if (!paged) return { ...totals, orphans: result.orphans };+ const byDomain = topCounts(result.orphans, row => row.domain);+ return {+ ...totals,+ by_domain: byDomain.counts,+ ...(byDomain.other ? { by_domain_other: byDomain.other } : {}),+ returned: page.returned,+ limit: page.limit,+ complete: page.complete,+ next_cursor: page.next_cursor,+ next_command: nextCommand,+ orphans: page.rows,+ };+}+// --- CLI entry point ---export async function runOrphans(engine: BrainEngine, args: string[]) {@@ -299,14 +336,20 @@ Options:--mode <m> Orphan definition: islanded (default) | inbound(legacy: pages with no inbound links, even if they link out)--source <id> Scope the scan to one brain source (default: brain-wide)+ --limit <n> Orphans per page (default 100)+ --cursor <c> The next page: next_cursor from the previous page+ --all Every orphan, no page limit--help, -h Show this helpOutput (default): grouped by domain, sorted alphabetically within each groupSummary line: N orphans out of M linkable pages (K total; K-M excluded)+Pages: the totals always count every orphan; one page of rows follows, and+--json carries complete, next_cursor and next_command for the next page.`);return;}+ const { request, rest } = parseListingFlags(args, 'gbrain orphans');const result = await findOrphans(engine, { includePseudo, sourceId, mode });if (count) {@@ -314,10 +357,14 @@ Summary line: N orphans out of M linkable pages (K total; K-M excluded)return;}+ const kind = `orphans:${mode ?? 'islanded'}:${sourceId ?? '*'}:${includePseudo ? 'all' : 'policy'}`;+ const page = pageSortedRows(result.orphans, row => [row.domain, row.source_id ?? '', row.slug], request, kind);+ const nextCommand = nextListingCommand(['gbrain', 'orphans', ...rest], page);+if (json) {- console.log(JSON.stringify(result, null, 2));+ console.log(JSON.stringify(orphansJson(result, page, nextCommand, request.cursor !== undefined || !page.complete), null, 2));return;}- console.log(formatOrphansText(result));+ console.log(formatOrphansText({ ...result, orphans: page.rows }, { complete: page.complete, next_command: nextCommand }));}diff --git a/src/commands/serve-status.ts b/src/commands/serve-status.tsindex 8a77372928..4f5e4f7b4a 100644--- a/src/commands/serve-status.ts+++ b/src/commands/serve-status.ts@@ -55,6 +55,7 @@ export function logStatusTransition(event: 'serve_status_mode_enter' | 'serve_stexport async function runStatusModeServe(reason: StatusReason, initialError: unknown, args: string[], connect: () => Promise<BrainEngine>,): Promise<void> {+ (await import('../core/serve-log.ts')).installServeLogSink({ http: args.includes('--http') });const state = initialStatusState(reason);const transport: StatusTransport = args.includes('--http') ? 'http' : 'stdio';const enteredAt = Date.now();diff --git a/src/core/behavior-change-notice.ts b/src/core/behavior-change-notice.tsindex cda8c94855..ae7ee51123 100644--- a/src/core/behavior-change-notice.ts+++ b/src/core/behavior-change-notice.ts@@ -1053,6 +1053,10 @@ export const BEHAVIOR_CHANGES: ReadonlyArray<{ since: string; text: ChangeText;{ since: '0.60.338.0', text: 'On Postgres, a keyword search whose words match more than 50,000 chunks now ranks the first 50,000 matches that pass its filters instead of all of them, so a common-word query on a large brain returns ranked rows in about a second instead of running into the keyword statement timeout and returning none; hybrid search reports `keyword_candidates_incomplete` when the bound applies. Its any-word retry (after an all-words match finds nothing) now matches only the words the planner statistics say fit about 20,000 chunks, still ranking with every word, and also reports `keyword_candidates_incomplete` when it drops a word.' },{ since: '0.60.338.0', text: 'The keyword arm keeps one chunk per page in its candidate pool (Postgres and PGLite), so a page with hundreds of matching chunks no longer pushes every other matching page out of the results.' },{ since: '0.60.338.0', text: 'The title arm\'s any-word retry (after an all-words title match finds nothing) now matches page titles only, as remote callers already did, and drops repeated words (#7135): a date in a question no longer pulls every dated timeline into ranking, which cut a 3-5 s title arm to well under a second on a large brain. A local all-words title match is unchanged.' },+ // GBRA-151 (#7246 bounded whole-brain outputs). `since` is stamped at the merge slot.+ { since: 'TBD', text: '`gbrain orphans` now prints at most 100 orphans per page (the totals still count every orphan). A paged `--json` result lists the totals and counts per domain first, then the page with `returned`, `limit`, `complete`, `next_cursor` and `next_command`; `--cursor <next_cursor>` prints the next page, `--limit <n>` sets the page size and `--all` prints every orphan in the earlier shape. A listing that fits in one page prints as before. MCP `find_orphans` adds `cursor`, `complete` and `next_cursor` beside offset paging.' },+ { since: 'TBD', text: 'MCP `find_anomalies` and `gbrain anomalies --json` list at most 20 slugs per anomalous cohort; `count` still covers the whole cohort and `page_slugs_complete: false` marks a row that left slugs out. `slug_limit` (MCP, up to 1000) or `--all` (CLI) lists more.' },+ { since: 'TBD', text: 'When `gbrain serve`\'s stdout or stderr is a regular file (the `gbrain mcp expose` service installs, or any `>>` redirect), serve rotates that file at 10 MiB, keeping 5 copies (`<log>.1` to `<log>.5`), and writes a line repeated within 10 minutes once, followed by one "[gbrain serve-log] repeated N more time(s)" line. `GBRAIN_SERVE_LOG_MAX_BYTES` (0 turns rotation off), `GBRAIN_SERVE_LOG_MAX_FILES` and `GBRAIN_SERVE_LOG_DEDUPE_SECONDS` (0 turns dedupe off) change it.' },];/** The newest disclosed change's release: the notice id moves only when a release adds rows. */diff --git a/src/core/bounded-listing-cli.ts b/src/core/bounded-listing-cli.tsnew file mode 100644index 0000000000..23e94c53a7--- /dev/null+++ b/src/core/bounded-listing-cli.ts@@ -0,0 +1,48 @@+/**+ * CLI half of the bounded-listing contract (#7246): `--limit`, `--cursor` and+ * `--all` parsing and the next page argv. Kept apart from bounded-listing.ts+ * so a command that only caps rows does not inherit these flags in the+ * generated CLI flag registry.+ */+import { opError } from './ops/contract.ts';+import { LISTING_DEFAULT_LIMIT, type ListingPage, type ListingRequest } from './bounded-listing.ts';++/**+ * Parses --limit/--cursor/--all out of argv for a CLI listing. Returns the+ * request and the argv without --cursor (the base for next_command, so the+ * next page keeps the caller's --limit).+ */+export function parseListingFlags(args: readonly string[], command: string): { request: ListingRequest; rest: string[] } {+ let limit: number | undefined;+ let cursor: string | undefined;+ let all = false;+ const rest: string[] = [];+ for (let i = 0; i < args.length; i++) {+ const token = args[i]!;+ const eq = token.indexOf('=');+ const flag = eq < 0 ? token : token.slice(0, eq);+ const inline = eq < 0 ? undefined : token.slice(eq + 1);+ if (token === '--all') { all = true; continue; }+ if (flag !== '--limit' && flag !== '--cursor') { rest.push(token); continue; }+ const value = inline ?? args[++i];+ if (value === undefined || value === '' || (inline === undefined && value.startsWith('--'))) {+ throw opError('invalid_params', `${flag} needs a value.`, `Example: ${command} ${flag === '--limit' ? `--limit ${LISTING_DEFAULT_LIMIT}` : '--cursor <next_cursor>'}`);+ }+ if (flag === '--cursor') { cursor = value; continue; }+ rest.push(...(inline === undefined ? [flag, value] : [token]));+ const n = Number(value);+ if (!Number.isInteger(n) || n < 1) {+ throw opError('invalid_params', `--limit must be a positive integer (got "${value}").`, `Example: ${command} --limit ${LISTING_DEFAULT_LIMIT}, or --all for every row.`);+ }+ limit = n;+ }+ if (all && (limit !== undefined || cursor !== undefined)) {+ throw opError('invalid_params', '--all lists every row, so it takes no --limit or --cursor.', `Use ${command} --all, or ${command} --limit <n> [--cursor <next_cursor>].`);+ }+ return { request: { limit: all ? null : (limit ?? LISTING_DEFAULT_LIMIT), ...(cursor !== undefined ? { cursor } : {}) }, rest };+}++/** The argv of the next page, or null when the page was the last one. */+export function nextListingCommand(base: readonly string[], page: Pick<ListingPage<unknown>, 'next_cursor'>): string[] | null {+ return page.next_cursor === null ? null : [...base, '--cursor', page.next_cursor];+}diff --git a/src/core/bounded-listing.ts b/src/core/bounded-listing.tsnew file mode 100644index 0000000000..0e7d7a5364--- /dev/null+++ b/src/core/bounded-listing.ts@@ -0,0 +1,106 @@+/**+ * Bounded whole-brain listings (#7246): one page of rows at a time, with the+ * totals first and an opaque keyset cursor for the next page.+ *+ * Contract every listing that uses this helper shares:+ * - CLI flags `--limit <n>` (default LISTING_DEFAULT_LIMIT), `--cursor <token>`+ * and `--all` (every row; trusted local CLI only, never with --limit or --cursor).+ * - MCP params `limit` (default LISTING_DEFAULT_LIMIT, at most LISTING_MAX_LIMIT)+ * and `cursor`; a remote caller is never unbounded.+ * - Output fields, after the listing's own counts: `returned`, `limit` (null+ * under --all), `complete` (true when no row was left out) and `next_cursor`+ * (null when complete); the CLI adds `next_command`, the argv of the next page.+ * The rows come last so a reader can stop after the summary.+ * - The cursor is base64url JSON `{"v":1,"k":<listing kind>,"a":[...sort key]}`:+ * the sort key of the last row returned. The next page starts strictly after+ * it, so rows added or removed between pages never shift a page. A cursor+ * from another listing (different kind, which includes its filters) is refused.+ */+import { opError } from './ops/contract.ts';++export const LISTING_DEFAULT_LIMIT = 100;+export const LISTING_MAX_LIMIT = 1000;++export interface ListingRequest {+ /** Rows per page; null means every row (CLI --all). */+ limit: number | null;+ cursor?: string;+}++export interface ListingPage<T> {+ rows: T[];+ returned: number;+ limit: number | null;+ complete: boolean;+ next_cursor: string | null;+}++function listingRefusal(message: string, suggestion: string) {+ return opError('invalid_params', message, suggestion);+}++export function encodeListingCursor(kind: string, after: readonly string[]): string {+ return Buffer.from(JSON.stringify({ v: 1, k: kind, a: after }), 'utf8').toString('base64url');+}++export function decodeListingCursor(kind: string, token: string): string[] {+ let parsed: unknown;+ try {+ parsed = JSON.parse(Buffer.from(token, 'base64url').toString('utf8'));+ } catch {+ parsed = null;+ }+ const value = parsed as { v?: unknown; k?: unknown; a?: unknown } | null;+ if (!value || value.v !== 1 || !Array.isArray(value.a) || !value.a.every(part => typeof part === 'string')) {+ throw listingRefusal('The cursor is not a listing cursor.', 'Pass the next_cursor value from the previous page unchanged, or drop the cursor to start from the first page.');+ }+ if (value.k !== kind) {+ throw listingRefusal('The cursor belongs to a different listing or filter set.', 'Rerun with the same filters as the page that returned it, or drop the cursor to start from the first page.');+ }+ return value.a as string[];+}++function compareKeys(a: readonly string[], b: readonly string[]): number {+ const n = Math.min(a.length, b.length);+ for (let i = 0; i < n; i++) {+ if (a[i] !== b[i]) return a[i]! < b[i]! ? -1 : 1;+ }+ return a.length - b.length;+}++/** Sorts rows by `key` (code-unit order) and returns the page after the cursor. */+export function pageSortedRows<T>(rows: readonly T[], key: (row: T) => string[], request: ListingRequest, kind: string): ListingPage<T> {+ const keyed = rows.map(row => ({ row, key: key(row) })).sort((x, y) => compareKeys(x.key, y.key));+ const after = request.cursor === undefined ? null : decodeListingCursor(kind, request.cursor);+ const start = after === null ? 0 : keyed.findIndex(entry => compareKeys(entry.key, after) > 0);+ const remaining = start < 0 ? [] : keyed.slice(start);+ const page = request.limit === null ? remaining : remaining.slice(0, request.limit);+ const complete = page.length === remaining.length;+ return {+ rows: page.map(entry => entry.row),+ returned: page.length,+ limit: request.limit,+ complete,+ next_cursor: complete ? null : encodeListingCursor(kind, page[page.length - 1]!.key),+ };+}++/** Counts rows per key, keeping the `top` largest keys; `other` counts the rows under every other key. */+export function topCounts<T>(rows: readonly T[], key: (row: T) => string, top = 20): { counts: Record<string, number>; other: number } {+ const totals = new Map<string, number>();+ for (const row of rows) {+ const name = key(row);+ totals.set(name, (totals.get(name) ?? 0) + 1);+ }+ const ranked = [...totals].sort((a, b) => b[1] - a[1] || (a[0] < b[0] ? -1 : 1));+ const counts: Record<string, number> = {};+ for (const [name, count] of ranked.slice(0, top)) counts[name] = count;+ return { counts, other: ranked.slice(top).reduce((n, [, count]) => n + count, 0) };+}++/** Caps one list field of a row at `limit` entries (null keeps every entry); a capped row gets `<field>_complete: false`. */+export function capRowList<T extends object>(row: T, field: keyof T & string, limit: number | null): T {+ const list = row[field];+ if (limit === null || !Array.isArray(list) || list.length <= limit) return row;+ return { ...row, [field]: list.slice(0, limit), [`${field}_complete`]: false };+}diff --git a/src/core/cli-flag-registry.generated.ts b/src/core/cli-flag-registry.generated.tsindex 95d4e6438c..73412dc7f7 100644--- a/src/core/cli-flag-registry.generated.ts+++ b/src/core/cli-flag-registry.generated.ts@@ -16,7 +16,7 @@export const CLI_FLAG_REGISTRY: Record<string, readonly string[]> = {'advisor': ['--apply', '--brain', '--help', '--json', '--skills-dir', '--source', '--workspace', '--yes'],'agent': ['--allow-old-serve', '--brain', '--detach', '--fanout-manifest', '--federated-read', '--flags', '--follow', '--harness', '--help', '--http', '--json', '--max-turns', '--mcp-only', '--model', '--no-follow', '--path', '--port', '--preset', '--reissue', '--scopes', '--show-token', '--since', '--source', '--subagent-def', '--surface', '--timeout-ms', '--token-ttl', '--tools', '--url', '--word', '--yes'],- 'anomalies': ['--brain', '--help', '--json', '--lookback-days', '--mcp-only', '--request-id', '--sigma', '--since', '--source'],+ 'anomalies': ['--all', '--brain', '--help', '--json', '--lookback-days', '--mcp-only', '--request-id', '--sigma', '--since', '--source'],'append': ['--brain', '--expect-tail', '--expected-revision', '--file', '--force', '--help', '--json', '--region', '--request-id', '--separator', '--source'],'apply-migrations': ['--accept-reviewed-inventory', '--acknowledge-no-backup', '--apply', '--apply-rewrites', '--backup-confirmed', '--brain', '--break-lock', '--confirm-quiesced', '--content-root', '--dry-run', '--export-db-only', '--export-source', '--force', '--force-all', '--force-orchestrator', '--force-retry', '--force-schema', '--help', '--host-dir', '--http', '--install', '--json', '--legacy-lock', '--list', '--locks', '--migrate-only', '--migration', '--mode', '--no-autopilot-install', '--non-interactive', '--only', '--path', '--prefer-postgres', '--probe', '--repo', '--require-db', '--skip-verify', '--source', '--statement-timeout', '--uninstall', '--url', '--yes'],'auth': ['--add', '--admin-intent', '--adopt-columns', '--adopt-permissions', '--all-new', '--allowed-operations', '--before', '--bound-brain', '--bound-max-concurrent', '--bound-slug-prefixes', '--bound-source', '--bound-tools', '--brain', '--budget-usd-per-day', '--category', '--cleanup-dead-local-locks', '--client', '--code', '--confirm-quiesced', '--confirm-relocated-root', '--days', '--delegated-namespace', '--delegated-slug-prefixes', '--disable', '--dry-run', '--enable', '--enable-dcr-insecure', '--expected-epoch', '--expected-state', '--federated-read', '--fix', '--force', '--grant-types', '--group-by', '--help', '--id', '--if-version', '--json', '--limit', '--manifest', '--max-concurrent', '--migrate-legacy', '--min-trust', '--no-pull', '--operations', '--origin', '--parked-pushes', '--pat-file', '--path', '--probe', '--profile', '--read-sources', '--redirect-uri', '--refresh-operations', '--repair', '--replace', '--request-id', '--reset-default', '--scopes', '--self-transfer', '--shared-skills', '--since', '--slug-prefixes', '--source', '--source-ids', '--sources', '--state', '--surface', '--takes-holders', '--token', '--token-endpoint-auth-method', '--token-ttl', '--usage', '--wait', '--warn-only', '--yes'],@@ -90,7 +90,7 @@ export const CLI_FLAG_REGISTRY: Record<string, readonly string[]> = {'notability-eval': ['--brain', '--embedding-dimensions', '--embedding-model', '--help', '--in', '--json', '--out', '--repo', '--skip-llm', '--source', '--status', '--target-high', '--target-low', '--target-medium'],'notices': ['--brain', '--help', '--json', '--source'],'onboard': ['--access', '--add', '--all', '--allowed-operations', '--apply', '--asof', '--auto', '--body', '--bound-slug-prefixes', '--brain', '--check', '--client', '--cursor', '--date', '--dated-since', '--days', '--entities', '--explain', '--federated-read', '--from-index', '--from-pages', '--full', '--fuzzy', '--group-by', '--help', '--history', '--http', '--id', '--include-deleted', '--json', '--kind', '--limit', '--max-usd', '--model', '--multimodal', '--no-autopilot-install', '--only', '--page', '--params', '--path', '--phase', '--prefer', '--probe', '--purge', '--recent', '--refresh-operations', '--remediate', '--remediation-plan', '--resume', '--row', '--save', '--scopes', '--session', '--since', '--slugs', '--source', '--sources', '--stale', '--surface', '--target-score', '--to', '--updated-after', '--url', '--yes'],- 'orphans': ['--accept-pending', '--background', '--brain', '--count', '--explain', '--follow', '--force', '--help', '--include-pseudo', '--json', '--mode', '--no-accept-pending', '--progress-interval', '--progress-json', '--quiet', '--source', '--timeout', '--timings', '--wait'],+ 'orphans': ['--accept-pending', '--all', '--background', '--brain', '--count', '--cursor', '--explain', '--follow', '--force', '--help', '--include-pseudo', '--json', '--limit', '--mode', '--no-accept-pending', '--progress-interval', '--progress-json', '--quiet', '--source', '--timeout', '--timings', '--wait'],'pages': ['--brain', '--dry-run', '--force', '--help', '--json', '--limit', '--older-than', '--retry-parked', '--source', '--source-id', '--state', '--yes'],'pglite-repair': ['--brain', '--break-lock', '--dry-run', '--expect', '--help', '--http', '--json', '--legacy-lock', '--path', '--probe', '--source', '--vectors', '--yes'],'post-upgrade': ['--accept-reviewed-inventory', '--acknowledge-no-backup', '--admin-intent', '--all', '--all-applied', '--apply', '--apply-clean-hunks', '--backup-confirmed', '--brain', '--catch-up', '--changed', '--check', '--concurrency', '--confirm-quiesced', '--confirm-relocated-root', '--content-root', '--cost-estimate', '--embedding-dimensions', '--embedding-model', '--exit-code', '--expand', '--expected-epoch', '--expected-state', '--explain', '--export-db-only', '--export-source', '--ff-only', '--force', '--force-all', '--force-orchestrator', '--force-retry', '--force-schema', '--format', '--held', '--help', '--host-dir', '--images', '--inject-bootstrap', '--inline', '--install', '--interval', '--json', '--limit', '--list', '--manifest', '--markdown', '--max-rss', '--max-usd', '--migrate-only', '--migration', '--mode', '--multimodal', '--name-only', '--no-autopilot-install', '--no-bun-floor-check', '--no-embed', '--no-expand', '--no-inject', '--no-worker', '--non-interactive', '--now', '--once', '--only', '--oversized', '--path', '--pause', '--phase', '--quiet', '--reason', '--refs', '--remediation-plan', '--repo', '--require-db', '--resume', '--retry-global', '--search-mode', '--self-transfer', '--skills-dir', '--skip-verify', '--source', '--stale', '--statement-timeout', '--status', '--swap-only', '--tags', '--target', '--uninstall', '--user', '--vectors', '--verify', '--version', '--workers', '--yes'],diff --git a/src/core/operation-manifest.generated.ts b/src/core/operation-manifest.generated.tsindex 37985096a7..c33f30fdb7 100644--- a/src/core/operation-manifest.generated.ts+++ b/src/core/operation-manifest.generated.ts@@ -3777,12 +3777,16 @@ export const OPERATION_MANIFEST: OperationMeta[] = [},"limit": {"type": "number",- "description": "Rows per page (default 100, max 1000); total_orphans counts every orphan and next_offset names the next page."+ "description": "Rows per page (default 100, max 1000); total_orphans counts every orphan, complete says whether this page holds the rest, and next_cursor (or next_offset) names the next page."},"offset": {"type": "number","description": "Skip the first N orphans (ordered by source_id, then slug)."},+ "cursor": {+ "type": "string",+ "description": "next_cursor from the previous page, with the same filters (instead of offset)."+ },"count_only": {"type": "boolean","description": "Return the totals with no rows."@@ -4640,6 +4644,10 @@ export const OPERATION_MANIFEST: OperationMeta[] = ["sigma": {"type": "number","description": "Threshold (default 3)."+ },+ "slug_limit": {+ "type": "number",+ "description": "Slugs listed per cohort (default 20, max 1000); count covers the whole cohort and page_slugs_complete is false when slugs were left out."}},"cliHints": {diff --git a/src/core/ops/orphans.ts b/src/core/ops/orphans.tsindex b19638ba16..7c2ea3440c 100644--- a/src/core/ops/orphans.ts+++ b/src/core/ops/orphans.ts@@ -8,11 +8,12 @@import { assertSourceInCallerScope, readPolicyOpts } from './context.ts';import type { Operation } from './contract.ts';import { invalidParam } from './op-fix.ts';+import { encodeListingCursor, LISTING_DEFAULT_LIMIT, LISTING_MAX_LIMIT, pageSortedRows } from '../bounded-listing.ts';// --- Orphans ----export const ORPHANS_DEFAULT_LIMIT = 100;-export const ORPHANS_MAX_LIMIT = 1000;+export const ORPHANS_DEFAULT_LIMIT = LISTING_DEFAULT_LIMIT;+export const ORPHANS_MAX_LIMIT = LISTING_MAX_LIMIT;const find_orphans: Operation = {name: 'find_orphans',@@ -35,9 +36,10 @@ const find_orphans: Operation = {},limit: {type: 'number',- description: `Rows per page (default ${ORPHANS_DEFAULT_LIMIT}, max ${ORPHANS_MAX_LIMIT}); total_orphans counts every orphan and next_offset names the next page.`,+ description: `Rows per page (default ${ORPHANS_DEFAULT_LIMIT}, max ${ORPHANS_MAX_LIMIT}); total_orphans counts every orphan, complete says whether this page holds the rest, and next_cursor (or next_offset) names the next page.`,},offset: { type: 'number', description: 'Skip the first N orphans (ordered by source_id, then slug).' },+ cursor: { type: 'string', description: 'next_cursor from the previous page, with the same filters (instead of offset).' },count_only: { type: 'boolean', description: 'Return the totals with no rows.' },},scope: 'read',@@ -72,10 +74,25 @@ const find_orphans: Operation = {...(mode ? { mode } : {}),...scope,});- const ordered = [...result.orphans].sort((a, b) =>- (a.source_id ?? '').localeCompare(b.source_id ?? '') || a.slug.localeCompare(b.slug));+ const cursor = p.cursor === undefined ? undefined : String(p.cursor);+ if (cursor !== undefined && offset !== 0) {+ throw invalidParam(ctx, 'find_orphans', 'cursor', 'find_orphans: pass cursor or offset, not both', { def: find_orphans.params.cursor });+ }+ // #7246: one cursor kind per filter set, so a cursor never resumes a different listing.+ const kind = `find_orphans:${mode ?? 'islanded'}:${named ?? '*'}:${p.include_pseudo === true ? 'all' : 'policy'}`;+ const key = (row: { source_id?: string; slug: string }) => [row.source_id ?? '', row.slug];+ if (p.count_only === true) {+ return { ...result, orphans: [], limit, offset, next_offset: null, complete: result.total_orphans === 0, next_cursor: null };+ }+ if (cursor !== undefined) {+ const page = pageSortedRows(result.orphans, key, { limit, cursor }, kind);+ return { ...result, orphans: page.rows, limit, offset, next_offset: null, complete: page.complete, next_cursor: page.next_cursor };+ }+ const ordered = pageSortedRows(result.orphans, key, { limit: null }, kind).rows;+ const rows = ordered.slice(offset, offset + limit);const next = offset + limit < ordered.length ? offset + limit : null;- return { ...result, orphans: p.count_only === true ? [] : ordered.slice(offset, offset + limit), limit, offset, next_offset: p.count_only === true ? null : next };+ return { ...result, orphans: rows, limit, offset, next_offset: next, complete: next === null,+ next_cursor: next === null ? null : encodeListingCursor(kind, key(rows[rows.length - 1]!)) };},cliHints: { name: 'orphans', hidden: true },};diff --git a/src/core/ops/salience.ts b/src/core/ops/salience.tsindex 9ab610402f..4504552e0c 100644--- a/src/core/ops/salience.ts+++ b/src/core/ops/salience.ts@@ -10,6 +10,8 @@import type { Operation } from './contract.ts';import { readPolicyOpts } from './context.ts';+import { invalidParam } from './op-fix.ts';+import { capRowList, LISTING_MAX_LIMIT } from '../bounded-listing.ts';import {GET_RECENT_SALIENCE_DESCRIPTION,FIND_ANOMALIES_DESCRIPTION,@@ -17,6 +19,9 @@ import {// --- v0.29: Salience + Anomaly Detection ---+/** #7246: slugs listed per anomalous cohort unless the caller asks for more (count always covers the whole cohort). */+export const ANOMALY_SLUG_DEFAULT_LIMIT = 20;+const get_recent_salience: Operation = {name: 'get_recent_salience',mutating: false,@@ -79,8 +84,17 @@ const find_anomalies: Operation = {type: 'number',description: 'Threshold (default 3).',},+ slug_limit: {+ type: 'number',+ description: `Slugs listed per cohort (default ${ANOMALY_SLUG_DEFAULT_LIMIT}, max ${LISTING_MAX_LIMIT}); count covers the whole cohort and page_slugs_complete is false when slugs were left out.`,+ },},handler: async (ctx, p) => {+ const slugLimit = p.slug_limit === undefined ? ANOMALY_SLUG_DEFAULT_LIMIT : Number(p.slug_limit);+ if (!Number.isInteger(slugLimit) || slugLimit < 1 || slugLimit > LISTING_MAX_LIMIT) {+ throw invalidParam(ctx, 'find_anomalies', 'slug_limit', `find_anomalies: slug_limit must be 1-${LISTING_MAX_LIMIT}`,+ { def: find_anomalies.params.slug_limit, example: ANOMALY_SLUG_DEFAULT_LIMIT });+ }// Scope by the caller's source (same v0.34.1 #861 source-isolation class as// get_recent_salience above — the v0.29 batch missed both). Applied to the// baseline AND today windows inside the engine so the anomaly math stays@@ -93,7 +107,7 @@ const find_anomalies: Operation = {...await readPolicyOpts(ctx),});- return anomalies;+ return anomalies.map(row => capRowList(row, 'page_slugs', slugLimit));},// hidden: 'anomalies' is in CLI_ONLY (src/cli.ts) — runAnomalies owns the// CLI surface; the non-hidden hint was dead (CLI_ONLY wins at dispatch).diff --git a/src/core/serve-log.ts b/src/core/serve-log.tsnew file mode 100644index 0000000000..633178b88b--- /dev/null+++ b/src/core/serve-log.ts@@ -0,0 +1,206 @@+/**+ * serve's own log hygiene (#7246): size-based rotation and dedupe of repeated+ * lines for a `gbrain serve` whose stdout or stderr is a regular file.+ *+ * The service installs `gbrain mcp expose` writes (launchd StandardOutPath,+ * systemd `append:`, the nohup `>>` fallback) and any operator `>>` redirect+ * hand serve an append-mode file descriptor it cannot reopen. So rotation is+ * copy-then-truncate on that descriptor: shift <path>.N-1 → <path>.N, copy+ * <path> → <path>.1, truncate <path> to zero, keep writing. Every write goes+ * at the file's current end, so a truncated file never grows a hole.+ *+ * Dedupe: a line seen again inside the window (a leading timestamp ignored)+ * is counted instead of written; when the window ends, or the process exits,+ * one "[gbrain serve-log] repeated N more time(s) in the last Ws: <line>" line+ * follows. The first occurrence is always written immediately.+ *+ * TTYs, pipes and journald are left alone. Knobs (env, read at serve start):+ * GBRAIN_SERVE_LOG_MAX_BYTES (default 10 MiB; 0 turns rotation off),+ * GBRAIN_SERVE_LOG_MAX_FILES (rotated copies kept, default 5),+ * GBRAIN_SERVE_LOG_DEDUPE_SECONDS (default 600; 0 turns dedupe off).+ */+import { copyFileSync, existsSync, fstatSync, ftruncateSync, readlinkSync, renameSync, statSync, writeSync } from 'node:fs';+import { formatWithOptions } from 'node:util';+import { serveErrPath, serveLogPath } from './serve-service.ts';++export interface ServeLogPolicy {+ maxBytes: number;+ maxFiles: number;+ dedupeWindowMs: number;+}++const DEFAULTS: ServeLogPolicy = { maxBytes: 10 * 1024 * 1024, maxFiles: 5, dedupeWindowMs: 600_000 };+const MAX_TRACKED_LINES = 10_000;+const LEADING_TIMESTAMP = /^\[?\d{4}-\d{2}-\d{2}[T ]\d{2}:\d{2}:\d{2}(?:\.\d+)?(?:Z|[+-]\d{2}:?\d{2})?\]?\s*/;++export function resolveServeLogPolicy(env: Record<string, string | undefined>, warn: (line: string) => void): ServeLogPolicy {+ const read = (name: string, fallback: number, min: number): number => {+ const raw = env[name];+ if (raw === undefined || raw === '') return fallback;+ const n = Number(raw);+ if (Number.isInteger(n) && n >= min) return n;+ warn(`[gbrain serve] ignoring invalid ${name}=${JSON.stringify(raw)} — using default ${fallback}`);+ return fallback;+ };+ return {+ maxBytes: read('GBRAIN_SERVE_LOG_MAX_BYTES', DEFAULTS.maxBytes, 0),+ maxFiles: read('GBRAIN_SERVE_LOG_MAX_FILES', DEFAULTS.maxFiles, 1),+ dedupeWindowMs: read('GBRAIN_SERVE_LOG_DEDUPE_SECONDS', DEFAULTS.dedupeWindowMs / 1000, 0) * 1000,+ };+}++export class LineDeduper {+ private readonly seen = new Map<string, { first: number; repeats: number; line: string }>();++ constructor(private readonly windowMs: number, private readonly now: () => number = Date.now) {}++ /** The lines to write for one complete line: pending summaries first, then the line unless it is a repeat. */+ accept(line: string): string[] {+ if (this.windowMs <= 0 || line.trim() === '') return [line];+ const out = this.flush(false);+ const key = line.replace(LEADING_TIMESTAMP, '');+ const entry = this.seen.get(key);+ if (entry) {+ entry.repeats++;+ return out;+ }+ if (this.seen.size >= MAX_TRACKED_LINES) out.push(...this.evict(this.seen.keys().next().value!));+ this.seen.set(key, { first: this.now(), repeats: 0, line });+ out.push(line);+ return out;+ }++ /** Summary lines for every line whose window has ended (all of them when forced). */+ flush(force: boolean): string[] {+ const out: string[] = [];+ for (const [key, entry] of this.seen) {+ if (!force && this.now() - entry.first < this.windowMs) break;+ out.push(...this.evict(key));+ }+ return out;+ }++ private evict(key: string): string[] {+ const entry = this.seen.get(key)!;+ this.seen.delete(key);+ return entry.repeats > 0+ ? [`[gbrain serve-log] repeated ${entry.repeats} more time(s) in the last ${Math.round(this.windowMs / 1000)}s: ${entry.line}`]+ : [];+ }+}++/** One append-mode log descriptor: dedupes complete lines and rotates at the size bound when its path is known. */+export class ServeLogFile {+ private readonly dedupe: LineDeduper;+ private atLineStart = true;++ constructor(private readonly fd: number, private readonly path: string | null, private readonly policy: ServeLogPolicy, now: () => number = Date.now) {+ this.dedupe = new LineDeduper(policy.dedupeWindowMs, now);+ }++ write(text: string): void {+ const parts = text.split('\n');+ const tail = parts.pop()!;+ const out: string[] = [];+ for (const line of parts) {+ out.push(...(this.atLineStart ? this.dedupe.accept(line) : [line]));+ this.atLineStart = true;+ }+ let chunk = out.map(line => `${line}\n`).join('');+ if (tail !== '') {+ chunk += tail;+ this.atLineStart = false;+ }+ this.emit(chunk);+ }++ /** Writes the summaries of windows that ended (all pending ones when forced, at exit). */+ flush(force: boolean): void {+ const lines = this.dedupe.flush(force);+ if (!lines.length) return;+ this.emit(`${this.atLineStart ? '' : '\n'}${lines.map(line => `${line}\n`).join('')}`);+ this.atLineStart = true;+ }++ private emit(chunk: string): void {+ if (chunk === '') return;+ const bytes = Buffer.from(chunk, 'utf8');+ if (this.path === null || this.policy.maxBytes <= 0) {+ writeSync(this.fd, bytes);+ return;+ }+ let size = fstatSync(this.fd).size;+ if (size > 0 && size + bytes.length > this.policy.maxBytes && this.rotate()) size = 0;+ writeSync(this.fd, bytes, 0, bytes.length, size);+ }++ private rotate(): boolean {+ const path = this.path!;+ const current = fstatSync(this.fd);+ if (!existsSync(path) || statSync(path).ino !== current.ino) return false;+ for (let i = this.policy.maxFiles - 1; i >= 1; i--) {+ if (existsSync(`${path}.${i}`)) renameSync(`${path}.${i}`, `${path}.${i + 1}`);+ }+ copyFileSync(path, `${path}.1`);+ ftruncateSync(this.fd, 0);+ return true;+ }+}++function regularFilePath(fd: number): { file: boolean; path: string | null } {+ let stat;+ try {+ stat = fstatSync(fd);+ } catch {+ return { file: false, path: null };+ }+ if (!stat.isFile()) return { file: false, path: null };+ const candidates: string[] = [];+ try { candidates.push(readlinkSync(`/proc/self/fd/${fd}`)); } catch { /* not Linux */ }+ candidates.push(serveLogPath(), serveErrPath());+ for (const candidate of candidates) {+ try {+ const s = statSync(candidate);+ if (s.ino === stat.ino && s.dev === stat.dev) return { file: true, path: candidate };+ } catch { /* not this one */ }+ }+ return { file: true, path: null };+}++let installed = false;++/**+ * Routes serve's console and stream writes for each log-file stream through a+ * ServeLogFile. stdout only under --http: stdio serve's stdout is the JSON-RPC+ * channel and is never touched.+ */+export function installServeLogSink(opts: { http: boolean; env?: Record<string, string | undefined> }): void {+ if (installed) return;+ const env = opts.env ?? process.env;+ const streams: Array<{ fd: number; stream: NodeJS.WriteStream; methods: Array<'log' | 'info' | 'debug' | 'error' | 'warn'> }> = [+ { fd: 2, stream: process.stderr, methods: ['error', 'warn'] },+ ...(opts.http ? [{ fd: 1, stream: process.stdout, methods: ['log', 'info', 'debug'] as Array<'log' | 'info' | 'debug'> }] : []),+ ];+ const targets = streams.map(entry => ({ ...entry, ...regularFilePath(entry.fd) })).filter(entry => entry.file);+ if (!targets.length) return;+ installed = true;+ const policy = resolveServeLogPolicy(env, line => process.stderr.write(`${line}\n`));+ const logs: ServeLogFile[] = [];+ for (const target of targets) {+ const log = new ServeLogFile(target.fd, target.path, policy);+ logs.push(log);+ const write = (chunk: string | Uint8Array, encodingOrCb?: BufferEncoding | ((err?: Error | null) => void), maybeCb?: (err?: Error | null) => void): boolean => {+ const cb = typeof encodingOrCb === 'function' ? encodingOrCb : maybeCb;+ const encoding = typeof encodingOrCb === 'string' ? encodingOrCb : 'utf8';+ log.write(typeof chunk === 'string' ? chunk : Buffer.from(chunk).toString(encoding));+ if (cb) queueMicrotask(() => cb(null));+ return true;+ };+ target.stream.write = write as typeof target.stream.write;+ for (const method of target.methods) console[method] = (...args: unknown[]) => log.write(`${formatWithOptions({ colors: false }, ...args)}\n`);+ }+ if (policy.dedupeWindowMs > 0) {+ setInterval(() => { for (const log of logs) log.flush(false); }, Math.min(policy.dedupeWindowMs, 60_000)).unref();+ }+ process.on('exit', () => { for (const log of logs) log.flush(true); });+}diff --git a/test/anomalies-bounded-7246.test.ts b/test/anomalies-bounded-7246.test.tsnew file mode 100644index 0000000000..78e406dca4--- /dev/null+++ b/test/anomalies-bounded-7246.test.ts@@ -0,0 +1,58 @@+/**+ * #7246: find_anomalies (and `gbrain anomalies --json`) returned every slug+ * of an anomalous cohort, so a bulk-import day put tens of thousands of slugs+ * in one response. Each row now carries at most `slug_limit` slugs (default+ * 20, max 1000) and `page_slugs_complete: false` when it left some out; the+ * count still covers the whole cohort. `--all` keeps every slug on the local CLI.+ *+ * Authoring gate: protects the output-size contract of a remote-reachable op;+ * fails if the cap is dropped or a remote caller can lift it; no existing test+ * covers the slug list size.+ */+import { describe, expect, test } from 'bun:test';+import { operations } from '../src/core/operations.ts';+import { runAnomalies } from '../src/commands/anomalies.ts';+import type { BrainEngine } from '../src/core/engine.ts';++const slugs = Array.from({ length: 500 }, (_, i) => `people/p-${i}`);+const row = { cohort_kind: 'type' as const, cohort_value: 'person', count: 500, baseline_mean: 1, baseline_stddev: 1, sigma_observed: 499 };+const engine = { kind: 'pglite', findAnomalies: async () => [{ ...row, page_slugs: [...slugs] }] } as unknown as BrainEngine;+const op = operations.find(o => o.name === 'find_anomalies')!;+const ctx = (remote: boolean) => ({ engine, config: { engine: 'pglite' }, logger: { info() {}, warn() {}, error() {} }, dryRun: false, remote }) as never;++async function cliJson(args: string[]) {+ const lines: string[] = [];+ const original = console.log;+ console.log = (...parts: unknown[]) => { lines.push(parts.map(String).join(' ')); };+ try {+ await runAnomalies(engine, ['--json', ...args]);+ } finally {+ console.log = original;+ }+ return JSON.parse(lines.join('\n'));+}++describe('find_anomalies bounded slug lists (#7246)', () => {+ test('the op caps page_slugs at 20 by default and marks the row incomplete', async () => {+ const [out] = await op.handler(ctx(true), {}) as Array<Record<string, unknown>>;+ expect(out!.page_slugs).toEqual(slugs.slice(0, 20));+ expect(out!.page_slugs_complete).toBe(false);+ expect(out!.count).toBe(500);+ });++ test('slug_limit raises the cap up to 1000, never unbounded for a remote caller', async () => {+ const [out] = await op.handler(ctx(true), { slug_limit: 1000 }) as Array<Record<string, unknown>>;+ expect(out!.page_slugs).toHaveLength(500);+ expect(out!.page_slugs_complete).toBeUndefined();+ await expect(op.handler(ctx(true), { slug_limit: 1001 })).rejects.toThrow('slug_limit');+ });++ test('gbrain anomalies --json is capped by default and --all keeps every slug', async () => {+ const [capped] = await cliJson([]);+ expect(capped.page_slugs).toHaveLength(20);+ expect(capped.page_slugs_complete).toBe(false);+ const [all] = await cliJson(['--all']);+ expect(all.page_slugs).toHaveLength(500);+ expect(all.page_slugs_complete).toBeUndefined();+ });+});diff --git a/test/bounded-listing-7246.test.ts b/test/bounded-listing-7246.test.tsnew file mode 100644index 0000000000..dc2bc04340--- /dev/null+++ b/test/bounded-listing-7246.test.ts@@ -0,0 +1,61 @@+/**+ * #7246: the shared bounded-listing helper (src/core/bounded-listing.ts and+ * its CLI half) that orphans uses and the sync status --detail bounding will+ * reuse. Protects the cursor contract: keyset pages never skip or repeat a+ * surviving row when rows are added or removed between pages, a foreign or+ * malformed cursor is refused, and the flag parser keeps --limit in the next+ * page's argv. Fails if the cursor degrades to an offset.+ */+import { describe, expect, test } from 'bun:test';+import { capRowList, decodeListingCursor, encodeListingCursor, pageSortedRows, topCounts } from '../src/core/bounded-listing.ts';+import { nextListingCommand, parseListingFlags } from '../src/core/bounded-listing-cli.ts';++const key = (row: { slug: string }) => [row.slug];+const rows = (...slugs: string[]) => slugs.map(slug => ({ slug }));++describe('bounded listing helper (#7246)', () => {+ test('a keyset page resumes after the last row even when rows change between pages', () => {+ const first = pageSortedRows(rows('d', 'b', 'a', 'c', 'e'), key, { limit: 2 }, 'k');+ expect(first.rows.map(r => r.slug)).toEqual(['a', 'b']);+ expect(first.complete).toBe(false);+ const second = pageSortedRows(rows('0', 'a', 'c', 'd', 'e', 'f'), key, { limit: 2, cursor: first.next_cursor! }, 'k');+ expect(second.rows.map(r => r.slug)).toEqual(['c', 'd']);+ const last = pageSortedRows(rows('0', 'a', 'c', 'd', 'e', 'f'), key, { limit: 2, cursor: second.next_cursor! }, 'k');+ expect(last.rows.map(r => r.slug)).toEqual(['e', 'f']);+ expect(last.complete).toBe(true);+ expect(last.next_cursor).toBeNull();+ });++ test('limit null returns every row; an exact-fit page is complete', () => {+ expect(pageSortedRows(rows('b', 'a'), key, { limit: null }, 'k')).toMatchObject({ returned: 2, limit: null, complete: true, next_cursor: null });+ expect(pageSortedRows(rows('b', 'a'), key, { limit: 2 }, 'k')).toMatchObject({ complete: true, next_cursor: null });+ });++ test('foreign and malformed cursors are refused', () => {+ expect(decodeListingCursor('k', encodeListingCursor('k', ['x', 'y']))).toEqual(['x', 'y']);+ expect(() => decodeListingCursor('other', encodeListingCursor('k', ['x']))).toThrow('different listing');+ expect(() => decodeListingCursor('k', 'not-a-cursor')).toThrow('not a listing cursor');+ });++ test('topCounts keeps the largest keys and counts the rest', () => {+ expect(topCounts(rows('a', 'a', 'b', 'c', 'c', 'c'), r => r.slug, 2)).toEqual({ counts: { c: 3, a: 2 }, other: 1 });+ });++ test('capRowList marks a capped row incomplete and leaves a short row untouched', () => {+ const row = { id: 1, items: [1, 2, 3] };+ expect(capRowList(row, 'items', 2) as unknown).toEqual({ id: 1, items: [1, 2], items_complete: false });+ expect(capRowList(row, 'items', 3)).toBe(row);+ expect(capRowList(row, 'items', null)).toBe(row);+ });++ test('parseListingFlags defaults to 100, keeps --limit for the next page and refuses --all with a limit', () => {+ expect(parseListingFlags(['--json'], 'gbrain x')).toEqual({ request: { limit: 100 }, rest: ['--json'] });+ const parsed = parseListingFlags(['--limit=5', '--cursor', 'abc', '--json'], 'gbrain x');+ expect(parsed).toEqual({ request: { limit: 5, cursor: 'abc' }, rest: ['--limit=5', '--json'] });+ expect(nextListingCommand(['gbrain', 'x', ...parsed.rest], { next_cursor: 'def' })).toEqual(['gbrain', 'x', '--limit=5', '--json', '--cursor', 'def']);+ expect(parseListingFlags(['--all'], 'gbrain x').request).toEqual({ limit: null });+ expect(() => parseListingFlags(['--all', '--limit', '3'], 'gbrain x')).toThrow('--all lists every row');+ expect(() => parseListingFlags(['--limit', '0'], 'gbrain x')).toThrow('--limit must be a positive integer');+ expect(() => parseListingFlags(['--cursor'], 'gbrain x')).toThrow('--cursor needs a value');+ });+});diff --git a/test/fixtures/goldens/cli/literal-imports.json b/test/fixtures/goldens/cli/literal-imports.jsonindex b8a40ee61a..2a9ea2f538 100644--- a/test/fixtures/goldens/cli/literal-imports.json+++ b/test/fixtures/goldens/cli/literal-imports.json@@ -180,6 +180,7 @@"./commands/salience.ts"],"serve": [+ "./core/serve-log.ts","./commands/serve.ts"],"skillopt": [diff --git a/test/fixtures/goldens/cli/tools-json.json b/test/fixtures/goldens/cli/tools-json.jsonindex 94efec5f1b..c9958be467 100644--- a/test/fixtures/goldens/cli/tools-json.json+++ b/test/fixtures/goldens/cli/tools-json.json@@ -2,8 +2,8 @@"golden": {"exitCode": 0,"stderr": "",- "stdoutBytes": 254763,- "stdoutSha256": "f6d6005ad68241f8e95fac4a2f61f62b074fd5a0a76206e8e410a02d425692df",+ "stdoutBytes": 255279,+ "stdoutSha256": "587625e601300f3576e9857ad6e27f3d26a951095fcb4303ee144ad4154a0fdc","toolNames": ["remember","entity",@@ -4541,6 +4541,7 @@"name": "find_orphans","parameters": {"count_only": "boolean?",+ "cursor": "string?","include_pseudo": "boolean?","limit": "number?","mode": "string?",@@ -4554,12 +4555,16 @@"description": "Return the totals with no rows.","type": "boolean"},+ "cursor": {+ "description": "next_cursor from the previous page, with the same filters (instead of offset).",+ "type": "string"+ },"include_pseudo": {"description": "Include auto-generated and pseudo pages (default: false)","type": "boolean"},"limit": {- "description": "Rows per page (default 100, max 1000); total_orphans counts every orphan and next_offset names the next page.",+ "description": "Rows per page (default 100, max 1000); total_orphans counts every orphan, complete says whether this page holds the rest, and next_cursor (or next_offset) names the next page.","type": "number"},"mode": {@@ -5565,7 +5570,8 @@"parameters": {"lookback_days": "number?","sigma": "number?",- "since": "string?"+ "since": "string?",+ "slug_limit": "number?"},"required_scopes": [],"schema": {@@ -5581,6 +5587,10 @@"since": {"description": "YYYY-MM-DD (default today).","type": "string"+ },+ "slug_limit": {+ "description": "Slugs listed per cohort (default 20, max 1000); count covers the whole cohort and page_slugs_complete is false when slugs were left out.",+ "type": "number"}},"required": [],diff --git a/test/orphans-bounded-7246.test.ts b/test/orphans-bounded-7246.test.tsnew file mode 100644index 0000000000..967f31ecb0--- /dev/null+++ b/test/orphans-bounded-7246.test.ts@@ -0,0 +1,111 @@+/**+ * #7246: `gbrain orphans --json` printed every orphan in one document (about+ * 27 MB on a brain with hundreds of thousands of pages). It now prints the+ * totals first, then one bounded page of rows with `complete` and a+ * `next_cursor` / `next_command`; `--all` keeps every row, and a listing+ * that fits in one page keeps the unpaged shape. The remote find_orphans op+ * pages by the same cursor and stays capped.+ *+ * Authoring gate: protects the CLI and MCP output-size contract; fails if the+ * CLI drops the default limit or the cursor skips or repeats rows; existing+ * orphans tests cover the data function and offset paging only.+ */+import { afterAll, beforeAll, describe, expect, test } from 'bun:test';+import { PGLiteEngine } from '../src/core/pglite-engine.ts';+import { runOrphans } from '../src/commands/orphans.ts';+import { operations } from '../src/core/operations.ts';++let engine: PGLiteEngine;++async function captureStdout(fn: () => Promise<void>): Promise<string> {+ const lines: string[] = [];+ const original = console.log;+ console.log = (...parts: unknown[]) => { lines.push(parts.map(String).join(' ')); };+ try {+ await fn();+ } finally {+ console.log = original;+ }+ return lines.join('\n');+}++async function orphansJson(args: string[]) {+ return JSON.parse(await captureStdout(() => runOrphans(engine, ['--json', ...args])));+}++beforeAll(async () => {+ engine = new PGLiteEngine();+ await engine.connect({});+ await engine.initSchema();+ for (let i = 0; i < 90; i++) {+ await engine.putPage(`people/p-${String(i).padStart(3, '0')}`, { type: 'person', title: `P ${i}`, compiled_truth: 'Body.' });+ }+ for (let i = 0; i < 60; i++) {+ await engine.putPage(`companies/c-${String(i).padStart(3, '0')}`, { type: 'company', title: `C ${i}`, compiled_truth: 'Body.' });+ }+}, 120_000);+afterAll(async () => { await engine.disconnect(); });++describe('gbrain orphans bounded output (#7246)', () => {+ test('--json prints the totals first and one default page of 100 rows with a next cursor', async () => {+ const out = await orphansJson([]);+ expect(out.total_orphans).toBe(150);+ expect(out.orphans).toHaveLength(100);+ expect(out.returned).toBe(100);+ expect(out.limit).toBe(100);+ expect(out.complete).toBe(false);+ expect(typeof out.next_cursor).toBe('string');+ expect(out.next_command).toEqual(['gbrain', 'orphans', '--json', '--cursor', out.next_cursor]);+ expect(out.by_domain).toEqual({ people: 90, companies: 60 });+ const keys = Object.keys(out);+ expect(keys[keys.length - 1]).toBe('orphans');+ expect(keys.indexOf('total_orphans')).toBeLessThan(keys.indexOf('orphans'));+ });++ test('following next_cursor returns every remaining orphan once, then complete', async () => {+ const first = await orphansJson(['--limit', '60']);+ const second = await orphansJson(['--limit', '60', '--cursor', first.next_cursor]);+ const third = await orphansJson(['--limit', '60', '--cursor', second.next_cursor]);+ expect([first.returned, second.returned, third.returned]).toEqual([60, 60, 30]);+ expect(third.complete).toBe(true);+ expect(third.next_cursor).toBeNull();+ expect(third.next_command).toBeNull();+ const slugs = [...first.orphans, ...second.orphans, ...third.orphans].map((o: { slug: string }) => o.slug);+ expect(new Set(slugs).size).toBe(150);+ });++ test('--all, and a listing that fits in one page, print the unpaged shape with every orphan', async () => {+ const all = await orphansJson(['--all']);+ expect(all.orphans).toHaveLength(150);+ expect(all.total_orphans).toBe(150);+ expect(Object.keys(all)).not.toContain('next_cursor');+ const fits = await orphansJson(['--limit', '150']);+ expect(fits).toEqual(all);+ });++ test('a cursor from a different filter set is refused', async () => {+ const first = await orphansJson(['--limit', '10']);+ await expect(runOrphans(engine, ['--json', '--mode', 'inbound', '--cursor', first.next_cursor])).rejects.toThrow('different listing');+ await expect(runOrphans(engine, ['--json', '--all', '--limit', '5'])).rejects.toThrow('--all lists every row');+ });++ test('text output is bounded and names the next-page command', async () => {+ const text = await captureStdout(() => runOrphans(engine, ['--limit', '5']));+ expect(text).toContain('150 orphans out of');+ expect(text.split('\n').filter(line => line.startsWith(' ')).length).toBe(5);+ expect(text).toContain('Showing 5 of 150 orphans. Next page: gbrain orphans --limit 5 --cursor ');+ });++ test('find_orphans pages by cursor and reports complete', async () => {+ const op = operations.find(o => o.name === 'find_orphans')!;+ const ctx = { engine, config: { engine: 'pglite' }, logger: { info() {}, warn() {}, error() {} }, dryRun: false, remote: true } as never;+ const first = await op.handler(ctx, { limit: 100 }) as { orphans: unknown[]; complete: boolean; next_cursor: string | null };+ expect(first.orphans).toHaveLength(100);+ expect(first.complete).toBe(false);+ const rest = await op.handler(ctx, { limit: 100, cursor: first.next_cursor }) as { orphans: unknown[]; complete: boolean; next_cursor: string | null };+ expect(rest.orphans).toHaveLength(50);+ expect(rest.complete).toBe(true);+ expect(rest.next_cursor).toBeNull();+ await expect(op.handler(ctx, { limit: 1001 })).rejects.toThrow('limit must be');+ });+});diff --git a/test/serve-log-7246.test.ts b/test/serve-log-7246.test.tsnew file mode 100644index 0000000000..e94fe0d299--- /dev/null+++ b/test/serve-log-7246.test.ts@@ -0,0 +1,116 @@+/**+ * #7246: serve's log was never rotated, and about 98% of it was the same+ * no-action warnings printed again on every managed pass. When serve's+ * stdout or stderr is a regular file (the launchd / systemd / nohup installs+ * `gbrain mcp expose` writes, or any `>>` redirect), serve now rotates that+ * file at a size bound with a capped number of copies, and collapses a line+ * repeated inside the dedupe window into its first occurrence plus one+ * "repeated N more time(s)" line.+ *+ * Authoring gate: protects the on-disk log bound and the first-occurrence+ * guarantee; fails if rotation stops at the bound, keeps more copies than the+ * cap, drops a first occurrence or miscounts repeats; nothing covered the+ * serve log before.+ */+import { afterEach, describe, expect, test } from 'bun:test';+import { closeSync, existsSync, mkdtempSync, openSync, readFileSync, rmSync, statSync } from 'node:fs';+import { tmpdir } from 'node:os';+import { join, resolve } from 'node:path';+import { LineDeduper, ServeLogFile, resolveServeLogPolicy } from '../src/core/serve-log.ts';++const dirs: string[] = [];+const scratch = () => { const dir = mkdtempSync(join(tmpdir(), 'serve-log-7246-')); dirs.push(dir); return dir; };+afterEach(() => { for (const dir of dirs.splice(0)) rmSync(dir, { recursive: true, force: true }); });++describe('LineDeduper (#7246)', () => {+ test('keeps the first occurrence, counts repeats inside the window, then summarizes once', () => {+ let now = 0;+ const dedupe = new LineDeduper(60_000, () => now);+ const warning = '[import] WARNING: a.md shares content_hash with b (abcd1234) but not its frontmatter.id. Indexing both.';+ expect(dedupe.accept(warning)).toEqual([warning]);+ now = 1_000;+ expect(dedupe.accept(warning)).toEqual([]);+ expect(dedupe.accept(warning)).toEqual([]);+ expect(dedupe.accept('a different line')).toEqual(['a different line']);+ now = 61_000;+ const after = dedupe.accept(warning);+ expect(after).toHaveLength(2);+ expect(after[0]).toBe(`[gbrain serve-log] repeated 2 more time(s) in the last 60s: ${warning}`);+ expect(after[1]).toBe(warning);+ });++ test('a leading timestamp does not make a repeat distinct, and exit flushes pending counts', () => {+ let now = 0;+ const dedupe = new LineDeduper(60_000, () => now);+ expect(dedupe.accept('2026-10-21T10:00:00.000Z content-sanity warn: x.md (9 bytes)')).toHaveLength(1);+ now = 5;+ expect(dedupe.accept('2026-10-21T10:00:05.123Z content-sanity warn: x.md (9 bytes)')).toEqual([]);+ expect(dedupe.flush(true)).toEqual(['[gbrain serve-log] repeated 1 more time(s) in the last 60s: 2026-10-21T10:00:00.000Z content-sanity warn: x.md (9 bytes)']);+ expect(dedupe.flush(true)).toEqual([]);+ });++ test('a zero window keeps every line', () => {+ const dedupe = new LineDeduper(0, () => 0);+ expect(dedupe.accept('same')).toEqual(['same']);+ expect(dedupe.accept('same')).toEqual(['same']);+ });+});++describe('ServeLogFile rotation (#7246)', () => {+ test('rotates at the size bound and keeps at most max_files copies', () => {+ const path = join(scratch(), 'serve.log');+ const fd = openSync(path, 'a');+ try {+ const log = new ServeLogFile(fd, path, { maxBytes: 1_000, maxFiles: 2, dedupeWindowMs: 0 });+ const lines = Array.from({ length: 60 }, (_, i) => `line ${String(i).padStart(3, '0')} ${'x'.repeat(90)}`);+ for (const line of lines) log.write(`${line}\n`);+ expect(statSync(path).size).toBeLessThanOrEqual(1_000);+ expect(existsSync(`${path}.1`)).toBe(true);+ expect(existsSync(`${path}.2`)).toBe(true);+ expect(existsSync(`${path}.3`)).toBe(false);+ const kept = [readFileSync(`${path}.2`, 'utf8'), readFileSync(`${path}.1`, 'utf8'), readFileSync(path, 'utf8')].join('').split('\n').filter(Boolean);+ expect(kept).toEqual(lines.slice(lines.length - kept.length));+ for (const file of [path, `${path}.1`, `${path}.2`]) expect(statSync(file).size).toBeLessThanOrEqual(1_000);+ } finally {+ closeSync(fd);+ }+ });+});++describe('resolveServeLogPolicy (#7246)', () => {+ test('defaults, overrides, and an invalid value falls back with a warning', () => {+ expect(resolveServeLogPolicy({}, () => {})).toEqual({ maxBytes: 10 * 1024 * 1024, maxFiles: 5, dedupeWindowMs: 600_000 });+ const warnings: string[] = [];+ const policy = resolveServeLogPolicy({ GBRAIN_SERVE_LOG_MAX_BYTES: '0', GBRAIN_SERVE_LOG_MAX_FILES: 'three', GBRAIN_SERVE_LOG_DEDUPE_SECONDS: '30' }, line => warnings.push(line));+ expect(policy).toEqual({ maxBytes: 0, maxFiles: 5, dedupeWindowMs: 30_000 });+ expect(warnings).toEqual(['[gbrain serve] ignoring invalid GBRAIN_SERVE_LOG_MAX_FILES="three" — using default 5']);+ });+});++describe('installServeLogSink on redirected streams (#7246)', () => {+ test('a serve process appending to log files dedupes stderr warnings and rotates stdout', async () => {+ const dir = scratch();+ const script = join(dir, 'child.ts');+ await Bun.write(script, [+ `import { installServeLogSink } from ${JSON.stringify(resolve('src/core/serve-log.ts'))};`,+ "installServeLogSink({ http: true });",+ "for (let i = 0; i < 100; i++) console.warn('[gbrain] markdown fence cap hit (100 fences/page); skipping additional fences.');",+ "console.error('a different warning');",+ "for (let i = 0; i < 40; i++) console.log(`request ${i} ${'y'.repeat(80)}`);",+ ].join('\n'));+ const child = Bun.spawn(['sh', '-c', 'exec "$BUN" "$SCRIPT" >> "$DIR/serve.log" 2>> "$DIR/serve.err"'], {+ env: { PATH: process.env.PATH, BUN: process.execPath, SCRIPT: script, DIR: dir, GBRAIN_SERVE_LOG_MAX_BYTES: '1024', GBRAIN_SERVE_LOG_MAX_FILES: '2' },+ });+ expect(await child.exited).toBe(0);+ const err = readFileSync(join(dir, 'serve.err'), 'utf8').split('\n').filter(Boolean);+ expect(err).toEqual([+ '[gbrain] markdown fence cap hit (100 fences/page); skipping additional fences.',+ 'a different warning',+ '[gbrain serve-log] repeated 99 more time(s) in the last 600s: [gbrain] markdown fence cap hit (100 fences/page); skipping additional fences.',+ ]);+ expect(statSync(join(dir, 'serve.log')).size).toBeLessThanOrEqual(1024);+ expect(existsSync(join(dir, 'serve.log.1'))).toBe(true);+ expect(existsSync(join(dir, 'serve.log.3'))).toBe(false);+ expect(readFileSync(join(dir, 'serve.log'), 'utf8').trimEnd().split('\n').pop()).toStartWith('request 39 ');+ }, 30_000);+});