Skip to content

Garry's Opinionated OpenClaw/Hermes Agent Brain

TypeScript

fix(sources): sources status --json bounds git_holds: counts per code with one example, 10 items, --holds / --limit / --cursor for the rest (#7326)

garrytan9d48dc4c6a8d
diff --git a/docs/architecture/key-files/commands-1.md b/docs/architecture/key-files/commands-1.md
index d167ca3fbf..56879d7b41 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. `--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` lists every slug on a local brain; MCP always caps. Pinned by `test/anomalies-bounded-7246.test.ts`.
+- `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. At most 20 `page_slugs` per cohort (`page_slugs_complete: false`; local `--all` lists all; `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/core-persistence-continued.md b/docs/architecture/key-files/core-persistence-continued.md
index 8bffece800..67f7099d53 100644
--- a/docs/architecture/key-files/core-persistence-continued.md
+++ b/docs/architecture/key-files/core-persistence-continued.md
@@ -14,6 +14,7 @@ The #6188 fence check and fence repair live in [fence repair](core-fence-repair.
- `src/core/persistence/connector-sync.ts` — managed Google/GitHub API ingestion through source-scoped journaled `connector_v2_import`/`_delete`/`_checkpoint`/`_google_receipts` intents and `managed-connector` checkpoint CAS, not Git cursors. The checkpoint key, admission `configHash`, mid-sweep change check and publication `source_changed` check all use the parsed-config identity from `connector-identity.ts`, so cycle stamps in `sources.config` never rotate them. Unbound connectors use reviewed `connector_database` SQL-only authority; bound connectors retain canonical file publication with guarded root/hash/revision/epoch. Every managed run checks the credential's resolved account against the pin in the connector state row before reading its checkpoint (`assertAccount`), then applies a requested `--reset-checkpoint` (pending writes resolved first, pin kept). Each import or delete is first screened by running `prepareConnectorMutation` on an unadmitted request through the no-op kernel; unchanged items take no admission. An unchanged checkpoint save is skipped and, when it would have stamped freshness, `last_sync_at` is stamped directly inside a lease-asserted coordinated write. Accepted-pending writes are progress: a 30-second total wait budget (writes committing within one second are free), at most one in-flight write per page, outstanding writes kept under the principal's outstanding and intent-byte limits, and `ConnectorWaitBudgetStop` (a `write_pending` error) when the budget is spent. The checkpoint never advances past a pending page; the run records its pending set in the state row, and the next run resolves it first (committed dropped, failed retried automatically through the retry-pointer path without `--retry-failed`, unreached failures after a complete sweep dropped and counted). Retired `managed_connector_*` intents route to `prepareOutdatedConnectorMutation`, which fails them `connector_intent_outdated` (detail `pre_upgrade` before the v176 cutoff). Standalone entry, page reads and submissions authenticate the current source, local grant and canonical owner and settle retained worktree publications before deriving request identity. Explicit `--retry-failed` atomically admits a linked attempt and stores a per-base-request `managed-connector-retry` pointer. Durable connector cursors, retry pointers and state rows survive generic seven-day checkpoint GC. Tests: `test/persistence-connectors.test.ts`, `test/persistence-connector-retry.test.ts`, `test/connector-checkpoint-identity.test.ts`, `test/connector-wave3.test.ts` and `test/helpers/connector-restart.ts` on PGLite and disposable Postgres. #6831: a page import whose content matches a source page purge tombstone is skipped per item instead of ending the run: screened before admission (`carriesPurgedPage`, the guard's content hash, read only when the source has a tombstone), and a `failed`/`purged_content` receipt the guard still produces (a purge that landed mid-run) is skipped wherever it surfaces (the item's wait, `refreshPending`, `resolvePendingSet`): it is dropped from `receipts`, never joins the automatic retry set, has its optimistic pending count taken back, and is counted in `last_run.purged_skipped` and `purged_items`. A replayed purged receipt is re-checked against the live tombstones (`purgedNow`) before `mayRetry`: still purged, it is skipped even under `--retry-failed`; cleared, it gets one automatic retry. A run that ends on any error except `LockStolenError` or an aborted caller signal records `last_failure` (code, else `connector_error`; message, the item and request when the run ended on that item's receipt, `consecutive`); only a complete `finish()` (cursor saved, nothing pending or failed) clears it. Tests: `test/connector-purged-item-6831.test.ts` (+ `test/e2e/` twin).
- `src/core/persistence/connector-identity.ts` — `connectorIdentity(kind, rawConfig, localPath)` returns the parsed connector config and a digest over every parsed leaf except credential-delivery fields (Google `access`/`tokenCommand`/`tokenEnv`; GitHub `tokenEnv` and `app` under `scope: repos`, `app.pemPath` always; under `scope: auto` the token env without an App and the App ids are identity). `services`/`repos` are sorted and de-duplicated; a parser leaf missing from `CONNECTOR_LEAF_RULES` joins the identity. #6561: a leaf a parser starts emitting with a behavior-preserving default declares it as `elideWhen` (Google `contactsDir: 'people'`) and is left out of the digest while it holds it, so unchanged sources keep the pre-field key; the non-elided digest is kept as `aliasDigests` (`connectorCheckpointKeys` returns the stable key then its alias keys; `connectorIdentityMatches` accepts an admitted write's frozen `configHash` under either). Also `connectorCheckpointKey` and `isConnectorIntentKind`/`connectorIntentSql`, the one predicate for both intent namespaces. Test: `test/connector-identity.test.ts` enumerates every parser leaf.
- `src/core/persistence/connector-state.ts` — (fix wave 4: also `first_attempt_at`, the autopilot connector dispatch gate, recorded before the first provider call of a validated, non-preview sync and seeded by migration v181) the per-source-incarnation `op='managed-connector-state'` row (fingerprint `digest({sourceId, incarnation})`, independent of the identity digest): account pin, pending set `{itemRef, requestId, baseRequestId, admittedAt}`, `upgrade_recovery` (`resumed`/`rewalking_once`/`none`) with `resumed_from`, `continuity_unverified` and last-run counts. `writeManagedConnectorState` checks the connector sync lease in the same statement. `connector-status.ts` renders it for `gbrain sources status` without the account. #6831: `purged_items` (newest `CONNECTOR_PURGED_LIMIT` purged skips) and `last_failure` (`ConnectorRunFailure`); `CONNECTOR_STOPPED_RUNS` (3) consecutive failed runs read as stopped in `connector-status.ts` (`sources status` lines, `readConnectorLastError` for `sync status`'s additive `connector_last_error`; `last_error`, `state` and `next` are untouched) and doctor `sync_freshness` (`stoppedConnectorIssues` in `doctor/sync-outcome.ts`).
+- `src/core/persistence/connector-status.ts` — `sources status` views of connector state and Git holds. `gitHoldStatusJson` (#7326) bounds `git_holds` in `--json`: summary by default (`count`, `by_code` with one example each, the first `HELD_STATUS_LIMIT` items, `items_complete`/`items_command`), every item read under `--holds`, or a `pageSortedRows` keyset page by path under `--limit`/`--cursor` (`test/sources-status-holds-bounded-7326.test.ts`, `test/sync-hold-surfaces.test.ts`).
- `src/core/connectors/item-holds.ts` — fix wave 4 connector item holds, shared by Gmail and GitHub on managed and unmanaged brains: `classifyConnectorError` (the one table: source-scoped, rate-limit and item-scoped codes, content vs transient class) and `ItemHoldsRun` (hold after 3 consecutive attempted runs at one upstream version; circuit breaker at 5 attempted items with half transient or 5 and half one code; backoff 1 h/6 h/24 h/daily for 7 days; cap 100, `connector_holds_exhausted`). A run's changes merge only in `finish()`, so mid-run checkpoints carry the holds the run began with and a cursor never passes an item that is not already held. `carryLegacyFailCounts` reads the retired Gmail ledger once.
- `src/core/connectors/item-holds-store.ts` + `connector-hold-session.ts` — reads holds from the cursor state (managed checkpoint row or the unmanaged state file) for `sources status`, doctor `connector_held_items` and `open_loops` completeness; the `connector-hold-retry` request rows and the pending `managed-connector-retry` pointers `sources retry-held` writes; the per-run session that skips held items, publishes holds on a managed abort (`publishHolds`), releases held items' terminal receipts from the automatic retry set and consumes retry-held keys. Git-source holds are not read here: only `sources status` (`persistence/connector-status.ts` `readGitHoldStatuses`, `sources status <id>` filters to one source) and `sources retry-held` (a Git source records a `sync-hold-retry` re-screen request for its held paths; `gbrain sync --retry-held` refuses with that pointer) show them beside connector holds. Writer deactivation and activation never read or block on them.
- `src/core/connectors/connector-text.ts` — #5752 render boundary: prose sanitized with `sanitizeForJsonb` before the no-op screen; identity fields refuse with `invalid_connector_text`.
diff --git a/scripts/module-size-limits.tsv b/scripts/module-size-limits.tsv
index 4809bfce14..0622de1c0a 100644
--- a/scripts/module-size-limits.tsv
+++ b/scripts/module-size-limits.tsv
@@ -30,7 +30,7 @@ src/commands/integrations.ts 1739 ratchet grown v0.46.26.0 megawave (#4039 conne
src/core/minions/handlers/subagent.ts 1925 ratchet merged: master v131 settle rework + dream-wave C5 peel + C6 accounting + C7 lease heartbeats/lost-lease aborts + C9 oneshot dispatch + adversarial fix batches; grown by #4078 subagent-loop capability fix; +6 lines (reasoning-item replay: adaptContentBlocksToChatBlocks handles 'reasoning' blocks); +3 wave G #4514: Anthropic-via-OpenRouter allowed on the subagent loop; +36 lines (code review, same PR): isPromptTooLongError walks a bounded .cause chain so it still matches post-normalizeAIError() wrapping, plus extractPromptTooLongDetail so the dead-lettered job's error carries the matched provider detail instead of the generic normalizeAIError() wrapper text; master integration: harness support: boundary wiring to shared grants, isolated setup, withdrawal and delegated guards; #5105: +13 call-site wiring to shared tool-write-identity helper across fresh and replay dispatch; +7 fix wave 9 lane B #4921: ai.chat.per_turn_timeout_ms read once and passed to the oneshot and gateway-loop paths (resolver lives in minions/handler-timeouts.ts)
src/commands/bootstrap.ts 2147 ratchet grandfathered at merge (grew past the 1500 cap on master); raised for #4066 HOME_WORKSPACE_GUARD_EXEMPT (status/uninstall/harness); +5 for the harnessDetect test seam (bulk lives in core/bootstrap/harness.ts); +23 for the contract subcommand dispatcher glue (#4105 absorb — bulk lives in core/bootstrap/contract.ts); +codex hooks-consent gate + mcp+hooks receipt registration + uninstall arm; +42 ambient-writeback WP8: interview-time SURFACE_MULTIUSER audience apply (pre-init ordering) + applyDeclaredAudienceFromInterview; +3 #4897 harness usage clause documenting --source ID semantics; +5 #5878: --refresh-skills dispatch and usage lines (logic in core/bootstrap/harness-skills.ts); +11 #5488: SUBCOMMAND_HELP harness entry (gate on --help / -h / help) — CLI help line, cannot move; +11 #4618 seat: --seat/--no-seat help lines and the runHooks parse (parse + notes live in core/bootstrap/hooks.ts parseSeatFlags); +13 #4082: runAdoptHooks (the --adopt branch of the hooks subcommand, kept out of runHooks for the function-size ratchet) and its two help lines (adoption logic lives in core/bootstrap/adopt-connection.ts + adopted-connections.ts)
src/core/minions/worker.ts 1794 ratchet grandfathered at merge (grew past the 1500 cap on master, #4170); grown v0.46.11.0 five-issue wave; security: durable queued authority and confined filesystem dispatch; typed readiness, configuration-blocked lifecycle and bounded release; post-validation readiness publication and confirmed isolated-execution stop evidence; latch typed lock-renewal faults before generic retry; +9 Lane D: JobDeferredError routing (deferJob helper); +1 spend authorization: runWithJobSpend import (both handler seams call it in place of the bare handler); +3 watchdog: gracefulShutdown records its reason and launchJob aborts a claim committed before it fired; +5 GBRA-130 A-30: watchdog-attribution import, InFlightJob.shared (interface field), the suspect-alone claim gate and option, and the watchdog settle call in the executeJob catch (logic in minions/watchdog-attribution.ts); +6 GBRA-133 2a.4 sync-queue wake: IdleWaiter import and field, claimStarted before each claim, the idle poll through it, and stop/requestShutdown ending its wait (logic in minions/idle-wait.ts); +1 GBRA-158 #7239: refusal.ts import (a deterministic refusal ends the job at once; classification in minions/refusal.ts); +3 #7242 lane reservation: lanes import and the longJobNames/shortJobReservedSlots defaults (the claim passes claimExclusions; policy in minions/lanes.ts); +2 #7242 terminal hook: onJobSettled default and the settle call (logic in terminal-hook.ts); #7252 x #7249 merge: both sides grew the file, re-summed (1794 measured)
-src/commands/sources.ts 2065 ratchet +5 PR #5955 / fix wave 14 P2.7: sources set-strategy dispatch and help row, the strategy field of sources list --json (body in sources-strategy.ts); +5 #5988: sources status/retry-held help rows describe Git holds (help lines cannot move); +2 #5988: sources status <id> filter and Git held files (view in persistence/connector-status.ts); +5 F0: sources refresh dispatch and help rows (command body in sources-refresh.ts, protocol in persistence/worktree-refresh.ts); +6 fix wave 5 #5409: mirror-readonly/mirror-writable dispatch, help rows and the list --json mirror_read_only field (body in sources-mirror.ts); grown v0.46.22.0 phone wave: github source kind (#4104); +129 v0.47 gmail-loops: google source-kind flags + vault preflight + duplicate-account warn + access-mode validation; +8 set-path dispatch + help rows (#4739 — command body peeled to sources-set-path.ts); +29 #4698 adoption: --calendar-id flag + duplicate-account warn scoped to overlapping services; #5105: trusted writer administration route; company handlers and receipt status wiring; parsing stays in dedicated modules; canonical reconciliation: +5 engine-free sibling-command dispatch and help row, implementation remains in source-reconcile.ts; +4 fix wave 3 lane A: sources status connector recovery state and run counts (view lives in persistence/connector-status.ts); +3 fix wave 4 lane B: sources retry-held dispatch and help row (command body in sources-retry-held.ts) and the connector first-sync note on add; bodies in source-delete.ts and sources-set-path.ts); +4 #5984: sources status shows the managed sync backlog (logic in persistence/sync-drain.ts); v0.60.48.0 merge: #5984 growth re-summed over v0.60.47.0 (2031 measured); +11 W-B4: sources shared-skills dispatch, its --help guard and help rows, and the shared_skills field/lines in sources status (body in sources-shared-skills.ts, view in shared-skills/source-opt-out.ts); +4 #6188: uncommitted legacy fence-repair notices in sources status (logic in fence-repair/uncommitted.ts); +7 #6317: data_moving/movement_state on sources status and its human line (reader in persistence/sync-movement.ts), writer movement help row; +1 GBRA-133: sources reset-upstream help row (body in sources-reset-upstream.ts); fix wave 20 integration: lane 3 (#6827) and master growth compose at 2062 measured; +3 GBRA-150: sources resolve-path dispatch and help rows (body in sources-resolve-path.ts)
+src/commands/sources.ts 2075 ratchet +5 PR #5955 / fix wave 14 P2.7: sources set-strategy dispatch and help row, the strategy field of sources list --json (body in sources-strategy.ts); +5 #5988: sources status/retry-held help rows describe Git holds (help lines cannot move); +2 #5988: sources status <id> filter and Git held files (view in persistence/connector-status.ts); +5 F0: sources refresh dispatch and help rows (command body in sources-refresh.ts, protocol in persistence/worktree-refresh.ts); +6 fix wave 5 #5409: mirror-readonly/mirror-writable dispatch, help rows and the list --json mirror_read_only field (body in sources-mirror.ts); grown v0.46.22.0 phone wave: github source kind (#4104); +129 v0.47 gmail-loops: google source-kind flags + vault preflight + duplicate-account warn + access-mode validation; +8 set-path dispatch + help rows (#4739 — command body peeled to sources-set-path.ts); +29 #4698 adoption: --calendar-id flag + duplicate-account warn scoped to overlapping services; #5105: trusted writer administration route; company handlers and receipt status wiring; parsing stays in dedicated modules; canonical reconciliation: +5 engine-free sibling-command dispatch and help row, implementation remains in source-reconcile.ts; +4 fix wave 3 lane A: sources status connector recovery state and run counts (view lives in persistence/connector-status.ts); +3 fix wave 4 lane B: sources retry-held dispatch and help row (command body in sources-retry-held.ts) and the connector first-sync note on add; bodies in source-delete.ts and sources-set-path.ts); +4 #5984: sources status shows the managed sync backlog (logic in persistence/sync-drain.ts); v0.60.48.0 merge: #5984 growth re-summed over v0.60.47.0 (2031 measured); +11 W-B4: sources shared-skills dispatch, its --help guard and help rows, and the shared_skills field/lines in sources status (body in sources-shared-skills.ts, view in shared-skills/source-opt-out.ts); +4 #6188: uncommitted legacy fence-repair notices in sources status (logic in fence-repair/uncommitted.ts); +7 #6317: data_moving/movement_state on sources status and its human line (reader in persistence/sync-movement.ts), writer movement help row; +1 GBRA-133: sources reset-upstream help row (body in sources-reset-upstream.ts); fix wave 20 integration: lane 3 (#6827) and master growth compose at 2062 measured; +3 GBRA-150: sources resolve-path dispatch and help rows (body in sources-resolve-path.ts); +10 #7326: sources status parses --holds/--limit/--cursor and passes the git_holds listing mode, plus 4 help lines (bounding logic in persistence/connector-status.ts gitHoldStatusJson)
src/core/link-extraction.ts 2421 ratchet grown v0.46.26.0 megawave: link-aware timeline split + delimiter-outside-links (#3957 #4062 #3737); +37 wave-k #3908 reimpl: isCrossSourceLinksEnabled config ladder; +10 wave #4277: parseTimelineEntries skips generated backlink receipts; +17 #4855: latin-fold in normalizeBasename + dir-hint step tries both slug grammars; +17: #4855 Latin stroke-letter fold; +5: #4873 ./-relative markdown links kept as live references; +34 wave review: `../y.md` sibling links resolve on the DB path + folded bare-wikilink grammar (#4873 class); +62 #4977: role-prior suppression in machine-list sections (rolePriorSuppressedRanges, EntityRef.index); +3 composed with #4985 (variation-selector strip) in the same wave; +4 #4995: markdown-link anchor strip + lowercase-candidate rationale comments; +6 pre-landing review: #4977 suppression on code-stripped content + truthful watermark/section-list comments; T2: source-qualified inference and atomic origin-scoped derived links; canonical attendance evidence, source-qualified orientation, strict attendee resolution, and relocated filesystem link scanner (command export preserved); +4: pack-owned fallback and ambiguous attendee guards Display-label attendance exclusion, indexed evidence membership, and bounded strict resolver caching; attendance-boundary review.; complete attendance resolution and fence-safe evidence traversal; frontmatter discovery, canonical basename admission and code-aware attendance comment masking; exclude inline HTML comment spans from admitted attendance ranges; +17 write-path wave: same-name rule for entity fuzzy matches + rename-alias fallback in makeResolver; +1 #5567: materialized marker ends bullet detail; +30 #5749: unique global-basename step before fuzzy and live keyword resolution (ResolveOptions, watermark note); #5765: bold **Attendees:** label accepted + LINK_EXTRACTOR_VERSION_TS bump note; +10 eval-wave N9-2/N9-3/N12-7: pack frontmatter mappings inherit FRONTMATTER_LINK_MAP direction, page-type-bound pack attended follows canonical attendance, LINK_EXTRACTOR_VERSION_TS bump note; +1 #5623: normalizeBasename collapses hyphen runs like slugifySegment (extractor watermark note); +11 #5562: parseTimelineEntries accepts dated ### headings (FS-extractor parity); +3 eval-wave N12-6: Participants accepted as attendance evidence + LINK_EXTRACTOR_VERSION_TS bump note; +22 P5 wanted pages: AuthoredRef on body link candidates; -33 lowered: P5 moved machine-section ranges to core/machine-sections.ts and stated relation types to core/line-grammar.ts; +7 P5: ExtractPageLinksOptions interface + wikilinkAuthoredRef helper (keeps extractPageLinks under the function-size limit); +32 P5: per-edge verb attachment (attachedVerb, VERB_RULES) + joined-as works_at + extractor watermark note; P5 x temporal-edges merge: verb attachment reads the verb at the link's own position in the window (excerptAnchor) and the within-page dedup (now dedupeCandidates) drops a mention of a target the page also links with a typed edge; links joined only by commas/conjunctions share the verb before the first (coordinated); board roles (BOARD_RE, BOARD_AFTER_RE) resolve to invested_in for an investor page and advises otherwise, never works_at; +1 fix wave 11 #6191: imports targetTakesVerb (role-verb target guard lives in link-target-roles.ts); v0.60.105.0 merge: #5984 Phase 5 link preparation (+6) re-summed over wave 11 at 2211; +109 Q2 Track C: stable verb-rule ids, traceLinkType/explainLinkType (reasons for every typing decision), per-occurrence typer hoisted out of extractPageLinks (makeTypeFor); unit logic lives in core/link-typing-units.ts; +25 Q2 Track C: typing-unit verb rules and vetoes in attachedVerb/traceLinkType, validity stints in explainLinkType; +4 U3: board-seat rule split out of INVESTED_RE (same verb and precedence) and investor-prior/link offsets passed to unit vetoes; +11 U2: locateLink shared by attachedVerb and the U2 post-pass in traceLinkType; -11 lowered: Q2 verdict reverted U2 (locateLink and the post-pass); +21 fix wave 13 P4.10 #6266: resolveSameDirSlug + exported resolveMarkdownLinkSlug, shared with the link validator; +41 Wave B PR 2 lane 2e: extractPageLinks split into extractBodyLinks (window-scoped, offset-shifted, pass-tagged candidates) and frontmatterLinks, plus entityRefPasses, candidateKey, rolePriorPhrases and the roleText/regexBudget/window options, so a segmented page streams through the same extractor (window and merge logic in core/page-body/segment-links.ts); +1 at the #6869 gate-ahead merge: the #6803 wave EXTRACTOR_BUMP_NOTES comment composed with lane 2e (2420 + 1)
src/core/embedding-migration.ts 1587 ratchet new row: crossed 1500 in v0.46.25.0 fix waves (#4305 #4306 chunk-model truth helpers); retired provider integration removed; safety wave: canonical projection readiness and fact-aware completion; file configuration publication retains lease-row locks; +8 transactional retained-vector rebuildability checks before destructive migration boundaries; archived eligibility: source-locked reconciliation and live/current smoke revalidation; +2 #5680: authorization_generation field and its carry-forward on same-target re-apply (settle idempotency); +10 #5226: plan carries chunks_to_restamp beside chunks_to_embed; +9 #5088: schema transition defers HNSW builds into the marker (deferred_ann_indexes), carry-forward on re-apply, verify blocks on pending/INVALID ANN indexes (build phase in embedding-ann-build.ts); +10 #5088: dim-pinned tables (query_cache, facts, and any later entry of TEXT_EMBEDDING_DIM_PINNED_TABLES) defer their HNSW through the same worklist (DEFERRED_ANN_TABLES, recordDeferredAnnIndexes); +25 wave 8 lane D1 #5885: takes in the dim-pinned column list, plan (takes_to_embed), status (takes_pending) and completion verify; +17 #5334: smoke check samples one representative chunk per distinct page (bounded index-ordered batch walk, longest chunk re-read under the page lock, title-prefixed bounded query); +1 #5334: the smoke-query length limits are shared with the worst-case budget
src/core/github-source.ts 1530 ratchet new row: crossed the 1500 unlisted cap in v0.46.23.0 review fix wave (scope-state gating, client hardening, symlink containment); merged reliability/shared-skills source integration; managed sweep lease wrapper; fix wave 3 lane A: config parser peeled to github-source-config.ts (-47), +account pin wiring and pinned-installation refresh
diff --git a/src/commands/sources.ts b/src/commands/sources.ts
index 253b404329..6b4ba2b7c0 100644
--- a/src/commands/sources.ts
+++ b/src/commands/sources.ts
@@ -1204,8 +1204,15 @@ async function runFederate(engine: BrainEngine, args: string[], value: boolean):
}
// ── v0.40 sources status (D12) ──────────────────────────────
-async function runStatus(engine: BrainEngine, args: string[]): Promise<void> {
- const json = args.includes('--json'), only = args.find(arg => !arg.startsWith('-'));
+async function runStatus(engine: BrainEngine, rawArgs: string[]): Promise<void> {
+ const { parseListingFlags } = await import('../core/bounded-listing-cli.ts');
+ const { request, rest: args } = parseListingFlags(rawArgs.filter(arg => arg !== '--holds'), 'gbrain sources status <id> --json');
+ const paged = rawArgs.some(arg => /^--(limit|cursor)(=|$)/.test(arg));
+ const json = args.includes('--json'), only = args.find((arg, i) => !arg.startsWith('-') && args[i - 1] !== '--limit');
+ if (request.cursor !== undefined && !only) {
+ throw opError('invalid_params', '--cursor pages the held files of one source.', 'Name the source the cursor came from: gbrain sources status <id> --json --limit <n> --cursor <next_cursor>.');
+ }
+ const holdListing = paged ? { mode: 'page' as const, request } : rawArgs.includes('--holds') || request.limit === null ? { mode: 'all' as const } : { mode: 'summary' as const };
const { loadAllSources } = await import('../core/sources-load.ts');
const { computeAllSourceMetrics } = await import('../core/source-health.ts');
const statusView = await import('../core/persistence/connector-status.ts');
@@ -1262,7 +1269,7 @@ async function runStatus(engine: BrainEngine, args: string[]): Promise<void> {
...(backlog.get(m.source_id) ? { managed_backlog: backlog.get(m.source_id) } : {}),
...(movement.get(m.source_id) ? { data_moving: movement.get(m.source_id)!.data_moving, not_moving_since: movement.get(m.source_id)!.not_moving_since,
movement_state: movement.get(m.source_id)!.movement_state, movement: movement.get(m.source_id) } : {}),
- ...(gitHolds.get(m.source_id) ? { git_holds: gitHolds.get(m.source_id) } : {}), ...(upstream.get(m.source_id) ? { upstream: upstream.get(m.source_id) } : {}),
+ ...(gitHolds.get(m.source_id) ? { git_holds: statusView.gitHoldStatusJson(m.source_id, gitHolds.get(m.source_id)!, holdListing) } : {}), ...(upstream.get(m.source_id) ? { upstream: upstream.get(m.source_id) } : {}),
...(sharedSkills.get(m.source_id) ? { shared_skills: sharedSkills.get(m.source_id) } : {}),
...(uncommitted.get(m.source_id) ? { fence_repairs_uncommitted: uncommitted.get(m.source_id) } : {}), ...(watermarks.get(m.source_id) ? { watermark: watermarks.get(m.source_id) } : {}),
}));
@@ -1969,7 +1976,10 @@ Subcommands:
next command; recent blocked-cursor conversions).
<id> filters to that source.
--json emits {schema_version:1, ...} on
- stdout for monitoring pipelines.
+ stdout for monitoring pipelines; git_holds
+ lists counts per code with one example and
+ 10 items (--holds: every item; --limit <n>
+ [--cursor <c>]: one page, by path).
archived [--json] List soft-deleted sources and their expiry.
purge [<id>] [--confirm-destructive]
Permanently delete archived sources.
diff --git a/src/core/behavior-change-notice.ts b/src/core/behavior-change-notice.ts
index 2741803cc7..1a1f136214 100644
--- a/src/core/behavior-change-notice.ts
+++ b/src/core/behavior-change-notice.ts
@@ -1124,6 +1124,7 @@ export const BEHAVIOR_CHANGES: ReadonlyArray<{ since: string; text: ChangeText;
{ 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. `gbrain anomalies --json --all` lists every slug on a local brain.' },
{ 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.' },
+ { since: 'TBD', text: '`gbrain sources status --json` no longer prints every held file of a source by default: `git_holds` now carries `count`, `by_code` (each hold code with its count and one example item, whose `fix` applies to the rest), and the first 10 items with `items_complete: false` and an `items_command`. `--holds` lists every held file read, as before, and `--limit <n> [--cursor <c>]` pages them by path (the cursor needs the source id). The text output is unchanged.' },
];
/** The newest disclosed change's release: the notice id moves only when a release adds rows. */
diff --git a/src/core/persistence/connector-status.ts b/src/core/persistence/connector-status.ts
index 43a4e9952b..6eea7b274c 100644
--- a/src/core/persistence/connector-status.ts
+++ b/src/core/persistence/connector-status.ts
@@ -19,6 +19,7 @@ import { managedBrain, readAllSourceHolds } from '../connectors/item-holds-store
import type { ItemHoldRecord } from '../connectors/item-holds.ts';
import { fenceAutoRepairFor, gitHoldItem, readGitHoldListing, readSyncConversions, readSyncHoldPolicy, type GitHoldItem, type SyncConversion } from './sync-holds.ts';
import { holdLine } from '../../commands/sync-diagnostics.ts';
+import { pageSortedRows, type ListingRequest } from '../bounded-listing.ts';
/** Fix wave 4: `sources status` lists this many held items per source, then "+N more". */
export const HELD_STATUS_LIMIT = 10;
@@ -178,6 +179,39 @@ export async function readGitHoldStatuses(engine: Pick<BrainEngine, 'executeRaw'
return out;
}
+/**
+ * #7326: what `sources status --json` lists of a source's held files. `summary` (the default): the count, the
+ * counts per code with one example each, and the first HELD_STATUS_LIMIT items; `all` (`--holds`): every item read;
+ * `page` (`--limit` / `--cursor`): one keyset page of items ordered by path.
+ */
+export type GitHoldListing = { mode: 'summary' } | { mode: 'all' } | { mode: 'page'; request: ListingRequest };
+
+/** Held items per code, largest first, each with its first item as the example (its fix and docs apply to the rest). */
+function holdsByCode(items: readonly GitHoldItem[]): Array<{ code: string; count: number; example: GitHoldItem }> {
+ const groups = new Map<string, { code: string; count: number; example: GitHoldItem }>();
+ for (const item of items) {
+ const group = groups.get(item.code);
+ if (group) group.count++;
+ else groups.set(item.code, { code: item.code, count: 1, example: item });
+ }
+ return [...groups.values()].sort((a, b) => b.count - a.count || (a.code < b.code ? -1 : 1));
+}
+
+/** A source's `git_holds` for `sources status --json`, summary first and items last, bounded by `listing`. */
+export function gitHoldStatusJson(sourceId: string, status: GitHoldStatus, listing: GitHoldListing) {
+ const { items, ...rest } = status;
+ const head = { ...rest, by_code: holdsByCode(items) };
+ if (listing.mode === 'all') return { ...head, items };
+ if (listing.mode === 'page') {
+ const page = pageSortedRows(items, item => [item.path], listing.request, `sources_status_git_holds:${sourceId}`);
+ const next = page.next_cursor === null ? null
+ : ['gbrain', 'sources', 'status', sourceId, '--json', '--limit', String(page.limit), '--cursor', page.next_cursor];
+ return { ...head, returned: page.returned, limit: page.limit, complete: page.complete, next_cursor: page.next_cursor, next_command: next, items: page.rows };
+ }
+ if (items.length <= HELD_STATUS_LIMIT) return { ...head, items };
+ return { ...head, items_complete: false, items_command: ['gbrain', 'sources', 'status', sourceId, '--json', '--holds'], items: items.slice(0, HELD_STATUS_LIMIT) };
+}
+
/** Held files: up to HELD_STATUS_LIMIT per source with each one's next step, then the re-screen and retry commands; then recent conversions. */
export function gitHoldStatusLines(sourceId: string, status: GitHoldStatus): string[] {
const lines: string[] = [];
diff --git a/test/sources-status-holds-bounded-7326.test.ts b/test/sources-status-holds-bounded-7326.test.ts
new file mode 100644
index 0000000000..3acf08177e
--- /dev/null
+++ b/test/sources-status-holds-bounded-7326.test.ts
@@ -0,0 +1,55 @@
+import { describe, expect, test } from 'bun:test';
+import { gitHoldStatusJson, HELD_STATUS_LIMIT, type GitHoldStatus } from '../src/core/persistence/connector-status.ts';
+import type { GitHoldItem } from '../src/core/persistence/sync-holds.ts';
+
+const item = (i: number, code: string): GitHoldItem => ({
+ path: `notes/file-${String(i).padStart(4, '0')}.md`, code: code as GitHoldItem['code'], message: 'held: a location-only message '.repeat(20),
+ slug: null, stale: false, held_since: '2026-01-01T00:00:00Z', docs: 'docs/guides/write-refusals.md',
+ fix: { argv: ['gbrain', 'repair', 'frontmatter', '--source', 'source-a'], why: 'Previews the repair; read-only. '.repeat(10) } as unknown as GitHoldItem['fix'],
+});
+
+const holds = (n: number): GitHoldStatus => ({
+ count: n,
+ items: Array.from({ length: n }, (_, i) => item(n - i, i % 3 === 0 ? 'invalid_fence' : 'invalid_frontmatter')),
+ sync_argv: ['gbrain', 'sync', '--source', 'source-a', '--no-pull'],
+});
+
+describe('#7326: sources status --json bounds git_holds', () => {
+ test('the default lists counts per code with one example and at most HELD_STATUS_LIMIT items', () => {
+ const out = gitHoldStatusJson('source-a', holds(500), { mode: 'summary' });
+ expect(out.count).toBe(500);
+ expect(out.items).toHaveLength(HELD_STATUS_LIMIT);
+ expect(out).toMatchObject({ items_complete: false, items_command: ['gbrain', 'sources', 'status', 'source-a', '--json', '--holds'] });
+ expect(out.by_code.map(g => [g.code, g.count])).toEqual([['invalid_frontmatter', 333], ['invalid_fence', 167]]);
+ expect(out.by_code[0]!.example.fix).toBeDefined();
+ expect(Object.keys(out).at(-1)).toBe('items');
+ const full = JSON.stringify(gitHoldStatusJson('source-a', holds(500), { mode: 'all' }));
+ expect(JSON.stringify(out).length).toBeLessThan(full.length / 10);
+ });
+
+ test('a source with few holds keeps every item and no paging fields', () => {
+ const out = gitHoldStatusJson('source-a', holds(3), { mode: 'summary' });
+ expect(out.items).toHaveLength(3);
+ expect(out).not.toHaveProperty('items_complete');
+ expect(out).not.toHaveProperty('items_command');
+ });
+
+ test('--holds lists every item read', () => {
+ expect(gitHoldStatusJson('source-a', holds(500), { mode: 'all' }).items).toHaveLength(500);
+ });
+
+ test('--limit / --cursor page the items by path without skipping or repeating', () => {
+ const status = holds(25);
+ const seen: string[] = [];
+ let cursor: string | undefined;
+ for (;;) {
+ const page = gitHoldStatusJson('source-a', status, { mode: 'page', request: { limit: 10, ...(cursor ? { cursor } : {}) } }) as ReturnType<typeof gitHoldStatusJson> & { next_cursor: string | null; next_command: string[] | null };
+ seen.push(...page.items.map(i => i.path));
+ if (!page.next_cursor) break;
+ expect(page.next_command).toEqual(['gbrain', 'sources', 'status', 'source-a', '--json', '--limit', '10', '--cursor', page.next_cursor]);
+ cursor = page.next_cursor;
+ }
+ expect(seen).toEqual(status.items.map(i => i.path).sort());
+ expect(() => gitHoldStatusJson('source-b', status, { mode: 'page', request: { limit: 10, cursor } })).toThrow();
+ });
+});
diff --git a/test/sync-hold-surfaces.test.ts b/test/sync-hold-surfaces.test.ts
index d9772f8e0a..e82adbbde3 100644
--- a/test/sync-hold-surfaces.test.ts
+++ b/test/sync-hold-surfaces.test.ts
@@ -138,6 +138,19 @@ describe('sources status and retry-held on Git sources', () => {
});
});
+ test('#7326: sources status --limit / --cursor page the held files of one source by path; --cursor needs the source and --limit is never read as a source id', async () => {
+ const first = JSON.parse(await captured(() => runSources(engine, ['status', 'notes-git', '--json', '--limit', '1']))).sources[0].git_holds;
+ expect(first).toMatchObject({ count: 2, returned: 1, limit: 1, complete: false });
+ expect(first.by_code.map((group: { code: string }) => group.code).sort()).toEqual(['file_too_large', 'invalid_frontmatter']);
+ expect(first.next_command).toEqual(['gbrain', 'sources', 'status', 'notes-git', '--json', '--limit', '1', '--cursor', first.next_cursor]);
+ const second = JSON.parse(await captured(() => runSources(engine, ['status', 'notes-git', '--json', '--limit', '1', '--cursor', first.next_cursor]))).sources[0].git_holds;
+ expect(second).toMatchObject({ returned: 1, complete: true, next_cursor: null });
+ expect([...first.items, ...second.items].map((item: { path: string }) => item.path)).toEqual(['notes/huge.md', 'notes/stale.md']);
+ const unnamed = JSON.parse(await captured(() => runSources(engine, ['status', '--json', '--limit', '5'])));
+ expect(unnamed.sources.find((s: { source_id: string }) => s.source_id === 'notes-git').git_holds.returned).toBe(2);
+ await expect(runSources(engine, ['status', '--json', '--cursor', first.next_cursor])).rejects.toThrow(/one source/);
+ });
+
test('sources status <unknown id> refuses with not_found and the list command', async () => {
await expect(runSources(engine, ['status', 'missing-src'])).rejects.toMatchObject({ code: 'not_found',
fix: { argv: ['gbrain', 'sources', 'list', '--json'] } });