Skip to content

Garry's Opinionated OpenClaw/Hermes Agent Brain

TypeScript

fix(repair): a held file-drift preview is one bounded window with stderr progress and a resumable --cursor (GBRA-133)

garrytan15cfb32caca8
diff --git a/docs/guides/repair.md b/docs/guides/repair.md
index e5ce5e24b2..74598f9389 100644
--- a/docs/guides/repair.md
+++ b/docs/guides/repair.md
@@ -2135,6 +2135,24 @@ the two `--prefer` values do opposite things in each state.
| `purged_differs` | Removes the file. | Imports the file as a new page. |
| `file_gone` | Recreates the file from the page. | Soft-deletes the page (the mass-delete valve applies). |
+A held preview covers one window of the selected holds, in held-path order:
+at most 200 pages, and it starts no page after 60 seconds of work (each page
+reads the database a few dozen times, so a large held set against a remote
+database takes minutes per hundred pages). It reports each page on stderr as
+it goes. The hash and the printed apply command cover only that window. A
+partial window lists `after_window` in its residuals and prints the next
+preview command with `--cursor <next_cursor>` (JSON: `details.window`):
+
+```bash
+gbrain repair file-drift --source <id> --held --side deleted --state file_gone --prefer database # window 1
+gbrain repair file-drift --source <id> --held --side deleted --state file_gone --prefer database --apply --expect <hash>
+gbrain repair file-drift --source <id> --held --side deleted --state file_gone --cursor <next_cursor> --prefer database # window 2
+```
+
+Apply each window (or decide not to), then preview the next one. Pages the
+apply resolved leave the held set, so rerunning without `--cursor` also
+starts from the first page still held.
+
A `file_gone` hold whose `meta.reason` is `never_committed` or `ignored`
(#7130) is a page whose file is missing although Git never committed it: the
sync could not tell a deletion from a file that never reached the repository,
diff --git a/src/commands/repair.ts b/src/commands/repair.ts
index 30fb3de4fe..268b3ad0b4 100644
--- a/src/commands/repair.ts
+++ b/src/commands/repair.ts
@@ -31,6 +31,8 @@ import { AUTO_REPAIR_REGISTRY, EXPLICIT_REPAIR_REGISTRY, LLM_REPAIR_REGISTRY, PR
import { CONTENT_REPAIR_KINDS } from '../core/repair/content-lane.ts';
import { kindErrorResult } from '../core/remediation/repairs.ts';
import { ItemRun } from '../core/item-failure.ts';
+import { createProgress } from '../core/progress.ts';
+import { cliOptsToProgressOptions, getCliOptions } from '../core/cli-options.ts';
/** The content-repair lane's command word (#6377): parsed like a kind, dispatched to repair-content.ts, never a RepairKind. */
export const CONTENT_LANE = 'content';
@@ -119,7 +121,11 @@ Options:
because --prefer file and --prefer database do opposite things in each state (tombstone_edited: restore
and import, or keep the deletion and remove the file; purged_differs: import as a new page, or remove the
file; file_gone: soft-delete the page, or recreate the file). Held pages of several sides or states are
- refused without --side; the preview prints each page's action.
+ refused without --side; the preview prints each page's action. One preview covers a window of at most
+ 200 held pages (or 60 s of work) in held-path order, reports progress on stderr, and its hash covers only
+ that window; a partial window prints next_cursor and the next preview command.
+ --cursor <next_cursor>
+ file-drift --held: continue after the window the previous preview covered (its next_cursor).
--since <ISO-8601|7d>
file-drift: keep only pages whose newest drift conflict is at or after the instant (with --all-drifted, or
the bare survey). An age (7d, 12h) is resolved once to a concrete instant; the preview, its hash and the
@@ -154,19 +160,19 @@ A sources add --url clone whose pull stops at pull_blocked_local_changes: docs/g
Renames whose identity sync did not keep (rename-identity): docs/guides/live-sync.md#renaming-a-page.`;
const BOOLEAN_FLAGS = new Set(['--apply', '--all', '--json', '--no-embed', '--include-ambiguous', '--diff', '--yes', '--no-llm', '--all-drifted', '--include-failures', '--force', '--close', '--held']);
-const VALUE_FLAGS = new Set(['--source', '--limit', '--expect', '--only', '--skip', '--slug', '--max-usd', '--prefer', '--request', '--class', '--since', '--keep', '--request-id', '--older-than', '--from', '--side', '--state', '--after']);
+const VALUE_FLAGS = new Set(['--source', '--limit', '--expect', '--only', '--skip', '--slug', '--max-usd', '--prefer', '--request', '--class', '--since', '--keep', '--request-id', '--older-than', '--from', '--side', '--state', '--after', '--cursor']);
/** Flags only some kinds accept, with the kinds that do. */
const KIND_FLAGS: Record<string, readonly string[]> = {
'--only': ['frontmatter', 'fences', 'slug-conflicts', 'file-drift', CONTENT_LANE], '--skip': ['frontmatter', 'fences', 'slug-conflicts', 'file-drift', CONTENT_LANE], '--diff': ['frontmatter', 'fences', 'slug-conflicts', CONTENT_LANE], '--yes': ['frontmatter', 'conversation-labels', 'stuck-recovery', 'ghost-pages', 'legacy-twins', 'rename-identity', 'url-clone-fences'],
'--slug': ['fences', 'file-drift', 'rename-identity', 'overwritten-edits', 'origin-twins'], '--from': ['rename-identity'], '--close': ['rename-identity'], '--prefer': ['file-drift'], '--request': ['file-drift'], '--all-drifted': ['file-drift'], '--class': ['file-drift'], '--since': ['file-drift'],
- '--held': ['file-drift'], '--side': ['file-drift'], '--state': ['file-drift'],
+ '--held': ['file-drift'], '--side': ['file-drift'], '--state': ['file-drift'], '--cursor': ['file-drift'],
'--keep': ['stuck-recovery'], '--request-id': ['stuck-recovery'],
'--older-than': ['receipt-compaction'], '--include-failures': ['receipt-compaction'], '--force': ['receipt-compaction'],
'--after': ['uncommitted-deletions'],
};
const VALUE_EXAMPLES: Record<string, string> = { '--source': 'default', '--limit': '50', '--expect': 'PLAN_HASH', '--only': 'notes/a.md', '--skip': 'notes/a.md',
'--slug': 'notes/a', '--max-usd': '0.50', '--prefer': 'file', '--request': 'REQUEST_UUID', '--class': 'review_required', '--since': '7d', '--side': 'deleted', '--state': 'tombstone_edited', '--keep': 'prior',
- '--request-id': '123e4567-e89b-42d3-a456-426614174000', '--older-than': '30d', '--from': 'notes/old', '--after': '1200' };
+ '--request-id': '123e4567-e89b-42d3-a456-426614174000', '--older-than': '30d', '--from': 'notes/old', '--after': '1200', '--cursor': 'NEXT_CURSOR' };
/** A usage refusal whose fix is the read-only preview (gbrain repair without --apply writes nothing). */
const invalid = (message: string, suggestion: string, preview: string[] = ['gbrain', 'repair', '--json']) => opError('invalid_params', message, suggestion,
{ fix: readFix('Previews the repair; without --apply it writes nothing.', { argv: preview }) });
@@ -174,7 +180,7 @@ const invalid = (message: string, suggestion: string, preview: string[] = ['gbra
interface RepairArgs { kind?: string; apply: boolean; all: boolean; json: boolean; noEmbed: boolean; includeAmbiguous: boolean; diff: boolean; yes: boolean;
noLlm: boolean; source?: string; limit?: string; expect?: string; maxUsd?: number; only: string[]; skip: string[]; slugs: string[];
allDrifted: boolean; prefer?: 'file' | 'database'; requests: string[]; driftClass?: string; since?: string;
- held: boolean; side?: string; state?: string;
+ held: boolean; side?: string; state?: string; cursor?: string;
keep?: 'prior' | 'disk' | 'withdrawn'; requestId?: string; olderThan?: string; includeFailures: boolean; force: boolean; from?: string; close: boolean; afterPage?: number }
/** `--max-usd` on a kind that never calls a paid model: the cap belongs to the doctor remediation run. */
@@ -261,6 +267,7 @@ export function parseRepairArgs(args: string[]): RepairArgs {
else if (flag === '--class') parsed.driftClass = value;
else if (flag === '--side') parsed.side = value;
else if (flag === '--state') parsed.state = value;
+ else if (flag === '--cursor') parsed.cursor = value;
else if (flag === '--since') {
try { parsed.since = parseSince(value, '--since'); } catch (error) {
throw invalid((error as Error).message, 'Pass an ISO-8601 instant (2026-10-01T00:00:00Z) or an age (7d, 12h); the preview prints the concrete instant it selected.', ['gbrain', 'repair', 'file-drift', ...(parsed.source ? ['--source', parsed.source] : []), '--json']);
@@ -366,7 +373,7 @@ export function renderRepairResult(result: RepairResult, opts: { diff: boolean }
export async function runRepairCommand(engine: BrainEngine, args: string[]): Promise<void> {
if (args.includes('--help') || args.includes('-h')) { console.log(REPAIR_HELP); return; }
const { kind, apply, all, json, noEmbed, includeAmbiguous, source, expect, only, skip, slugs, diff, noLlm, maxUsd, limit: limitText,
- prefer, requests, allDrifted, driftClass, since, held, side, state, keep, requestId, olderThan, includeFailures, force, from, close, afterPage } = parseRepairArgs(args);
+ prefer, requests, allDrifted, driftClass, since, held, side, state, cursor, keep, requestId, olderThan, includeFailures, force, from, close, afterPage } = parseRepairArgs(args);
const limit = limitText === undefined ? undefined : Number(limitText);
if (limit !== undefined && (!Number.isSafeInteger(limit) || limit < 1)) throw invalid('--limit must be a positive integer.', 'Pass --limit as a positive whole number, e.g. --limit 50, or omit it to repair every item.');
// #6712 PR 2: a repair apply is a soak intervention; a file-drift apply is a content decision (soak-counters.ts).
@@ -408,7 +415,8 @@ export async function runRepairCommand(engine: BrainEngine, args: string[]): Pro
const results = await runRepairKinds(kinds, scope, { apply, source, noEmbed, named: kind !== undefined }, k => runner.run(k, scope, { limit, sourceFlag: source, explicit: k === kind, expect, includeAmbiguous,
...(k === kind && KIND_FLAGS['--only']!.includes(k) ? { only, skip } : {}), ...(k === kind && slugs.length ? { slugs } : {}),
...(k === kind && noLlm ? { noLlm } : {}), ...(k === kind && maxUsd !== undefined ? { maxLlmUsd: maxUsd } : {}),
- ...(k === kind && k === 'file-drift' ? { prefer, requests, allDrifted, driftClass, since, ...(held ? { held } : {}), ...(side ? { side } : {}), ...(state ? { state } : {}) } : {}),
+ ...(k === kind && k === 'file-drift' ? { prefer, requests, allDrifted, driftClass, since, ...(held ? { held } : {}), ...(side ? { side } : {}), ...(state ? { state } : {}), ...(cursor ? { cursor } : {}),
+ ...(apply ? {} : { progress: createProgress(cliOptsToProgressOptions(getCliOptions())) }) } : {}),
...(k === kind && keep ? { keep } : {}), ...(k === kind && requestId ? { requestId } : {}),
...(k === kind && k === 'receipt-compaction' ? { olderThan, includeFailures, force } : {}),
...(k === kind && k === 'rename-identity' ? { from, close } : {}), ...(k === kind && afterPage !== undefined ? { afterPage } : {}) }));
diff --git a/src/core/behavior-change-notice.ts b/src/core/behavior-change-notice.ts
index d94e084dae..a521597ebd 100644
--- a/src/core/behavior-change-notice.ts
+++ b/src/core/behavior-change-notice.ts
@@ -1073,6 +1073,8 @@ export const BEHAVIOR_CHANGES: ReadonlyArray<{ since: string; text: ChangeText;
{ since: '0.60.347.0', text: 'After a model or dimension swap, `gbrain embed --stale`, the embed backfill and `gbrain migrate embeddings` now mark old-model chunks for re-embedding in windows of 1,000 pages (all committed together) instead of one statement over the whole brain, which a large brain cancelled at the statement timeout on every run. The drift check before the embedder probe is one page-first lookup instead of two counts over every chunk, so a count that timed out can no longer skip the swap silently; the "embedder probe failed" warning no longer names a chunk count.' },
// #7211 (GBRA-145). `since` is restamped at the merge slot.
{ since: '0.60.347.0', text: '`gbrain embed --facts` no longer fails a whole batch, and every later run, on one fact longer than the embedding input limit: that fact is skipped (never truncated), keeps its text and stays stale, and the result reports it (`refused_oversized`, `refused_samples` with fact ids, `refused_fix`) without counting it in `remaining` or against `--max-facts`. Doctor `fact_take_vectors` adds `facts.oversized`, and `gbrain embed --held` lists them. Shorten or split the fact, or withdraw it with `gbrain forget <fact-id>`, and the next run embeds it once it fits.' },
+ // GBRA-133 (held file-drift preview windows). `since` is stamped at the merge slot.
+ { since: 'TBD', text: '`gbrain repair file-drift --held` previews one window of the selected holds at a time, in held-path order: at most 200 pages, starting no page after 60 seconds of work, with each page reported on stderr. The hash and apply command cover only that window; a partial window prints `next_cursor` and the next preview command (`--cursor <next_cursor>`). Before, the preview prepared every held page (up to 1,000, silently dropping the rest) before printing anything, so a large held set against a remote database printed nothing for an hour.' },
];
/** The newest disclosed change's release: the notice id moves only when a release adds rows. */
diff --git a/src/core/cli-flag-registry.generated.ts b/src/core/cli-flag-registry.generated.ts
index 61585da64f..ac11a53082 100644
--- a/src/core/cli-flag-registry.generated.ts
+++ b/src/core/cli-flag-registry.generated.ts
@@ -103,13 +103,13 @@ export const CLI_FLAG_REGISTRY: Record<string, readonly string[]> = {
'questions': ['--brain', '--defer', '--entity', '--fail-fast', '--full', '--help', '--id', '--include-archived', '--json', '--prefix', '--probe', '--publish', '--source', '--tools-json', '--wait-ms', '--yes'],
'recall': ['--accept-pending', '--access', '--add', '--all', '--all-subjects', '--allowed-operations', '--as-context', '--asof', '--background', '--body', '--bound-slug-prefixes', '--brain', '--budget-policy', '--budget-tokens', '--client', '--cursor', '--date', '--dated-since', '--days', '--entities', '--explain', '--federated-read', '--follow', '--from-index', '--full', '--fuzzy', '--grep', '--group-by', '--help', '--http', '--id', '--include-deleted', '--include-expired', '--json', '--kind', '--limit', '--match', '--max-usd', '--mcp-only', '--model', '--multimodal', '--no-accept-pending', '--no-autopilot-install', '--page', '--params', '--path', '--pending', '--phase', '--prefer', '--progress-interval', '--progress-json', '--purge', '--query', '--question', '--quiet', '--reason', '--recent', '--refresh-operations', '--request-id', '--rollup', '--row', '--scopes', '--session', '--session-id', '--since', '--since-last-run', '--slugs', '--source', '--source-id', '--sources', '--stale', '--status', '--supersessions', '--surface', '--timeout', '--timings', '--to', '--today', '--updated-after', '--url', '--vacuum', '--wait', '--watch', '--yes'],
'reconcile-links': ['--accept-pending', '--background', '--body', '--brain', '--dry-run', '--explain', '--follow', '--help', '--json', '--no-accept-pending', '--progress-interval', '--progress-json', '--quiet', '--source', '--timeout', '--timings', '--wait'],
- 'reindex': ['--accept-pending', '--admin-intent', '--aliases', '--all-drifted', '--apply', '--background', '--body', '--brain', '--class', '--close', '--concurrency', '--confirm-relocated-root', '--cost-estimate', '--dim', '--dry-run', '--embedding-dimensions', '--embedding-model', '--expect', '--expected-epoch', '--expected-state', '--explain', '--follow', '--force', '--force-rechunk', '--from', '--held', '--help', '--include-ambiguous', '--json', '--keep', '--limit', '--manifest', '--markdown', '--max-cost', '--max-runtime', '--max-usd', '--multimodal', '--no-accept-pending', '--no-embed', '--no-embedding', '--no-llm', '--only', '--oversized', '--path', '--plan', '--prefer', '--progress-interval', '--progress-json', '--quiet', '--repo', '--request', '--request-id', '--self-transfer', '--side', '--since', '--skip', '--slug', '--source', '--stale', '--state', '--status', '--supabase', '--timeout', '--timings', '--to', '--type', '--vectors', '--wait', '--workers', '--yes'],
+ 'reindex': ['--accept-pending', '--admin-intent', '--aliases', '--all-drifted', '--apply', '--background', '--body', '--brain', '--class', '--close', '--concurrency', '--confirm-relocated-root', '--cost-estimate', '--cursor', '--dim', '--dry-run', '--embedding-dimensions', '--embedding-model', '--expect', '--expected-epoch', '--expected-state', '--explain', '--follow', '--force', '--force-rechunk', '--from', '--held', '--help', '--include-ambiguous', '--json', '--keep', '--limit', '--manifest', '--markdown', '--max-cost', '--max-runtime', '--max-usd', '--multimodal', '--no-accept-pending', '--no-embed', '--no-embedding', '--no-llm', '--only', '--oversized', '--path', '--plan', '--prefer', '--progress-interval', '--progress-json', '--quiet', '--repo', '--request', '--request-id', '--self-transfer', '--side', '--since', '--skip', '--slug', '--source', '--stale', '--state', '--status', '--supabase', '--timeout', '--timings', '--to', '--type', '--vectors', '--wait', '--workers', '--yes'],
'reindex-code': ['--accept-pending', '--apply', '--background', '--brain', '--break-lock', '--client', '--concurrency', '--db-url', '--dry-run', '--embedding-dimensions', '--embedding-model', '--expect', '--explain', '--follow', '--force', '--help', '--http', '--id', '--json', '--legacy-lock', '--max-cost', '--max-cost-usd', '--max-runtime', '--max-usd', '--no-accept-pending', '--no-embed', '--non-interactive', '--only', '--path', '--probe', '--progress-interval', '--progress-json', '--quiet', '--scopes', '--source', '--status', '--timeout', '--timings', '--trust', '--wait', '--workers', '--yes'],
'reindex-frontmatter': ['--apply', '--brain', '--concurrency', '--dry-run', '--expect', '--force', '--help', '--json', '--max-cost', '--max-usd', '--non-interactive', '--slug-prefix', '--source', '--trust', '--workers', '--yes'],
'reindex-search-vector': ['--accept-pending', '--background', '--brain', '--dry-run', '--explain', '--follow', '--help', '--json', '--no-accept-pending', '--progress-interval', '--progress-json', '--quiet', '--resume', '--source', '--timeout', '--timings', '--wait', '--yes'],
'reinit-pglite': ['--abbrev-ref', '--acknowledge-managed', '--all', '--allow-create-db', '--allow-docker', '--allow-empty', '--apply', '--body', '--brain', '--break-lock', '--cached', '--chat-model', '--check', '--concurrency', '--confirm-destructive', '--content-root', '--db-only', '--detail', '--diff-filter', '--dim', '--embedding-dimensions', '--embedding-model', '--empty', '--exclude', '--exclude-standard', '--expansion-model', '--expect', '--filters', '--fix', '--force', '--force-break-lock', '--format', '--full', '--full-history', '--git', '--grant-types', '--hard-deadline', '--help', '--http', '--include-gitignored', '--include-hidden', '--interval', '--is-ancestor', '--is-shallow-repository', '--issuer-url', '--json', '--key', '--lanes', '--local-postgres', '--max-age', '--max-cost', '--max-sources', '--max-usd', '--mcp-only', '--mcp-url', '--migrate-only', '--missing-path', '--model', '--name-only', '--no-auto-embed', '--no-bulk', '--no-delegate', '--no-embed', '--no-embedding', '--no-extract', '--no-git', '--no-gpg-sign', '--no-hard-deadline', '--no-lanes', '--no-llm', '--no-migrate', '--no-pull', '--no-renames', '--no-repair', '--no-schema-pack', '--no-sync', '--no-verify', '--non-interactive', '--oauth-client-id', '--oauth-client-secret', '--others', '--parallel', '--path', '--pglite', '--plan', '--prefer', '--prefer-postgres', '--preview', '--priority', '--provenance', '--query', '--quiet', '--redact-paths', '--repo', '--reset-checkpoint', '--retry-failed', '--retry-held', '--schema-pack', '--scopes', '--search-mode', '--serial', '--show-toplevel', '--skip-embed-check', '--skip-failed', '--slugs', '--source', '--source-id', '--src-subpath', '--stale', '--status', '--strategy', '--supabase', '--surface', '--timeout', '--to', '--trust', '--url', '--verify', '--version', '--watch', '--workers', '--working-tree', '--yes'],
'remote': ['--brain', '--help', '--json', '--mcp-only', '--only', '--remediation-plan', '--request-id', '--scopes', '--source', '--timeout'],
- 'repair': ['--acknowledge-managed', '--after', '--all', '--all-drifted', '--apply', '--brain', '--break-lock', '--class', '--client', '--close', '--diff', '--expect', '--ff-only', '--force', '--force-break-lock', '--from', '--full', '--held', '--help', '--id', '--include-ambiguous', '--include-failures', '--include-repairs', '--json', '--keep', '--limit', '--max-cost', '--max-cost-usd', '--max-usd', '--no-delegate', '--no-embed', '--no-llm', '--older-than', '--only', '--prefer', '--probe', '--remediate', '--remediation-plan', '--request', '--request-id', '--reset-checkpoint', '--retry-failed', '--scopes', '--side', '--since', '--skip', '--skip-failed', '--slug', '--slugs', '--source', '--stale', '--state', '--url', '--yes'],
+ 'repair': ['--accept-pending', '--acknowledge-managed', '--after', '--all', '--all-drifted', '--apply', '--background', '--brain', '--break-lock', '--class', '--client', '--close', '--cursor', '--diff', '--expect', '--explain', '--ff-only', '--follow', '--force', '--force-break-lock', '--from', '--full', '--held', '--help', '--id', '--include-ambiguous', '--include-failures', '--include-repairs', '--json', '--keep', '--limit', '--max-cost', '--max-cost-usd', '--max-usd', '--no-accept-pending', '--no-delegate', '--no-embed', '--no-llm', '--older-than', '--only', '--prefer', '--probe', '--progress-interval', '--progress-json', '--quiet', '--remediate', '--remediation-plan', '--request', '--request-id', '--reset-checkpoint', '--retry-failed', '--scopes', '--side', '--since', '--skip', '--skip-failed', '--slug', '--slugs', '--source', '--stale', '--state', '--timeout', '--timings', '--url', '--wait', '--yes'],
'repair-jsonb': ['--accept-pending', '--background', '--brain', '--dry-run', '--explain', '--follow', '--help', '--json', '--no-accept-pending', '--probe', '--progress-interval', '--progress-json', '--quiet', '--source', '--supabase', '--timeout', '--timings', '--url', '--wait'],
'report': ['--brain', '--content', '--dir', '--help', '--json', '--source', '--title', '--type'],
'repos': ['--abandon', '--abbrev-ref', '--abort', '--accept-suggested', '--access', '--account', '--add', '--admin-intent', '--adopt-columns', '--adopt-permissions', '--adopt-slug-path', '--after', '--all', '--all-new', '--allow-unverified-remote', '--allowed-operations', '--app-id', '--app-install', '--app-pem', '--apply', '--audit', '--auto-additive', '--autostash', '--backups', '--batch-check', '--before', '--bound-brain', '--bound-max-concurrent', '--bound-slug-prefixes', '--bound-source', '--bound-tools', '--brain', '--branch', '--break-lock', '--budget-usd-per-day', '--cached', '--calendar-id', '--category', '--classify', '--cleanup-dead-local-locks', '--clear', '--client', '--clone-dir', '--code', '--confirm-destructive', '--confirm-quiesced', '--confirm-relocated-root', '--conflicts', '--contacts-dir', '--count', '--days', '--decisions', '--delegated-namespace', '--delegated-slug-prefixes', '--depth', '--detect', '--diff-filter', '--dir', '--disable', '--dry-run', '--enable', '--error-unmatch', '--exclude', '--expect-local', '--expect-remote', '--expect-upstream', '--expected-epoch', '--expected-incarnation', '--expected-state', '--federated', '--federated-read', '--fetch-timeout-ms', '--ff-only', '--file', '--fix', '--force', '--format', '--from', '--full', '--future-days', '--get', '--git-dir', '--git-path', '--github-repo', '--grant-types', '--group-by', '--hard', '--help', '--history-days', '--http', '--id', '--if-version', '--include', '--include-warns', '--is-ancestor', '--is-inside-work-tree', '--json', '--keep', '--keep-storage', '--kind', '--lanes', '--limit', '--local', '--local-env-vars', '--loops-exclude-labels', '--manifest', '--max-cost-usd', '--message', '--migrate-legacy', '--migration', '--min-trust', '--name', '--name-only', '--no-autostash', '--no-cron', '--no-embed', '--no-federate', '--no-federated', '--no-harden', '--no-lanes', '--no-pull', '--no-tags', '--no-verify', '--not', '--only', '--operations', '--origin', '--others', '--out', '--params', '--parked-pushes', '--pat-file', '--path', '--path-format', '--plan', '--porcelain', '--preview', '--probe', '--profile', '--pull', '--push-only', '--quiet', '--read-sources', '--rebase', '--redirect-uri', '--refresh-operations', '--remove-backup', '--repair', '--replace', '--repos', '--request-id', '--require-clean', '--reset-checkpoint', '--reset-default', '--resolve', '--resume', '--retry-failed', '--scope', '--scopes', '--secret', '--self-transfer', '--services', '--set', '--set-upstream-to', '--shared-skills', '--short', '--show-toplevel', '--since', '--slug-prefixes', '--source', '--source-id', '--source-ids', '--sources', '--stale', '--state', '--status', '--stdin', '--surface', '--symbolic-full-name', '--takes-holders', '--token', '--token-command', '--token-endpoint-auth-method', '--token-env', '--token-ttl', '--unindexed', '--unset-all', '--untracked-files', '--url', '--usage', '--verify', '--wait', '--wait-drain', '--warn-only', '--window', '--yes'],
diff --git a/src/core/repair/core.ts b/src/core/repair/core.ts
index a8c3beec79..380b630adf 100644
--- a/src/core/repair/core.ts
+++ b/src/core/repair/core.ts
@@ -48,6 +48,7 @@ import { repairAdmissionWindow, repairPublicationOwner, settleRepairReceipts, ty
import { RECEIPT_RESERVATION_FLOOR } from '../persistence/receipt-bytes.ts';
import { readFix } from '../ops/op-fix.ts';
import { ItemRun, type ItemFailure } from '../item-failure.ts';
+import type { ProgressReporter } from '../progress.ts';
export const REPAIR_KINDS = ['timeline', 'visibility', 'safe-chunks', 'contextual-mode', 'connector-checkpoints', 'request-indexes', 'connector-fences', 'take-supersession', 'accepted-takes', 'orphan-bindings', 'embedding-effects', 'attribution-backfill', 'planner-stats', 'google-file-modes', 'stale-atoms', 'atoms-restore', 'extractor-facts', 'conversation-labels', 'captured-facts', 'redacted-facts', 'loop-facts', 'ontology-facts', 'facts-rehome', 'consolidate-ties', 'orphan-children', 'failed-writes', 'split-facts', 'frontmatter', 'fences', 'slug-conflicts', 'timeline-comments', 'managed-sync-orphans', 'content-receipt-root', 'frontmatter-keys', 'file-drift', 'stuck-recovery', 'ghost-pages', 'origin-twins', 'receipt-compaction', 'aliases', 'rename-identity', 'overwritten-edits', 'legacy-twins', 'missing-tables', 'url-clone-fences', 'segmented-mirror', 'uncommitted-deletions'] as const;
export type RepairKind = typeof REPAIR_KINDS[number];
@@ -107,6 +108,8 @@ export interface RepairPlanOptions { apply: boolean; expect?: string; includeAmb
since?: string;
/** #6712 PR 4b `file-drift`: the source's held `file_drift` pages, of one side and (for `deleted`) one state. */
held?: boolean; side?: string; state?: string;
+ /** `file-drift --held`: the window starts after the held file this `next_cursor` names (`--cursor`); `progress` reports the preview's pages on stderr. */
+ cursor?: string; progress?: ProgressReporter;
/** `stuck-recovery`: the version an apply keeps, and the one request a run selects. */
keep?: 'prior' | 'disk' | 'withdrawn'; requestId?: string;
/** `receipt-compaction` (#6696 A9): the age (`72h`, `30d`), failures too, and compaction inside the retention window. */
@@ -310,6 +313,7 @@ export async function runRepair(ctx: OperationContext, handler: RepairHandler, s
opts: { apply: boolean; limit?: number; embeddingModel?: string; sourceFlag?: string; embed?: boolean; applyArgs?: string[];
explicit?: boolean; expect?: string; includeAmbiguous?: boolean; only?: string[]; skip?: string[]; slugs?: string[]; noLlm?: boolean;
prefer?: 'file' | 'database'; requests?: string[]; allDrifted?: boolean; driftClass?: string; since?: string; held?: boolean; side?: string; state?: string;
+ cursor?: string; progress?: ProgressReporter;
keep?: 'prior' | 'disk' | 'withdrawn'; requestId?: string; olderThan?: string; includeFailures?: boolean; force?: boolean; from?: string; close?: boolean; afterPage?: number;
spec?: Pick<RepairKindSpec, 'explicit_only' | 'consent' | 'spends'>; maxLlmUsd?: number; deadline?: number; now?: () => number;
/** Test seam: who publishes this run's admissions (default: this process's consumer, else a live full one on this host). */
@@ -332,6 +336,7 @@ async function runRepairScoped(ctx: OperationContext, handler: RepairHandler, sc
...(opts.prefer ? { prefer: opts.prefer } : {}), ...(opts.requests?.length ? { requests: opts.requests } : {}),
...(opts.allDrifted ? { allDrifted: true } : {}), ...(opts.driftClass ? { driftClass: opts.driftClass } : {}), ...(opts.since ? { since: opts.since } : {}),
...(opts.held ? { held: true } : {}), ...(opts.side ? { side: opts.side } : {}), ...(opts.state ? { state: opts.state } : {}),
+ ...(opts.cursor ? { cursor: opts.cursor } : {}), ...(opts.progress ? { progress: opts.progress } : {}),
...(opts.keep ? { keep: opts.keep } : {}), ...(opts.requestId ? { requestId: opts.requestId } : {}),
...(opts.olderThan ? { olderThan: opts.olderThan } : {}), ...(opts.includeFailures ? { includeFailures: true } : {}), ...(opts.force ? { force: true } : {}),
...(opts.from ? { from: opts.from } : {}), ...(opts.close ? { close: true } : {}), ...(opts.afterPage !== undefined ? { afterPage: opts.afterPage } : {}) };
@@ -360,7 +365,7 @@ async function runRepairScoped(ctx: OperationContext, handler: RepairHandler, sc
...(opts.slugs ?? []).flatMap(slug => ['--slug', slug]), ...(opts.from ? ['--from', opts.from] : []), ...(opts.close ? ['--close'] : []),
...(opts.requests ?? []).flatMap(id => ['--request', id]),
...(opts.allDrifted ? ['--all-drifted'] : []), ...(opts.driftClass ? ['--class', opts.driftClass] : []), ...(opts.since ? ['--since', opts.since] : []),
- ...(opts.held ? ['--held'] : []), ...(opts.side ? ['--side', opts.side] : []), ...(opts.state ? ['--state', opts.state] : []),
+ ...(opts.held ? ['--held'] : []), ...(opts.side ? ['--side', opts.side] : []), ...(opts.state ? ['--state', opts.state] : []), ...(opts.cursor ? ['--cursor', opts.cursor] : []),
...(opts.prefer ? ['--prefer', opts.prefer] : [])].map(arg => ` ${shellQuote([arg])}`).join('')}`
+ `${opts.includeAmbiguous ? ' --include-ambiguous' : ''}${llm && opts.noLlm ? ' --no-llm' : ''}${llm && opts.maxLlmUsd !== undefined ? ` --max-usd ${opts.maxLlmUsd}` : ''}`
+ ` --apply${plan.preview_hash ? ` --expect ${plan.preview_hash}` : ''}${spec?.consent === 'destructive' ? ' --yes' : ''}`,
diff --git a/src/core/repair/file-drift.ts b/src/core/repair/file-drift.ts
index e2b605c979..f8bf8ff7c0 100644
--- a/src/core/repair/file-drift.ts
+++ b/src/core/repair/file-drift.ts
@@ -124,12 +124,27 @@ const DELETED_CHANGES: Record<DeletedDriftChange, string> = {
};
const ALL_DRIFTED_LIMIT = 1000;
+/**
+ * A `--held` preview covers one window of the selected holds, in held-path order after `--cursor`: at most this many pages,
+ * and it starts no page after the window's time budget (or the run's deadline) has passed. Each page costs a few dozen
+ * database round trips, so a whole large held set in one preview ran for an hour against a remote database with no output.
+ */
+const HELD_WINDOW_PAGES = 200;
+const HELD_WINDOW_BUDGET_MS = 60_000;
+const HELD_CURSOR_PREFIX = 'h1.';
+const heldCursor = (path: string) => HELD_CURSOR_PREFIX + Buffer.from(path, 'utf8').toString('base64url');
+function heldCursorPath(sourceId: string, cursor: string): string {
+ const path = cursor.startsWith(HELD_CURSOR_PREFIX) ? Buffer.from(cursor.slice(HELD_CURSOR_PREFIX.length), 'base64url').toString('utf8') : '';
+ if (!path || heldCursor(path) !== cursor) throw opError('invalid_params', `--cursor ${cursor} is not a cursor a held file-drift preview printed.`,
+ `Nothing was previewed. Pass the next_cursor the previous preview printed, or drop --cursor to start from the first held file of '${sourceId}'.`);
+ return path;
+}
const TOP_FIELDS = ['title', 'type', 'compiled_truth', 'timeline'] as const;
const artifactDirectory = () => join(canonicalFilesystemPath(configDir()), 'repair-previews', 'file-drift');
const escapePointer = (key: string) => key.replace(/~/g, '~0').replace(/\//g, '~1');
function previewCommand(sourceId: string, opts: RepairPlanOptions): string {
- const select = opts.held ? ` --held${opts.side ? ` --side ${opts.side}` : ''}${opts.state ? ` --state ${opts.state}` : ''}`
+ const select = opts.held ? ` --held${opts.side ? ` --side ${opts.side}` : ''}${opts.state ? ` --state ${opts.state}` : ''}${opts.cursor ? ` --cursor ${opts.cursor}` : ''}`
: opts.allDrifted ? ` --all-drifted${opts.driftClass ? ` --class ${opts.driftClass}` : ''}${opts.since ? ` --since ${opts.since}` : ''}`
: [...(opts.slugs ?? []).map(slug => ` --slug ${slug}`), ...(opts.requests ?? []).map(id => ` --request ${id}`)].join('');
const globs = [...(opts.only ?? []).flatMap(glob => ['--only', glob]), ...(opts.skip ?? []).flatMap(glob => ['--skip', glob])];
@@ -281,17 +296,19 @@ function unknownDriftDetail(sourceId: string, { slug, reason }: UnknownDrift): s
* no side and are listed with their single-page route.
*/
async function selectHeld(engine: BrainEngine, sourceId: string, opts: RepairPlanOptions & { prefer: DriftSide }):
- Promise<{ targets: HeldTarget[]; notSelected: number; legacy: GitHoldRecord[] }> {
- const rows = await engine.executeRaw<{ record: GitHoldRecord }>(`SELECT h.completed_keys->0 AS record FROM op_checkpoints h
+ Promise<{ targets: HeldTarget[]; before: number; notSelected: number; legacy: GitHoldRecord[] }> {
+ const after = opts.cursor ? heldCursorPath(sourceId, opts.cursor) : null;
+ const rows = await engine.executeRaw<{ record: GitHoldRecord; in_window: boolean }>(`SELECT h.completed_keys->0 AS record,
+ ($3::text IS NULL OR (h.completed_keys->0->>'path') COLLATE "C" > $3::text) AS in_window FROM op_checkpoints h
JOIN sources s ON s.id=h.completed_keys->0->>'source_id' AND s.incarnation::text=h.completed_keys->0->>'incarnation'
- WHERE h.op=$1 AND s.id=$2 AND h.completed_keys->0->>'code'='file_drift' ORDER BY h.fingerprint`, [GIT_HOLD_OP, sourceId]);
- const targets: HeldTarget[] = [], legacy: GitHoldRecord[] = [];
+ WHERE h.op=$1 AND s.id=$2 AND h.completed_keys->0->>'code'='file_drift' ORDER BY (h.completed_keys->0->>'path') COLLATE "C"`, [GIT_HOLD_OP, sourceId, after]);
+ const targets: Array<HeldTarget & { inWindow: boolean }> = [], legacy: GitHoldRecord[] = [];
let notSelected = 0;
- for (const { record } of rows) {
+ for (const { record, in_window } of rows) {
if (!selectedByGlobs(record.path, opts)) { notSelected++; continue; }
const side = fileDriftSide(record.meta);
- if (!side || side === 'deleted' && !record.meta.state) { legacy.push(record); continue; }
- targets.push({ hold: record, side, ...(side === 'deleted' ? { state: record.meta.state } : {}) });
+ if (!side || side === 'deleted' && !record.meta.state) { if (in_window) legacy.push(record); continue; }
+ targets.push({ hold: record, side, ...(side === 'deleted' ? { state: record.meta.state } : {}), inWindow: in_window === true });
}
const key = (target: Pick<HeldTarget, 'side' | 'state'>) => target.state ? `${target.side}/${target.state}` : target.side;
const groups = new Map<string, { side: FileDriftSide; state?: FileDriftDeletedState; count: number }>();
@@ -308,8 +325,8 @@ async function selectHeld(engine: BrainEngine, sourceId: string, opts: RepairPla
}
const only = !opts.side && groups.size === 1 ? [...groups.values()][0]! : null;
if (only?.side === 'deleted') throw stateRequired(sourceId, opts, [only.state!]);
- return { targets: targets.filter(target => !opts.side || target.side === opts.side && (!opts.state || target.state === opts.state)).slice(0, ALL_DRIFTED_LIMIT),
- notSelected, legacy };
+ const selected = targets.filter(target => !opts.side || target.side === opts.side && (!opts.state || target.state === opts.state));
+ return { targets: selected.filter(target => target.inWindow).map(({ inWindow: _inWindow, ...target }) => target), before: selected.filter(target => !target.inWindow).length, notSelected, legacy };
}
/** #6712 PR 4b: the `--held` preview of one Decision, keeping the run's `--only` / `--skip` globs. */
@@ -329,13 +346,14 @@ function stateRequired(sourceId: string, opts: RepairPlanOptions, states: readon
function validateOptions(scope: RepairScope, opts: RepairPlanOptions | undefined): asserts opts is RepairPlanOptions & { prefer: DriftSide } {
if (opts?.remote !== false) throw trustedCliRequired('gbrain repair file-drift runs only for the trusted local CLI on the brain host.');
- const usage = 'gbrain repair file-drift --source <id> (--slug <slug>... | --request <id>... | --all-drifted [--class <name>] [--since <ISO-8601|7d>] | --held [--side both|unknown|deleted [--state tombstone_edited|purged_differs|file_gone]]) [--only <glob>]... [--skip <glob>]... --prefer file|database';
+ const usage = 'gbrain repair file-drift --source <id> (--slug <slug>... | --request <id>... | --all-drifted [--class <name>] [--since <ISO-8601|7d>] | --held [--side both|unknown|deleted [--state tombstone_edited|purged_differs|file_gone]] [--cursor <next_cursor>]) [--only <glob>]... [--skip <glob>]... --prefer file|database';
if (scope.source_ids.length !== 1) throw opError('invalid_params', 'gbrain repair file-drift needs exactly one --source.', `Name the source: ${usage}`);
if (opts.prefer !== 'file' && opts.prefer !== 'database') throw opError('invalid_params', 'gbrain repair file-drift needs --prefer file or --prefer database.',
`Choose the side whose content wins (protected metadata, tags union, protected takes and private facts are kept either way): ${usage}`);
const modes = [opts.slugs?.length ? 1 : 0, opts.requests?.length ? 1 : 0, opts.allDrifted ? 1 : 0, opts.held ? 1 : 0].reduce((a, b) => a + b, 0);
if (modes !== 1) throw opError('invalid_params', 'Select pages one way: --slug, --request, --all-drifted or --held.', `Pick one selection: ${usage}`);
if ((opts.side || opts.state) && !opts.held) throw opError('invalid_params', '--side and --state only narrow --held.', `Drop them, or select the held pages with --held: ${usage}`);
+ if (opts.cursor && !opts.held) throw opError('invalid_params', '--cursor only continues a --held preview.', `Drop --cursor, or continue the held preview that printed it: ${usage}`);
if (opts.side && !(FILE_DRIFT_SIDES as readonly string[]).includes(opts.side)) throw opError('invalid_params', `Unknown file-drift side '${opts.side}'.`,
`Pass --side ${FILE_DRIFT_SIDES.join(', --side ')}; gbrain sources status ${scope.source_ids[0]} --json lists each held file's side.`);
if (opts.state && !(FILE_DRIFT_DELETED_STATES as readonly string[]).includes(opts.state)) throw opError('invalid_params', `Unknown deleted-side state '${opts.state}'.`,
@@ -563,7 +581,7 @@ export const fileDriftRepair: RepairHandler = {
const skip = [...new Set(opts.skip ?? [])].sort();
const selection = digest({ prefer: opts.prefer, slugs: opts.slugs ?? [], requests: opts.requests ?? [], all: opts.allDrifted === true, class: opts.driftClass ?? null,
...(opts.since ? { since: opts.since } : {}), ...(only.length ? { only } : {}), ...(skip.length ? { skip } : {}),
- ...(opts.held ? { held: true, side: opts.side ?? null, state: opts.state ?? null } : {}) });
+ ...(opts.held ? { held: true, side: opts.side ?? null, state: opts.state ?? null } : {}), ...(opts.cursor ? { cursor: opts.cursor } : {}) });
if (opts.apply) {
if (!opts.expect) throw new OperationError('invalid_params', 'gbrain repair file-drift --apply applies only the set a preview printed.',
`Preview first: ${command} — then run the apply command it prints with --expect <preview-hash>.`, 'docs/guides/repair.md#explicit-only-repair-kinds');
@@ -589,7 +607,7 @@ export const fileDriftRepair: RepairHandler = {
const assessmentAt = new Date().toISOString();
const pages: PlannedPage[] = [];
const listing: NonNullable<RepairPlan['listing']> = [];
- const residuals: Record<string, number> = notSelected ? { not_selected: notSelected } : {};
+ const residuals: Record<string, number> = { ...(notSelected ? { not_selected: notSelected } : {}), ...(held?.before ? { before_cursor: held.before } : {}) };
const count = (key: string) => { residuals[key] = (residuals[key] ?? 0) + 1; };
for (const hold of held?.legacy ?? []) {
count('legacy_side');
@@ -600,9 +618,15 @@ export const fileDriftRepair: RepairHandler = {
count(`unknown_${row.reason}`);
listing.push({ item: `${sourceId}:${row.slug}`, class: 'unknown', detail: unknownDriftDetail(sourceId, row) });
}
- const targets: Array<{ slug: string | null; held?: HeldTarget }> = held ? held.targets.map(target => ({ slug: target.hold.slug, held: target })) : slugs.map(slug => ({ slug }));
+ const targets: Array<{ slug: string | null; held?: HeldTarget }> = held ? held.targets.slice(0, HELD_WINDOW_PAGES).map(target => ({ slug: target.hold.slug, held: target })) : slugs.map(slug => ({ slug }));
+ const windowEnd = Math.min(Date.now() + HELD_WINDOW_BUDGET_MS, opts.deadline ?? Infinity);
+ let previewed = 0;
+ opts.progress?.start('repair.file_drift.preview', targets.length);
await asLocalCli(engine, async () => {
for (const { slug: targetSlug, held: target } of targets) {
+ if (held && previewed > 0 && Date.now() >= windowEnd) break;
+ previewed++;
+ opts.progress?.tick(1, targetSlug ?? target?.hold.path);
const label = targetSlug ?? target?.hold.path ?? '';
try {
if (target?.state === 'tombstone_edited' || target?.state === 'purged_differs') {
@@ -651,6 +675,11 @@ export const fileDriftRepair: RepairHandler = {
}
}
});
+ opts.progress?.finish();
+ const remaining = held ? held.targets.length - previewed : 0;
+ const nextCursor = remaining > 0 ? heldCursor(held!.targets[previewed - 1]!.hold.path) : undefined;
+ const nextCommand = nextCursor ? previewCommand(sourceId, { ...opts, cursor: nextCursor }) : undefined;
+ if (remaining > 0) residuals.after_window = remaining;
const hash = previewHash({ kind: 'file-drift-v1', brain_id: scope.brain_id, source_id: sourceId, selection,
pages: pages.map(page => 'soft_delete' in page ? [page.slug, page.soft_delete.ghost.revision, ABSENT_FILE_HASH, 'soft_delete']
: 'remove_file' in page ? [page.slug, page.remove_file.revision, page.remove_file.raw_file_hash, 'remove_file', page.remove_file.state, page.remove_file.marker_digest]
@@ -660,7 +689,8 @@ export const fileDriftRepair: RepairHandler = {
const recreated = pages.flatMap(page => 'preview' in page && page.file_gone ? [page.preview.preconditions.relative_path] : []);
// #6712 PR 4b: a removed file is gone only once its deletion is committed; without Git durability the next sync finds the committed file held again.
const removed = pages.flatMap(page => 'remove_file' in page ? [page.remove_file.path] : []);
- let warnings: string[] = [];
+ let warnings: string[] = nextCommand ? [`This preview covered ${previewed} of the ${held!.targets.length} selected held pages${opts.cursor ? ' after its cursor' : ''} (one window stops at ${HELD_WINDOW_PAGES} pages or ${HELD_WINDOW_BUDGET_MS / 1000} s); its hash and apply command cover only these. `
+ + `After applying this window (or deciding not to), preview the next one: ${nextCommand}`] : [];
if (recreated.length || removed.length) {
const binding = await getWorktreeBinding(engine, sourceId);
const root = join(binding!.local_path!, binding!.relative_path);
@@ -679,6 +709,7 @@ export const fileDriftRepair: RepairHandler = {
return { items: pages.map((page, index) => item({ source_id: sourceId, slug: page.slug, artifact_digest: digest(page), selection }, index, hash, index === pages.length - 1, opts.prefer)),
preview_hash: hash, residuals, listing, ...(warnings.length ? { warnings } : {}),
details: { prefer: opts.prefer, ...(artifact ? { artifact } : {}),
+ ...(held ? { window: { previewed, remaining, complete: remaining === 0, ...(nextCursor ? { next_cursor: nextCursor, next_command: nextCommand } : {}) } } : {}),
pages: pages.map(page => 'soft_delete' in page ? { slug: page.slug, action: 'soft_delete', path: page.soft_delete.ghost.path, verb: fileDriftActionVerb('deleted', 'file_gone', 'file'), exceptions: page.exceptions }
: 'remove_file' in page ? { slug: page.slug, action: 'remove_file', state: page.remove_file.state, path: page.remove_file.path, verb: fileDriftActionVerb('deleted', page.remove_file.state, 'database'), exceptions: page.exceptions }
: 'import_file' in page ? { slug: page.slug, action: 'import_file', state: page.import_file.state, path: page.import_file.path, verb: fileDriftActionVerb('deleted', page.import_file.state, 'file'), exceptions: page.exceptions, result_digest: page.import_file.result_digest }
diff --git a/src/core/repair/registry.ts b/src/core/repair/registry.ts
index e73a2a3a1f..a04ba8677a 100644
--- a/src/core/repair/registry.ts
+++ b/src/core/repair/registry.ts
@@ -83,6 +83,7 @@ import { segmentedMirrorRepair } from './segmented-mirror.ts';
import { uncommittedDeletionsRepair, UNCOMMITTED_DELETIONS_CONSENT_TEXT } from './uncommitted-deletions.ts';
import { ERROR_CATALOGUE, catalogueError } from '../error-catalogue.ts';
import type { OperationError } from '../ops/contract.ts';
+import type { ProgressReporter } from '../progress.ts';
export interface RepairKindSpec {
kind: RepairKind;
@@ -584,7 +585,7 @@ export async function repairRunner(engine: BrainEngine, opts: { apply: boolean;
*/
async run(kind: RepairKind, scope: RepairScope, run: { limit?: number; sourceFlag?: string; explicit?: boolean; expect?: string; includeAmbiguous?: boolean; only?: string[]; skip?: string[];
slugs?: string[]; noLlm?: boolean; maxLlmUsd?: number; deadline?: number;
- prefer?: 'file' | 'database'; requests?: string[]; allDrifted?: boolean; driftClass?: string; since?: string; held?: boolean; side?: string; state?: string;
+ prefer?: 'file' | 'database'; requests?: string[]; allDrifted?: boolean; driftClass?: string; since?: string; held?: boolean; side?: string; state?: string; cursor?: string; progress?: ProgressReporter;
keep?: 'prior' | 'disk' | 'withdrawn'; requestId?: string; olderThan?: string; includeFailures?: boolean; force?: boolean; from?: string; close?: boolean; afterPage?: number } = {}): Promise<RepairResult> {
const ctx = { engine, config, logger, dryRun: !opts.apply, remote: false, sourceId: scope.source_ids[0], writeWaitMs } as OperationContext;
const spec = repairSpec(kind, opts.registry);
@@ -594,7 +595,7 @@ export async function repairRunner(engine: BrainEngine, opts: { apply: boolean;
...(run.afterPage !== undefined ? ['--after', String(run.afterPage)] : [])],
explicit: run.explicit, expect: run.expect, includeAmbiguous: run.includeAmbiguous, only: run.only, skip: run.skip, slugs: run.slugs, noLlm: run.noLlm,
maxLlmUsd: run.maxLlmUsd, deadline: run.deadline, prefer: run.prefer, requests: run.requests, allDrifted: run.allDrifted, driftClass: run.driftClass, since: run.since,
- held: run.held, side: run.side, state: run.state, keep: run.keep, requestId: run.requestId, olderThan: run.olderThan, includeFailures: run.includeFailures, force: run.force, from: run.from, close: run.close, afterPage: run.afterPage });
+ held: run.held, side: run.side, state: run.state, cursor: run.cursor, progress: run.progress, keep: run.keep, requestId: run.requestId, olderThan: run.olderThan, includeFailures: run.includeFailures, force: run.force, from: run.from, close: run.close, afterPage: run.afterPage });
},
};
}
diff --git a/test/postgres-unit-arms.txt b/test/postgres-unit-arms.txt
index 6c7db283bf..33065bd6aa 100644
--- a/test/postgres-unit-arms.txt
+++ b/test/postgres-unit-arms.txt
@@ -380,6 +380,7 @@ test/repair-failed-writes-drift-w411.test.ts
test/repair-fences.test.ts
test/repair-file-drift-deleted-6712.test.ts
test/repair-file-drift-held-6712.test.ts
+test/repair-file-drift-held-window-gbra133.test.ts
test/repair-frontmatter-keys-sweep-6454.test.ts
test/repair-frontmatter.test.ts
test/repair-receipt-compaction.test.ts
diff --git a/test/repair-file-drift-held-window-gbra133.test.ts b/test/repair-file-drift-held-window-gbra133.test.ts
new file mode 100644
index 0000000000..25abb1524e
--- /dev/null
+++ b/test/repair-file-drift-held-window-gbra133.test.ts
@@ -0,0 +1,168 @@
+/**
+ * GBRA-133: `gbrain repair file-drift --held` previews one bounded window of the selected holds, in held-path order.
+ * - a window stops at 200 pages, or starts no page once its time budget (or the run's deadline) has passed;
+ * - a partial window prints `next_cursor` and the next preview command, and its hash and apply command cover only it
+ * (the apply carries `--cursor`); the windows of one held set cover every page exactly once;
+ * - the preview reports each page to its progress reporter (stderr on the CLI);
+ * - a cursor no preview printed, or `--cursor` without `--held`, is refused before any page is read.
+ * Before: the preview prepared every held page before printing anything (each page costs a few dozen round trips), so a
+ * large held set against a remote database printed nothing for an hour.
+ * Real PGLite (and Postgres when DATABASE_URL is set) with a claimed canonical Git worktree and real files; no seams.
+ */
+import { afterAll, beforeAll, describe, expect, test } from 'bun:test';
+import { execFileSync } from 'node:child_process';
+import { randomUUID } from 'node:crypto';
+import { existsSync, mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from 'node:fs';
+import { tmpdir } from 'node:os';
+import { join } from 'node:path';
+import type { BrainEngine } from '../src/core/engine.ts';
+import type { OperationContext } from '../src/core/operations.ts';
+import { OperationError } from '../src/core/ops/contract.ts';
+import { PGLiteEngine } from '../src/core/pglite-engine.ts';
+import { RECOVERY_VERSION } from '../src/core/markdown.ts';
+import { claimWorktree } from '../src/core/persistence/ownership.ts';
+import { submitPageMutation } from '../src/core/persistence/page-mutations.ts';
+import { disposePersistenceConsumer } from '../src/core/persistence/service.ts';
+import { gitBlobOid } from '../src/core/persistence/digest.ts';
+import { SYNC_ORIGIN_DELETED_OP } from '../src/core/persistence/sync-pass-row.ts';
+import { gitHoldItem, readGitHold, writeGitHold, type FileDriftDeletedState, type FileDriftSide } from '../src/core/persistence/sync-holds.ts';
+import { repairRunner } from '../src/core/repair/registry.ts';
+import { resolveRepairScope } from '../src/core/repair/core.ts';
+import { withEnv } from './helpers/with-env.ts';
+import type { ProgressReporter } from '../src/core/progress.ts';
+import { requirePostgresTestDatabase, testBackends } from './helpers/test-backends.ts';
+import { isolatedPersistencePostgres } from './helpers/persistence-postgres.ts';
+
+const logger = { info() {}, warn() {}, error() {} };
+const git = (root: string, ...args: string[]) => execFileSync('git', ['-C', root, '-c', 'user.name=Example', '-c', '[email protected]',
+ '-c', 'commit.gpgsign=false', ...args], { encoding: 'utf8', stdio: ['ignore', 'pipe', 'pipe'] }).trim();
+const page = (title: string, body: string) => `---\ntype: note\ntitle: ${title}\n---\n${body}\n`;
+
+for (const backend of testBackends()) describe(`GBRA-133: a held file-drift preview is one bounded window (${backend})`, () => {
+ let engine: BrainEngine;
+ let closePostgres: (() => Promise<void>) | undefined;
+
+ beforeAll(async () => {
+ if (backend === 'pglite') {
+ const pglite = new PGLiteEngine();
+ await pglite.connect({}); await pglite.initSchema(); engine = pglite;
+ } else {
+ const pg = await isolatedPersistencePostgres(requirePostgresTestDatabase());
+ engine = pg.engine; closePostgres = pg.close;
+ }
+ }, 120_000);
+ afterAll(async () => {
+ await disposePersistenceConsumer(engine);
+ if (closePostgres) await closePostgres(); else await engine.disconnect();
+ });
+
+ interface Fixture { root: string; sourceId: string; ctx: OperationContext; incarnation: string }
+ async function fixture(run: (f: Fixture) => Promise<void>): Promise<void> {
+ const dir = mkdtempSync(join(tmpdir(), 'gbrain-6712-held-'));
+ const root = join(dir, 'brain'); mkdirSync(root);
+ execFileSync('git', ['init', '-q'], { cwd: root });
+ const sourceId = `held6712-${randomUUID().slice(0, 8)}`;
+ try {
+ await withEnv({ GBRAIN_HOME: join(dir, 'home') }, async () => {
+ await engine.executeRaw('INSERT INTO sources(id,name,local_path) VALUES($1,$1,$2)', [sourceId, root]);
+ await engine.setConfig('sync.write_through', 'true');
+ await claimWorktree(engine, sourceId, root);
+ await engine.executeRaw('UPDATE persistence_brain SET enabled=true WHERE singleton=1');
+ const [source] = await engine.executeRaw<{ incarnation: string }>('SELECT incarnation::text AS incarnation FROM sources WHERE id=$1', [sourceId]);
+ const ctx = { engine, sourceId, remote: false, config: { engine: engine.kind, embedding_disabled: true } as never, dryRun: false, logger } as OperationContext;
+ await run({ root, sourceId, ctx, incarnation: source!.incarnation });
+ });
+ } finally {
+ await disposePersistenceConsumer(engine);
+ await engine.executeRaw('UPDATE persistence_brain SET enabled=false WHERE singleton=1');
+ await engine.executeRaw('UPDATE sources SET archived=true WHERE id=$1', [sourceId]);
+ rmSync(dir, { recursive: true, force: true });
+ }
+ }
+
+ const put = (ctx: OperationContext, slug: string, body: string) =>
+ submitPageMutation(ctx, { operation: 'put_page', params: { slug, content: page(slug, body), request_id: randomUUID() } });
+ const snapshot = (sourceId: string, slug: string) => engine.readPageSnapshot(slug, { sourceId, includeDeleted: true });
+ const remove = async (ctx: OperationContext, sourceId: string, slug: string, purge = false) => submitPageMutation(ctx, { operation: 'delete_page',
+ params: { slug, request_id: randomUUID(), expected_revision: (await snapshot(sourceId, slug))!.revision, ...(purge ? { purge: true } : {}) } });
+ const commitAll = (root: string, message: string) => { git(root, 'add', '-A'); git(root, 'commit', '-q', '--allow-empty', '-m', message); };
+ /** The `file_drift` hold sync writes for a Decision (design v3.2 §4): its side, and for a deleted side its state. */
+ const hold = (f: Fixture, input: { path: string; slug: string | null; pageId: number | null; side: FileDriftSide; state?: FileDriftDeletedState; revision?: string }) =>
+ engine.transaction(tx => writeGitHold(tx, { source_id: f.sourceId, incarnation: f.incarnation, path: input.path, source_path: input.path, slug: input.slug,
+ page_id: input.pageId, code: 'file_drift', message: `${input.path} is held: file drift (${input.side}${input.state ? ` ${input.state}` : ''})`, upstream_version: null,
+ observed_at: new Date().toISOString(), run_id: null, mode: 'managed',
+ meta: { recovery_version: RECOVERY_VERSION, side: input.side, ...(input.state ? { state: input.state } : {}), ...(input.revision ? { page_revision: input.revision } : {}) } }));
+ const run = async (sourceId: string, opts: { cursor?: string; deadline?: number; expect?: string; progress?: ProgressReporter; held?: boolean; slugs?: string[] }) =>
+ (await repairRunner(engine, { apply: opts.expect !== undefined, logger })).run('file-drift', await resolveRepairScope(engine, sourceId),
+ { explicit: true, sourceFlag: sourceId, prefer: 'database', ...(opts.held === false ? {} : { held: true, side: 'deleted', state: 'file_gone' }), ...(opts.slugs ? { slugs: opts.slugs } : {}),
+ ...(opts.cursor ? { cursor: opts.cursor } : {}), ...(opts.deadline !== undefined ? { deadline: opts.deadline } : {}), ...(opts.expect ? { expect: opts.expect } : {}),
+ ...(opts.progress ? { progress: opts.progress } : {}) });
+ const refusal = async (promise: Promise<unknown>) => { try { await promise; } catch (error) { return error as OperationError; } throw new Error('expected a refusal'); };
+ /** `count` live pages whose committed files are then removed in one commit, each held as the file_gone Decision. */
+ async function fileGone(f: Fixture, count: number): Promise<string[]> {
+ const slugs = Array.from({ length: count }, (_, i) => `notes/gone-${String(i).padStart(4, '0')}`);
+ for (const slug of slugs) await put(f.ctx, slug, `The page ${slug}.`);
+ commitAll(f.root, 'pages');
+ git(f.root, 'rm', '-q', '--', ...slugs.map(slug => `${slug}.md`)); git(f.root, 'commit', '-q', '-m', 'remove');
+ for (const slug of slugs) {
+ const live = (await snapshot(f.sourceId, slug))!;
+ await hold(f, { path: `${slug}.md`, slug, pageId: Number(live.page.id), side: 'deleted', state: 'file_gone', revision: live.revision });
+ }
+ return slugs;
+ }
+ const window = (result: Awaited<ReturnType<typeof run>>) => (result.details as { window?: { previewed: number; remaining: number; complete: boolean; next_cursor?: string; next_command?: string } }).window!;
+ const slugsOf = (result: Awaited<ReturnType<typeof run>>) => (result.details!.pages as Array<{ slug: string }>).map(page => page.slug);
+
+ test('past its time budget a window previews one page; the cursors walk the held set once, and an apply covers only its window', () => fixture(async f => {
+ const slugs = await fileGone(f, 3);
+ const ticks: string[] = [];
+ const progress = { start: (phase: string, total?: number) => ticks.push(`start ${phase} ${total}`), tick: (_n?: number, note?: string) => ticks.push(`tick ${note}`),
+ heartbeat() {}, finish: () => ticks.push('finish'), child: () => progress } as unknown as ProgressReporter;
+ const first = await run(f.sourceId, { deadline: Date.now() - 1, progress });
+ expect(slugsOf(first)).toEqual([slugs[0]]);
+ expect(ticks).toEqual(['start repair.file_drift.preview 3', `tick ${slugs[0]}`, 'finish']);
+ expect(window(first)).toMatchObject({ previewed: 1, remaining: 2, complete: false });
+ expect(first.residuals).toMatchObject({ after_window: 2 });
+ const cursor = window(first).next_cursor!;
+ expect(window(first).next_command).toBe(`gbrain repair file-drift --source ${f.sourceId} --held --side deleted --state file_gone --cursor ${cursor} --prefer database`);
+ expect(first.warnings!.join('\n')).toContain(`preview the next one: ${window(first).next_command}`);
+ expect(first.apply_command).not.toContain('--cursor');
+
+ const second = await run(f.sourceId, { cursor, deadline: Date.now() - 1 });
+ expect(slugsOf(second)).toEqual([slugs[1]]);
+ expect(second.residuals).toMatchObject({ before_cursor: 1, after_window: 1 });
+ expect(second.apply_command).toContain(`--cursor ${cursor} --prefer database --apply --expect ${second.preview_hash}`);
+ const third = await run(f.sourceId, { cursor: window(second).next_cursor! });
+ expect(slugsOf(third)).toEqual([slugs[2]]);
+ expect(window(third)).toEqual({ previewed: 1, remaining: 0, complete: true });
+ expect((third.warnings ?? []).filter(warning => warning.includes('preview the next one'))).toEqual([]);
+
+ // The second window's apply recreates only its page; the hash is bound to its cursor.
+ const applied = await run(f.sourceId, { cursor, expect: second.preview_hash! });
+ expect(applied.outcomes).toEqual({ repaired: 1 });
+ expect(existsSync(join(f.root, `${slugs[1]}.md`))).toBe(true);
+ for (const slug of [slugs[0], slugs[2]]) expect(existsSync(join(f.root, `${slug}.md`))).toBe(false);
+ const elsewhere = await refusal(run(f.sourceId, { expect: third.preview_hash! }));
+ expect(elsewhere.code).toBe('preview_changed');
+ }), 240_000);
+
+ test('a window stops at 200 pages and the next one previews the rest', () => fixture(async f => {
+ const slugs = await fileGone(f, 203);
+ const first = await run(f.sourceId, {});
+ expect(slugsOf(first)).toEqual(slugs.slice(0, 200));
+ expect(window(first)).toMatchObject({ previewed: 200, remaining: 3, complete: false });
+ const rest = await run(f.sourceId, { cursor: window(first).next_cursor! });
+ expect(slugsOf(rest)).toEqual(slugs.slice(200));
+ expect(window(rest)).toEqual({ previewed: 3, remaining: 0, complete: true });
+ }), 600_000);
+
+ test('a cursor no preview printed, or --cursor without --held, is refused', () => fixture(async f => {
+ await fileGone(f, 1);
+ const forged = await refusal(run(f.sourceId, { cursor: 'not-a-cursor' }));
+ expect(forged.code).toBe('invalid_params');
+ expect(forged.suggestion).toContain('Pass the next_cursor the previous preview printed');
+ const unheld = await refusal(run(f.sourceId, { held: false, slugs: ['notes/gone-0000'], cursor: 'h1.bm90ZXM' }));
+ expect(unheld.code).toBe('invalid_params');
+ expect(unheld.message).toBe('--cursor only continues a --held preview.');
+ }), 240_000);
+});