Garry's Opinionated OpenClaw/Hermes Agent Brain
TypeScript
fix(#7130 review): byte-exact Git names, commit evidence wins over ignore, existing origins keep drift checks, working-tree brake fails closed on file-backed count, legacy origin evidence path, repair cursor/marker/continuation
garrytan7402473938c2
diff --git a/docs/guides/repair.md b/docs/guides/repair.mdindex 7d8d0a0ee7..c5fa9be244 100644--- a/docs/guides/repair.md+++ b/docs/guides/repair.md@@ -1143,8 +1143,10 @@ retention window. Sync now holds such a page instead`ignored`). For a brain already hit, doctor `uncommitted_sync_deletions`counts, on each source's owner host, the tombstones a sync deleted whose file`.gitignore` excludes or no commit of HEAD's history holds (and that is not on-the disk). It reads at most 20,000 tombstones per source and the Git evidence-of 2,000 files per run, sync deletions first, and says when it was bounded.+the disk). It reads at most 2,000 tombstones per run across sources, newest+page id first, with their Git evidence; when it was bounded it says so and+names the preview that continues below the last page it read+(`--after <page-id>`).Off the owner host, or on a brain without managed sync, it is `ok` and notapplicable. To restore them, preview, then apply after the user agrees:@@ -1157,8 +1159,10 @@ gbrain repair uncommitted-deletions --source default --apply --expect <hash> --y(`pg_dump`, or a `gbrain backup create` taken before the purge) can bring themback.** Restore what is still there before the purge runs.-The preview writes nothing. Its default set is the pages a sync deleted (a-committed `managed_sync_delete` request is the newest deletion of the slug);+The preview writes nothing. Its default set is the pages a sync deleted (the+open `sync-delete-tombstone` record of the page's current tombstone, or the+committed `managed_sync_delete` receipt that made it; a record left from an+earlier deletion of the same page does not count);pages another writer deleted are listed apart and join the hashed set only with`--include-ambiguous`. The apply needs the user's consent: without `--yes` aterminal asks, and a non-interactive run exits 3 with the consent payload and@@ -1172,8 +1176,15 @@ checkout again is skipped `file_restored` (commit it and sync instead); onepurged in between is skipped `purged`. A wrong or stale hash refuses[`preview_changed`](#preview-changed), and off the owner host the preview andthe apply refuse [`not_owner_host`](error-codes.md#not_owner_host). Undo one-page with `gbrain delete <slug>`. A preview lists at most 1,000 pages; apply-them, then preview again. The repair runs only when named, never on upgrade or+page with `gbrain delete <slug>`. One preview reads a bounded window of at+most 5,000 tombstones, newest page id first, and lists at most 1,000 pages.+When it is bounded its `details.truncated` is true and `details.next_after`+names the page id to continue below: after applying this set (or deciding not+to), preview the next window with+`gbrain repair uncommitted-deletions --source default --after <next_after>`.+The hash covers `--after`, and the printed apply command carries it. An apply+stopped part way (`--limit`, a time budget) resumes over the rest of the same+approved set when rerun. The repair runs only when named, never on upgrade orfrom a maintenance cycle.<a id="legacy-twins"></a>diff --git a/src/commands/doctor/checks/uncommitted-sync-deletions.ts b/src/commands/doctor/checks/uncommitted-sync-deletions.tsindex facc567365..923cbc4516 100644--- a/src/commands/doctor/checks/uncommitted-sync-deletions.ts+++ b/src/commands/doctor/checks/uncommitted-sync-deletions.ts@@ -5,8 +5,9 @@* the only copy of the page and the purge removes it for good after its retention window. The finding names the* read-only `gbrain repair uncommitted-deletions --source <id>` preview; restoring is the user's decision.*- * Read-only and bounded: at most `TOMBSTONE_SCAN_LIMIT` tombstones per source and `DOCTOR_PATH_LIMIT` Git evidence reads- * per run (sync deletions first), with `truncated` / `exact` details. Pages deleted by another writer are counted apart+ * Read-only and bounded: at most `DOCTOR_PATH_LIMIT` tombstones read and checked per run across sources (descending page+ * id), with `truncated` / `exact` details; a bounded source names the `next_after` page id, and the message names the+ * repair preview that continues from it (`--after`). Pages deleted by another writer are counted apart* and never warn. Off the owner host, on a brain without managed sync or with no bound source it is `ok` + info* (`not_applicable`); a checkout or Git history that cannot be read is the unknown convention (`warn`, `health: unknown`).*/@@ -27,7 +28,7 @@ async function runUncommittedSyncDeletions(ctx: DoctorContext): Promise<Check[]>let budget = DOCTOR_PATH_LIMIT;for (const sourceId of sourceIds) {const scan = await scanUncommittedDeletions(engine, sourceId, { pathLimit: budget });- budget -= scan.checked;+ budget -= scan.tombstones;scans.push(scan);}const bySync = scans.flatMap(scan => scan.pages.filter(page => page.deleted_by === 'sync'));@@ -36,15 +37,18 @@ async function runUncommittedSyncDeletions(ctx: DoctorContext): Promise<Check[]>const truncated = scans.some(scan => scan.truncated);const details = { count: bySync.length, other_writer_count: byOther.length, truncated, exact: !truncated && !unknown.length, purged: PURGED_NOTE, docs: DOCS,by_source: scans.map(scan => ({ source_id: scan.source_id, status: scan.status, ...(scan.reason ? { reason: scan.reason } : {}), sync_deleted: scan.pages.filter(page => page.deleted_by === 'sync').length,- other_writer: scan.pages.filter(page => page.deleted_by !== 'sync').length, tombstones: scan.tombstones, checked: scan.checked, unknown: scan.unknown, truncated: scan.truncated })),+ other_writer: scan.pages.filter(page => page.deleted_by !== 'sync').length, tombstones: scan.tombstones, checked: scan.checked, unknown: scan.unknown, truncated: scan.truncated,+ ...(scan.next_after !== undefined ? { next_after: scan.next_after } : {}) })),samples: bySync.slice(0, SAMPLE_LIMIT).map(({ source_id, slug, source_path, deleted_at, evidence }) => ({ source_id, slug, source_path, deleted_at, evidence })) };const otherNote = byOther.length ? ` ${byOther.length} more soft-deleted page(s) with an uncommitted file were deleted by another writer, not by a sync (the preview lists them; --include-ambiguous restores them).` : '';+ const continueNote = truncated ? ` This check is bounded (${DOCTOR_PATH_LIMIT} tombstones per run); preview past it with `+ + `${scans.filter(scan => scan.truncated).map(scan => `gbrain repair uncommitted-deletions --source ${scan.source_id}${scan.next_after !== undefined ? ` --after ${scan.next_after}` : ''}`).join('; ')}.` : '';if (bySync.length) {const sources = [...new Set(bySync.map(page => page.source_id))];checks.push({ name: 'uncommitted_sync_deletions', status: 'warn', details: { ...details, ...(unknown.length ? { health: 'unknown' } : {}) },message: `${bySync.length}${details.exact ? '' : '+'} soft-deleted page(s) were removed by a sync although Git never held their file (.gitignore excludes it, or it was never committed), so each tombstone may be the only copy and the purge removes it for good `+ `(${sources.map(source => `${source}: ${bySync.filter(page => page.source_id === source).length}`).join('; ')}; e.g. ${details.samples.map(page => `${page.source_id}:${page.slug} (${page.source_path}, ${page.evidence})`).join(', ')}). `- + `Preview the restore with gbrain repair uncommitted-deletions --source ${sources[0]}. ${PURGED_NOTE}${otherNote}`,+ + `Preview the restore with gbrain repair uncommitted-deletions --source ${sources[0]}. ${PURGED_NOTE}${otherNote}${continueNote}`,fix: agentFix(['gbrain', 'repair', 'uncommitted-deletions', '--source', sources[0]!, '--json'],'Read-only preview: lists each page with its recorded path, deletion time and evidence, and prints the apply command with its hash. Apply only after the user agrees (each page comes back live and database-only).','uncommitted_sync_deletions', { docs: DOCS }) });@@ -67,7 +71,7 @@ async function runUncommittedSyncDeletions(ctx: DoctorContext): Promise<Check[]>return checks;}checks.push({ name: 'uncommitted_sync_deletions', status: 'ok', details,- message: `No soft-deleted page was removed by a sync while Git never held its file (${scans.reduce((sum, scan) => sum + scan.checked, 0)} tombstone(s) checked${truncated ? '; bounded, more not checked' : ''}).${otherNote}` });+ message: `No soft-deleted page was removed by a sync while Git never held its file (${scans.reduce((sum, scan) => sum + scan.checked, 0)} tombstone(s) checked${truncated ? '; bounded, more not checked' : ''}).${otherNote}${continueNote}` });} catch (error) {checks.push(checkError('uncommitted_sync_deletions', 'check soft-deleted pages for files Git never held', error, { details: { count: 'unknown', health: 'unknown', docs: DOCS } }));}diff --git a/src/commands/repair.ts b/src/commands/repair.tsindex 031341b952..30fb3de4fe 100644--- a/src/commands/repair.ts+++ b/src/commands/repair.ts@@ -76,7 +76,7 @@ export const REPAIR_HELP = `Usage: gbrain repair [<kind>] [--apply] [--source <i[--keep prior|disk|withdrawn --apply --expect <preview-hash> --yes] [--json]gbrain repair ghost-pages --source <id> [--apply --expect <preview-hash> --yes] [--json]gbrain repair legacy-twins --source <id> [--apply --expect <preview-hash> --yes] [--json]- gbrain repair uncommitted-deletions --source <id> [--include-ambiguous] [--apply --expect <preview-hash> --yes] [--json]+ gbrain repair uncommitted-deletions --source <id> [--after <page-id>] [--include-ambiguous] [--apply --expect <preview-hash> --yes] [--json]gbrain repair url-clone-fences [--source <id>] [--apply --expect <preview-hash> --yes] [--json]gbrain repair rename-identity --source <id> [--slug <new-slug> [--from <old-slug>] [--close][--apply --expect <preview-hash> --yes]] [--json]@@ -134,6 +134,9 @@ Options:withdrawn is a withdrawal-mirror effect's only choice).--request-id <uuid>stuck-recovery: resolve only this request's recovery (default: every blocked record of the source).+ --after <page-id>+ uncommitted-deletions: preview the next window, below the next_after page id the previous preview printed;+ the hash and the apply command carry it.--yes frontmatter, conversation-labels, stuck-recovery, ghost-pages, legacy-twins, rename-identity, url-clone-fences, uncommitted-deletions --apply: the user agreedto the previewed changes (destructive consent; without it a terminal asks, and a non-interactive run exits 3 with the consent payload).--json Machine-readable output with a stable shape (frontmatter: every per-file diff).@@ -151,7 +154,7 @@ A sources add --url clone whose pull stops at pull_blocked_local_changes: docs/gRenames 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']);+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']);/** 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'],@@ -159,10 +162,11 @@ const KIND_FLAGS: Record<string, readonly string[]> = {'--held': ['file-drift'], '--side': ['file-drift'], '--state': ['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' };+ '--request-id': '123e4567-e89b-42d3-a456-426614174000', '--older-than': '30d', '--from': 'notes/old', '--after': '1200' };/** 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 }) });@@ -171,7 +175,7 @@ interface RepairArgs { kind?: string; apply: boolean; all: boolean; json: booleanoLlm: 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;- keep?: 'prior' | 'disk' | 'withdrawn'; requestId?: string; olderThan?: string; includeFailures: boolean; force: boolean; from?: string; close: boolean }+ 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. */function maxUsdRefusal(flag: string, cap: string | undefined, kind: string | undefined): OperationError {@@ -267,6 +271,11 @@ export function parseRepairArgs(args: string[]): RepairArgs {['gbrain', 'repair', 'receipt-compaction', '--json']);parsed.olderThan = value;}+ else if (flag === '--after') {+ if (!/^[1-9]\d{0,15}$/.test(value)) throw invalid(`--after takes the page id a preview printed as next_after (got "${value}").`, 'Pass the next_after page id from the previous preview, e.g. --after 1200.',+ ['gbrain', 'repair', 'uncommitted-deletions', ...(parsed.source ? ['--source', parsed.source] : []), '--json']);+ parsed.afterPage = Number(value);+ }else if (flag === '--keep') keepText = value;else if (flag === '--request-id') {if (!/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i.test(value)) throw invalid(`--request-id must be a request UUID (got "${value}").`,@@ -357,7 +366,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 } = parseRepairArgs(args);+ prefer, requests, allDrifted, driftClass, since, held, side, state, 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).@@ -382,6 +391,7 @@ export async function runRepairCommand(engine: BrainEngine, args: string[]): Proconst preview = ['gbrain', 'repair', kind, ...(source ? ['--source', source] : []), ...only.flatMap(path => ['--only', path]), ...skip.flatMap(path => ['--skip', path]),...(includeAmbiguous ? ['--include-ambiguous'] : []), ...(requestId ? ['--request-id', requestId] : []),...(olderThan ? ['--older-than', olderThan] : []), ...(includeFailures ? ['--include-failures'] : []), ...(force ? ['--force'] : []),+ ...(afterPage !== undefined ? ['--after', String(afterPage)] : []),...(kind === 'rename-identity' ? [...slugs.flatMap(slug => ['--slug', slug]), ...(from ? ['--from', from] : []), ...(close ? ['--close'] : [])] : []),...(kind === 'origin-twins' ? slugs.flatMap(slug => ['--slug', slug]) : [])];const custom = repairSpec(kind as RepairKind).consentText;@@ -401,7 +411,7 @@ export async function runRepairCommand(engine: BrainEngine, args: string[]): Pro...(k === kind && k === 'file-drift' ? { prefer, requests, allDrifted, driftClass, since, ...(held ? { held } : {}), ...(side ? { side } : {}), ...(state ? { state } : {}) } : {}),...(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 && k === 'rename-identity' ? { from, close } : {}), ...(k === kind && afterPage !== undefined ? { afterPage } : {}) }));if (apply) clearHealthMemo(engine);const paidKinds = results.filter(r => r.paid).map(r => r.kind);if (json) {diff --git a/src/commands/sync/preflight.ts b/src/commands/sync/preflight.tsindex 12171ea87a..80bd62bc3c 100644--- a/src/commands/sync/preflight.ts+++ b/src/commands/sync/preflight.ts@@ -1113,32 +1113,33 @@ async function computeFilteredDelta(// modifies still import, and committing the deletions (or// GBRAIN_ALLOW_MASS_RECONCILE=1) re-enables them.if (importWorkingTree && filtered.deleted.length > 0 && !massReconcileAllowed()) {- try {- const rows = await engine.executeRaw<{ count: number }>(- opts.sourceId- ? `SELECT count(*)::int AS count FROM pages WHERE deleted_at IS NULL AND source_id = $1`- : `SELECT count(*)::int AS count FROM pages WHERE deleted_at IS NULL`,- opts.sourceId ? [opts.sourceId] : [],+ // #7130: the ratio is of the source's file-backed pages (the pages a missing file can delete). A failed read of the+ // count or the caps withholds every deletion: the brake cannot be checked, so nothing is deleted.+ const sid = opts.sourceId ?? DEFAULT_SOURCE_ID;+ const read = await Promise.all([+ engine.executeRaw<{ count: number }>(`SELECT count(*)::int AS count FROM pages WHERE deleted_at IS NULL AND source_id = $1 AND source_path IS NOT NULL`, [sid]),+ readSyncDeleteCaps(engine, sid),+ ]).then(([rows, caps]) => ({ pageCount: Number(rows[0]?.count ?? 0), caps }), (error: unknown) => ({ error }));+ if ('error' in read) {+ serr(`\n WARNING: refusing to delete ${filtered.deleted.length} page(s) from a working-tree sync: the delete limits could not be read (${read.error instanceof Error ? read.error.message : String(read.error)}). Adds/modifies still import; sync again once the database answers.\n`);+ filtered.deleted = [];+ }+ const { pageCount, caps } = 'error' in read ? { pageCount: 0, caps: null } : read;+ // The absolute caps apply on a detached HEAD too.+ const trip = caps ? syncDeleteTrip(filtered.deleted.length, pageCount, caps) : null;+ if (trip && caps) {+ serr(`\n WARNING: refusing to delete ${filtered.deleted.length} page(s) from a working-tree sync (${syncDeleteTripText(trip, caps)}). ` ++ `Commit the deletions and sync again, raise the cap (gbrain config set ${trip === 'max_deletes' ? 'sync.max_deletes' : 'sync.max_delete_ratio'}.source.${sid} <value>), or re-run with GBRAIN_ALLOW_MASS_RECONCILE=1. Adds/modifies still import.\n`);+ filtered.deleted = [];+ } else if (!detachedHead && filtered.deleted.length >= 10 && pageCount > 0 && filtered.deleted.length > pageCount * MASS_RECONCILE_RATIO) {+ serr(+ `\n WARNING: refusing to delete ${filtered.deleted.length} page(s) from a working-tree ` ++ `sync (> ${Math.round(MASS_RECONCILE_RATIO * 100)}% of ${pageCount} file-backed page(s)). An uncommitted ` ++ `tree deleting this much is almost always transient (mid-rebase, accidental rm) — commit the ` ++ `deletions to apply them, or re-run with GBRAIN_ALLOW_MASS_RECONCILE=1. Adds/modifies still import.\n`,);- const pageCount = Number(rows[0]?.count ?? 0);- // #7130: the absolute caps (sync.max_deletes, sync.max_delete_ratio) apply on a detached HEAD too.- const sid = opts.sourceId ?? DEFAULT_SOURCE_ID;- const caps = await readSyncDeleteCaps(engine, sid);- const trip = syncDeleteTrip(filtered.deleted.length, pageCount, caps);- if (trip) {- serr(`\n WARNING: refusing to delete ${filtered.deleted.length} page(s) from a working-tree sync (${syncDeleteTripText(trip, caps)}). ` +- `Commit the deletions and sync again, raise the cap (gbrain config set ${trip === 'max_deletes' ? 'sync.max_deletes' : 'sync.max_delete_ratio'}.source.${sid} <value>), or re-run with GBRAIN_ALLOW_MASS_RECONCILE=1. Adds/modifies still import.\n`);- filtered.deleted = [];- } else if (!detachedHead && filtered.deleted.length >= 10 && pageCount > 0 && filtered.deleted.length > pageCount * MASS_RECONCILE_RATIO) {- serr(- `\n WARNING: refusing to delete ${filtered.deleted.length} page(s) from a working-tree ` +- `sync (> ${Math.round(MASS_RECONCILE_RATIO * 100)}% of ${pageCount} page(s)). An uncommitted ` +- `tree deleting this much is almost always transient (mid-rebase, accidental rm) — commit the ` +- `deletions to apply them, or re-run with GBRAIN_ALLOW_MASS_RECONCILE=1. Adds/modifies still import.\n`,- );- filtered.deleted = [];- }- } catch { /* valve is best-effort — a count failure must not block the sync */ }+ filtered.deleted = [];+ }}// NAV-4: warn when --exclude filtered out every candidate change — almostdiff --git a/src/core/cli-flag-registry.generated.ts b/src/core/cli-flag-registry.generated.tsindex d3a09fecea..148686c1a5 100644--- a/src/core/cli-flag-registry.generated.ts+++ b/src/core/cli-flag-registry.generated.ts@@ -41,7 +41,7 @@ export const CLI_FLAG_REGISTRY: Record<string, readonly string[]> = {'code-def': ['--all-sources', '--brain', '--force', '--help', '--json', '--lang', '--limit', '--no-embed', '--no-json', '--probe', '--source', '--yes'],'code-refs': ['--all-sources', '--brain', '--force', '--help', '--json', '--lang', '--limit', '--no-embed', '--no-json', '--probe', '--source', '--yes'],'compile-context': ['--brain', '--budget', '--check', '--error-unmatch', '--git-path', '--help', '--include', '--include-core', '--json', '--out', '--remove-core', '--revision', '--show-toplevel', '--source', '--stdout', '--target'],- 'config': ['--accept-pending', '--admin-intent', '--all', '--all-from', '--apply', '--background', '--brain', '--budget-ms', '--call-site', '--confirm-quiesced', '--coverage-override', '--dataset', '--db-url', '--dim', '--dry-run', '--egress', '--embedding-dimensions', '--embedding-model', '--expected-state', '--explain', '--file', '--fix', '--follow', '--force', '--from', '--harness', '--help', '--http', '--id', '--include-withdrawals', '--input', '--items-out', '--json', '--limit', '--markdown', '--min', '--no-accept-pending', '--no-autopilot-install', '--no-embedding', '--no-hooks', '--no-llm', '--only', '--out', '--path', '--pattern', '--phase', '--probe', '--progress-interval', '--progress-json', '--provider', '--publish', '--query', '--quiet', '--raw', '--recommended', '--remediate', '--remediation-plan', '--remove', '--revision', '--session', '--shadow', '--since', '--slot', '--source', '--stale', '--status', '--stdin', '--suite', '--surface', '--target', '--threshold', '--tier', '--timeout', '--to', '--url', '--wait', '--what-if-threshold', '--yes'],+ 'config': ['--accept-pending', '--admin-intent', '--all', '--all-from', '--apply', '--background', '--brain', '--budget-ms', '--call-site', '--confirm-quiesced', '--coverage-override', '--dataset', '--db-url', '--diff-filter', '--dim', '--dry-run', '--egress', '--embedding-dimensions', '--embedding-model', '--exclude', '--expected-state', '--explain', '--file', '--fix', '--follow', '--force', '--format', '--from', '--full', '--hard-deadline', '--harness', '--help', '--http', '--id', '--include-hidden', '--include-withdrawals', '--input', '--items-out', '--json', '--limit', '--markdown', '--min', '--name-only', '--no-accept-pending', '--no-autopilot-install', '--no-embed', '--no-embedding', '--no-extract', '--no-hard-deadline', '--no-hooks', '--no-llm', '--no-pull', '--no-renames', '--no-schema-pack', '--only', '--out', '--path', '--pattern', '--phase', '--probe', '--progress-interval', '--progress-json', '--provider', '--publish', '--query', '--quiet', '--raw', '--recommended', '--remediate', '--remediation-plan', '--remove', '--repo', '--revision', '--session', '--shadow', '--since', '--slot', '--source', '--src-subpath', '--stale', '--status', '--stdin', '--strategy', '--suite', '--surface', '--target', '--threshold', '--tier', '--timeout', '--to', '--url', '--wait', '--what-if-threshold', '--working-tree', '--yes'],'connect': ['--agent', '--auto', '--bearer-token-env-var', '--bind', '--brain', '--client-id', '--client-secret', '--credentials-file', '--env', '--force', '--fresh-token', '--grant-types', '--harness', '--header', '--help', '--http', '--install', '--issuer-url', '--json', '--mcp-only', '--mcp-url', '--name', '--oauth', '--oauth-client-id', '--oauth-client-secret', '--public-url', '--pure', '--register', '--remove', '--root', '--scope', '--scopes', '--show-token', '--source', '--status', '--surface', '--timeout-ms', '--token', '--token-endpoint-auth-method', '--url', '--version', '--yes'],'connectors': ['--accept-pending', '--all', '--background', '--brain', '--cookie', '--dry-run', '--embed', '--explain', '--follow', '--force', '--full', '--help', '--install', '--json', '--limit', '--no-accept-pending', '--no-browser', '--probe', '--progress-interval', '--progress-json', '--quiet', '--source', '--timeout', '--token', '--try-oauth', '--wait', '--window-days', '--yes'],'conversation-parser': ['--brain', '--help', '--json', '--source'],@@ -49,7 +49,7 @@ export const CLI_FLAG_REGISTRY: Record<string, readonly string[]> = {'creds': ['--allow-create-db', '--allow-docker', '--brain', '--chat-model', '--content-root', '--db-only', '--embedding-dimensions', '--embedding-model', '--expansion-model', '--force', '--git', '--grant-types', '--help', '--http', '--ids', '--issuer-url', '--json', '--key', '--local-postgres', '--mcp-only', '--mcp-url', '--migrate-only', '--model', '--no-embedding', '--no-git', '--non-interactive', '--oauth-client-id', '--oauth-client-secret', '--out', '--passphrase-env', '--path', '--pglite', '--plan', '--prefer-postgres', '--provenance', '--provider', '--query', '--schema-pack', '--scopes', '--search-mode', '--skip-embed-check', '--source', '--status', '--supabase', '--surface', '--to', '--url', '--version'],'db-repair': ['--accept-pending', '--apply', '--apply-rewrites', '--background', '--brain', '--break-lock', '--db-url', '--dry-run', '--explain', '--filter', '--follow', '--force', '--force-retry', '--format', '--help', '--http', '--json', '--legacy-lock', '--locks', '--name', '--no-accept-pending', '--path', '--prefer-postgres', '--probe', '--progress-interval', '--progress-json', '--quiet', '--remediate', '--restart', '--skip-verify', '--source', '--statement-timeout', '--supabase', '--timeout', '--undo-last-rewrite', '--url', '--version', '--wait', '--yes'],'decide': ['--accept-all', '--all', '--all-from', '--apply', '--brain', '--call-site', '--dataset', '--dry-run', '--egress', '--embedding-dimensions', '--embedding-model', '--expect', '--from', '--help', '--include-withdrawals', '--input', '--items-out', '--json', '--kind', '--limit', '--max-cost', '--max-usd', '--min', '--non-interactive', '--out', '--provenance', '--provider', '--query', '--rate', '--reason', '--reason-family', '--recommended', '--remove', '--shadow', '--since', '--slot', '--source', '--status', '--suite', '--target', '--threshold', '--trust', '--undo', '--uri-prefix', '--version', '--what-if-threshold', '--yes'],- 'doctor': ['--abandon', '--abbrev-ref', '--accept-pending', '--access', '--account', '--acknowledge-managed', '--add', '--admin-intent', '--adopt', '--adopt-columns', '--adopt-permissions', '--aliases', '--all', '--all-drifted', '--all-from', '--allow-old-serve', '--allow-shell-jobs', '--allow-unverified-remote', '--allowed-operations', '--apply', '--apply-rewrites', '--assign-corpus', '--audit', '--auto', '--auto-additive', '--auto-fix', '--autostash', '--background', '--batch', '--batch-check', '--bound-brain', '--bound-max-concurrent', '--bound-slug-prefixes', '--bound-source', '--bound-tools', '--brain', '--branch', '--break-lock', '--budget-ms', '--budget-usd', '--by-mention', '--cached', '--call-site', '--catch-up', '--check', '--class', '--clear', '--clear-never-installed', '--client', '--close', '--concurrency', '--confidence', '--confirm', '--confirm-quiesced', '--confirm-relocated-root', '--conflicts', '--contacts-dir', '--content-audit', '--content-root', '--conversation', '--count', '--cursor', '--dataset', '--db-url', '--delegated-namespace', '--delegated-slug-prefixes', '--delete-brain', '--dest', '--detach', '--detail', '--diff-filter', '--dim', '--dir', '--disable', '--drain', '--drain-timeout', '--dry-run', '--egress', '--embedding-dimensions', '--embedding-model', '--enable', '--enable-dcr', '--end-of-options', '--entity', '--env', '--error-unmatch', '--exclude', '--exclude-standard', '--expand', '--expect', '--expect-local', '--expect-remote', '--expect-upstream', '--expected-epoch', '--expected-revision', '--expected-state', '--explain', '--facts', '--fast', '--federated-read', '--fetch-timeout-ms', '--ff-only', '--file', '--fix', '--follow', '--force', '--force-break-lock', '--force-rechunk', '--force-retry', '--force-schema', '--format', '--fresh', '--fresh-token', '--from', '--from-meetings', '--from-pages', '--full', '--fuzzy', '--get', '--git-common-dir', '--git-dir', '--git-path', '--group', '--group-by', '--hard', '--hard-deadline', '--harness', '--held', '--help', '--home', '--http', '--id', '--if-version', '--ignore-env-override', '--images', '--include-ambiguous', '--include-deleted', '--include-failures', '--include-flagged', '--include-frontmatter', '--include-gitignored', '--include-hidden', '--include-pseudo', '--include-repairs', '--include-withdrawals', '--index-audit', '--init', '--input', '--install', '--is-ancestor', '--is-inside-work-tree', '--items-out', '--job-isolation', '--jq', '--json', '--keep', '--keep-checkout', '--lanes', '--lang', '--left-right', '--legacy-lock', '--limit', '--link-source', '--link-type', '--list', '--literal-pathspecs', '--local', '--local-env-vars', '--locks', '--log-noop', '--manifest', '--markdown', '--max-cost', '--max-cost-usd', '--max-jobs', '--max-rss', '--max-runtime', '--max-usd', '--max-waiting', '--mcp-only', '--migrate-legacy', '--migrate-only', '--migration', '--min', '--min-n', '--mode', '--multimodal', '--name', '--name-only', '--nice', '--no-accept-pending', '--no-autopilot-install', '--no-autostash', '--no-capture', '--no-confirm', '--no-cron', '--no-delegate', '--no-edit', '--no-embed', '--no-embedding', '--no-expand', '--no-extract', '--no-filters', '--no-hooks', '--no-lanes', '--no-llm', '--no-migrate', '--no-probe', '--no-pull', '--no-renames', '--no-repair', '--no-schema-pack', '--no-seat', '--no-tags', '--no-verify', '--no-walk', '--non-interactive', '--now', '--older-than', '--once', '--only', '--operations', '--others', '--out', '--output', '--oversized', '--overwrite', '--page', '--parallel', '--params', '--parked-pushes', '--pat-file', '--path', '--path-format', '--pglite', '--phase', '--pid-file', '--plan', '--porcelain', '--port', '--prefer', '--prefer-postgres', '--preset', '--preview', '--probe', '--probe-pglite', '--profile', '--progress-interval', '--progress-json', '--project', '--provider', '--providers', '--prune-orphans', '--public-url', '--pull', '--pure', '--purge', '--push-only', '--query', '--question', '--queue', '--quiet', '--rate', '--reauth', '--rebase', '--rebuild', '--recommended', '--redact-paths', '--reference-date', '--refresh', '--refresh-operations', '--refresh-skills', '--regenerate', '--reissue', '--relative', '--relower', '--remediate', '--remediation-plan', '--remove', '--remove-core', '--repair', '--repair-unknown-markers', '--replace', '--repo', '--request', '--request-id', '--require-clean', '--reranker', '--reset', '--reset-checkpoint', '--reset-default', '--resolve', '--restore-only', '--resume', '--retry-failed', '--retry-global', '--retry-held', '--retry-parked', '--reverse', '--review-lower', '--revision', '--rollback-to-source', '--save', '--scope', '--scopes', '--search-mode', '--seat', '--section', '--select', '--self-transfer', '--semantic', '--session', '--session-id', '--set', '--set-upstream-to', '--shadow', '--short', '--show-current', '--show-prefix', '--show-token', '--show-toplevel', '--side', '--since', '--since-last-run', '--skills-dir', '--skip', '--skip-bare-tweet', '--skip-failed', '--skip-urls', '--skip-verify', '--slot', '--slug', '--slugs', '--source', '--source-id', '--sources', '--src-subpath', '--staged', '--stale', '--state', '--statement-timeout', '--status', '--stdin', '--strategy', '--strict', '--suite', '--supabase', '--surface', '--symbol-kind', '--symbolic-full-name', '--takes-holders', '--target', '--target-score', '--threshold', '--tier', '--timeout', '--to', '--token', '--token-ttl', '--top-k', '--trust', '--type', '--unindexed', '--uninstall', '--unsafe-bypass-dream-guard', '--unset-all', '--untracked-files', '--url', '--url-env', '--user', '--vacuum', '--vectors', '--verbose', '--verify', '--version', '--wait', '--wait-drain', '--warn-only', '--watch', '--what-if-threshold', '--window', '--workers', '--working-tree', '--workspace', '--yes'],+ 'doctor': ['--abandon', '--abbrev-ref', '--accept-pending', '--access', '--account', '--acknowledge-managed', '--add', '--admin-intent', '--adopt', '--adopt-columns', '--adopt-permissions', '--after', '--aliases', '--all', '--all-drifted', '--all-from', '--allow-old-serve', '--allow-shell-jobs', '--allow-unverified-remote', '--allowed-operations', '--apply', '--apply-rewrites', '--assign-corpus', '--audit', '--auto', '--auto-additive', '--auto-fix', '--autostash', '--background', '--batch', '--batch-check', '--bound-brain', '--bound-max-concurrent', '--bound-slug-prefixes', '--bound-source', '--bound-tools', '--brain', '--branch', '--break-lock', '--budget-ms', '--budget-usd', '--by-mention', '--cached', '--call-site', '--catch-up', '--check', '--class', '--clear', '--clear-never-installed', '--client', '--close', '--concurrency', '--confidence', '--confirm', '--confirm-quiesced', '--confirm-relocated-root', '--conflicts', '--contacts-dir', '--content-audit', '--content-root', '--conversation', '--count', '--cursor', '--dataset', '--db-url', '--delegated-namespace', '--delegated-slug-prefixes', '--delete-brain', '--dest', '--detach', '--detail', '--diff-filter', '--dim', '--dir', '--disable', '--drain', '--drain-timeout', '--dry-run', '--egress', '--embedding-dimensions', '--embedding-model', '--enable', '--enable-dcr', '--end-of-options', '--entity', '--env', '--error-unmatch', '--exclude', '--exclude-standard', '--expand', '--expect', '--expect-local', '--expect-remote', '--expect-upstream', '--expected-epoch', '--expected-revision', '--expected-state', '--explain', '--facts', '--fast', '--federated-read', '--fetch-timeout-ms', '--ff-only', '--file', '--fix', '--follow', '--force', '--force-break-lock', '--force-rechunk', '--force-retry', '--force-schema', '--format', '--fresh', '--fresh-token', '--from', '--from-meetings', '--from-pages', '--full', '--fuzzy', '--get', '--git-common-dir', '--git-dir', '--git-path', '--group', '--group-by', '--hard', '--hard-deadline', '--harness', '--held', '--help', '--home', '--http', '--id', '--if-version', '--ignore-env-override', '--images', '--include-ambiguous', '--include-deleted', '--include-failures', '--include-flagged', '--include-frontmatter', '--include-gitignored', '--include-hidden', '--include-pseudo', '--include-repairs', '--include-withdrawals', '--index-audit', '--init', '--input', '--install', '--is-ancestor', '--is-inside-work-tree', '--items-out', '--job-isolation', '--jq', '--json', '--keep', '--keep-checkout', '--lanes', '--lang', '--left-right', '--legacy-lock', '--limit', '--link-source', '--link-type', '--list', '--literal-pathspecs', '--local', '--local-env-vars', '--locks', '--log-noop', '--manifest', '--markdown', '--max-cost', '--max-cost-usd', '--max-jobs', '--max-rss', '--max-runtime', '--max-usd', '--max-waiting', '--mcp-only', '--migrate-legacy', '--migrate-only', '--migration', '--min', '--min-n', '--mode', '--multimodal', '--name', '--name-only', '--nice', '--no-accept-pending', '--no-autopilot-install', '--no-autostash', '--no-capture', '--no-confirm', '--no-cron', '--no-delegate', '--no-edit', '--no-embed', '--no-embedding', '--no-expand', '--no-extract', '--no-filters', '--no-hooks', '--no-lanes', '--no-llm', '--no-migrate', '--no-probe', '--no-pull', '--no-renames', '--no-repair', '--no-schema-pack', '--no-seat', '--no-tags', '--no-verify', '--no-walk', '--non-interactive', '--now', '--older-than', '--once', '--only', '--operations', '--others', '--out', '--output', '--oversized', '--overwrite', '--page', '--parallel', '--params', '--parked-pushes', '--pat-file', '--path', '--path-format', '--pglite', '--phase', '--pid-file', '--plan', '--porcelain', '--port', '--prefer', '--prefer-postgres', '--preset', '--preview', '--probe', '--probe-pglite', '--profile', '--progress-interval', '--progress-json', '--project', '--provider', '--providers', '--prune-orphans', '--public-url', '--pull', '--pure', '--purge', '--push-only', '--query', '--question', '--queue', '--quiet', '--rate', '--reauth', '--rebase', '--rebuild', '--recommended', '--redact-paths', '--reference-date', '--refresh', '--refresh-operations', '--refresh-skills', '--regenerate', '--reissue', '--relative', '--relower', '--remediate', '--remediation-plan', '--remove', '--remove-core', '--repair', '--repair-unknown-markers', '--replace', '--repo', '--request', '--request-id', '--require-clean', '--reranker', '--reset', '--reset-checkpoint', '--reset-default', '--resolve', '--restore-only', '--resume', '--retry-failed', '--retry-global', '--retry-held', '--retry-parked', '--reverse', '--review-lower', '--revision', '--rollback-to-source', '--save', '--scope', '--scopes', '--search-mode', '--seat', '--section', '--select', '--self-transfer', '--semantic', '--session', '--session-id', '--set', '--set-upstream-to', '--shadow', '--short', '--show-current', '--show-prefix', '--show-token', '--show-toplevel', '--side', '--since', '--since-last-run', '--skills-dir', '--skip', '--skip-bare-tweet', '--skip-failed', '--skip-urls', '--skip-verify', '--slot', '--slug', '--slugs', '--source', '--source-id', '--sources', '--src-subpath', '--staged', '--stale', '--state', '--statement-timeout', '--status', '--stdin', '--strategy', '--strict', '--suite', '--supabase', '--surface', '--symbol-kind', '--symbolic-full-name', '--takes-holders', '--target', '--target-score', '--threshold', '--tier', '--timeout', '--to', '--token', '--token-ttl', '--top-k', '--trust', '--type', '--unindexed', '--uninstall', '--unsafe-bypass-dream-guard', '--unset-all', '--untracked-files', '--url', '--url-env', '--user', '--vacuum', '--vectors', '--verbose', '--verify', '--version', '--wait', '--wait-drain', '--warn-only', '--watch', '--what-if-threshold', '--window', '--workers', '--working-tree', '--workspace', '--yes'],'dream': ['--audit-rejects', '--brain', '--cancel-unmatched', '--date', '--dir', '--drain', '--dry-run', '--eval-run', '--force', '--from', '--help', '--input', '--install', '--json', '--limit', '--list', '--max-usd', '--once', '--path', '--phase', '--probe', '--pull', '--reconcile-queue', '--since', '--source', '--source-id', '--threshold', '--to', '--unsafe-bypass-dream-guard', '--window', '--yes'],'edge-proposals': ['--access', '--add', '--all', '--all-applied', '--all-held', '--allowed-operations', '--asof', '--body', '--bound-slug-prefixes', '--brain', '--client', '--cursor', '--date', '--dated-since', '--days', '--entities', '--federated-read', '--from-index', '--full', '--fuzzy', '--group-by', '--help', '--http', '--id', '--include-deleted', '--json', '--kind', '--limit', '--max-usd', '--model', '--multimodal', '--no-autopilot-install', '--page', '--params', '--path', '--phase', '--prefer', '--purge', '--recent', '--refresh-operations', '--row', '--scopes', '--session', '--since', '--slugs', '--source', '--sources', '--stale', '--status', '--surface', '--to', '--updated-after', '--url', '--yes'],'edges-backfill': ['--all-sources', '--brain', '--concurrency', '--help', '--json', '--max-chunks', '--source', '--workers'],@@ -82,7 +82,7 @@ export const CLI_FLAG_REGISTRY: Record<string, readonly string[]> = {'lint': ['--abbrev-ref', '--accept-pending', '--adopt-slug-path', '--audit', '--autostash', '--background', '--brain', '--branch', '--cached', '--client', '--confirm-relocated-root', '--conflicts', '--dry-run', '--enable', '--exclude', '--expect-remote', '--expected-epoch', '--expected-revision', '--explain', '--ff-only', '--file', '--fix', '--follow', '--force', '--get', '--git-dir', '--git-path', '--grammar-diagnostics', '--hard', '--help', '--id', '--infer-entity', '--is-inside-work-tree', '--json', '--keep', '--local', '--local-env-vars', '--manifest', '--max-cost-usd', '--no-accept-pending', '--no-autostash', '--no-cron', '--no-pull', '--no-tags', '--no-verify', '--only', '--pat-file', '--path', '--prefer', '--preview', '--probe', '--progress-interval', '--progress-json', '--provenance', '--pull', '--purge', '--push-only', '--quiet', '--rebase', '--require-clean', '--resolve', '--scopes', '--self-transfer', '--short', '--show-toplevel', '--slug', '--slugs', '--source', '--source-id', '--timeout', '--unset-all', '--wait', '--yes'],'loops': ['--all', '--as-of', '--brain', '--dry-run', '--fail-fast', '--help', '--json', '--note', '--source', '--stale-ok', '--status', '--tools-json', '--top', '--type'],'lsd': ['--brain', '--force-resume', '--help', '--json', '--judge-model', '--limit', '--list-runs', '--max-cost', '--max-far-set', '--max-ideas-per-judge-call', '--max-usd', '--no-save', '--resume', '--save', '--source', '--strict-budget', '--yes'],- 'maintain': ['--account', '--admin-intent', '--adopt-columns', '--adopt-permissions', '--all', '--apply', '--assign-corpus', '--audit', '--background', '--brain', '--break-lock', '--budget-ms', '--by-mention', '--cached', '--catch-up', '--concurrency', '--conflicts', '--contacts-dir', '--content-audit', '--conversation', '--count', '--detach', '--detail', '--dim', '--dir', '--drain', '--dry-run', '--enable', '--entity', '--expect', '--expected-revision', '--expected-state', '--explain', '--facts', '--fast', '--fix', '--follow', '--force', '--force-retry', '--force-schema', '--format', '--from-meetings', '--full', '--group-by', '--hard-deadline', '--harness', '--help', '--http', '--id', '--images', '--include-ambiguous', '--include-flagged', '--include-frontmatter', '--include-gitignored', '--include-repairs', '--index-audit', '--infer-dates', '--install', '--json', '--keep-checkout', '--kind', '--lang', '--left-right', '--limit', '--link-source', '--link-type', '--list', '--locks', '--markdown', '--max-cost', '--max-cost-usd', '--max-jobs', '--max-rss', '--max-usd', '--migrate-legacy', '--migrate-only', '--multimodal', '--name', '--ner', '--no-autopilot-install', '--no-capture', '--no-delegate', '--no-embed', '--no-pull', '--once', '--only', '--operations', '--oversized', '--pack', '--page', '--parallel', '--params', '--path', '--pglite', '--phase', '--pid-file', '--plan', '--porcelain', '--prefer', '--preview', '--probe', '--probe-pglite', '--project', '--providers', '--prune-orphans', '--push-only', '--query', '--question', '--queue', '--reauth', '--rebuild', '--regenerate', '--remediate', '--remediation-plan', '--remove', '--remove-core', '--request-id', '--reset', '--reset-default', '--resume', '--retry-failed', '--retry-held', '--retry-parked', '--reverse', '--safe', '--scope', '--scopes', '--show-current', '--show-toplevel', '--since', '--skills-dir', '--skip-failed', '--slot', '--slug', '--slugs', '--source', '--source-id', '--sources', '--stale', '--state', '--status', '--supabase', '--symbol-kind', '--takes-holders', '--target', '--target-score', '--tier', '--to', '--token', '--top-k', '--type', '--unindexed', '--url-env', '--user', '--verbose', '--version', '--window', '--workers', '--yes'],+ 'maintain': ['--account', '--admin-intent', '--adopt-columns', '--adopt-permissions', '--after', '--all', '--apply', '--assign-corpus', '--audit', '--background', '--brain', '--break-lock', '--budget-ms', '--by-mention', '--cached', '--catch-up', '--concurrency', '--conflicts', '--contacts-dir', '--content-audit', '--conversation', '--count', '--detach', '--detail', '--dim', '--dir', '--drain', '--dry-run', '--enable', '--entity', '--expect', '--expected-revision', '--expected-state', '--explain', '--facts', '--fast', '--fix', '--follow', '--force', '--force-retry', '--force-schema', '--format', '--from-meetings', '--full', '--group-by', '--hard-deadline', '--harness', '--help', '--http', '--id', '--images', '--include-ambiguous', '--include-flagged', '--include-frontmatter', '--include-gitignored', '--include-repairs', '--index-audit', '--infer-dates', '--install', '--json', '--keep-checkout', '--kind', '--lang', '--left-right', '--limit', '--link-source', '--link-type', '--list', '--locks', '--markdown', '--max-cost', '--max-cost-usd', '--max-jobs', '--max-rss', '--max-usd', '--migrate-legacy', '--migrate-only', '--multimodal', '--name', '--ner', '--no-autopilot-install', '--no-capture', '--no-delegate', '--no-embed', '--no-pull', '--once', '--only', '--operations', '--oversized', '--pack', '--page', '--parallel', '--params', '--path', '--pglite', '--phase', '--pid-file', '--plan', '--porcelain', '--prefer', '--preview', '--probe', '--probe-pglite', '--project', '--providers', '--prune-orphans', '--push-only', '--query', '--question', '--queue', '--reauth', '--rebuild', '--regenerate', '--remediate', '--remediation-plan', '--remove', '--remove-core', '--request-id', '--reset', '--reset-default', '--resume', '--retry-failed', '--retry-held', '--retry-parked', '--reverse', '--safe', '--scope', '--scopes', '--show-current', '--show-toplevel', '--since', '--skills-dir', '--skip-failed', '--slot', '--slug', '--slugs', '--source', '--source-id', '--sources', '--stale', '--state', '--status', '--supabase', '--symbol-kind', '--takes-holders', '--target', '--target-score', '--tier', '--to', '--token', '--top-k', '--type', '--unindexed', '--url-env', '--user', '--verbose', '--version', '--window', '--workers', '--yes'],'mcp': ['--admin-token-file', '--agent', '--arg', '--bearer-token-env-var', '--bound-brain', '--bound-max-concurrent', '--bound-slug-prefixes', '--bound-source', '--bound-tools', '--brain', '--budget-usd-per-day', '--client', '--credentials-file', '--credentials-out', '--delegate', '--delegated-namespace', '--delegated-slug-prefixes', '--dry-run', '--enable-dcr', '--federated-read', '--flow', '--force', '--funnel', '--harness', '--header', '--help', '--if-version', '--install', '--issuer-url', '--json', '--limit', '--mcp-only', '--mcp-url', '--no-install', '--no-service', '--no-tailscale', '--oauth-client-id', '--oauth-client-secret', '--oauth-request', '--port', '--profile', '--queue', '--redirect-uri', '--remove', '--resume', '--root', '--scope', '--scopes', '--skills', '--source', '--status', '--surface', '--timeout-ms', '--token', '--token-endpoint-auth-method', '--token-ttl', '--url', '--yes'],'migrate': ['--accept-pending', '--admin-intent', '--all', '--apply', '--background', '--batch-size', '--brain', '--catch-up', '--dim', '--drain-timeout', '--dry-run', '--embedding-dimensions', '--embedding-model', '--expect', '--expected-epoch', '--expected-state', '--explain', '--facts', '--follow', '--force', '--force-retry', '--harness', '--held', '--help', '--ignore-env-override', '--images', '--include-null-signature', '--json', '--locks', '--manifest', '--max-cost', '--max-cost-usd', '--max-usd', '--no-accept-pending', '--no-embed', '--no-embedding', '--no-migrate', '--non-interactive', '--only', '--oversized', '--pace', '--pace-max-concurrency', '--path', '--pglite', '--plan', '--priority', '--probe', '--progress-interval', '--progress-json', '--quiet', '--replace', '--reranker', '--resume', '--retarget', '--rollback-to-source', '--scope', '--skip-verify', '--slugs', '--source', '--stale', '--statement-timeout', '--status', '--timeout', '--to', '--trigger-bypass', '--trust', '--url', '--url-env', '--wait', '--yes'],'models': ['--batch', '--brain', '--concurrent', '--cycles', '--dim', '--dimensions', '--embedding-dimensions', '--embedding-model', '--help', '--json', '--limit', '--max-tokens', '--max-usd', '--output', '--receipt-dir', '--skip', '--slot-a-model', '--slot-b-model', '--slot-c-model', '--slug', '--source', '--status', '--task', '--to', '--yes'],@@ -91,7 +91,7 @@ export const CLI_FLAG_REGISTRY: Record<string, readonly string[]> = {'notices': ['--brain', '--help', '--json', '--source'],'onboard': ['--access', '--add', '--all', '--allowed-operations', '--apply', '--asof', '--auto', '--body', '--bound-slug-prefixes', '--brain', '--check', '--client', '--cursor', '--date', '--dated-since', '--days', '--entities', '--explain', '--federated-read', '--from-index', '--from-pages', '--full', '--fuzzy', '--group-by', '--help', '--history', '--http', '--id', '--include-deleted', '--json', '--kind', '--limit', '--max-usd', '--model', '--multimodal', '--no-autopilot-install', '--only', '--page', '--params', '--path', '--phase', '--prefer', '--probe', '--purge', '--recent', '--refresh-operations', '--remediate', '--remediation-plan', '--resume', '--row', '--save', '--scopes', '--session', '--since', '--slugs', '--source', '--sources', '--stale', '--surface', '--target-score', '--to', '--updated-after', '--url', '--yes'],'orphans': ['--accept-pending', '--background', '--brain', '--count', '--explain', '--follow', '--force', '--help', '--include-pseudo', '--json', '--mode', '--no-accept-pending', '--progress-interval', '--progress-json', '--quiet', '--source', '--timeout', '--wait'],- 'pages': ['--brain', '--dry-run', '--force', '--help', '--json', '--limit', '--older-than', '--retry-parked', '--source', '--state', '--yes'],+ 'pages': ['--brain', '--dry-run', '--force', '--help', '--json', '--limit', '--older-than', '--retry-parked', '--source', '--source-id', '--state', '--yes'],'pglite-repair': ['--brain', '--break-lock', '--dry-run', '--expect', '--help', '--http', '--json', '--legacy-lock', '--path', '--probe', '--source', '--vectors', '--yes'],'post-upgrade': ['--accept-reviewed-inventory', '--acknowledge-no-backup', '--admin-intent', '--all', '--all-applied', '--apply', '--apply-clean-hunks', '--backup-confirmed', '--brain', '--catch-up', '--changed', '--check', '--concurrency', '--confirm-quiesced', '--confirm-relocated-root', '--content-root', '--cost-estimate', '--embedding-dimensions', '--embedding-model', '--exit-code', '--expand', '--expected-epoch', '--expected-state', '--explain', '--export-db-only', '--export-source', '--ff-only', '--force', '--force-all', '--force-orchestrator', '--force-retry', '--force-schema', '--format', '--held', '--help', '--host-dir', '--images', '--inject-bootstrap', '--inline', '--install', '--interval', '--json', '--limit', '--list', '--manifest', '--markdown', '--max-rss', '--max-usd', '--migrate-only', '--migration', '--mode', '--multimodal', '--name-only', '--no-autopilot-install', '--no-bun-floor-check', '--no-embed', '--no-expand', '--no-inject', '--no-worker', '--non-interactive', '--now', '--once', '--only', '--oversized', '--path', '--pause', '--phase', '--quiet', '--reason', '--refs', '--remediation-plan', '--repo', '--require-db', '--resume', '--retry-global', '--search-mode', '--self-transfer', '--skills-dir', '--skip-verify', '--source', '--stale', '--statement-timeout', '--status', '--swap-only', '--tags', '--target', '--uninstall', '--user', '--vectors', '--verify', '--version', '--workers', '--yes'],'pricing': ['--brain', '--help', '--input', '--json', '--max-cost', '--max-runtime', '--output', '--rate', '--source'],@@ -109,7 +109,7 @@ export const CLI_FLAG_REGISTRY: Record<string, readonly string[]> = {'reindex-search-vector': ['--accept-pending', '--background', '--brain', '--dry-run', '--explain', '--follow', '--help', '--json', '--no-accept-pending', '--progress-interval', '--progress-json', '--quiet', '--resume', '--source', '--timeout', '--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', '--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': ['--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-jsonb': ['--accept-pending', '--background', '--brain', '--dry-run', '--explain', '--follow', '--help', '--json', '--no-accept-pending', '--probe', '--progress-interval', '--progress-json', '--quiet', '--source', '--supabase', '--timeout', '--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'],@@ -130,7 +130,7 @@ export const CLI_FLAG_REGISTRY: Record<string, readonly string[]> = {'status': ['--abbrev-ref', '--acknowledge-managed', '--all', '--allow-empty', '--apply', '--body', '--brain', '--break-lock', '--cached', '--check', '--concurrency', '--confirm-destructive', '--deadline-ms', '--delete', '--detail', '--diff-filter', '--empty', '--enable', '--exclude', '--exclude-standard', '--fast', '--filters', '--fix', '--force-break-lock', '--format', '--full', '--full-history', '--funnel', '--hard-deadline', '--help', '--include-gitignored', '--include-hidden', '--install', '--interval', '--is-ancestor', '--is-shallow-repository', '--json', '--lanes', '--max-age', '--max-sources', '--mcp-only', '--missing-path', '--name-only', '--no-auto-embed', '--no-bulk', '--no-delegate', '--no-embed', '--no-extract', '--no-gpg-sign', '--no-hard-deadline', '--no-lanes', '--no-llm', '--no-pull', '--no-renames', '--no-repair', '--no-schema-pack', '--no-verify', '--no-walk', '--others', '--parallel', '--path', '--prefer', '--preview', '--priority', '--quiet', '--redact-paths', '--repo', '--request-id', '--reset-checkpoint', '--retry-failed', '--retry-held', '--section', '--serial', '--show-toplevel', '--skip-failed', '--slugs', '--source', '--source-id', '--src-subpath', '--stale', '--status', '--strategy', '--timeout', '--url', '--verify', '--watch', '--workers', '--working-tree', '--yes'],'storage': ['--brain', '--fix', '--help', '--json', '--plan', '--repo', '--restore-only', '--source', '--to'],'sweep': ['--accept-pending', '--apply', '--assign-corpus', '--background', '--batch-limit', '--brain', '--budget-ms', '--delete-brain', '--explain', '--follow', '--help', '--home', '--json', '--no-accept-pending', '--no-delegate', '--once', '--only', '--progress-interval', '--progress-json', '--quiet', '--retry-failed', '--session', '--source', '--source-id', '--stale', '--timeout', '--wait'],- 'sync': ['--abbrev-ref', '--accept-pending', '--account', '--acknowledge-managed', '--admin-intent', '--adopt-columns', '--adopt-permissions', '--all', '--allow-empty', '--apply', '--apply-rewrites', '--assign-corpus', '--audit', '--auto', '--background', '--batch', '--batch-size', '--body', '--brain', '--branch', '--break-lock', '--budget-ms', '--by-mention', '--cached', '--catch-up', '--check', '--client', '--close', '--concurrency', '--confirm-destructive', '--confirm-quiesced', '--confirm-relocated-root', '--conflicts', '--contacts-dir', '--content-audit', '--conversation', '--count', '--db-url', '--delete-brain', '--depth', '--detach', '--detail', '--diff-filter', '--dim', '--dir', '--drain', '--dry-run', '--embedding-dimensions', '--embedding-model', '--empty', '--enable', '--entity', '--exclude', '--exclude-standard', '--expect', '--expect-local', '--expect-upstream', '--expected-epoch', '--expected-revision', '--expected-state', '--explain', '--facts', '--fast', '--ff-only', '--filters', '--first-parent', '--fix', '--follow', '--force', '--force-break-lock', '--force-rechunk', '--force-retry', '--force-schema', '--format', '--fresh', '--from', '--from-meetings', '--full', '--full-history', '--git-dir', '--git-path', '--group-by', '--hard-deadline', '--harness', '--held', '--help', '--home', '--http', '--id', '--images', '--include-ambiguous', '--include-flagged', '--include-frontmatter', '--include-gitignored', '--include-hidden', '--include-null-signature', '--include-repairs', '--index-audit', '--infer-dates', '--install', '--interval', '--is-ancestor', '--is-shallow-repository', '--json', '--keep-checkout', '--kind', '--lanes', '--lang', '--left-right', '--legacy-lock', '--limit', '--link-source', '--link-type', '--list', '--locks', '--log-noop', '--manifest', '--markdown', '--max-age', '--max-cost', '--max-cost-usd', '--max-jobs', '--max-rss', '--max-sources', '--max-usd', '--migrate-legacy', '--migrate-only', '--missing-path', '--multimodal', '--name', '--name-only', '--name-status', '--ner', '--no-accept-pending', '--no-auto-embed', '--no-autopilot-install', '--no-bulk', '--no-capture', '--no-delegate', '--no-embed', '--no-extract', '--no-gpg-sign', '--no-hard-deadline', '--no-lanes', '--no-llm', '--no-pull', '--no-renames', '--no-repair', '--no-schema-pack', '--no-verify', '--no-walk', '--once', '--only', '--operations', '--others', '--oversized', '--overwrite', '--pace', '--pace-max-concurrency', '--pack', '--page', '--parallel', '--params', '--path', '--path-format', '--pglite', '--phase', '--pid-file', '--plan', '--porcelain', '--prefer', '--prefer-postgres', '--preview', '--priority', '--probe', '--probe-pglite', '--progress-interval', '--progress-json', '--project', '--providers', '--prune-orphans', '--pull', '--push-only', '--query', '--question', '--queue', '--quiet', '--raw', '--reauth', '--rebuild', '--redact-paths', '--refresh', '--regenerate', '--relative', '--remediate', '--remediation-plan', '--remove', '--remove-core', '--replace', '--repo', '--request-id', '--reset', '--reset-checkpoint', '--reset-default', '--restore-only', '--resume', '--retry-failed', '--retry-held', '--retry-parked', '--reverse', '--scope', '--scopes', '--self-transfer', '--serial', '--short', '--show-current', '--show-toplevel', '--side', '--since', '--skills-dir', '--skip', '--skip-failed', '--slot', '--slug', '--slugs', '--source', '--source-id', '--sources', '--src-subpath', '--stale', '--state', '--status', '--stdin', '--strategy', '--supabase', '--symbol-kind', '--symbolic-full-name', '--takes-holders', '--target', '--target-score', '--tier', '--timeout', '--to', '--token', '--top-k', '--type', '--unindexed', '--url', '--url-env', '--user', '--verbose', '--verify', '--version', '--wait', '--watch', '--window', '--workers', '--working-tree', '--yes'],+ 'sync': ['--abbrev-ref', '--accept-pending', '--account', '--acknowledge-managed', '--admin-intent', '--adopt-columns', '--adopt-permissions', '--after', '--all', '--allow-empty', '--apply', '--apply-rewrites', '--assign-corpus', '--audit', '--auto', '--background', '--batch', '--batch-size', '--body', '--brain', '--branch', '--break-lock', '--budget-ms', '--by-mention', '--cached', '--catch-up', '--check', '--client', '--close', '--concurrency', '--confirm-destructive', '--confirm-quiesced', '--confirm-relocated-root', '--conflicts', '--contacts-dir', '--content-audit', '--conversation', '--count', '--db-url', '--delete-brain', '--depth', '--detach', '--detail', '--diff-filter', '--dim', '--dir', '--drain', '--dry-run', '--embedding-dimensions', '--embedding-model', '--empty', '--enable', '--entity', '--exclude', '--exclude-standard', '--expect', '--expect-local', '--expect-upstream', '--expected-epoch', '--expected-revision', '--expected-state', '--explain', '--facts', '--fast', '--ff-only', '--filters', '--first-parent', '--fix', '--follow', '--force', '--force-break-lock', '--force-rechunk', '--force-retry', '--force-schema', '--format', '--fresh', '--from', '--from-meetings', '--full', '--full-history', '--git-dir', '--git-path', '--group-by', '--hard-deadline', '--harness', '--held', '--help', '--home', '--http', '--id', '--images', '--include-ambiguous', '--include-flagged', '--include-frontmatter', '--include-gitignored', '--include-hidden', '--include-null-signature', '--include-repairs', '--index-audit', '--infer-dates', '--install', '--interval', '--is-ancestor', '--is-shallow-repository', '--json', '--keep-checkout', '--kind', '--lanes', '--lang', '--left-right', '--legacy-lock', '--limit', '--link-source', '--link-type', '--list', '--locks', '--log-noop', '--manifest', '--markdown', '--max-age', '--max-cost', '--max-cost-usd', '--max-jobs', '--max-rss', '--max-sources', '--max-usd', '--migrate-legacy', '--migrate-only', '--missing-path', '--multimodal', '--name', '--name-only', '--name-status', '--ner', '--no-accept-pending', '--no-auto-embed', '--no-autopilot-install', '--no-bulk', '--no-capture', '--no-delegate', '--no-embed', '--no-extract', '--no-gpg-sign', '--no-hard-deadline', '--no-lanes', '--no-llm', '--no-pull', '--no-renames', '--no-repair', '--no-schema-pack', '--no-verify', '--no-walk', '--once', '--only', '--operations', '--others', '--oversized', '--overwrite', '--pace', '--pace-max-concurrency', '--pack', '--page', '--parallel', '--params', '--path', '--path-format', '--pglite', '--phase', '--pid-file', '--plan', '--porcelain', '--prefer', '--prefer-postgres', '--preview', '--priority', '--probe', '--probe-pglite', '--progress-interval', '--progress-json', '--project', '--providers', '--prune-orphans', '--pull', '--push-only', '--query', '--question', '--queue', '--quiet', '--raw', '--reauth', '--rebuild', '--redact-paths', '--refresh', '--regenerate', '--relative', '--remediate', '--remediation-plan', '--remove', '--remove-core', '--replace', '--repo', '--request-id', '--reset', '--reset-checkpoint', '--reset-default', '--restore-only', '--resume', '--retry-failed', '--retry-held', '--retry-parked', '--reverse', '--scope', '--scopes', '--self-transfer', '--serial', '--short', '--show-current', '--show-toplevel', '--side', '--since', '--skills-dir', '--skip', '--skip-failed', '--slot', '--slug', '--slugs', '--source', '--source-id', '--sources', '--src-subpath', '--stale', '--state', '--status', '--stdin', '--strategy', '--supabase', '--symbol-kind', '--symbolic-full-name', '--takes-holders', '--target', '--target-score', '--tier', '--timeout', '--to', '--token', '--top-k', '--type', '--unindexed', '--url', '--url-env', '--user', '--verbose', '--verify', '--version', '--wait', '--watch', '--window', '--workers', '--working-tree', '--yes'],'takes': ['--about', '--accept', '--applied', '--apply', '--batch-size', '--before', '--brain', '--bucket-size', '--by', '--claim', '--date', '--dim', '--dir', '--domain', '--dry-run', '--embedding-dimensions', '--embedding-model', '--evidence', '--expected-revision', '--expired', '--failed', '--force', '--from-pages', '--group-by', '--help', '--holder', '--include-covered', '--json', '--kind', '--limit', '--max-pages', '--min-confidence', '--min-n', '--no-embed', '--no-embedding', '--offset', '--outcome', '--path', '--quality', '--reject', '--request-id', '--retry-failed', '--row', '--semantic', '--since', '--slug', '--sort', '--source', '--source-id', '--stale', '--state', '--status', '--supabase', '--to', '--unapplied', '--unit', '--until', '--value', '--verdict', '--weight', '--who', '--yes'],'think': ['--anchor', '--brain', '--calibration-holder', '--help', '--json', '--mcp-only', '--model', '--only', '--reference-date', '--request-id', '--rounds', '--save', '--since', '--source', '--source-id', '--take', '--until', '--with-calibration'],'transcripts': ['--accept-pending', '--all', '--all-discovery', '--apply', '--background', '--brain', '--days', '--dry-run', '--embed', '--explain', '--facts', '--follow', '--format', '--full', '--help', '--include-self', '--json', '--limit', '--max-bytes', '--max-cost-usd', '--no-accept-pending', '--only', '--progress-interval', '--progress-json', '--purge', '--quiet', '--since', '--source', '--source-id', '--timeout', '--wait'],diff --git a/src/core/persistence/page-prepare.ts b/src/core/persistence/page-prepare.tsindex 2cdec2586f..96933b4fa8 100644--- a/src/core/persistence/page-prepare.ts+++ b/src/core/persistence/page-prepare.ts@@ -296,8 +296,9 @@ export async function prepareFileTarget(engine: BrainEngine, row: Pick<WriteRequ{ fix: ownerStatusFix(row.source_id) });// #7130: a canonical file under a path the checkout's .gitignore excludes would never be committed, so the page would be// file-backed by a file no history holds (and a later sync could read its absence as a deletion). The write publishes- // to the database only and binds no file; a declared db_only page keeps its cache file as before.- if (!isSourceDbOnlySlug(root, row.slug, 'not_db_only') && await gitIgnoresUntracked(root, relative(root, path).split(sep).join('/'))) return undefined;+ // to the database only and binds no file; a declared db_only page keeps its cache file as before. A page that already+ // records a file keeps it (and its drift checks): only a person's detach turns it database-only.+ if (!snapshot?.page.source_path && !recordedPathFromFileUri(snapshot?.page.source_uri, root) && !isSourceDbOnlySlug(root, row.slug, 'not_db_only') && await gitIgnoresUntracked(root, relative(root, path).split(sep).join('/'))) return undefined;if (options.excludeTombstone && snapshot?.page.deleted_at) {const rel = relative(root, path).split(sep).join('/');if (matchesAnyGlob(rel, options.excludeTombstone.patterns)) { options.excludeTombstone.onExcluded(rel); return undefined; }diff --git a/src/core/persistence/sync-discovery.ts b/src/core/persistence/sync-discovery.tsindex 52575622ed..3476f74887 100644--- a/src/core/persistence/sync-discovery.ts+++ b/src/core/persistence/sync-discovery.ts@@ -350,9 +350,9 @@ export async function discoverManagedSync(engine: BrainEngine, opts: SyncOpts, cconst entries = new Map<string, SyncEntry>();const renamedFrom = new Map<string, { from: string; identityHead?: string }>();let workingTreeKept: string[] | undefined;- let treeAbsent: Array<{ id: number; gitPath: string }> = [];+ let treeAbsent: Array<{ id: number; gitPath: string; evidencePath?: string }> = [];// #7130: deletions no Git change names (a tree walk's absent pages, a re-screened held deletion) need a commit that held the file.- const unproven = new Set<string>();+ const unproven = new Map<string, string>();const discoveredAt = new Date().toISOString();// #5988: active holds are re-screened when their file changed, left, or a newer reader may import it.const holds = company ? [] : (await readGitSourceHolds(engine, { sourceIds: [sourceId] }))[0]?.holds.filter(hold => hold.incarnation === incarnation) ?? [];@@ -413,7 +413,12 @@ export async function discoverManagedSync(engine: BrainEngine, opts: SyncOpts, c// #5988: the old page of a held rename keeps its origin until the renamed file imports.return !holdRenameOrigins.has(origin);});- treeAbsent = absent.map(page => ({ id: page.id, gitPath: gitPathOf(syncOriginPath(page.source_path)) }));+ treeAbsent = absent.map(page => {+ const origin = syncOriginPath(page.source_path);+ // #7130: a legacy origin recorded Git-root-relative under a source-root scope is already the file's Git path.+ const legacy = slugMode === 'source-root' && scope && origin.startsWith(`${scope}/`) && sameSyncOrigin(origin, origin.slice(scope.length + 1), originScope, page.slug);+ return { id: page.id, gitPath: gitPathOf(origin), ...(legacy ? { evidencePath: origin } : {}) };+ });}if (working) {for (const path of [...dirty.added, ...dirty.modified]) put(path, 'import', true);@@ -423,7 +428,7 @@ export async function discoverManagedSync(engine: BrainEngine, opts: SyncOpts, cif (treeAbsent.length) {// A path the selected working tree already decided (an import or a deletion above) is not re-judged.const kept = await keptWorkingTreePages(engine, { sourceId, incarnation, root, nativeRoot, nativeGitRoot }, treeAbsent.filter(page => !entries.has(page.gitPath)));- for (const page of treeAbsent) if (!entries.has(page.gitPath) && !kept.has(page.gitPath)) { put(page.gitPath, 'delete'); unproven.add(page.gitPath); }+ for (const page of treeAbsent) if (!entries.has(page.gitPath) && !kept.has(page.gitPath)) { put(page.gitPath, 'delete'); unproven.set(page.gitPath, page.evidencePath ?? page.gitPath); }if (kept.size) workingTreeKept = [...kept];}// #6278 (B7): every scheduled path is consumed by this discovery: it is screened as an entry (the file changed in Git),@@ -456,14 +461,14 @@ export async function discoverManagedSync(engine: BrainEngine, opts: SyncOpts, c}if (!changed) continue;put(gitPath, present ? 'import' : 'delete', workingHold);- if (!present) unproven.add(gitPath);+ if (!present) unproven.set(gitPath, gitPath);}}let uncommittedKept: string[] | undefined;- const unprovenDeletes = [...unproven].filter(path => entries.get(path)?.action === 'delete');+ const unprovenDeletes = [...unproven.keys()].filter(path => entries.get(path)?.action === 'delete');if (unprovenDeletes.length && !company) {- const evidence = await readOriginEvidence(gitRoot, [target, source.last_commit], unprovenDeletes);- uncommittedKept = unprovenDeletes.filter(path => evidence.get(path) !== 'committed');+ const evidence = await readOriginEvidence(gitRoot, [target, source.last_commit], unprovenDeletes.map(path => unproven.get(path)!));+ uncommittedKept = unprovenDeletes.filter(path => evidence.get(unproven.get(path)!) !== 'committed');for (const path of uncommittedKept) entries.delete(path);}if (company) {diff --git a/src/core/persistence/sync-origin-evidence.ts b/src/core/persistence/sync-origin-evidence.tsindex a9455f534f..2fe517b2f6 100644--- a/src/core/persistence/sync-origin-evidence.ts+++ b/src/core/persistence/sync-origin-evidence.ts@@ -14,7 +14,7 @@ import { gitChildEnv } from '../git-env.ts';const execFileAsync = promisify(execFile);-/** `committed`: some commit of the history holds the path. `never_committed`: none does. `ignored`: `.gitignore` excludes it. `unknown`: a read failed. */+/** `committed`: some commit of the history holds the path. `never_committed`: none does. `ignored`: none does and `.gitignore` excludes it (a commit's evidence wins over a later ignore rule). `unknown`: a read failed. */export type OriginEvidence = 'committed' | 'never_committed' | 'ignored' | 'unknown';/** Paths per Git invocation (argument-list bound). */@@ -71,15 +71,16 @@ export async function readOriginEvidence(gitRoot: string, commits: ReadonlyArrayfor (let i = 0; i < paths.length; i += BATCH) {const batch = paths.slice(i, i + BATCH);const touched = tips.length ? await git(gitRoot, ['log', ...tips, '--format=', '--name-only', '--no-renames', '-z', '--', ...batch], true) : { code: 0, stdout: '' };- const committed = new Set(touched.stdout.split('\0').map(path => path.trim()).filter(Boolean));+ // With an empty format and -z, every name is one NUL-terminated record (no separator between commits): read each byte for byte.+ const committed = new Set(touched.stdout.split('\0').filter(Boolean));const ignoredRead = await checkIgnore(gitRoot, batch);const ignored = new Set(ignoredRead.stdout.split('\0').filter(Boolean));// check-ignore exits 1 when no path is ignored; anything else but 0 is a failed read.const ignoreKnown = ignoredRead.code === 0 || ignoredRead.code === 1;for (const path of batch) {if (touched.code !== 0 || !ignoreKnown) evidence.set(path, 'unknown');- else if (ignored.has(path)) evidence.set(path, 'ignored');- else evidence.set(path, committed.has(path) ? 'committed' : 'never_committed');+ else if (committed.has(path)) evidence.set(path, 'committed');+ else evidence.set(path, ignored.has(path) ? 'ignored' : 'never_committed');}}return evidence;diff --git a/src/core/repair/core.ts b/src/core/repair/core.tsindex c6340945b0..a8c3beec79 100644--- a/src/core/repair/core.ts+++ b/src/core/repair/core.ts@@ -112,7 +112,9 @@ export interface RepairPlanOptions { apply: boolean; expect?: string; includeAmb/** `receipt-compaction` (#6696 A9): the age (`72h`, `30d`), failures too, and compaction inside the retention window. */olderThan?: string; includeFailures?: boolean; force?: boolean;/** `rename-identity` (#6729): the old slug that disambiguates a pair (`--from`), and the close disposition (`--close`). */- from?: string; close?: boolean }+ from?: string; close?: boolean;+ /** `uncommitted-deletions` (#7130): the preview window starts below this page id (`--after`). */+ afterPage?: number }export interface RepairHandler {kind: RepairKind;@@ -308,7 +310,7 @@ export async function runRepair(ctx: OperationContext, handler: RepairHandler, sopts: { 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;- keep?: 'prior' | 'disk' | 'withdrawn'; requestId?: string; olderThan?: string; includeFailures?: boolean; force?: boolean; from?: string; close?: boolean;+ 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). */publicationOwner?: () => Promise<{ alive: boolean; owner: string }> }): Promise<RepairResult> {@@ -332,7 +334,7 @@ async function runRepairScoped(ctx: OperationContext, handler: RepairHandler, sc...(opts.held ? { held: true } : {}), ...(opts.side ? { side: opts.side } : {}), ...(opts.state ? { state: opts.state } : {}),...(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.from ? { from: opts.from } : {}), ...(opts.close ? { close: true } : {}), ...(opts.afterPage !== undefined ? { afterPage: opts.afterPage } : {}) };const plan = await handler.plan(ctx.engine, scope, resumed, planOpts);const pending = opts.limit !== undefined ? plan.items.slice(0, opts.limit) : plan.items;const counters = await capacity(ctx);diff --git a/src/core/repair/registry.ts b/src/core/repair/registry.tsindex cb637c5354..75722b75f7 100644--- a/src/core/repair/registry.ts+++ b/src/core/repair/registry.ts@@ -583,15 +583,16 @@ 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;- keep?: 'prior' | 'disk' | 'withdrawn'; requestId?: string; olderThan?: string; includeFailures?: boolean; force?: boolean; from?: string; close?: boolean } = {}): Promise<RepairResult> {+ 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);return runRepair(ctx, spec.handler, scope, { apply: opts.apply, limit: run.limit, embeddingModel, sourceFlag: run.sourceFlag, spec,embed: !opts.noEmbed && embeddingModel !== undefined, applyArgs: [...(opts.noEmbed && spec.embeds === 'inline' ? ['--no-embed'] : []),- ...(run.olderThan ? ['--older-than', run.olderThan] : []), ...(run.includeFailures ? ['--include-failures'] : []), ...(run.force ? ['--force'] : [])],+ ...(run.olderThan ? ['--older-than', run.olderThan] : []), ...(run.includeFailures ? ['--include-failures'] : []), ...(run.force ? ['--force'] : []),+ ...(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 });+ 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 });},};}diff --git a/src/core/repair/uncommitted-deletions.ts b/src/core/repair/uncommitted-deletions.tsindex d5fe305e8f..70d25af69c 100644--- a/src/core/repair/uncommitted-deletions.ts+++ b/src/core/repair/uncommitted-deletions.ts@@ -13,7 +13,9 @@* written, so the next sync has no file to read as missing and never deletes it again. A page that changed since the* preview is skipped `changed_since_preview`; one whose file is back in the checkout is skipped `file_restored` (sync* reads it); one purged in between is skipped `purged`. Pages already purged cannot be restored by this command; only- * a backup can bring them back. Never runs on upgrade or from a maintenance cycle.+ * a backup can bring them back. One preview reads one bounded window of tombstones (descending page id); a truncated+ * preview prints `next_after`, and `--after <page id>` previews the next window (the hash covers it). Never runs on upgrade+ * or from a maintenance cycle.*/import type { BrainEngine } from '../engine.ts';import { opError, OperationError, type OperationContext } from '../ops/contract.ts';@@ -44,7 +46,7 @@ export const UNCOMMITTED_DELETIONS_CONSENT_TEXT = {user_message: 'Restore the previewed pages that a sync deleted without Git evidence? They come back live as database-only pages; no file is written',};-interface Selection { source_ids: string[]; include_ambiguous: boolean }+interface Selection { source_ids: string[]; include_ambiguous: boolean; after: number | null }interface ApprovedDeletion extends UncommittedDeletion { owner: GhostOwner; selection: Selection }interface DeletionItem extends RepairItem { page: UncommittedDeletion; hash: string; last: boolean }@@ -63,8 +65,8 @@ const hashParts = (scope: RepairScope, owner: GhostOwner | undefined, selection:const describeDeletion = (page: UncommittedDeletion) => `file ${page.source_path} ${page.evidence === 'ignored' ? 'is excluded by .gitignore' : 'was never committed'}; `+ `deleted ${page.deleted_at} by ${page.deleted_by === 'sync' ? 'a managed sync' : 'another writer'}; revision ${page.revision}`;-function item(page: UncommittedDeletion, hash: string, last: boolean): DeletionItem {- return { cursor: { phase: 1, id: page.page_id }, source_id: page.source_id, slug: page.slug, chars: 0, action: `restore_detached:${page.evidence}`, page, hash, last };+function item(page: UncommittedDeletion, hash: string, index: number, last: boolean): DeletionItem {+ return { cursor: { phase: 1, id: index }, source_id: page.source_id, slug: page.slug, chars: 0, action: `restore_detached:${page.evidence}`, page, hash, last };}export const uncommittedDeletionsRepair: RepairHandler = {@@ -78,7 +80,7 @@ export const uncommittedDeletionsRepair: RepairHandler = {}const sourceId = scope.source_ids[0]!;const command = uncommittedDeletionsPreviewCommand(sourceId);- const selection: Selection = { source_ids: scope.source_ids, include_ambiguous: opts?.includeAmbiguous === true };+ const selection: Selection = { source_ids: scope.source_ids, include_ambiguous: opts?.includeAmbiguous === true, after: opts?.afterPage ?? null };if (opts?.apply) {if (!opts.expect) {throw opError('invalid_params', 'gbrain repair uncommitted-deletions --apply restores only the set a preview printed.',@@ -90,15 +92,18 @@ export const uncommittedDeletionsRepair: RepairHandler = {const owner = context.ok ? context.owner : undefined;const approved = await loadApprovedSet<ApprovedDeletion>(engine, { command: 'uncommitted-deletions', hash: opts.expect, previewCommand: command,emptyHash: async () => previewHash(hashParts(scope, owner, selection, [])) });- if (approved.items.some(page => JSON.stringify(page.selection) !== JSON.stringify(selection) || !sameOwner(owner, page.owner))) throw previewChangedError(opts.expect, command);- const items = approved.items.map(({ selection: _selection, owner: _owner, ...page }, index) => item(page, opts.expect!, index === approved.items.length - 1));+ if (approved.items.some(page => JSON.stringify(page.selection.source_ids) !== JSON.stringify(selection.source_ids) || page.selection.include_ambiguous !== selection.include_ambiguous+ || (page.selection.after ?? null) !== selection.after || !sameOwner(owner, page.owner))) throw previewChangedError(opts.expect, command);+ const items = approved.items.map(({ selection: _selection, owner: _owner, ...page }, index) => item(page, opts.expect!, index, index === approved.items.length - 1));return { items: items.filter(entry => afterCursor(entry.cursor, after)), preview_hash: opts.expect, residuals: {} };}- const scan = await scanUncommittedDeletions(engine, sourceId, { pathLimit: PATH_LIMIT });+ const scan = await scanUncommittedDeletions(engine, sourceId, { pathLimit: PATH_LIMIT, ...(selection.after !== null ? { after: selection.after } : {}) });if (scan.reason === 'not_owner_host') throw notOwnerHost(sourceId);const eligible = scan.pages.filter(page => selection.include_ambiguous || page.deleted_by === 'sync');const selected = eligible.slice(0, UNCOMMITTED_DELETIONS_LIMIT);- const excluded = scan.pages.filter(page => !selection.include_ambiguous && page.deleted_by !== 'sync');+ const cut = eligible.length > selected.length ? selected[selected.length - 1]!.page_id : undefined;+ const next = cut ?? scan.next_after;+ const excluded = scan.pages.filter(page => !selection.include_ambiguous && page.deleted_by !== 'sync' && (cut === undefined || page.page_id > cut));const hash = previewHash(hashParts(scope, scan.owner, selection, selected));if (selected.length) await saveApprovedSet<ApprovedDeletion>(engine, { command: 'uncommitted-deletions', hash }, selected.map(page => ({ ...page, owner: scan.owner!, selection })));const warnings = [@@ -107,14 +112,15 @@ export const uncommittedDeletionsRepair: RepairHandler = {: scan.reason === 'mirror_read_only' ? 'a read-only mirror publishes no file' : 'its checkout or Git history could not be read on this host'}; nothing is listed.`] : []),...(scan.unknown ? [`${scan.unknown} soft-deleted page(s) are not listed because Git could not answer for their file; fix the checkout and preview again.`] : []),...(excluded.length ? [`${excluded.length} more soft-deleted page(s) with an uncommitted file were deleted by another writer, not by a sync; they are listed apart and restored only with --include-ambiguous.`] : []),- ...(scan.truncated || eligible.length > selected.length ? [`More soft-deleted pages may qualify past this bounded preview; apply this set, then preview again.`] : []),+ ...(scan.truncated || cut !== undefined ? [`This preview read one bounded window of tombstones; more may qualify below page id ${next}. `+ + `After applying this set (or deciding not to), preview the next window: ${command} --after ${next}${selection.include_ambiguous ? ' --include-ambiguous' : ''}`] : []),];- return { warnings, items: selected.map((page, index) => item(page, hash, index === selected.length - 1)), preview_hash: hash,+ return { warnings, items: selected.map((page, index) => item(page, hash, index, index === selected.length - 1)), preview_hash: hash,residuals: { tombstones: scan.tombstones, checked: scan.checked, committed: scan.committed, file_present: scan.file_present, unknown: scan.unknown, ...(excluded.length ? { deleted_by_other: excluded.length } : {}) },listing: [...selected.map(page => ({ item: `${page.source_id}:${page.slug}`, class: `restore:${page.evidence}`, detail: describeDeletion(page) })),...excluded.map(page => ({ item: `${page.source_id}:${page.slug}`, class: 'excluded:deleted_by_other', detail: `${describeDeletion(page)}; restored only with --include-ambiguous` }))],details: { pages: selected.map(({ source_id, slug, source_path, deleted_at, evidence, deleted_by }) => ({ source_id, slug, source_path, deleted_at, evidence, deleted_by })),- purged: PURGED_NOTE, undo: 'gbrain delete <slug>', truncated: scan.truncated, docs: DOCS } };+ purged: PURGED_NOTE, undo: 'gbrain delete <slug>', truncated: scan.truncated || cut !== undefined, ...(next !== undefined ? { next_after: next } : {}), docs: DOCS } };},async apply(ctx, entry): Promise<RepairItemOutcome> {const { page, hash, last } = entry as DeletionItem;diff --git a/src/core/uncommitted-deletions.ts b/src/core/uncommitted-deletions.tsindex f6fbe11af5..b1cb15a0f8 100644--- a/src/core/uncommitted-deletions.ts+++ b/src/core/uncommitted-deletions.ts@@ -5,12 +5,13 @@* the only copy of the page and the purge removes it for good after its retention window.** One source is scanned on its canonical owner host only (the checkout and its `.gitignore` are read there): its- * tombstones that still record a file (newest deletion first, at most `TOMBSTONE_SCAN_LIMIT`), the request that deleted- * each (a committed `managed_sync_delete` request, or an `op_checkpoints` `sync-delete-tombstone` marker naming the page,- * is a sync deletion), and, for at most `pathLimit` of them, sync deletions first, the Git evidence of the recorded file- * (`readOriginEvidence` over HEAD's history, `sync-origin-evidence.ts`). A page is listed when `.gitignore` excludes its- * file, or when no commit holds it and it is not on the disk. A path whose evidence could not be read is counted- * `unknown`, never listed. Purged pages have no row left and are out of reach: only a backup brings them back.+ * tombstones that still record a file, in descending page id, one bounded window at a time (at most `pathLimit` rows+ * below the `after` page id; `next_after` names the next window), whether a sync made each tombstone (`syncDeleteOrigin`:+ * its open `sync-delete-tombstone` record at the page's current `deleted_at`, or the committed `managed_sync_delete`+ * receipt that deleted it), and the Git evidence of each recorded file (`readOriginEvidence` over HEAD's history,+ * `sync-origin-evidence.ts`). A page is listed when `.gitignore` excludes its file, or when no commit holds it and it+ * is not on the disk. A path whose evidence could not be read is counted `unknown`, never listed. Purged pages have no+ * row left and are out of reach: only a backup brings them back.** Readers: doctor `uncommitted_sync_deletions` and `gbrain repair uncommitted-deletions`.*/@@ -21,8 +22,9 @@ import { isOpPageSlug } from './ops/context.ts';import { canonicalPath, sourceContext, type GhostOwner } from './ghost-pages.ts';import { managedPersistenceEnabled } from './persistence/ownership.ts';import { readOriginEvidence } from './persistence/sync-origin-evidence.ts';+import { syncDeleteOrigin } from './persistence/sync-delete-tombstones.ts';-/** `deleted_by: 'sync'` when a committed managed sync request (or a sync tombstone marker) deleted the page; `other` otherwise (a hand delete, a repair, an unknown writer). */+/** `deleted_by: 'sync'` when a managed sync made the current tombstone (`syncDeleteOrigin`); `other` otherwise (a hand delete, a repair, an unknown writer). */export interface UncommittedDeletion {source_id: string; slug: string; page_id: number; revision: string; source_path: string;/** The recorded file's path relative to the Git work tree. */@@ -38,9 +40,9 @@ export interface UncommittedDeletionScan {/** 'not_managed' | 'not_applicable' | 'not_owner_host' | 'mirror_read_only' | 'storage_unavailable' | 'not_a_git_checkout' */reason?: string;pages: UncommittedDeletion[];- /** Tombstones recording a file that were read. */+ /** Tombstones recording a file read in this window. */tombstones: number;- /** Tombstones whose file evidence was read (at most the path limit). */+ /** Tombstones whose file evidence was read. */checked: number;/** Checked tombstones whose file Git once committed: not listed. */committed: number;@@ -48,53 +50,40 @@ export interface UncommittedDeletionScan {file_present: number;/** Checked tombstones whose evidence could not be read: not listed. */unknown: number;+ /** More tombstones remain below this window; `next_after` is the page id the next window starts below. */truncated: boolean;+ next_after?: number;owner?: GhostOwner;root?: string;}-/** Tombstones read per source. */-export const TOMBSTONE_SCAN_LIMIT = 20_000;/** File evidence the doctor reads per run, across sources (each 500 paths cost one `git log` and one `git check-ignore`). */export const DOCTOR_PATH_LIMIT = 2_000;-export const SYNC_DELETE_TOMBSTONE_OP = 'sync-delete-tombstone';export const PURGED_NOTE = 'Pages already purged cannot be restored by this command; only a backup (pg_dump, or gbrain backup create taken before the purge) can bring them back.';-interface TombstoneRow { id: number; slug: string; source_path: string; source_uri: string | null; deleted_at: Date | string; revision: string }+interface TombstoneRow { id: number; slug: string; source_path: string; source_uri: string | null; deleted_at: Date | string; revision: string; by_sync: boolean }-/** The tombstones a sync deleted: the newest deleting request of the slug is a managed sync delete, or a sync tombstone marker names the page. */-async function readSyncDeleted(engine: BrainEngine, sourceId: string, rows: TombstoneRow[]): Promise<Set<number>> {- if (!rows.length) return new Set();- const [source] = await engine.executeRaw<{ incarnation: string }>('SELECT incarnation::text AS incarnation FROM sources WHERE id=$1', [sourceId]);- const requests = source ? await engine.executeRaw<{ slug: string; kind: string | null }>(`SELECT DISTINCT ON (slug) slug, intent->>'kind' AS kind FROM persistence_requests- WHERE source_id=$1 AND source_incarnation=$2::uuid AND state='committed' AND slug=ANY($3::text[])- AND (operation='delete_page' OR intent->>'kind'='managed_sync_delete') ORDER BY slug, sequence DESC`, [sourceId, source.incarnation, rows.map(row => row.slug)]) : [];- const bySync = new Set(requests.filter(row => row.kind === 'managed_sync_delete').map(row => row.slug));- const markers = new Set((await engine.executeRaw<{ fingerprint: string }>('SELECT fingerprint FROM op_checkpoints WHERE op=$1 AND fingerprint=ANY($2::text[])',- [SYNC_DELETE_TOMBSTONE_OP, rows.map(row => String(row.id))])).map(row => row.fingerprint));- return new Set(rows.filter(row => bySync.has(row.slug) || markers.has(String(row.id))).map(row => Number(row.id)));-}--/** One source's soft-deleted pages whose recorded file Git never held, sync deletions first. */-export async function scanUncommittedDeletions(engine: BrainEngine, sourceId: string, opts: { pathLimit: number }): Promise<UncommittedDeletionScan> {+/** One window of one source's soft-deleted pages whose recorded file Git never held, below page id `after` (descending). */+export async function scanUncommittedDeletions(engine: BrainEngine, sourceId: string, opts: { pathLimit: number; after?: number }): Promise<UncommittedDeletionScan> {const scan: UncommittedDeletionScan = { source_id: sourceId, status: 'known', pages: [], tombstones: 0, checked: 0, committed: 0, file_present: 0, unknown: 0, truncated: false };if (!await managedPersistenceEnabled(engine)) return { ...scan, status: 'not_applicable', reason: 'not_managed' };const context = await sourceContext(engine, sourceId);if (!context.ok && context.status === 'not_applicable') return { ...scan, status: 'not_applicable', reason: context.reason };- const rows = await engine.executeRaw<TombstoneRow>(`SELECT id, slug, source_path, source_uri, deleted_at, knowledge_revision::text AS revision FROM pages- WHERE source_id=$1 AND deleted_at IS NOT NULL AND NULLIF(btrim(source_path), '') IS NOT NULL ORDER BY deleted_at DESC, id LIMIT ${TOMBSTONE_SCAN_LIMIT + 1}`, [sourceId]);- scan.truncated = rows.length > TOMBSTONE_SCAN_LIMIT;- const tombstones = rows.slice(0, TOMBSTONE_SCAN_LIMIT).filter(row => isOpPageSlug(row.slug));+ const window = Math.max(0, opts.pathLimit);+ const rows = await engine.executeRaw<TombstoneRow>(`SELECT p.id, p.slug, p.source_path, p.source_uri, p.deleted_at, p.knowledge_revision::text AS revision, ${syncDeleteOrigin('p')} AS by_sync+ FROM pages p WHERE p.source_id=$1 AND p.deleted_at IS NOT NULL AND NULLIF(btrim(p.source_path), '') IS NOT NULL AND ($2::bigint IS NULL OR p.id < $2::bigint)+ ORDER BY p.id DESC LIMIT ${window + 1}`, [sourceId, opts.after ?? null]);+ scan.truncated = rows.length > window;+ const read = rows.slice(0, window);+ if (scan.truncated && read.length) scan.next_after = Number(read[read.length - 1]!.id);+ const tombstones = read.filter(row => isOpPageSlug(row.slug));scan.tombstones = tombstones.length;if (!context.ok) return tombstones.length ? { ...scan, status: 'unknown', reason: context.reason } : scan;Object.assign(scan, { owner: context.owner, root: context.root });if (!tombstones.length) return scan;if (!context.gitScope) return { ...scan, status: 'not_applicable', reason: 'not_a_git_checkout' };- const bySync = await readSyncDeleted(engine, sourceId, tombstones);- const ordered = [...tombstones.filter(row => bySync.has(Number(row.id))), ...tombstones.filter(row => !bySync.has(Number(row.id)))];- if (ordered.length > opts.pathLimit) scan.truncated = true;const gitRoot = resolve(context.root, ...context.gitScope.map(() => '..'));- const candidates = ordered.slice(0, Math.max(0, opts.pathLimit)).flatMap(row => {+ const candidates = tombstones.flatMap(row => {const file = canonicalPath(context, row);const gitPath = relative(gitRoot, file).split(sep).join('/');return gitPath.startsWith('../') ? [] : [{ row, file, gitPath }];@@ -107,7 +96,7 @@ export async function scanUncommittedDeletions(engine: BrainEngine, sourceId: stif (found === 'committed') { scan.committed++; continue; }if (found === 'never_committed' && existsSync(file)) { scan.file_present++; continue; }scan.pages.push({ source_id: sourceId, slug: row.slug, page_id: Number(row.id), revision: row.revision, source_path: row.source_path, git_path: gitPath,- deleted_at: new Date(row.deleted_at).toISOString(), evidence: found, deleted_by: bySync.has(Number(row.id)) ? 'sync' : 'other' });+ deleted_at: new Date(row.deleted_at).toISOString(), evidence: found, deleted_by: row.by_sync === true ? 'sync' : 'other' });}return scan;}diff --git a/test/postgres-unit-arms.txt b/test/postgres-unit-arms.txtindex d5d958402b..19b0b863d9 100644--- a/test/postgres-unit-arms.txt+++ b/test/postgres-unit-arms.txt@@ -394,6 +394,7 @@ test/sync-absent-from-worktree-s27.test.tstest/sync-admission-6712.test.tstest/sync-capacity-preflight.test.tstest/sync-checkpoint-moved-6834.test.ts+test/sync-discovery-legacy-origin-7130.test.tstest/sync-drain-claims.test.tstest/sync-drain-effect-recovery-blocked.test.tstest/sync-drain-head-blocked-6543.test.tsdiff --git a/test/repair-uncommitted-deletions-7130.test.ts b/test/repair-uncommitted-deletions-7130.test.tsindex 8b7a0bbbbf..f398cd4562 100644--- a/test/repair-uncommitted-deletions-7130.test.ts+++ b/test/repair-uncommitted-deletions-7130.test.ts@@ -9,7 +9,10 @@* - `gbrain repair uncommitted-deletions --source <id>` previews them with a hash and the purge caveat, refuses a wrong* hash (preview_changed), exits 3 without --yes, and with the right hash restores each live and detached* (database-only, no file written); the next sync, incremental and full, keeps them live and the control deleted;- * - off the owner host the doctor check is not_applicable and the repair refuses not_owner_host.+ * - off the owner host the doctor check is not_applicable and the repair refuses not_owner_host;+ * - an apply stopped by --limit resumes over the rest of the approved set; a sync-delete record of an earlier tombstone+ * does not make a later hand delete a sync deletion; a bounded scan continues below next_after, and --after previews+ * and applies that window under its own hash.*/import { beforeEach, afterEach, describe, expect, test } from 'bun:test';import { execFileSync } from 'node:child_process';@@ -26,6 +29,7 @@ import { EXPLICIT_REPAIR_REGISTRY, repairRunner } from '../src/core/repair/regisimport { runRepairCommand } from '../src/commands/repair.ts';import { uncommittedSyncDeletionsEntry } from '../src/commands/doctor/checks/uncommitted-sync-deletions.ts';import { categorizeCheck } from '../src/core/doctor-categories.ts';+import { scanUncommittedDeletions } from '../src/core/uncommitted-deletions.ts';import { _resetCliExitVerdictForTests, currentExitCode } from '../src/core/cli-force-exit.ts';import { managedBrain } from './helpers/managed-brain.ts';import { requirePostgresTestDatabase, testBackends } from './helpers/test-backends.ts';@@ -61,8 +65,10 @@ async function refusal(fn: () => Promise<unknown>): Promise<OperationError> {const pageRow = async (engine: BrainEngine, slug: string) => (await engine.executeRaw<{ live: boolean; source_path: string | null; database_only_reason: string | null }>("SELECT deleted_at IS NULL AS live, source_path, database_only_reason FROM pages WHERE source_id='default' AND slug=$1", [slug]))[0];const doctor = async (engine: BrainEngine) => (await uncommittedSyncDeletionsEntry.run({ engine } as never) as Array<Record<string, any>>)[0]!;-const repair = async (engine: BrainEngine, opts: { apply?: boolean; expect?: string; includeAmbiguous?: boolean } = {}) => (await repairRunner(engine, { apply: opts.apply === true, logger }))- .run(KIND, await resolveRepairScope(engine, 'default'), { explicit: true, sourceFlag: 'default', expect: opts.expect, includeAmbiguous: opts.includeAmbiguous });+const repair = async (engine: BrainEngine, opts: { apply?: boolean; expect?: string; includeAmbiguous?: boolean; limit?: number; afterPage?: number } = {}) => (await repairRunner(engine, { apply: opts.apply === true, logger }))+ .run(KIND, await resolveRepairScope(engine, 'default'), { explicit: true, sourceFlag: 'default', expect: opts.expect, includeAmbiguous: opts.includeAmbiguous, limit: opts.limit,+ ...(opts.afterPage !== undefined ? { afterPage: opts.afterPage } : {}) });+const pageId = async (engine: BrainEngine, slug: string) => Number((await engine.executeRaw<{ id: number }>("SELECT id FROM pages WHERE source_id='default' AND slug=$1", [slug]))[0]!.id);/** Imports untracked files from the working tree (working mode), then returns to committed mode. */async function importUntracked(engine: BrainEngine, root: string, files: Record<string, string>) {@@ -156,7 +162,8 @@ for (const backend of testBackends()) describe(`[${backend}] #7130: restoring patest('a sync tombstone marker counts as a sync deletion; off the owner host the doctor check is not applicable and the repair refuses not_owner_host', () => managedBrain(async ({ engine, ctx, root }) => {await hitBrain(engine, ctx, root);const [hand] = await engine.executeRaw<{ id: number }>("SELECT id FROM pages WHERE source_id='default' AND slug='notes/hand'");- await engine.executeRaw("INSERT INTO op_checkpoints(op, fingerprint, completed_keys) VALUES ('sync-delete-tombstone', $1, '[]'::jsonb)", [String(hand!.id)]);+ await engine.executeRaw(`INSERT INTO op_checkpoints(op, fingerprint, completed_keys) SELECT 'sync-delete-tombstone', id::text,+ jsonb_build_array(jsonb_build_object('page_id', id, 'slug', slug, 'deleted_at', deleted_at)) FROM pages WHERE id=$1`, [hand!.id]);expect(await doctor(engine)).toMatchObject({ status: 'warn', details: { count: 3, other_writer_count: 0 } });const hash = (await repair(engine)).preview_hash!;await withEnv({ GBRAIN_HOME: join(dirname(root), 'other-host') }, async () => {@@ -166,4 +173,52 @@ for (const backend of testBackends()) describe(`[${backend}] #7130: restoring pa});expect((await pageRow(engine, 'notes/draft'))!.live).toBe(false);}, { databaseUrl, setup }), 240_000);++ test('an apply stopped by --limit resumes and restores the rest of the approved set', () => managedBrain(async ({ engine, ctx, root }) => {+ await hitBrain(engine, ctx, root);+ const preview = await repair(engine);+ expect(preview.affected).toBe(2);+ const first = await repair(engine, { apply: true, expect: preview.preview_hash!, limit: 1 });+ expect(first).toMatchObject({ applied: 1, complete: false });+ const rest = await repair(engine, { apply: true, expect: preview.preview_hash! });+ expect(rest).toMatchObject({ applied: 1, failed: [], complete: true });+ for (const slug of ['notes/draft', 'scratch/agent']) expect(await pageRow(engine, slug)).toEqual({ live: true, source_path: null, database_only_reason: 'detached' });+ }, { databaseUrl, setup }), 240_000);++ test('a sync-delete record left from an earlier tombstone does not make a later hand delete a sync deletion', () => managedBrain(async ({ engine, ctx, root }) => {+ await hitBrain(engine, ctx, root);+ await engine.executeRaw(`INSERT INTO op_checkpoints(op, fingerprint, completed_keys) SELECT 'sync-delete-tombstone', id::text,+ jsonb_build_array(jsonb_build_object('page_id', id, 'slug', slug, 'deleted_at', deleted_at - interval '1 hour')) FROM pages WHERE id=$1`, [await pageId(engine, 'notes/hand')]);+ expect(await doctor(engine)).toMatchObject({ status: 'warn', details: { count: 2, other_writer_count: 1 } });+ const preview = await repair(engine);+ expect(preview.listing!.find(entry => entry.item === 'default:notes/hand')?.class).toBe('excluded:deleted_by_other');+ }, { databaseUrl, setup }), 240_000);++ test('a bounded scan continues below next_after; --after previews and applies the next window under its own hash', () => managedBrain(async ({ engine, ctx, root }) => {+ await hitBrain(engine, ctx, root);+ const seen: string[] = [];+ let after: number | undefined;+ for (let window = 0; window < 10; window++) {+ const scan = await scanUncommittedDeletions(engine, 'default', { pathLimit: 1, ...(after !== undefined ? { after } : {}) });+ seen.push(...scan.pages.map(page => page.slug));+ if (!scan.truncated) break;+ expect(scan.next_after).toBeDefined();+ after = scan.next_after;+ }+ expect(seen.sort()).toEqual(['notes/draft', 'notes/hand', 'scratch/agent']);++ const [lower, upper] = (await Promise.all(['notes/draft', 'scratch/agent'].map(async slug => ({ slug, id: await pageId(engine, slug) })))).sort((a, b) => a.id - b.id);+ const whole = await repair(engine);+ const preview = JSON.parse(await capture(() => runRepairCommand(engine, ['uncommitted-deletions', '--source', 'default', '--after', String(upper!.id), '--json']))).results[0];+ expect(preview.affected).toBe(1);+ expect(preview.sample).toEqual([`default:${lower!.slug}`]);+ expect(preview.preview_hash).not.toBe(whole.preview_hash);+ expect(preview.apply_command).toBe(`gbrain repair uncommitted-deletions --source default --after ${upper!.id} --apply --expect ${preview.preview_hash} --yes`);+ expect((await refusal(() => repair(engine, { apply: true, expect: preview.preview_hash }))).code).toBe('preview_changed');+ const applied = JSON.parse(await withEnv({ GBRAIN_INTERACTIVE: '0', CI: '1' }, () => capture(() => runRepairCommand(engine,+ ['uncommitted-deletions', '--source', 'default', '--after', String(upper!.id), '--apply', '--expect', preview.preview_hash, '--yes', '--json'])))).results[0];+ expect(applied).toMatchObject({ applied: 1, complete: true });+ expect((await pageRow(engine, lower!.slug))!.live).toBe(true);+ expect((await pageRow(engine, upper!.slug))!.live).toBe(false);+ }, { databaseUrl, setup }), 240_000);});diff --git a/test/sync-classic-uncommitted-7130.test.ts b/test/sync-classic-uncommitted-7130.test.tsindex 16f8f3ac2a..385eeeff2a 100644--- a/test/sync-classic-uncommitted-7130.test.ts+++ b/test/sync-classic-uncommitted-7130.test.ts@@ -4,7 +4,8 @@* - `sync --full` keeps every stale page when Git cannot list the history that proves a file was committed (a dangling* ref fails `git log --all`); it used to skip the #2426 never-committed gate and delete them all;* - the absolute caps (`sync.max_deletes`, per source too) withhold a classic full reconcile and a working-tree sync- * below the 50% valve, and `GBRAIN_ALLOW_MASS_RECONCILE=1` still lets the deletion through.+ * below the 50% valve, and `GBRAIN_ALLOW_MASS_RECONCILE=1` still lets the deletion through;+ * - the working-tree valve's ratio is of the source's file-backed pages, so database-only pages cannot dilute it.*/import { afterAll, beforeAll, beforeEach, describe, expect, test } from 'bun:test';import { execFileSync } from 'node:child_process';@@ -69,6 +70,15 @@ describe('#7130 classic sync: a missing file is deletion evidence only when Gitexpect((await live()).length).toBe(30);}, 120_000);+ test('the working-tree valve counts the source\'s file-backed pages, not its database-only pages', async () => {+ seed(Array.from({ length: 20 }, (_, i) => `n${String(i).padStart(2, '0')}`));+ expect(['first_sync', 'synced']).toContain((await sync()).status);+ for (let i = 0; i < 30; i++) await engine.putPage(`memories/m${i}`, { type: 'concept', title: `m${i}`, compiled_truth: `Database-only note ${i}.`, timeline: '', frontmatter: { type: 'concept' } });+ for (let i = 0; i < 12; i++) rmSync(join(repoPath, `notes/n${String(i).padStart(2, '0')}.md`));+ await withEnv({ GBRAIN_ALLOW_MASS_RECONCILE: undefined }, () => sync({ workingTree: true }));+ expect((await live()).filter(slug => slug.startsWith('notes/')).length).toBe(20);+ }, 120_000);+test('sync.max_deletes withholds a working-tree sync\'s uncommitted deletions', async () => {seed(Array.from({ length: 40 }, (_, i) => `n${String(i).padStart(2, '0')}`));expect(['first_sync', 'synced']).toContain((await sync()).status);diff --git a/test/sync-discovery-legacy-origin-7130.test.ts b/test/sync-discovery-legacy-origin-7130.test.tsnew file mode 100644index 0000000000..16832b3ee5--- /dev/null+++ b/test/sync-discovery-legacy-origin-7130.test.ts@@ -0,0 +1,65 @@+/**+ * #7130: a legacy origin recorded Git-root-relative in a source-root source (`content/a.md` under scope `content`) is read+ * for origin evidence at its real Git path, so full discovery and the dry run list its committed removal as a delete,+ * as the pass does, instead of keeping it as never committed.+ */+import { describe, expect, test } from 'bun:test';+import { execFileSync } from 'node:child_process';+import { writeFileSync } from 'node:fs';+import { dirname, join } from 'node:path';+import { discoverManagedSync } from '../src/core/persistence/sync-discovery.ts';+import { readShadowLevel } from '../src/core/persistence/sync-pass.ts';+import { performManagedSync } from '../src/core/persistence/sync-run.ts';+import { disposePersistenceConsumer } from '../src/core/persistence/service.ts';+import { managedBrain } from './helpers/managed-brain.ts';+import { requirePostgresTestDatabase, testBackends } from './helpers/test-backends.ts';++const git = (root: string, ...args: string[]) => execFileSync('git', ['-C', root, ...args], {+ encoding: 'utf8', stdio: ['ignore', 'pipe', 'pipe'],+}).trim();+const commit = (root: string, path: string, message: string) => {+ git(root, 'add', '--', path);+ git(root, '-c', 'user.name=Example', '-c', '[email protected]', 'commit', '-qm', message);+};+const note = (name: string) => `---\ntype: concept\ntitle: ${name}\n---\n\nDistinct body of ${name}.\n`;+const OPTS = { sourceId: 'default', noPull: true, noEmbed: true, noExtract: true };++for (const backend of testBackends()) {+ const databaseUrl = backend === 'postgres' ? requirePostgresTestDatabase() : undefined;+ describe(`[${backend}] #7130: legacy Git-root origin in a source-root source`, () => {+ test('full discovery retains a committed removal as a delete rather than an uncommitted hold', () => managedBrain(async ({ engine, root }) => {+ expect((await performManagedSync(engine, OPTS)).status).toBe('first_sync');+ const original = await engine.readPageSnapshot('a', { sourceId: 'default' });+ expect(original?.page.source_path).toBe('a.md');++ await disposePersistenceConsumer(engine);+ await engine.executeRaw('UPDATE persistence_brain SET enabled=false WHERE singleton=1');+ try {+ await engine.executeRaw("UPDATE pages SET source_path='content/a.md' WHERE source_id='default' AND slug='a'");+ } finally {+ await engine.executeRaw('UPDATE persistence_brain SET enabled=true WHERE singleton=1');+ }++ git(dirname(root), 'rm', '-q', '--', 'content/a.md');+ commit(dirname(root), 'content', 'Remove the committed note');++ const level = await readShadowLevel(engine, { sourceId: 'default', full: true });+ expect(level?.paths.find(entry => entry.path === 'content/a.md')?.result.cls).toBe('delete');++ const discovery = await discoverManagedSync(engine, { ...OPTS, full: true, dryRun: true });+ expect(discovery.slugMode).toBe('source-root');+ expect(discovery.entries.filter(entry => entry.action === 'delete')).toEqual([+ expect.objectContaining({ slug: 'a', pageId: original!.page.id, sourcePath: 'content/a.md', action: 'delete' }),+ ]);+ expect(discovery.uncommittedKept ?? []).toEqual([]);+ }, {+ databaseUrl,+ setup: async ({ engine, root }) => {+ git(dirname(root), 'init', '-q');+ for (const name of ['a', 'b']) writeFileSync(join(root, `${name}.md`), note(name));+ commit(dirname(root), 'content', 'Seed the nested source');+ await engine.executeRaw(`UPDATE sources SET config=jsonb_set(config,'{slug_root_mode}','"source-root"') WHERE id='default'`);+ },+ }), 240_000);+ });+}diff --git a/test/sync-uncommitted-origin-7130.test.ts b/test/sync-uncommitted-origin-7130.test.tsindex 4ed05cf890..0e742ba4fc 100644--- a/test/sync-uncommitted-origin-7130.test.ts+++ b/test/sync-uncommitted-origin-7130.test.ts@@ -137,6 +137,24 @@ for (const backend of testBackends()) describe(`[${backend}] #7130: an absent fiawait performManagedSync(engine, { ...OPTS, full: true });expect(await liveSlugs(engine)).toContain('ingested/report');}, { databaseUrl, setup: setupNotes(['a'], 'ingested/\n') }), 240_000);++ test('a page that already records a file keeps it when a rule later ignores it: an unimported disk edit still refuses the write (source_changed)', () => managedBrain(async ({ engine, ctx, root }) => {+ expect((await performManagedSync(engine, OPTS)).status).toBe('first_sync');+ await importUntracked(engine, root, { 'drafts/x.md': 'A draft imported from the working tree.' });+ writeFileSync(join(root, '.gitignore'), 'drafts/\n');+ writeFileSync(join(root, 'drafts/x.md'), note('drafts/x', 'A newer edit on disk that no sync imported.'));+ const requestId = randomUUID();+ const revision = (await engine.readPageSnapshot('drafts/x', { sourceId: 'default' }))!.revision;+ const refusal = await submitPageMutation(ctx as OperationContext, { operation: 'put_page', params: { slug: 'drafts/x', request_id: requestId, expected_revision: revision, content: note('drafts/x', 'An agent rewrite.') } })+ .then(() => null, (error: { code?: string }) => error.code ?? 'unknown');+ await waitFor(async () => refusal !== null || ['committed', 'failed', 'cancelled', 'conflict'].includes((await engine.executeRaw<{ state: string }>('SELECT state FROM persistence_requests WHERE request_id=$1::uuid', [requestId]))[0]?.state ?? ''),+ { timeoutMs: 20_000, label: 'put_page settles' });+ const [request] = await engine.executeRaw<{ error_code: string | null }>('SELECT error_code FROM persistence_requests WHERE request_id=$1::uuid', [requestId]);+ expect(request?.error_code ?? refusal).toBe('source_changed');+ const page = await engine.getPage('drafts/x', { sourceId: 'default' });+ expect(page?.compiled_truth).not.toContain('An agent rewrite.');+ expect((await engine.executeRaw<{ source_path: string | null }>("SELECT source_path FROM pages WHERE source_id='default' AND slug='drafts/x'"))[0]).toEqual({ source_path: 'drafts/x.md' });+ }, { databaseUrl, setup: setupNotes(['a']) }), 240_000);});describe('#7130: origin evidence', () => {@@ -154,6 +172,12 @@ describe('#7130: origin evidence', () => {expect(Object.fromEntries(await readOriginEvidence(join(root, 'missing'), [head], ['notes/never.md']))).toEqual({ 'notes/never.md': 'unknown' });expect(await gitIgnoresUntracked(root, 'scratch/agent.md')).toBe(true);expect(await gitIgnoresUntracked(root, 'notes/never.md')).toBe(false);+ // A name is read byte for byte: only ' lead.md' and '\nlead.md' were committed, so 'lead.md' has no commit. A removed+ // file that a later rule ignores is still committed (its removal is a real deletion).+ writeFileSync(join(root, ' lead.md'), 'x'); writeFileSync(join(root, '\nlead.md'), 'y'); mkdirSync(join(root, 'old')); writeFileSync(join(root, 'old/x.md'), 'x');+ commit(root, 'three'); git(root, 'rm', '-q', ' lead.md', '\nlead.md', 'old/x.md'); writeFileSync(join(root, '.gitignore'), 'scratch/\nold/\n'); commit(root, 'four');+ const later = await readOriginEvidence(root, [git(root, 'rev-parse', 'HEAD')], [' lead.md', '\nlead.md', 'lead.md', 'old/x.md']);+ expect(Object.fromEntries(later)).toEqual({ ' lead.md': 'committed', '\nlead.md': 'committed', 'lead.md': 'never_committed', 'old/x.md': 'committed' });} finally { rmSync(root, { recursive: true, force: true }); }});});