Skip to content

Garry's Opinionated OpenClaw/Hermes Agent Brain

TypeScript

chore(listing): copy the bounded-listing helpers from GBRA-151 (#7246) byte for byte

garrytanb190238e3ceb
diff --git a/docs/architecture/key-files/core-utilities-2.md b/docs/architecture/key-files/core-utilities-2.md
index 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/src/core/bounded-listing-cli.ts b/src/core/bounded-listing-cli.ts
new file mode 100644
index 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.ts
new file mode 100644
index 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 };
+}