Garry's Opinionated OpenClaw/Hermes Agent Brain
TypeScript
feat(repair): file-drift provenance per held gone file, --provenance selector, database-only keep for never-committed pages; repair applies stop with a result on a database refusal or a termination signal (GBRA-133)
garrytan5d394645211b
diff --git a/docs/ENGINES.md b/docs/ENGINES.mdindex fcf1e51c6d..5a696d6d42 100644--- a/docs/ENGINES.md+++ b/docs/ENGINES.md@@ -780,11 +780,21 @@ Size the pooler for every process at once:```long-running processes x GBRAIN_POOL_SIZE- + processes with GBRAIN_DIRECT_DATABASE_URL x GBRAIN_DIRECT_POOL_SIZE (default 3)- + one-shot commands running at the same time x their pool+ + processes whose direct route lands on this pooler x GBRAIN_DIRECT_POOL_SIZE (default 3)+ + one-shot commands running at the same time x their pool (a full `gbrain sync` is one too)+ + parallel import workers x 2 (an unmanaged sync of more than 100 files, `--workers N`, or the sync a serve runs)<= the pooler's client limit (Supabase Supavisor: the project's pool_size)```+The direct route lands on the pooler when `GBRAIN_DIRECT_DATABASE_URL` names it,+and also when gbrain derives it from a Supabase pooler URL whose user does not+name the project (`postgres.<ref>`): the derived route keeps the pooler host on+port 5432, its session port, even when the main URL uses transaction mode+(6543). Two long-running processes at the+defaults (10 + 3 each) already pass a client limit of 25, so a scheduled+`gbrain sync` next to a `gbrain serve` on the same session port can exhaust it.+`GBRAIN_MAX_CONNECTIONS` caps a sync's worker fan-out to fit a budget.+When the sum does not fit, run fewer long-running processes (for example oneshared `gbrain serve --http` instead of one stdio `serve` per agent session),or raise the pooler's limit. Do not lower a long-running process below 6.diff --git a/docs/guides/repair.md b/docs/guides/repair.mdindex f247e7e5b3..a98632cdc3 100644--- a/docs/guides/repair.md+++ b/docs/guides/repair.md@@ -2166,7 +2166,8 @@ gbrain repair file-drift --source <id> --held --side deleted --state file_gone -gbrain repair file-drift --source <id> --held --side deleted --state file_gone --cursor <next_cursor> --prefer database # window 2```-The apply reports each page on stderr as well. Apply each window (or decide not to), then preview the next one. Pages the+The apply reports each page on stderr as well. If the database refuses an item (a deadlock, a serialization failure, a lost+connection), the apply stops with a result naming what it applied, the reason and the command that resumes from that item. Apply each window (or decide not to), then preview the next one. Pages theapply resolved leave the held set, so rerunning without `--cursor` alsostarts from the first page still held.@@ -2176,6 +2177,36 @@ sync could not tell a deletion from a file that never reached the repository,so the page may hold the only copy. `--prefer file` deletes it after review;committing the file again clears the hold.+<a id="file-drift-provenance"></a>**Provenance: who deleted each gone file.** Every page of a+`--held --side deleted --state file_gone` preview names where its file went+(JSON: `details.pages[].provenance`, counted in `details.provenance`), read from+HEAD's full history with `--full-history`, so a deletion on a branch a merge+kept is found (a plain `git log --diff-filter=D -- <path>` simplifies it away):++| Provenance | Meaning |+|---|---|+| `deleted_by_commit` | The newest commit that deleted the file, with its sha, author, date and subject (a merge only when its resolution dropped the file). |+| `never_committed` | No commit ever held the file, so the page holds the only copy. |+| `deletion_uncommitted` | HEAD still holds the file; only the worktree lost it. |+| `unknown` | Git could not answer. |++`--provenance <kind>` keeps only the held files of one provenance, so each+population gets its own decision:++```bash+# Pages no commit ever held: keep each one database-only. No file is written; the page+# forgets its recorded path (database_only_reason=detached) and the hold is cleared.+gbrain repair file-drift --source <id> --held --side deleted --state file_gone --provenance never_committed --prefer database+# Files a commit deleted on purpose: accept the deletions (soft-deletes those pages).+gbrain repair file-drift --source <id> --held --side deleted --state file_gone --provenance deleted_by_commit --prefer file+```++`--provenance never_committed --prefer file` is refused: it would soft-delete+the only copy of each page. A database-only page is no longer screened against+a file; a file synced back at its old path binds it again. The apply re-checks+each page (same revision, file still missing, still never committed) and+reports `changed_since_preview` otherwise.+`both` and `unknown` resolve as `--slug` does above. `--only` / `--skip` narrowthe held set by file path, and the preview lists each page's action.diff --git a/src/commands/repair.ts b/src/commands/repair.tsindex aba8d4c074..edca031da9 100644--- a/src/commands/repair.ts+++ b/src/commands/repair.ts@@ -32,6 +32,7 @@ import { CONTENT_REPAIR_KINDS } from '../core/repair/content-lane.ts';import { kindErrorResult } from '../core/remediation/repairs.ts';import { ItemRun } from '../core/item-failure.ts';import { createProgress } from '../core/progress.ts';+import { registerSignalOwner } from '../core/process-cleanup.ts';import { cliOptsToProgressOptions, getCliOptions } from '../core/cli-options.ts';/** The content-repair lane's command word (#6377): parsed like a kind, dispatched to repair-content.ts, never a RepairKind. */@@ -124,6 +125,13 @@ Options:refused without --side; the preview prints each page's action. One preview covers a window of at most200 held pages (or 60 s of work) in held-path order, reports progress on stderr, and its hash covers onlythat window; a partial window prints next_cursor and the next preview command.+ --provenance never_committed|deleted_by_commit|deletion_uncommitted+ file-drift --held --side deleted --state file_gone: only the held files of one provenance (each preview+ page names its own: the commit that deleted the file, with its author, date and subject, read with+ --full-history; never_committed when no commit held it; deletion_uncommitted when HEAD still has it).+ never_committed with --prefer database keeps each page database-only and writes no file;+ never_committed with --prefer file is refused (the page holds the only copy). deleted_by_commit with+ --prefer file accepts the deletions.--cursor <next_cursor>file-drift --held: continue after the window the previous preview covered (its next_cursor).--since <ISO-8601|7d>@@ -160,19 +168,19 @@ 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', '--after', '--cursor']);+const VALUE_FLAGS = new Set(['--source', '--limit', '--expect', '--only', '--skip', '--slug', '--max-usd', '--prefer', '--request', '--class', '--since', '--keep', '--request-id', '--older-than', '--from', '--side', '--state', '--after', '--cursor', '--provenance']);/** Flags only some kinds accept, with the kinds that do. */const KIND_FLAGS: Record<string, readonly string[]> = {'--only': ['frontmatter', 'fences', 'slug-conflicts', 'file-drift', CONTENT_LANE], '--skip': ['frontmatter', 'fences', 'slug-conflicts', 'file-drift', CONTENT_LANE], '--diff': ['frontmatter', 'fences', 'slug-conflicts', CONTENT_LANE], '--yes': ['frontmatter', 'conversation-labels', 'stuck-recovery', 'ghost-pages', 'legacy-twins', 'rename-identity', 'url-clone-fences'],'--slug': ['fences', 'file-drift', 'rename-identity', 'overwritten-edits', 'origin-twins'], '--from': ['rename-identity'], '--close': ['rename-identity'], '--prefer': ['file-drift'], '--request': ['file-drift'], '--all-drifted': ['file-drift'], '--class': ['file-drift', 'visibility'], '--since': ['file-drift'],- '--held': ['file-drift'], '--side': ['file-drift'], '--state': ['file-drift'], '--cursor': ['file-drift'],+ '--held': ['file-drift'], '--side': ['file-drift'], '--state': ['file-drift'], '--cursor': ['file-drift'], '--provenance': ['file-drift'],'--keep': ['stuck-recovery'], '--request-id': ['stuck-recovery'],'--older-than': ['receipt-compaction'], '--include-failures': ['receipt-compaction'], '--force': ['receipt-compaction'],'--after': ['uncommitted-deletions'],};const VALUE_EXAMPLES: Record<string, string> = { '--source': 'default', '--limit': '50', '--expect': 'PLAN_HASH', '--only': 'notes/a.md', '--skip': 'notes/a.md','--slug': 'notes/a', '--max-usd': '0.50', '--prefer': 'file', '--request': 'REQUEST_UUID', '--class': 'review_required', '--since': '7d', '--side': 'deleted', '--state': 'tombstone_edited', '--keep': 'prior',- '--request-id': '123e4567-e89b-42d3-a456-426614174000', '--older-than': '30d', '--from': 'notes/old', '--after': '1200', '--cursor': 'NEXT_CURSOR' };+ '--request-id': '123e4567-e89b-42d3-a456-426614174000', '--older-than': '30d', '--from': 'notes/old', '--after': '1200', '--cursor': 'NEXT_CURSOR', '--provenance': 'never_committed' };/** 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 }) });@@ -180,7 +188,7 @@ const invalid = (message: string, suggestion: string, preview: string[] = ['gbrainterface RepairArgs { kind?: string; apply: boolean; all: boolean; json: boolean; noEmbed: boolean; includeAmbiguous: boolean; diff: boolean; yes: boolean;noLlm: boolean; source?: string; limit?: string; expect?: string; maxUsd?: number; only: string[]; skip: string[]; slugs: string[];allDrifted: boolean; prefer?: 'file' | 'database'; requests: string[]; driftClass?: string; since?: string;- held: boolean; side?: string; state?: string; cursor?: string;+ held: boolean; side?: string; state?: string; provenance?: string; cursor?: string;keep?: 'prior' | 'disk' | 'withdrawn'; requestId?: string; olderThan?: string; includeFailures: boolean; force: boolean; from?: string; close: boolean; afterPage?: number }/** `--max-usd` on a kind that never calls a paid model: the cap belongs to the doctor remediation run. */@@ -268,6 +276,7 @@ export function parseRepairArgs(args: string[]): RepairArgs {else if (flag === '--side') parsed.side = value;else if (flag === '--state') parsed.state = value;else if (flag === '--cursor') parsed.cursor = value;+ else if (flag === '--provenance') parsed.provenance = value;else if (flag === '--since') {try { parsed.since = parseSince(value, '--since'); } catch (error) {throw invalid((error as Error).message, 'Pass an ISO-8601 instant (2026-10-01T00:00:00Z) or an age (7d, 12h); the preview prints the concrete instant it selected.', ['gbrain', 'repair', 'file-drift', ...(parsed.source ? ['--source', parsed.source] : []), '--json']);@@ -373,7 +382,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, cursor, keep, requestId, olderThan, includeFailures, force, from, close, afterPage } = parseRepairArgs(args);+ prefer, requests, allDrifted, driftClass, since, held, side, state, provenance, cursor, keep, requestId, olderThan, includeFailures, force, from, close, afterPage } = parseRepairArgs(args);const limit = limitText === undefined ? undefined : Number(limitText);if (limit !== undefined && (!Number.isSafeInteger(limit) || limit < 1)) throw invalid('--limit must be a positive integer.', 'Pass --limit as a positive whole number, e.g. --limit 50, or omit it to repair every item.');// #6712 PR 2: a repair apply is a soak intervention; a file-drift apply is a content decision (soak-counters.ts).@@ -412,15 +421,23 @@ export async function runRepairCommand(engine: BrainEngine, args: string[]): Proif (!auth) return;}const runner = await repairRunner(engine, { apply, noEmbed });+ // GBRA-133: a SIGTERM or SIGHUP (an outer timeout, a closed terminal) stops an apply before its next item, so the run still+ // prints its result (what it applied and the resume command); a second signal takes the ordinary cleanup-and-exit path.+ const stop = new AbortController();+ const releaseSignals = apply ? registerSignalOwner('repair apply', signal => {+ if (!stop.signal.aborted) { process.stderr.write(`[repair] ${signal}: stopping after the current item; send it again to exit now\n`); stop.abort(signal); return; }+ releaseSignals?.(); process.kill(process.pid, signal);+ }) : undefined;const results = await runRepairKinds(kinds, scope, { apply, source, noEmbed, named: kind !== undefined }, k => runner.run(k, scope, { limit, sourceFlag: source, explicit: k === kind, expect, includeAmbiguous,...(k === kind && KIND_FLAGS['--only']!.includes(k) ? { only, skip } : {}), ...(k === kind && slugs.length ? { slugs } : {}),...(k === kind && noLlm ? { noLlm } : {}), ...(k === kind && maxUsd !== undefined ? { maxLlmUsd: maxUsd } : {}),...(k === kind && k === 'visibility' && driftClass ? { driftClass } : {}),- ...(k === kind && k === 'file-drift' ? { prefer, requests, allDrifted, driftClass, since, ...(held ? { held } : {}), ...(side ? { side } : {}), ...(state ? { state } : {}), ...(cursor ? { cursor } : {}),+ ...(k === kind && k === 'file-drift' ? { prefer, requests, allDrifted, driftClass, since, ...(held ? { held } : {}), ...(side ? { side } : {}), ...(state ? { state } : {}), ...(provenance ? { provenance } : {}), ...(cursor ? { cursor } : {}),progress: createProgress(cliOptsToProgressOptions(getCliOptions())) } : {}),...(k === kind && keep ? { keep } : {}), ...(k === kind && requestId ? { requestId } : {}),...(k === kind && k === 'receipt-compaction' ? { olderThan, includeFailures, force } : {}),- ...(k === kind && k === 'rename-identity' ? { from, close } : {}), ...(k === kind && afterPage !== undefined ? { afterPage } : {}) }));+ ...(k === kind && k === 'rename-identity' ? { from, close } : {}), ...(k === kind && afterPage !== undefined ? { afterPage } : {}),+ ...(apply ? { stop: stop.signal } : {}) })).finally(() => releaseSignals?.());if (apply) clearHealthMemo(engine);const paidKinds = results.filter(r => r.paid).map(r => r.kind);if (json) {diff --git a/src/core/behavior-change-notice.ts b/src/core/behavior-change-notice.tsindex fee04fe2d2..9009d3b547 100644--- a/src/core/behavior-change-notice.ts+++ b/src/core/behavior-change-notice.ts@@ -1086,6 +1086,9 @@ export const BEHAVIOR_CHANGES: ReadonlyArray<{ since: string; text: ChangeText;{ since: '0.60.351.0', text: '`gbrain repair visibility` previews one class at a time, in the order remote callers are exposed: world facts from a private page (remotely readable ones first), Life Chronicle events, alias-only pages, then atoms and concepts; only that last class (`--class lineage`) reads concept-provenance links, and `--class facts|events|aliases|lineage` previews one. A preview lists one window (1,000 items, `--limit` up to 10,000), reports progress on stderr and prints `--apply --expect <hash>`, which applies exactly that window and resumes after its last applied item; apply it, then preview again for the next window. A bare `--apply` (`--all`, the remediation plan) still applies every class. Each plan statement is bounded at 120 s; a class that overruns is reported and skipped while the others are listed. The fact and concept-lineage plans are set-based now (a large brain timed out on them), and doctor `derived_visibility` counts facts first and reports derived-page counts as unknown when they overrun the same bound. A doctor rerun hint capped to fit an agent tool call also names the uncapped `--budget-ms` to use in a terminal.' },// GBRA-133 (held file-drift preview windows). `since` is stamped at the merge slot.{ since: '0.60.353.0', text: '`gbrain repair file-drift --held` previews one window of the selected holds at a time, in held-path order: at most 200 pages, starting no page after 60 seconds of work, with each page reported on stderr. The hash and apply command cover only that window; a partial window prints `next_cursor` and the next preview command (`--cursor <next_cursor>`). Before, the preview prepared every held page (up to 1,000, silently dropping the rest) before printing anything, so a large held set against a remote database printed nothing for an hour. The apply reports each page on stderr too, and reads the preview artifact once instead of parsing it again for every page (seconds per page with large pages). With Git durability off, a preview that recreates or removes files now leads with "The next sync undoes this repair unless …" and the commit command, and reports `undone_by_next_sync_unless_committed`.' },+ // GBRA-133 (file-drift provenance, database and signal stops). `since` is stamped at the merge slot.+ { since: 'TBD', text: 'A `gbrain repair file-drift --held --side deleted --state file_gone` preview names each gone file\'s provenance (`details.pages[].provenance`, counted in `details.provenance`): the newest commit of HEAD\'s full history that deleted it (sha, author, date, subject), `never_committed` when no commit held it, or `deletion_uncommitted` when HEAD still holds it. New `--provenance never_committed|deleted_by_commit|deletion_uncommitted` keeps only the holds of one provenance. `--provenance never_committed --prefer database` keeps each page database-only: no file is written, the page forgets its recorded path (`database_only_reason=detached`) and the hold is cleared, so the next sync holds nothing again; `--prefer file` with it is refused, since each page holds the only copy.' },+ { since: 'TBD', text: 'A `gbrain repair <kind> --apply` that the database refuses mid-run (deadlock 40P01, serialization failure 40001, a lost connection) now stops with a result (`stopped.reason` `database_contention` or `connection_lost`, the SQLSTATE in its message, what it applied, and the command that resumes from the refused item) instead of ending with an error and, under `--json`, no record of what it applied. A SIGTERM or SIGHUP (an outer timeout, a closed terminal) stops the apply before its next item with `stopped.reason: interrupted` and the same result; a second signal exits at once.' },];/** The newest disclosed change's release: the notice id moves only when a release adds rows. */diff --git a/src/core/cli-flag-registry.generated.ts b/src/core/cli-flag-registry.generated.tsindex 57d61ab1ab..2ae7f4bb35 100644--- a/src/core/cli-flag-registry.generated.ts+++ b/src/core/cli-flag-registry.generated.ts@@ -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', '--timings', '--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', '--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-policy', '--budget-tokens', '--budget-usd', '--by-mention', '--cached', '--call-site', '--catch-up', '--check', '--class', '--clear', '--clear-never-installed', '--cli-socket', '--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', '--dimensions', '--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', '--first-parent', '--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-facts', '--max-jobs', '--max-rss', '--max-runtime', '--max-usd', '--max-waiting', '--mcp-only', '--migrate-legacy', '--migrate-only', '--migration', '--min', '--min-n', '--mode', '--model', '--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-embed-cache', '--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', '--reader-mode', '--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', '--slot-a-model', '--slot-b-model', '--slot-c-model', '--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', '--timings', '--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', '--all', '--all-drifted', '--all-from', '--allow-old-serve', '--allow-shell-jobs', '--allow-unverified-remote', '--allowed-operations', '--apply', '--apply-rewrites', '--assign-corpus', '--audit', '--auto', '--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', '--by-mention', '--cached', '--call-site', '--catch-up', '--check', '--class', '--clear', '--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', '--dimensions', '--dir', '--drain', '--drain-timeout', '--dry-run', '--egress', '--embedding-dimensions', '--embedding-model', '--enable', '--enable-dcr', '--end-of-options', '--entity', '--env', '--error-unmatch', '--exclude', '--exclude-standard', '--expect', '--expect-local', '--expect-remote', '--expect-upstream', '--expected-epoch', '--expected-revision', '--expected-state', '--explain', '--facts', '--fast', '--federated-read', '--fetch-timeout-ms', '--ff-only', '--file', '--first-parent', '--fix', '--follow', '--force', '--force-break-lock', '--force-rechunk', '--force-retry', '--force-schema', '--format', '--fresh', '--from', '--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-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', '--mode', '--model', '--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-embed-cache', '--no-embedding', '--no-extract', '--no-hooks', '--no-lanes', '--no-llm', '--no-migrate', '--no-pull', '--no-renames', '--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', '--progress-interval', '--progress-json', '--project', '--provenance', '--provider', '--providers', '--prune-orphans', '--public-url', '--pull', '--pure', '--push-only', '--query', '--question', '--queue', '--quiet', '--rate', '--reader-mode', '--reauth', '--rebase', '--recommended', '--reference-date', '--refresh', '--refresh-operations', '--refresh-skills', '--regenerate', '--reissue', '--relative', '--relower', '--remediate', '--remediation-plan', '--remove', '--remove-core', '--repair', '--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', '--scope', '--scopes', '--seat', '--section', '--select', '--self-transfer', '--session', '--set', '--set-upstream-to', '--shadow', '--short', '--show-current', '--show-prefix', '--show-token', '--show-toplevel', '--side', '--since', '--skills-dir', '--skip', '--skip-bare-tweet', '--skip-failed', '--skip-urls', '--skip-verify', '--slot', '--slot-a-model', '--slot-b-model', '--slot-c-model', '--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', '--timings', '--to', '--token', '--token-ttl', '--top-k', '--trust', '--type', '--unindexed', '--uninstall', '--unsafe-bypass-dream-guard', '--unset-all', '--untracked-files', '--url', '--url-env', '--user', '--vectors', '--verbose', '--verify', '--version', '--wait', '--wait-drain', '--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'],@@ -75,7 +75,7 @@ export const CLI_FLAG_REGISTRY: Record<string, readonly string[]> = {'graph-query': ['--brain', '--depth', '--direction', '--help', '--hop', '--include-foreign', '--json', '--mcp-only', '--request-id', '--source', '--type'],'hook': ['--allow-unverified-remote', '--auto', '--batch-check', '--brain', '--branch', '--cached', '--count', '--diff-filter', '--enable', '--end-of-options', '--env', '--get', '--harness', '--help', '--jq', '--json', '--limit', '--name-only', '--others', '--pat-file', '--path', '--porcelain', '--pure', '--quiet', '--remove', '--seat', '--session', '--show-current', '--show-toplevel', '--since', '--source', '--yes'],'import': ['--accept-pending', '--admin-intent', '--allow-empty', '--allow-noncanonical-root', '--apply', '--background', '--batch-check', '--brain', '--cached', '--confirm-relocated-root', '--diff-filter', '--dim', '--embedding-dimensions', '--embedding-model', '--empty', '--exclude', '--exclude-standard', '--expected-epoch', '--expected-state', '--explain', '--follow', '--force', '--force-rechunk', '--format', '--fresh', '--help', '--include-gitignored', '--is-shallow-repository', '--json', '--literal-pathspecs', '--log-noop', '--manifest', '--name-only', '--no-accept-pending', '--no-embed', '--no-embedding', '--no-gpg-sign', '--no-pull', '--no-renames', '--no-verify', '--only', '--others', '--path', '--probe', '--progress-interval', '--progress-json', '--quiet', '--self-transfer', '--show-toplevel', '--skip-failed', '--slugs', '--source', '--source-id', '--stale', '--status', '--supabase', '--timeout', '--timings', '--to', '--url', '--verify', '--wait', '--workers'],- 'init': ['--access', '--acknowledge-managed', '--adopt', '--after', '--aliases', '--all', '--all-drifted', '--allow-create-db', '--allow-docker', '--apply', '--assign-corpus', '--audit', '--auto', '--auto-additive', '--background', '--batch', '--bound-slug-prefixes', '--brain', '--break-lock', '--budget-ms', '--budget-policy', '--budget-tokens', '--budget-usd', '--by-mention', '--catch-up', '--chat-model', '--check', '--class', '--clear-never-installed', '--cli-socket', '--client', '--close', '--confirm-relocated-root', '--conflicts', '--content-root', '--conversation', '--cursor', '--db-only', '--dest', '--detach', '--detail', '--dim', '--disable', '--drain', '--embedding-dimensions', '--embedding-model', '--enable', '--entity', '--exclude', '--expand', '--expansion-model', '--expect', '--expect-local', '--expect-remote', '--expect-upstream', '--explain', '--facts', '--fast', '--file', '--fix', '--force', '--force-retry', '--format', '--fresh-token', '--from', '--from-meetings', '--full', '--git', '--grant-types', '--group-by', '--harness', '--held', '--help', '--http', '--id', '--images', '--include-ambiguous', '--include-frontmatter', '--include-gitignored', '--include-hidden', '--install', '--issuer-url', '--json', '--keep', '--keep-checkout', '--key', '--lanes', '--legacy-lock', '--limit', '--list', '--local-postgres', '--markdown', '--max-cost-usd', '--max-facts', '--max-usd', '--mcp-only', '--mcp-url', '--migrate-only', '--migration', '--min-n', '--model', '--no-autopilot-install', '--no-autostash', '--no-delegate', '--no-embed', '--no-embedding', '--no-expand', '--no-extract', '--no-filters', '--no-git', '--no-lanes', '--no-llm', '--no-probe', '--no-pull', '--no-renames', '--no-repair', '--no-schema-pack', '--non-interactive', '--oauth-client-id', '--oauth-client-secret', '--older-than', '--once', '--only', '--oversized', '--page', '--params', '--pat-file', '--path', '--pglite', '--phase', '--plan', '--prefer', '--prefer-postgres', '--preview', '--probe', '--profile', '--provenance', '--providers', '--pull', '--purge', '--push-only', '--query', '--question', '--quiet', '--rebase', '--rebuild', '--redact-paths', '--reference-date', '--remediate', '--remove', '--repair', '--repair-unknown-markers', '--repo', '--request', '--reset', '--resolve', '--resume', '--retry-failed', '--retry-parked', '--save', '--schema-pack', '--scope', '--scopes', '--search-mode', '--section', '--self-transfer', '--semantic', '--session', '--session-id', '--show-toplevel', '--side', '--since', '--since-last-run', '--skip', '--skip-embed-check', '--skip-failed', '--slug', '--slugs', '--source', '--source-id', '--src-subpath', '--stale', '--state', '--status', '--stdin', '--strategy', '--supabase', '--surface', '--tier', '--timeout', '--to', '--token', '--touchpoint', '--url', '--url-env', '--user', '--vacuum', '--verbose', '--version', '--wait', '--warn-only', '--watch', '--working-tree', '--workspace', '--yes'],+ 'init': ['--access', '--allow-create-db', '--allow-docker', '--apply', '--auto', '--brain', '--break-lock', '--budget-ms', '--chat-model', '--check', '--content-root', '--db-only', '--dest', '--dim', '--embedding-dimensions', '--embedding-model', '--expansion-model', '--facts', '--fix', '--force', '--full', '--git', '--grant-types', '--harness', '--held', '--help', '--http', '--images', '--issuer-url', '--json', '--key', '--legacy-lock', '--limit', '--local-postgres', '--markdown', '--max-usd', '--mcp-only', '--mcp-url', '--migrate-only', '--migration', '--model', '--no-autopilot-install', '--no-embed', '--no-embedding', '--no-git', '--non-interactive', '--oauth-client-id', '--oauth-client-secret', '--once', '--only', '--page', '--params', '--path', '--pglite', '--phase', '--plan', '--prefer', '--prefer-postgres', '--preview', '--probe', '--provenance', '--query', '--quiet', '--reference-date', '--remediate', '--remove', '--reset', '--save', '--schema-pack', '--scope', '--scopes', '--search-mode', '--section', '--show-toplevel', '--side', '--skip-embed-check', '--source', '--source-id', '--stale', '--state', '--status', '--supabase', '--surface', '--to', '--touchpoint', '--url', '--url-env', '--version', '--wait', '--workspace', '--yes'],'integrations': ['--auto', '--brain', '--dry-run', '--help', '--json', '--overwrite', '--refresh', '--source', '--target'],'integrity': ['--accept-pending', '--auto', '--backend', '--background', '--body', '--brain', '--check', '--confidence', '--cost', '--dry-run', '--explain', '--follow', '--fresh', '--help', '--json', '--limit', '--no-accept-pending', '--progress-interval', '--progress-json', '--quiet', '--review-lower', '--skip-bare-tweet', '--skip-urls', '--source', '--timeout', '--timings', '--type', '--wait'],'jobs': ['--abbrev-ref', '--access', '--account', '--acknowledge-managed', '--add', '--admin-intent', '--adopt-slug-path', '--aliases', '--all', '--all-sources', '--allow-empty', '--allow-shell-jobs', '--allowed-operations', '--apply', '--asof', '--auto', '--background', '--backoff-delay', '--backoff-jitter', '--backoff-type', '--batch-size', '--body', '--bound-slug-prefixes', '--brain', '--break-lock', '--budget-ms', '--by-mention', '--cached', '--catch-up', '--check', '--cli-path', '--client', '--close', '--cluster-errors', '--concurrency', '--confidence', '--confirm-destructive', '--confirm-relocated-root', '--cost-estimate', '--cursor', '--date', '--dated-since', '--days', '--delay', '--detach', '--detail', '--diff-filter', '--dir', '--drain', '--drain-timeout', '--dry-run', '--embedding-dimensions', '--embedding-model', '--empty', '--enable', '--entities', '--exclude', '--exclude-standard', '--expect', '--expect-local', '--expect-upstream', '--expected-state', '--explain', '--facts', '--federated-read', '--ff-only', '--file', '--filters', '--finished-since', '--fix', '--follow', '--force', '--force-break-lock', '--force-retry', '--format', '--fresh', '--from-index', '--from-meetings', '--full', '--full-history', '--fuzzy', '--git', '--grammar-diagnostics', '--group', '--group-by', '--hard-deadline', '--health-interval', '--held', '--help', '--http', '--id', '--idempotency-key', '--ids', '--images', '--include-ambiguous', '--include-deleted', '--include-frontmatter', '--include-gitignored', '--include-hidden', '--include-null-signature', '--infer-dates', '--inject-bootstrap', '--inline', '--input', '--install', '--interval', '--is-ancestor', '--is-shallow-repository', '--job-id', '--job-isolation', '--json', '--keep', '--kind', '--lanes', '--legacy-lock', '--limit', '--list', '--lock-duration-ms', '--log-noop', '--markdown', '--max-age', '--max-attempts', '--max-cost', '--max-cost-usd', '--max-crashes', '--max-rss', '--max-sources', '--max-stalled', '--max-usd', '--max-waiting', '--mcp-only', '--migration', '--min-context', '--missing-path', '--mode', '--model', '--multimodal', '--name', '--name-only', '--ner', '--nice', '--no-auto-embed', '--no-autopilot-install', '--no-bulk', '--no-confirm', '--no-delegate', '--no-embed', '--no-embedding', '--no-extract', '--no-gpg-sign', '--no-hard-deadline', '--no-inject', '--no-lanes', '--no-llm', '--no-pull', '--no-renames', '--no-repair', '--no-schema-pack', '--no-verify', '--no-worker', '--non-interactive', '--now', '--older-than', '--once', '--only', '--order', '--others', '--output', '--override-disabled', '--oversized', '--pace', '--pace-max-concurrency', '--pack', '--page', '--parallel', '--params', '--pat-file', '--path', '--pause', '--pglite', '--phase', '--pid-file', '--plan', '--port', '--prefer', '--preview', '--priority', '--probe', '--prune-orphans', '--pull', '--purge', '--question', '--queue', '--queue-only', '--quiet', '--rate', '--reason', '--rebuild', '--recent', '--record', '--redact-paths', '--redact-secrets', '--reenrich-after', '--refresh-ms', '--refresh-operations', '--remediate', '--repo', '--request-id', '--reset-checkpoint', '--resume', '--retry-failed', '--retry-global', '--retry-held', '--retry-parked', '--review-lower', '--row', '--scope', '--scopes', '--section', '--segment-limit', '--select', '--self-transfer', '--serial', '--session', '--show-toplevel', '--side', '--sigkill-rescue', '--since', '--skip', '--skip-bare-tweet', '--skip-failed', '--skip-urls', '--sleep', '--slug', '--slugs', '--source', '--source-guard', '--source-id', '--sources', '--src-subpath', '--stale', '--state', '--statement-timeout', '--status', '--strategy', '--suites', '--surface', '--swap-only', '--target', '--thin', '--thin-threshold', '--tier', '--timeout', '--timeout-ms', '--to', '--token', '--trust', '--type', '--types', '--uninstall', '--updated-after', '--url', '--user', '--vectors', '--verbose', '--verify', '--version', '--watch', '--wedge-rescue', '--workers', '--working-tree', '--yes'],@@ -103,13 +103,13 @@ export const CLI_FLAG_REGISTRY: Record<string, readonly string[]> = {'questions': ['--brain', '--defer', '--entity', '--fail-fast', '--full', '--help', '--id', '--include-archived', '--json', '--prefix', '--probe', '--publish', '--source', '--tools-json', '--wait-ms', '--yes'],'recall': ['--accept-pending', '--access', '--add', '--all', '--all-subjects', '--allowed-operations', '--as-context', '--asof', '--background', '--body', '--bound-slug-prefixes', '--brain', '--budget-policy', '--budget-tokens', '--client', '--cursor', '--date', '--dated-since', '--days', '--entities', '--entity', '--explain', '--federated-read', '--follow', '--from-index', '--full', '--fuzzy', '--grep', '--group-by', '--help', '--http', '--id', '--include-deleted', '--include-expired', '--json', '--kind', '--limit', '--match', '--max-usd', '--mcp-only', '--model', '--multimodal', '--no-accept-pending', '--no-autopilot-install', '--page', '--params', '--path', '--pending', '--phase', '--prefer', '--progress-interval', '--progress-json', '--purge', '--query', '--question', '--quiet', '--reason', '--recent', '--refresh-operations', '--request-id', '--rollup', '--row', '--scopes', '--session', '--session-id', '--since', '--since-last-run', '--slugs', '--source', '--source-id', '--sources', '--stale', '--status', '--supersessions', '--surface', '--timeout', '--timings', '--to', '--today', '--updated-after', '--url', '--vacuum', '--wait', '--watch', '--yes'],'reconcile-links': ['--accept-pending', '--background', '--body', '--brain', '--dry-run', '--explain', '--follow', '--help', '--json', '--no-accept-pending', '--progress-interval', '--progress-json', '--quiet', '--source', '--timeout', '--timings', '--wait'],- 'reindex': ['--accept-pending', '--admin-intent', '--aliases', '--all-drifted', '--apply', '--background', '--body', '--brain', '--class', '--close', '--concurrency', '--confirm-relocated-root', '--cost-estimate', '--cursor', '--dim', '--dry-run', '--embedding-dimensions', '--embedding-model', '--expect', '--expected-epoch', '--expected-state', '--explain', '--follow', '--force', '--force-rechunk', '--from', '--held', '--help', '--include-ambiguous', '--json', '--keep', '--limit', '--manifest', '--markdown', '--max-cost', '--max-runtime', '--max-usd', '--multimodal', '--no-accept-pending', '--no-embed', '--no-embedding', '--no-llm', '--only', '--oversized', '--path', '--plan', '--prefer', '--progress-interval', '--progress-json', '--quiet', '--repo', '--request', '--request-id', '--self-transfer', '--side', '--since', '--skip', '--slug', '--source', '--stale', '--state', '--status', '--supabase', '--timeout', '--timings', '--to', '--type', '--vectors', '--wait', '--workers', '--yes'],+ 'reindex': ['--accept-pending', '--admin-intent', '--aliases', '--all-drifted', '--apply', '--background', '--body', '--brain', '--class', '--close', '--concurrency', '--confirm-relocated-root', '--cost-estimate', '--cursor', '--dim', '--dry-run', '--embedding-dimensions', '--embedding-model', '--expect', '--expected-epoch', '--expected-state', '--explain', '--follow', '--force', '--force-rechunk', '--from', '--held', '--help', '--include-ambiguous', '--json', '--keep', '--limit', '--manifest', '--markdown', '--max-cost', '--max-runtime', '--max-usd', '--multimodal', '--no-accept-pending', '--no-embed', '--no-embedding', '--no-llm', '--only', '--oversized', '--path', '--plan', '--prefer', '--progress-interval', '--progress-json', '--provenance', '--quiet', '--repo', '--request', '--request-id', '--self-transfer', '--side', '--since', '--skip', '--slug', '--source', '--stale', '--state', '--status', '--supabase', '--timeout', '--timings', '--to', '--type', '--vectors', '--wait', '--workers', '--yes'],'reindex-code': ['--accept-pending', '--apply', '--background', '--brain', '--break-lock', '--client', '--concurrency', '--db-url', '--dry-run', '--embedding-dimensions', '--embedding-model', '--expect', '--explain', '--follow', '--force', '--help', '--http', '--id', '--json', '--legacy-lock', '--max-cost', '--max-cost-usd', '--max-runtime', '--max-usd', '--no-accept-pending', '--no-embed', '--non-interactive', '--only', '--path', '--probe', '--progress-interval', '--progress-json', '--quiet', '--scopes', '--source', '--status', '--timeout', '--timings', '--trust', '--wait', '--workers', '--yes'],'reindex-frontmatter': ['--apply', '--brain', '--concurrency', '--dry-run', '--expect', '--force', '--help', '--json', '--max-cost', '--max-usd', '--non-interactive', '--slug-prefix', '--source', '--trust', '--workers', '--yes'],'reindex-search-vector': ['--accept-pending', '--background', '--brain', '--dry-run', '--explain', '--follow', '--help', '--json', '--no-accept-pending', '--progress-interval', '--progress-json', '--quiet', '--resume', '--source', '--timeout', '--timings', '--wait', '--yes'],'reinit-pglite': ['--abbrev-ref', '--acknowledge-managed', '--all', '--allow-create-db', '--allow-docker', '--allow-empty', '--apply', '--body', '--brain', '--break-lock', '--cached', '--chat-model', '--check', '--concurrency', '--confirm-destructive', '--content-root', '--db-only', '--detail', '--diff-filter', '--dim', '--embedding-dimensions', '--embedding-model', '--empty', '--exclude', '--exclude-standard', '--expansion-model', '--expect', '--filters', '--fix', '--force', '--force-break-lock', '--format', '--full', '--full-history', '--git', '--grant-types', '--hard-deadline', '--help', '--http', '--include-gitignored', '--include-hidden', '--interval', '--is-ancestor', '--is-shallow-repository', '--issuer-url', '--json', '--key', '--lanes', '--local-postgres', '--max-age', '--max-cost', '--max-sources', '--max-usd', '--mcp-only', '--mcp-url', '--migrate-only', '--missing-path', '--model', '--name-only', '--no-auto-embed', '--no-bulk', '--no-delegate', '--no-embed', '--no-embedding', '--no-extract', '--no-git', '--no-gpg-sign', '--no-hard-deadline', '--no-lanes', '--no-llm', '--no-migrate', '--no-pull', '--no-renames', '--no-repair', '--no-schema-pack', '--no-sync', '--no-verify', '--non-interactive', '--oauth-client-id', '--oauth-client-secret', '--others', '--parallel', '--path', '--pglite', '--plan', '--prefer', '--prefer-postgres', '--preview', '--priority', '--provenance', '--query', '--quiet', '--redact-paths', '--repo', '--reset-checkpoint', '--retry-failed', '--retry-held', '--schema-pack', '--scopes', '--search-mode', '--serial', '--show-toplevel', '--skip-embed-check', '--skip-failed', '--slugs', '--source', '--source-id', '--src-subpath', '--stale', '--status', '--strategy', '--supabase', '--surface', '--timeout', '--to', '--trust', '--url', '--verify', '--version', '--watch', '--workers', '--working-tree', '--yes'],'remote': ['--brain', '--help', '--json', '--mcp-only', '--only', '--remediation-plan', '--request-id', '--scopes', '--source', '--timeout'],- 'repair': ['--accept-pending', '--acknowledge-managed', '--after', '--all', '--all-drifted', '--apply', '--background', '--brain', '--break-lock', '--class', '--client', '--close', '--cursor', '--diff', '--expect', '--explain', '--ff-only', '--follow', '--force', '--force-break-lock', '--from', '--full', '--held', '--help', '--id', '--include-ambiguous', '--include-failures', '--include-repairs', '--json', '--keep', '--limit', '--max-cost', '--max-cost-usd', '--max-usd', '--no-accept-pending', '--no-delegate', '--no-embed', '--no-llm', '--older-than', '--only', '--prefer', '--probe', '--progress-interval', '--progress-json', '--quiet', '--remediate', '--remediation-plan', '--request', '--request-id', '--reset-checkpoint', '--retry-failed', '--scopes', '--side', '--since', '--skip', '--skip-failed', '--slug', '--slugs', '--source', '--stale', '--state', '--timeout', '--timings', '--url', '--wait', '--yes'],+ 'repair': ['--accept-pending', '--acknowledge-managed', '--after', '--all', '--all-drifted', '--apply', '--background', '--brain', '--break-lock', '--class', '--client', '--close', '--cursor', '--diff', '--expect', '--explain', '--ff-only', '--follow', '--force', '--force-break-lock', '--from', '--full', '--full-history', '--held', '--help', '--id', '--include-ambiguous', '--include-failures', '--include-repairs', '--json', '--keep', '--limit', '--max-cost', '--max-cost-usd', '--max-usd', '--no-accept-pending', '--no-delegate', '--no-embed', '--no-llm', '--older-than', '--only', '--prefer', '--probe', '--progress-interval', '--progress-json', '--provenance', '--quiet', '--remediate', '--remediation-plan', '--request', '--request-id', '--reset-checkpoint', '--retry-failed', '--scopes', '--side', '--since', '--skip', '--skip-failed', '--slug', '--slugs', '--source', '--stale', '--state', '--timeout', '--timings', '--url', '--wait', '--yes'],'repair-jsonb': ['--accept-pending', '--background', '--brain', '--dry-run', '--explain', '--follow', '--help', '--json', '--no-accept-pending', '--probe', '--progress-interval', '--progress-json', '--quiet', '--source', '--supabase', '--timeout', '--timings', '--url', '--wait'],'report': ['--brain', '--content', '--dir', '--help', '--json', '--source', '--title', '--type'],'repos': ['--abandon', '--abbrev-ref', '--abort', '--accept-suggested', '--access', '--account', '--add', '--admin-intent', '--adopt-columns', '--adopt-permissions', '--adopt-slug-path', '--after', '--all', '--all-new', '--allow-unverified-remote', '--allowed-operations', '--app-id', '--app-install', '--app-pem', '--apply', '--audit', '--auto-additive', '--autostash', '--backups', '--batch-check', '--before', '--bound-brain', '--bound-max-concurrent', '--bound-slug-prefixes', '--bound-source', '--bound-tools', '--brain', '--branch', '--break-lock', '--budget-usd-per-day', '--cached', '--calendar-id', '--category', '--classify', '--cleanup-dead-local-locks', '--clear', '--client', '--clone-dir', '--code', '--confirm-destructive', '--confirm-quiesced', '--confirm-relocated-root', '--conflicts', '--contacts-dir', '--count', '--days', '--decisions', '--delegated-namespace', '--delegated-slug-prefixes', '--depth', '--detect', '--diff-filter', '--dir', '--disable', '--dry-run', '--enable', '--error-unmatch', '--exclude', '--expect-local', '--expect-remote', '--expect-upstream', '--expected-epoch', '--expected-incarnation', '--expected-state', '--federated', '--federated-read', '--fetch-timeout-ms', '--ff-only', '--file', '--fix', '--force', '--format', '--from', '--full', '--future-days', '--get', '--git-dir', '--git-path', '--github-repo', '--grant-types', '--group-by', '--hard', '--help', '--history-days', '--http', '--id', '--if-version', '--include', '--include-warns', '--is-ancestor', '--is-inside-work-tree', '--json', '--keep', '--keep-storage', '--kind', '--lanes', '--limit', '--local', '--local-env-vars', '--loops-exclude-labels', '--manifest', '--max-cost-usd', '--message', '--migrate-legacy', '--migration', '--min-trust', '--name', '--name-only', '--no-autostash', '--no-cron', '--no-embed', '--no-federate', '--no-federated', '--no-harden', '--no-lanes', '--no-pull', '--no-tags', '--no-verify', '--not', '--only', '--operations', '--origin', '--others', '--out', '--params', '--parked-pushes', '--pat-file', '--path', '--path-format', '--plan', '--porcelain', '--preview', '--probe', '--profile', '--pull', '--push-only', '--quiet', '--read-sources', '--rebase', '--redirect-uri', '--refresh-operations', '--remove-backup', '--repair', '--replace', '--repos', '--request-id', '--require-clean', '--reset-checkpoint', '--reset-default', '--resolve', '--resume', '--retry-failed', '--scope', '--scopes', '--secret', '--self-transfer', '--services', '--set', '--set-upstream-to', '--shared-skills', '--short', '--show-toplevel', '--since', '--slug-prefixes', '--source', '--source-id', '--source-ids', '--sources', '--stale', '--state', '--status', '--stdin', '--surface', '--symbolic-full-name', '--takes-holders', '--token', '--token-command', '--token-endpoint-auth-method', '--token-env', '--token-ttl', '--unindexed', '--unset-all', '--untracked-files', '--url', '--usage', '--verify', '--wait', '--wait-drain', '--warn-only', '--window', '--yes'],diff --git a/src/core/persistence/coordinator.ts b/src/core/persistence/coordinator.tsindex 5a0a4e452c..ca9446cc83 100644--- a/src/core/persistence/coordinator.ts+++ b/src/core/persistence/coordinator.ts@@ -64,7 +64,7 @@ interface PreparedMutationBase {contentUnchanged?: boolean;deferEmbedding?: boolean;/** Why a page write bound to a worktree publishes no file (receipt `write_through.skipped`). */- databaseOnlyReason?: 'db_only' | 'unbound_source' | 'mirror_read_only' | 'sync_excluded' | 'shared_origin' | 'origin_twin';+ databaseOnlyReason?: 'db_only' | 'unbound_source' | 'mirror_read_only' | 'sync_excluded' | 'shared_origin' | 'origin_twin' | 'detached';/** #6517: the receipt's `write_through.warning` for a database-only publication, set by `validate` under the publication guards. */databaseOnlyWarning?: string;/**diff --git a/src/core/persistence/prepared-maintenance.ts b/src/core/persistence/prepared-maintenance.tsindex deb04ca82c..2b3629b543 100644--- a/src/core/persistence/prepared-maintenance.ts+++ b/src/core/persistence/prepared-maintenance.ts@@ -205,7 +205,7 @@ export function maintenanceDriftRefusal(sourceId: string, slug: string): Operati* atom, whose file the retirement removed): a missing canonical file publishes, so it is no ghost.*/export const PUBLISHES_WITHOUT_FILE: ReadonlySet<string> = new Set(['managed_maintenance_chronicle_event', 'managed_maintenance_chronicle_retire', 'managed_maintenance_retire_stale_atoms',- 'managed_maintenance_retire_ghost_page', 'managed_maintenance_restore_reextract_atom']);+ 'managed_maintenance_retire_ghost_page', 'managed_maintenance_restore_reextract_atom', 'managed_maintenance_file_drift_detach']);/** #6696 (A12): `source_changed` / `canonical_file_missing` before admission: the page's recorded file is gone; never a new request. */export function maintenanceGhostRefusal(sourceId: string, slug: string): OperationError {@@ -539,6 +539,7 @@ async function prepareMaintenanceKind(engine: BrainEngine, row: WriteRequest, coif (row.intent?.kind === 'managed_maintenance_restore_reextract_atom') return (await import('../repair/atoms-restore.ts')).prepareAtomRestore(engine, row, config);if (row.intent?.kind === 'managed_maintenance_retire_ghost_page') return (await import('../repair/ghost-pages.ts')).prepareGhostPageRetirement(engine, row, config);if (row.intent?.kind === 'managed_maintenance_file_drift_remove') return (await import('../repair/file-drift.ts')).prepareDriftFileRemoval(engine, row);+ if (row.intent?.kind === 'managed_maintenance_file_drift_detach') return (await import('../repair/file-drift.ts')).prepareDriftDetach(engine, row);if (row.intent?.kind === 'managed_maintenance_merge_legacy_twin') return (await import('../repair/legacy-twins.ts')).prepareLegacyTwinMerge(engine, row, config);if (row.intent?.kind === 'managed_maintenance_resolve_origin_twin') return (await import('../repair/origin-twins.ts')).prepareOriginTwinResolve(engine, row, config);if (row.intent?.kind !== 'managed_maintenance_consolidate') throw opError('invalid_params', 'Unsupported maintenance request.',diff --git a/src/core/persistence/sync-origin-evidence.ts b/src/core/persistence/sync-origin-evidence.tsindex 2fe517b2f6..0f1a48b057 100644--- a/src/core/persistence/sync-origin-evidence.ts+++ b/src/core/persistence/sync-origin-evidence.ts@@ -85,3 +85,53 @@ export async function readOriginEvidence(gitRoot: string, commits: ReadonlyArray}return evidence;}++/**+ * GBRA-133: where a held file whose page is still live went. `deleted_by_commit`: the newest commit of HEAD's full history+ * (`--full-history`, so a side branch's deletion that a merge kept is not simplified away; a merge counts against its first+ * parent) that deleted the path, with its author, date and subject. `deletion_uncommitted`: HEAD still holds the path, so+ * only the worktree lost it. `never_committed`: no commit of HEAD's history ever held it (a checkout with no commit yet+ * included). `unknown`: Git could not answer, or the history touched the path without a deletion this read can name.+ */+export type DeletionProvenance =+ | { kind: 'deleted_by_commit'; commit: string; author: string; date: string; subject: string }+ | { kind: 'deletion_uncommitted' } | { kind: 'never_committed' } | { kind: 'unknown' };+export const DELETION_PROVENANCES = ['deleted_by_commit', 'deletion_uncommitted', 'never_committed'] as const;++/** Paths relative to `root` (a work tree or a directory inside one), read against HEAD in bounded batches. */+export async function readDeletionProvenance(root: string, paths: readonly string[]): Promise<Map<string, DeletionProvenance>> {+ const provenance = new Map<string, DeletionProvenance>();+ const unique = [...new Set(paths)];+ const head = await git(root, ['rev-parse', '--verify', '--quiet', 'HEAD^{commit}']);+ const unborn = head.code === 1 && (await git(root, ['rev-parse', '--is-inside-work-tree'])).stdout.trim() === 'true';+ for (const path of unique) provenance.set(path, unborn ? { kind: 'never_committed' } : { kind: 'unknown' });+ if (head.code !== 0) return provenance;+ for (let i = 0; i < unique.length; i += BATCH) {+ const batch = unique.slice(i, i + BATCH);+ // A side branch's own deleting commit names who removed the path and why; a merge counts (against its first parent) only+ // for a path no ordinary commit deleted, where the merge's resolution dropped it.+ for (const merges of [['--no-merges'], ['--merges', '--diff-merges=first-parent']]) {+ const open = batch.filter(path => provenance.get(path)?.kind === 'unknown');+ if (!open.length) break;+ const deleted = await git(root, ['log', '--full-history', '--no-renames', ...merges, '--diff-filter=D', '--relative', '-z',+ '--format=%x1e%H%x1f%an%x1f%aI%x1f%s', '--name-only', 'HEAD', '--', ...open], true);+ if (deleted.code !== 0) break;+ for (const record of deleted.stdout.split('\x1e').slice(1)) {+ const [header = '', ...names] = record.split('\0');+ const [commit = '', author = '', date = '', subject = ''] = header.trim().split('\x1f');+ for (const name of names.map(entry => entry.replace(/^\n+/, '')).filter(Boolean)) {+ if (provenance.get(name)?.kind === 'unknown' && open.includes(name)) provenance.set(name, { kind: 'deleted_by_commit', commit, author, date, subject });+ }+ }+ }+ const rest = batch.filter(path => provenance.get(path)?.kind === 'unknown');+ if (!rest.length) continue;+ const listed = await git(root, ['ls-tree', '-r', '-z', '--name-only', 'HEAD', '--', ...rest], true);+ const touched = await git(root, ['log', '--full-history', '--no-renames', '--relative', '-z', '--format=', '--name-only', 'HEAD', '--', ...rest], true);+ if (listed.code !== 0 || touched.code !== 0) continue;+ const inHead = new Set(listed.stdout.split('\0').filter(Boolean));+ const seen = new Set(touched.stdout.split('\0').map(entry => entry.replace(/^\n+/, '')).filter(Boolean));+ for (const path of rest) provenance.set(path, inHead.has(path) ? { kind: 'deletion_uncommitted' } : seen.has(path) ? { kind: 'unknown' } : { kind: 'never_committed' });+ }+ return provenance;+}diff --git a/src/core/repair/core.ts b/src/core/repair/core.tsindex aed4ebe862..12b6890bdb 100644--- a/src/core/repair/core.ts+++ b/src/core/repair/core.ts@@ -47,7 +47,7 @@ import { acceptedPendingReceipt } from '../persistence/accepted-pending.ts';import { repairAdmissionWindow, repairPublicationOwner, settleRepairReceipts, type PendingRepair } from './settle.ts';import { RECEIPT_RESERVATION_FLOOR } from '../persistence/receipt-bytes.ts';import { readFix } from '../ops/op-fix.ts';-import { ItemRun, type ItemFailure } from '../item-failure.ts';+import { classifyItemFailure, ItemRun, type ItemFailure } from '../item-failure.ts';import type { ProgressReporter } from '../progress.ts';export const REPAIR_KINDS = ['timeline', 'visibility', 'safe-chunks', 'contextual-mode', 'connector-checkpoints', 'request-indexes', 'connector-fences', 'take-supersession', 'accepted-takes', 'orphan-bindings', 'embedding-effects', 'attribution-backfill', 'planner-stats', 'google-file-modes', 'stale-atoms', 'atoms-restore', 'extractor-facts', 'conversation-labels', 'captured-facts', 'redacted-facts', 'loop-facts', 'ontology-facts', 'facts-rehome', 'consolidate-ties', 'orphan-children', 'failed-writes', 'split-facts', 'frontmatter', 'fences', 'slug-conflicts', 'timeline-comments', 'managed-sync-orphans', 'content-receipt-root', 'frontmatter-keys', 'file-drift', 'stuck-recovery', 'ghost-pages', 'origin-twins', 'receipt-compaction', 'aliases', 'rename-identity', 'overwritten-edits', 'legacy-twins', 'missing-tables', 'url-clone-fences', 'segmented-mirror', 'uncommitted-deletions'] as const;@@ -108,6 +108,8 @@ export interface RepairPlanOptions { apply: boolean; expect?: string; includeAmbsince?: string;/** #6712 PR 4b `file-drift`: the source's held `file_drift` pages, of one side and (for `deleted`) one state. */held?: boolean; side?: string; state?: string;+ /** GBRA-133 `file-drift --held --side deleted --state file_gone`: only holds of this deletion provenance (`--provenance`). */+ provenance?: string;/** `file-drift --held`: the window starts after the held file this `next_cursor` names (`--cursor`); `progress` reports the preview's pages, and an apply's items, on stderr. */cursor?: string; progress?: ProgressReporter;/** `stuck-recovery`: the version an apply keeps, and the one request a run selects. */@@ -315,9 +317,11 @@ 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;- cursor?: string; progress?: ProgressReporter;+ provenance?: string; cursor?: string; progress?: ProgressReporter;keep?: 'prior' | 'disk' | 'withdrawn'; requestId?: string; olderThan?: string; includeFailures?: boolean; force?: boolean; from?: string; close?: boolean; afterPage?: number;spec?: Pick<RepairKindSpec, 'explicit_only' | 'consent' | 'spends'>; maxLlmUsd?: number; deadline?: number; now?: () => number;+ /** GBRA-133: the CLI's termination signal; the apply stops before the next item with a result instead of dying mid-run. */+ stop?: AbortSignal;/** 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> {// #6696 (A5): an approved local repair is the operator's own write; a maintenance cycle's background scope still wins.@@ -338,7 +342,7 @@ async function runRepairScoped(ctx: OperationContext, handler: RepairHandler, sc...(opts.prefer ? { prefer: opts.prefer } : {}), ...(opts.requests?.length ? { requests: opts.requests } : {}),...(opts.allDrifted ? { allDrifted: true } : {}), ...(opts.driftClass ? { driftClass: opts.driftClass } : {}), ...(opts.since ? { since: opts.since } : {}),...(opts.held ? { held: true } : {}), ...(opts.side ? { side: opts.side } : {}), ...(opts.state ? { state: opts.state } : {}),- ...(opts.cursor ? { cursor: opts.cursor } : {}), ...(opts.progress ? { progress: opts.progress } : {}),+ ...(opts.provenance ? { provenance: opts.provenance } : {}), ...(opts.cursor ? { cursor: opts.cursor } : {}), ...(opts.progress ? { progress: opts.progress } : {}),...(opts.keep ? { keep: opts.keep } : {}), ...(opts.requestId ? { requestId: opts.requestId } : {}),...(opts.olderThan ? { olderThan: opts.olderThan } : {}), ...(opts.includeFailures ? { includeFailures: true } : {}), ...(opts.force ? { force: true } : {}),...(opts.from ? { from: opts.from } : {}), ...(opts.close ? { close: true } : {}), ...(opts.afterPage !== undefined ? { afterPage: opts.afterPage } : {}),@@ -368,7 +372,8 @@ async function runRepairScoped(ctx: OperationContext, handler: RepairHandler, sc...(opts.slugs ?? []).flatMap(slug => ['--slug', slug]), ...(opts.from ? ['--from', opts.from] : []), ...(opts.close ? ['--close'] : []),...(opts.requests ?? []).flatMap(id => ['--request', id]),...(opts.allDrifted ? ['--all-drifted'] : []), ...(opts.driftClass ? ['--class', opts.driftClass] : []), ...(opts.since ? ['--since', opts.since] : []),- ...(opts.held ? ['--held'] : []), ...(opts.side ? ['--side', opts.side] : []), ...(opts.state ? ['--state', opts.state] : []), ...(opts.cursor ? ['--cursor', opts.cursor] : []),+ ...(opts.held ? ['--held'] : []), ...(opts.side ? ['--side', opts.side] : []), ...(opts.state ? ['--state', opts.state] : []),+ ...(opts.provenance ? ['--provenance', opts.provenance] : []), ...(opts.cursor ? ['--cursor', opts.cursor] : []),...(opts.prefer ? ['--prefer', opts.prefer] : [])].map(arg => ` ${shellQuote([arg])}`).join('')}`+ `${opts.includeAmbiguous ? ' --include-ambiguous' : ''}${llm && opts.noLlm ? ' --no-llm' : ''}${llm && opts.maxLlmUsd !== undefined ? ` --max-usd ${opts.maxLlmUsd}` : ''}`+ ` --apply${plan.preview_hash ? ` --expect ${plan.preview_hash}` : ''}${spec?.consent === 'destructive' ? ' --yes' : ''}`,@@ -435,6 +440,10 @@ async function runRepairScoped(ctx: OperationContext, handler: RepairHandler, scresult.stopped = pendingStop(settleMs ? `; nothing published for ${Math.round(settleMs / 1000)}s` : '');return finish();}+ if (opts.stop?.aborted) {+ return stopAfterSettle({ reason: 'interrupted', message: `Stopped before ${item.source_id}:${item.slug}: this process received ${String(opts.stop.reason ?? 'a termination signal')} `+ + `(${remaining} item(s) still pending; the items before it stay applied). Rerun \`${result.apply_command}\` to resume.` });+ }if (opts.deadline !== undefined && now() >= opts.deadline) {return stopAfterSettle({ reason: 'time_budget', message: `Stopped before ${item.source_id}:${item.slug}: this run reached its time budget (${remaining} item(s) still pending). `+ `The next run resumes; rerun \`${result.apply_command}\` to continue now.` });@@ -505,6 +514,16 @@ async function runRepairScoped(ctx: OperationContext, handler: RepairHandler, screturn stopAfterSettle({ reason: error.code, message: `The canonical writer for source '${item.source_id}' is held (${error.code}). `+ `Inspect it with: gbrain sources writer status ${item.source_id} — then rerun \`${result.apply_command}\` to resume.` });}+ // GBRA-133: a deadlock, a serialization failure or a lost database connection stops the run with what it applied and+ // the resume command in the result (the cursor stays before this item), instead of ending the command with no record.+ const database = classifyItemFailure(error);+ if (database.scope === 'run' && (database.code === 'database_contention' || database.code === 'connection_lost')) {+ const sqlstate = (error as { code?: unknown } | null)?.code;+ return stopAfterSettle({ reason: database.code, message: redactConnectionInfo(`Stopped at ${item.source_id}:${item.slug}: the database refused this item`+ + `${typeof sqlstate === 'string' ? ` (${sqlstate})` : ''}: ${database.message.slice(0, 300)}. The items before it stay applied `+ + `(${remaining} item(s) still pending). Rerun \`${result.apply_command}\` to resume from this item.`),+ fix: readFix(`Previews ${handler.kind} again (read-only) to show whether the database accepts work again.`, { argv: ['gbrain', 'repair', handler.kind, ...(opts.sourceFlag ? ['--source', opts.sourceFlag] : []), '--json'] }) });+ }// An apply bound to an approved preview (`--expect`) applies that set or answers why not; only the kinds' own refusals continue it.if (opts.expect && !(error instanceof OperationError && REPAIR_ITEM_FAILURE_CODES.has(error.code))) throw error;const { failure, systemic: stop } = items.record(`${item.source_id}:${item.slug}`, error);diff --git a/src/core/repair/file-drift.ts b/src/core/repair/file-drift.tsindex 99bb4ac03c..521d9acf53 100644--- a/src/core/repair/file-drift.ts+++ b/src/core/repair/file-drift.ts@@ -79,6 +79,8 @@ import type { WriteRequest } from '../persistence/model.ts';import { resolveSlugForPath } from '../sync.ts';import { getWorktreeBinding } from '../persistence/ownership.ts';import { gitDurabilityPolicy } from '../persistence/git-durability-policy.ts';+import { DETACHED_REASON } from '../persistence/detached-pages.ts';+import { DELETION_PROVENANCES, readDeletionProvenance, type DeletionProvenance } from '../persistence/sync-origin-evidence.ts';import { ghostPageNow, scanGhostSource, type GhostOwner, type GhostPage } from '../ghost-pages.ts';import { MASS_RECONCILE_MIN_PAGES, MASS_RECONCILE_RATIO, massReconcileAllowed } from '../sync-reconcile.ts';import { GHOST_PURGE_FUSE_HOURS, GHOST_REPAIR_LIMIT, ghostScanRefusal, massGhosts, massRefusal, retireGhost } from './ghost-pages.ts';@@ -110,12 +112,21 @@ export interface DeletedDriftPin { state: 'tombstone_edited' | 'purged_differs';export interface RemoveFilePage { slug: string; prefer: 'database'; exceptions: DriftException[]; remove_file: DeletedDriftPin }/** #6712 PR 4b `--prefer file` on a deleted side: the file's bytes are imported (restoring the tombstone, or as a new page). */export interface ImportFilePage { slug: string; prefer: 'file'; exceptions: DriftException[]; import_file: DeletedDriftPin & { result_digest: string } }-type PlannedPage = ArtifactPage | SoftDeletePage | RemoveFilePage | ImportFilePage;+/**+ * GBRA-133 `--provenance never_committed --prefer database`: a live page whose held file no commit ever held keeps its content+ * database-only. The apply forgets the page's recorded file (`database_only_reason=detached`, as `restore --detach` does),+ * writes no file and clears the hold, bound to the page's id, revision and path and to the hold it observed.+ */+export interface DetachPin { path: string; page_id: number; revision: string; observed_at: string }+export interface DetachPage { slug: string; prefer: 'database'; exceptions: DriftException[]; detach_page: DetachPin }+type PlannedPage = ArtifactPage | SoftDeletePage | RemoveFilePage | ImportFilePage | DetachPage;/** #6712 PR 4b: one held `file_drift` page a `--held` selection resolves. */-interface HeldTarget { hold: GitHoldRecord; side: FileDriftSide; state?: FileDriftDeletedState }+interface HeldTarget { hold: GitHoldRecord; side: FileDriftSide; state?: FileDriftDeletedState; provenance?: DeletionProvenance }/** The coordinated removal `--prefer database` admits for a held file whose page is deleted (prepared by `prepareDriftFileRemoval`). */export const FILE_DRIFT_REMOVE_INTENT = 'managed_maintenance_file_drift_remove';+/** GBRA-133: the database-only keep of a live page whose held file no commit ever held (`prepareDriftDetach`). */+export const FILE_DRIFT_DETACH_INTENT = 'managed_maintenance_file_drift_detach';const DELETED_CHANGES: Record<DeletedDriftChange, string> = {file_gone: 'the file is gone now, so nothing is left to resolve',live_page: 'a live page records the file again, so it is no longer a deleted-side Decision',@@ -144,7 +155,7 @@ const artifactDirectory = () => join(canonicalFilesystemPath(configDir()), 'repaconst escapePointer = (key: string) => key.replace(/~/g, '~0').replace(/\//g, '~1');function previewCommand(sourceId: string, opts: RepairPlanOptions): string {- const select = opts.held ? ` --held${opts.side ? ` --side ${opts.side}` : ''}${opts.state ? ` --state ${opts.state}` : ''}${opts.cursor ? ` --cursor ${opts.cursor}` : ''}`+ const select = opts.held ? ` --held${opts.side ? ` --side ${opts.side}` : ''}${opts.state ? ` --state ${opts.state}` : ''}${opts.provenance ? ` --provenance ${opts.provenance}` : ''}${opts.cursor ? ` --cursor ${opts.cursor}` : ''}`: opts.allDrifted ? ` --all-drifted${opts.driftClass ? ` --class ${opts.driftClass}` : ''}${opts.since ? ` --since ${opts.since}` : ''}`: [...(opts.slugs ?? []).map(slug => ` --slug ${slug}`), ...(opts.requests ?? []).map(id => ` --request ${id}`)].join('');const globs = [...(opts.only ?? []).flatMap(glob => ['--only', glob]), ...(opts.skip ?? []).flatMap(glob => ['--skip', glob])];@@ -307,7 +318,7 @@ function unknownDriftDetail(sourceId: string, { slug, reason }: UnknownDrift): s* no side and are listed with their single-page route.*/async function selectHeld(engine: BrainEngine, sourceId: string, opts: RepairPlanOptions & { prefer: DriftSide }):- Promise<{ targets: HeldTarget[]; before: number; notSelected: number; legacy: GitHoldRecord[] }> {+ Promise<{ targets: HeldTarget[]; before: number; notSelected: number; legacy: GitHoldRecord[]; otherProvenance: number; provenance?: Record<string, number> }> {const after = opts.cursor ? heldCursorPath(sourceId, opts.cursor) : null;const rows = await engine.executeRaw<{ record: GitHoldRecord; in_window: boolean }>(`SELECT h.completed_keys->0 AS record,($3::text IS NULL OR (h.completed_keys->0->>'path') COLLATE "C" > $3::text) AS in_window FROM op_checkpoints h@@ -337,7 +348,21 @@ async function selectHeld(engine: BrainEngine, sourceId: string, opts: RepairPlaconst only = !opts.side && groups.size === 1 ? [...groups.values()][0]! : null;if (only?.side === 'deleted') throw stateRequired(sourceId, opts, [only.state!]);const selected = targets.filter(target => !opts.side || target.side === opts.side && (!opts.state || target.state === opts.state));- return { targets: selected.filter(target => target.inWindow).map(({ inWindow: _inWindow, ...target }) => target), before: selected.filter(target => !target.inWindow).length, notSelected, legacy };+ let window = selected.filter(target => target.inWindow).map(({ inWindow: _inWindow, ...target }) => target);+ // GBRA-133: a gone file's provenance (sync-origin-evidence.ts), read for every held file a --provenance selection filters, else for one window.+ const gone = window.filter(target => target.state === 'file_gone').slice(0, opts.provenance ? undefined : HELD_WINDOW_PAGES);+ const provenance: Record<string, number> = {};+ if (gone.length) {+ const binding = await getWorktreeBinding(engine, sourceId);+ const read = await readDeletionProvenance(join(binding!.local_path!, binding!.relative_path), gone.map(target => target.hold.path));+ for (const target of gone) {+ target.provenance = read.get(target.hold.path) ?? { kind: 'unknown' };+ provenance[target.provenance.kind] = (provenance[target.provenance.kind] ?? 0) + 1;+ }+ }+ const otherProvenance = opts.provenance ? window.filter(target => target.provenance?.kind !== opts.provenance).length : 0;+ if (opts.provenance) window = window.filter(target => target.provenance?.kind === opts.provenance);+ return { targets: window, before: selected.filter(target => !target.inWindow).length, notSelected, legacy, otherProvenance, ...(gone.length ? { provenance } : {}) };}/** #6712 PR 4b: the `--held` preview of one Decision, keeping the run's `--only` / `--skip` globs. */@@ -357,7 +382,7 @@ function stateRequired(sourceId: string, opts: RepairPlanOptions, states: readonfunction validateOptions(scope: RepairScope, opts: RepairPlanOptions | undefined): asserts opts is RepairPlanOptions & { prefer: DriftSide } {if (opts?.remote !== false) throw trustedCliRequired('gbrain repair file-drift runs only for the trusted local CLI on the brain host.');- const usage = 'gbrain repair file-drift --source <id> (--slug <slug>... | --request <id>... | --all-drifted [--class <name>] [--since <ISO-8601|7d>] | --held [--side both|unknown|deleted [--state tombstone_edited|purged_differs|file_gone]] [--cursor <next_cursor>]) [--only <glob>]... [--skip <glob>]... --prefer file|database';+ const usage = 'gbrain repair file-drift --source <id> (--slug <slug>... | --request <id>... | --all-drifted [--class <name>] [--since <ISO-8601|7d>] | --held [--side both|unknown|deleted [--state tombstone_edited|purged_differs|file_gone [--provenance never_committed|deleted_by_commit|deletion_uncommitted]]] [--cursor <next_cursor>]) [--only <glob>]... [--skip <glob>]... --prefer file|database';if (scope.source_ids.length !== 1) throw opError('invalid_params', 'gbrain repair file-drift needs exactly one --source.', `Name the source: ${usage}`);if (opts.prefer !== 'file' && opts.prefer !== 'database') throw opError('invalid_params', 'gbrain repair file-drift needs --prefer file or --prefer database.',`Choose the side whose content wins (protected metadata, tags union, protected takes and private facts are kept either way): ${usage}`);@@ -371,6 +396,13 @@ function validateOptions(scope: RepairScope, opts: RepairPlanOptions | undefined`Pass --state ${FILE_DRIFT_DELETED_STATES.join(', --state ')} with --side deleted; gbrain sources status ${scope.source_ids[0]} --json lists each held file's state.`);if (opts.state && opts.side !== 'deleted') throw opError('invalid_params', '--state only narrows --side deleted.', `Drop --state, or pass --side deleted with it: ${usage}`);if (opts.side === 'deleted' && !opts.state) throw stateRequired(scope.source_ids[0]!, opts, FILE_DRIFT_DELETED_STATES);+ if (opts.provenance && !(DELETION_PROVENANCES as readonly string[]).includes(opts.provenance)) throw opError('invalid_params', `Unknown deletion provenance '${opts.provenance}'.`,+ `Pass --provenance ${DELETION_PROVENANCES.join(', --provenance ')}; each page of a --held --side deleted --state file_gone preview names its provenance.`);+ if (opts.provenance && opts.state !== 'file_gone') throw opError('invalid_params', '--provenance only narrows --held --side deleted --state file_gone.',+ `Add --held --side deleted --state file_gone, or drop --provenance: ${usage}`);+ if (opts.provenance === 'never_committed' && opts.prefer === 'file') throw opError('invalid_params', 'A never-committed held file cannot be resolved --prefer file.',+ `Nothing was previewed. No commit ever held these files, so each page holds the only copy of its content and --prefer file would soft-delete it (purged after ${GHOST_PURGE_FUSE_HOURS} h). `+ + `Keep them database-only with --prefer database, or preview one page alone with --slug when its deletion is really intended.`);if (opts.driftClass && !opts.allDrifted) throw opError('invalid_params', '--class only narrows --all-drifted.', `Drop --class, or use it with --all-drifted: ${usage}`);if (opts.since && !opts.allDrifted) throw opError('invalid_params', '--since only narrows --all-drifted.', `Drop --since, or use it with --all-drifted: ${usage}`);if (opts.driftClass && !(DRIFT_CLASSES as readonly string[]).includes(opts.driftClass)) throw opError('invalid_params', `Unknown drift class '${opts.driftClass}'.`,@@ -466,7 +498,7 @@ export async function prepareDriftPage(engine: BrainEngine, sourceId: string, sl* #6712 wave: the resolution of a selected page whose canonical file is gone (`canonical_file_missing`), or the reason it* is skipped. Only a deletion gone from HEAD is file-drift's; one still committed at HEAD routes elsewhere.*/-async function fileGonePage(engine: BrainEngine, sourceId: string, slug: string, opts: RepairPlanOptions & { prefer: DriftSide }, assessmentAt: string):+async function fileGonePage(engine: BrainEngine, sourceId: string, slug: string, opts: RepairPlanOptions & { prefer: DriftSide }, assessmentAt: string, target?: HeldTarget):Promise<{ page: PlannedPage; detail: string } | { skip: string; detail: string }> {const now = await ghostPageNow(engine, sourceId, slug);if (!now.ghost) return { skip: `unknown_${now.reason}`, detail: now.reason };@@ -475,6 +507,10 @@ async function fileGonePage(engine: BrainEngine, sourceId: string, slug: string,const root = join(binding!.local_path!, binding!.relative_path);const deletion = canonicalDeletionState(root, join(root, ...now.ghost.path.split('/')));if (deletion !== 'gone') return { skip: deletion === 'in_head' ? 'deletion_uncommitted' : 'unknown_deletion_state', detail: missingFileRoute(sourceId, slug, now.ghost.path, deletion) };+ if (opts.provenance === 'never_committed' && target?.provenance?.kind === 'never_committed') {+ return { page: { slug, prefer: 'database', exceptions: [], detach_page: { path: now.ghost.path, page_id: now.ghost.page_id, revision: now.ghost.revision, observed_at: target.hold.observed_at } },+ detail: `keeps the page database-only: no commit ever held ${now.ghost.path}, so the page holds the only copy; no file is written and the page forgets that path` };+ }if (opts.prefer === 'file') return { page: { slug, prefer: 'file', exceptions: [], soft_delete: { ghost: now.ghost, owner: now.owner } },detail: `soft-deletes the page: its file ${now.ghost.path} is gone from the last commit (purged after ${GHOST_PURGE_FUSE_HOURS} h; gbrain restore ${slug} --force undoes it until then)` };const page = await prepareDriftPage(engine, sourceId, slug, 'database', assessmentAt, { fileGone: true });@@ -547,14 +583,56 @@ export async function prepareDriftFileRemoval(engine: BrainEngine, row: WriteReqhold_cleared: await clearGitHold(tx, { sourceId: row.source_id, incarnation: row.source_incarnation, path: pin.path, observedAt: pin.observed_at }) }) };}+/**+ * GBRA-133: the preparer of `managed_maintenance_file_drift_detach`. It re-checks, here and under the publication guard, that+ * the page is the previewed one (id, revision, recorded path), still live with its file missing, and that no commit of HEAD's+ * history holds the path. The apply clears the page's recorded file (`database_only_reason=detached`, so no sync reads the+ * missing file as a deletion again) and the hold it resolves in the publishing transaction; no file is written.+ */+export async function prepareDriftDetach(engine: BrainEngine, row: WriteRequest): Promise<PreparedMutation> {+ const pin = row.intent?.target as DetachPin | undefined;+ if (row.authority.remote || !pin || typeof pin.path !== 'string' || typeof pin.revision !== 'string' || typeof pin.observed_at !== 'string'+ || pin.page_id !== (row.page_id === null || row.page_id === undefined ? null : Number(row.page_id))) {+ throw opError('invalid_params', 'The file-drift database-only intent does not name its page.',+ `Request ${row.request_id} in source ${row.source_id} does not name the held page it keeps, so nothing changed. Preview the repair again with gbrain repair file-drift --source ${row.source_id} --held --side deleted --state file_gone --provenance never_committed --prefer database.`);+ }+ const changed = (why: string) => opError('changed_since_preview', `${pin.path} changed since its database-only keep was previewed: ${why}.`,+ `Nothing was written for ${row.slug}. Preview again with gbrain repair file-drift --source ${row.source_id} --held --side deleted --state file_gone --provenance never_committed --prefer database and apply its new hash.`,+ { fix: readFix('Lists the held files of this source with their side and state, read-only.', { argv: ['gbrain', 'sources', 'status', row.source_id, '--json'] }) });+ const now = await ghostPageNow(engine, row.source_id, row.slug);+ if (!now.ghost) throw changed(`the page is no longer a live page whose file is missing (${now.reason})`);+ if (now.ghost.page_id !== pin.page_id || now.ghost.revision !== pin.revision || now.ghost.path !== pin.path) throw changed('the page, its revision or its recorded path changed');+ const binding = await getWorktreeBinding(engine, row.source_id);+ const found = (await readDeletionProvenance(join(binding!.local_path!, binding!.relative_path), [pin.path])).get(pin.path);+ if (found?.kind !== 'never_committed') throw changed(`its provenance is ${found?.kind ?? 'unknown'} now`);+ const locked = async (tx: BrainEngine) => {+ const [page] = await tx.executeRaw<{ id: number }>('SELECT id FROM pages WHERE id=$1 AND source_id=$2 AND slug=$3 AND deleted_at IS NULL AND source_path IS NOT NULL', [pin.page_id, row.source_id, row.slug]);+ if (!page) throw changed('the page was deleted, renamed or already forgot its file');+ };+ return { observedRevision: pin.revision, databaseOnlyReason: 'detached',+ validate: async tx => { await locked(tx); },+ apply: async tx => {+ await tx.executeRaw('UPDATE pages SET source_path=NULL, source_uri=NULL, database_only_reason=$2 WHERE id=$1', [pin.page_id, DETACHED_REASON]);+ return { status: 'detached', slug: row.slug, source_id: row.source_id, path: pin.path,+ hold_cleared: await clearGitHold(tx, { sourceId: row.source_id, incarnation: row.source_incarnation, path: pin.path, observedAt: pin.observed_at }) };+ } };+}+/*** #6712 PR 4b: one held deleted-side page applied as previewed. `remove_file` admits the coordinated removal, bound to the* pin; `import_file` re-reads the pin and submits the managed file repair of the exact previewed bytes and result.*/-async function applyDeletedSide(ctx: OperationContext, page: ApprovedPage, artifact: RemoveFilePage | ImportFilePage, requestId: string, embed: boolean): Promise<RepairItemOutcome> {- const pin = 'remove_file' in artifact ? artifact.remove_file : artifact.import_file;- const action = 'remove_file' in artifact ? 'remove_file' : 'import_file';+async function applyDeletedSide(ctx: OperationContext, page: ApprovedPage, artifact: RemoveFilePage | ImportFilePage | DetachPage, requestId: string, embed: boolean): Promise<RepairItemOutcome> {+ const action = 'remove_file' in artifact ? 'remove_file' : 'import_file' in artifact ? 'import_file' : 'detach_page';try {+ if ('detach_page' in artifact) {+ const authority = await maintenancePreflight(ctx.engine, page.source_id);+ if (!authority) throw opError('owner_unavailable', 'Keeping a held page database-only needs the managed write path.',+ `Managed persistence is off for this brain, so ${artifact.detach_page.path} was not resolved. Held file-drift pages exist only on managed sources; check the source with gbrain sources status ${page.source_id} --json.`);+ await submitMaintenanceIntent(ctx.engine, authority, artifact.slug, { kind: FILE_DRIFT_DETACH_INTENT, expected_revision: artifact.detach_page.revision, target: artifact.detach_page }, requestId);+ return { applied: true, outcome: 'repaired', detail: { request_id: requestId, prefer: 'database', action } };+ }+ const pin = 'remove_file' in artifact ? artifact.remove_file : artifact.import_file;if ('remove_file' in artifact) {await assertDeletedPin(ctx.engine, page.source_id, pin);const authority = await maintenancePreflight(ctx.engine, page.source_id);@@ -576,6 +654,13 @@ async function applyDeletedSide(ctx: OperationContext, page: ApprovedPage, artif}}+/** GBRA-133: one held gone file's provenance, as the preview lists it. */+function provenanceText(found: DeletionProvenance): string {+ if (found.kind === 'deleted_by_commit') return `deleted by commit ${found.commit.slice(0, 12)} (${found.date}, ${found.author}: ${found.subject})`;+ return found.kind === 'never_committed' ? 'never committed: no commit held the file' : found.kind === 'deletion_uncommitted' ? 'deletion uncommitted: HEAD still holds the file'+ : 'provenance unknown: Git could not name the deleting commit';+}+function item(page: ApprovedPage, index: number, hash: string, last: boolean, prefer: DriftSide): DriftItem {return { cursor: { phase: 0, id: index + 1 }, source_id: page.source_id, slug: page.slug, chars: 0, action: `prefer_${prefer}`, page, hash, last };}@@ -618,7 +703,8 @@ export const fileDriftRepair: RepairHandler = {const assessmentAt = new Date().toISOString();const pages: PlannedPage[] = [];const listing: NonNullable<RepairPlan['listing']> = [];- const residuals: Record<string, number> = { ...(notSelected ? { not_selected: notSelected } : {}), ...(held?.before ? { before_cursor: held.before } : {}) };+ const residuals: Record<string, number> = { ...(notSelected ? { not_selected: notSelected } : {}), ...(held?.before ? { before_cursor: held.before } : {}),+ ...(held?.otherProvenance ? { other_provenance: held.otherProvenance } : {}) };const count = (key: string) => { residuals[key] = (residuals[key] ?? 0) + 1; };for (const hold of held?.legacy ?? []) {count('legacy_side');@@ -658,7 +744,7 @@ export const fileDriftRepair: RepairHandler = {continue;}if (live.reason === 'canonical_file_missing') {- const gone = await fileGonePage(engine, sourceId, slug, opts, assessmentAt);+ const gone = await fileGonePage(engine, sourceId, slug, opts, assessmentAt, target);if ('skip' in gone) {count(gone.skip);if (gone.skip !== 'not_selected') listing.push({ item: `${sourceId}:${slug}`, class: gone.skip.startsWith('unknown_') ? 'unknown' : gone.skip, detail: gone.detail });@@ -693,6 +779,7 @@ export const fileDriftRepair: RepairHandler = {if (remaining > 0) residuals.after_window = remaining;const hash = previewHash({ kind: 'file-drift-v1', brain_id: scope.brain_id, source_id: sourceId, selection,pages: pages.map(page => 'soft_delete' in page ? [page.slug, page.soft_delete.ghost.revision, ABSENT_FILE_HASH, 'soft_delete']+ : 'detach_page' in page ? [page.slug, page.detach_page.revision, ABSENT_FILE_HASH, 'detach_page', page.detach_page.page_id, page.detach_page.observed_at]: 'remove_file' in page ? [page.slug, page.remove_file.revision, page.remove_file.raw_file_hash, 'remove_file', page.remove_file.state, page.remove_file.marker_digest]: 'import_file' in page ? [page.slug, page.import_file.revision, page.import_file.raw_file_hash, page.import_file.result_digest, page.import_file.state, page.import_file.marker_digest]: [page.slug, page.preview.preconditions.revision, page.preview.preconditions.raw_file_hash, page.preview.result_digest]) });@@ -712,6 +799,11 @@ export const fileDriftRepair: RepairHandler = {undoneBySync = { recreated: recreated.length, removed: removed.length };}}+ const provenanceOf = new Map((held?.targets ?? []).flatMap(target => target.provenance && target.hold.slug ? [[target.hold.slug, target.provenance] as const] : []));+ for (const entry of listing) {+ const found = provenanceOf.get(entry.item.slice(sourceId.length + 1));+ if (found) entry.detail = `${entry.detail}; ${provenanceText(found)}`;+ }let artifact: string | undefined;if (pages.length) {await assertReconcileOutputPath(engine, sourceId, artifactDirectory());@@ -724,12 +816,15 @@ export const fileDriftRepair: RepairHandler = {details: { prefer: opts.prefer, ...(artifact ? { artifact } : {}),...(undoneBySync ? { undone_by_next_sync_unless_committed: undoneBySync } : {}),...(held ? { window: { previewed, remaining, complete: remaining === 0, ...(nextCursor ? { next_cursor: nextCursor, next_command: nextCommand } : {}) } } : {}),- pages: pages.map(page => 'soft_delete' in page ? { slug: page.slug, action: 'soft_delete', path: page.soft_delete.ghost.path, verb: fileDriftActionVerb('deleted', 'file_gone', 'file'), exceptions: page.exceptions }+ ...(held?.provenance ? { provenance: held.provenance } : {}),+ pages: pages.map(page => ({ ...('soft_delete' in page ? { slug: page.slug, action: 'soft_delete', path: page.soft_delete.ghost.path, verb: fileDriftActionVerb('deleted', 'file_gone', 'file'), exceptions: page.exceptions }+ : 'detach_page' in page ? { slug: page.slug, action: 'detach_page', path: page.detach_page.path, verb: 'keep the page database-only (no file)', exceptions: page.exceptions }: 'remove_file' in page ? { slug: page.slug, action: 'remove_file', state: page.remove_file.state, path: page.remove_file.path, verb: fileDriftActionVerb('deleted', page.remove_file.state, 'database'), exceptions: page.exceptions }: 'import_file' in page ? { slug: page.slug, action: 'import_file', state: page.import_file.state, path: page.import_file.path, verb: fileDriftActionVerb('deleted', page.import_file.state, 'file'), exceptions: page.exceptions, result_digest: page.import_file.result_digest }: { slug: page.slug, ...(page.file_gone ? { action: 'recreate_file' } : {}), ...(page.class ? { class: page.class } : {}),verb: page.file_gone ? fileDriftActionVerb('deleted', 'file_gone', 'database') : fileDriftActionVerb('both', undefined, page.prefer),adopt_slug_path: page.adopt_slug_path, exceptions: page.exceptions, result_digest: page.preview.result_digest }),+ ...(provenanceOf.get(page.slug) ? { provenance: provenanceOf.get(page.slug) } : {}) })),protections: 'Protected metadata stays as the database holds it, tags are the union of both sides, and protected takes and private fact rows are kept; exceptions lists each page\'s.' } };},async apply(ctx, entry, opts): Promise<RepairItemOutcome> {@@ -739,7 +834,7 @@ export const fileDriftRepair: RepairHandler = {if (!artifact || digest(artifact) !== page.artifact_digest) throw previewChangedError(opts?.expect ?? hash, command);const requestId = requestIdFor(hash, page);let outcome: RepairItemOutcome;- if ('remove_file' in artifact || 'import_file' in artifact) outcome = await applyDeletedSide(ctx, page, artifact, requestId, opts?.embed !== false);+ if ('remove_file' in artifact || 'import_file' in artifact || 'detach_page' in artifact) outcome = await applyDeletedSide(ctx, page, artifact, requestId, opts?.embed !== false);else if ('soft_delete' in artifact) {const retired = await retireGhost(ctx, artifact.soft_delete.ghost, artifact.soft_delete.owner, async () => requestId);outcome = retired.applied ? { applied: true, outcome: 'repaired', detail: { request_id: requestId, prefer: 'file', action: 'soft_delete' } }diff --git a/src/core/repair/registry.ts b/src/core/repair/registry.tsindex c31b04bcf0..ce944b07b7 100644--- a/src/core/repair/registry.ts+++ b/src/core/repair/registry.ts@@ -585,8 +585,8 @@ export async function repairRunner(engine: BrainEngine, opts: { apply: boolean;* `maxLlmUsd`: what this run may spend on a paid chat model (`spends: 'llm'` kinds; undefined = no run cap).*/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; cursor?: string; progress?: ProgressReporter;+ slugs?: string[]; noLlm?: boolean; maxLlmUsd?: number; deadline?: number; stop?: AbortSignal;+ prefer?: 'file' | 'database'; requests?: string[]; allDrifted?: boolean; driftClass?: string; since?: string; held?: boolean; side?: string; state?: string; provenance?: string; cursor?: string; progress?: ProgressReporter;keep?: 'prior' | 'disk' | 'withdrawn'; requestId?: string; olderThan?: string; includeFailures?: boolean; force?: boolean; from?: string; close?: boolean; afterPage?: number } = {}): Promise<RepairResult> {const ctx = { engine, config, logger, dryRun: !opts.apply, remote: false, sourceId: scope.source_ids[0], writeWaitMs } as OperationContext;const spec = repairSpec(kind, opts.registry);@@ -595,8 +595,8 @@ export async function repairRunner(engine: BrainEngine, opts: { apply: boolean;...(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, cursor: run.cursor, progress: run.progress, keep: run.keep, requestId: run.requestId, olderThan: run.olderThan, includeFailures: run.includeFailures, force: run.force, from: run.from, close: run.close, afterPage: run.afterPage });+ maxLlmUsd: run.maxLlmUsd, deadline: run.deadline, ...(run.stop ? { stop: run.stop } : {}), prefer: run.prefer, requests: run.requests, allDrifted: run.allDrifted, driftClass: run.driftClass, since: run.since,+ held: run.held, side: run.side, state: run.state, provenance: run.provenance, cursor: run.cursor, progress: run.progress, keep: run.keep, requestId: run.requestId, olderThan: run.olderThan, includeFailures: run.includeFailures, force: run.force, from: run.from, close: run.close, afterPage: run.afterPage });},};}diff --git a/test/repair-database-stop-gbra133.test.ts b/test/repair-database-stop-gbra133.test.tsnew file mode 100644index 0000000000..89947d1157--- /dev/null+++ b/test/repair-database-stop-gbra133.test.ts@@ -0,0 +1,82 @@+/**+ * GBRA-133: a repair apply that the database refuses mid-run (a deadlock, a serialization failure, a lost connection) stops+ * with a result: what it applied, the stop reason with the SQLSTATE, and the resume command; the cursor stays before the+ * refused item, so the same command resumes there. Before, the error ended the command and an `--apply --json` run left+ * no record of what it had applied. A termination signal (the CLI's SIGTERM or SIGHUP) stops the apply the same way before+ * its next item. Real PGLite (and Postgres when DATABASE_URL is set) for the cursor; a stub kind.+ */+import { afterAll, beforeAll, describe, expect, test } from 'bun:test';+import type { BrainEngine } from '../src/core/engine.ts';+import { PGLiteEngine } from '../src/core/pglite-engine.ts';+import { disposePersistenceConsumer } from '../src/core/persistence/service.ts';+import { afterCursor, resolveRepairScope, runRepair, type RepairHandler, type RepairItem, type RepairKind } from '../src/core/repair/core.ts';+import { isolatedPersistencePostgres } from './helpers/persistence-postgres.ts';+import { requirePostgresTestDatabase, testBackends } from './helpers/test-backends.ts';++const quiet = { info() {}, warn() {}, error() {} };++for (const backend of testBackends()) describe(`[${backend}] GBRA-133: a database refusal stops a repair apply with a result`, () => {+ let engine: BrainEngine;+ let close: (() => Promise<void>) | undefined;+ beforeAll(async () => {+ if (backend === 'pglite') { const pglite = new PGLiteEngine(); await pglite.connect({}); await pglite.initSchema(); engine = pglite; }+ else { const pg = await isolatedPersistencePostgres(requirePostgresTestDatabase()); engine = pg.engine; close = pg.close; }+ }, 120_000);+ afterAll(async () => { await disposePersistenceConsumer(engine); if (close) await close(); else await engine.disconnect(); });++ const items: RepairItem[] = [1, 2, 3].map(id => ({ cursor: { phase: 0, id }, source_id: 'default', slug: `notes/p${id}`, chars: 0, action: 'stub' }));+ function stub(failing: Map<number, unknown>) {+ const applied: number[] = [];+ const handler: RepairHandler = {+ kind: 'gbra133-stub' as RepairKind,+ async plan(_engine, _scope, after) { return { items: items.filter(item => afterCursor(item.cursor, after)), residuals: {}, preview_hash: 'stub-hash' }; },+ async apply(_ctx, item) {+ const error = failing.get(item.cursor.id);+ if (error) { failing.delete(item.cursor.id); throw error; }+ applied.push(item.cursor.id);+ return { applied: true, outcome: 'repaired' };+ },+ };+ return { handler, applied };+ }+ const ctx = () => ({ engine, sourceId: 'default', remote: false, config: { engine: engine.kind, embedding_disabled: true }, dryRun: false, logger: quiet }) as never;++ for (const [name, error, reason] of [+ ['a deadlock (40P01)', Object.assign(new Error('deadlock detected'), { code: '40P01' }), 'database_contention'],+ ['a serialization failure (40001)', Object.assign(new Error('could not serialize access due to concurrent update'), { code: '40001' }), 'database_contention'],+ ['a lost connection', Object.assign(new Error('Connection terminated unexpectedly'), { code: 'CONNECTION_CLOSED' }), 'connection_lost'],+ ] as const) test(`${name}: the run stops with what it applied and resumes at the refused item`, async () => {+ await engine.executeRaw("DELETE FROM op_checkpoints WHERE op='repair'");+ const { handler, applied } = stub(new Map([[2, error]]));+ const scope = await resolveRepairScope(engine);+ const first = await runRepair(ctx(), handler, scope, { apply: true, expect: 'stub-hash', explicit: true });+ expect(applied).toEqual([1]);+ expect(first.applied).toBe(1);+ expect(first.complete).toBe(false);+ expect(first.stopped).toMatchObject({ reason });+ expect(first.stopped!.message).toStartWith('Stopped at default:notes/p2: the database refused this item');+ if (error.code !== 'CONNECTION_CLOSED') expect(first.stopped!.message).toContain(`(${error.code})`);+ expect(first.stopped!.message).toContain(`Rerun \`${first.apply_command}\` to resume from this item.`);+ expect(first.stopped!.fix?.argv).toEqual(['gbrain', 'repair', 'gbra133-stub', '--json']);+ const second = await runRepair(ctx(), handler, scope, { apply: true, expect: 'stub-hash', explicit: true });+ expect(applied).toEqual([1, 2, 3]);+ expect(second).toMatchObject({ applied: 2, complete: true, resumed_from: { phase: 0, id: 1 } });+ expect(second.stopped).toBeUndefined();+ }, 60_000);++ test('a termination signal stops the apply before its next item with a result, and the same command resumes', async () => {+ await engine.executeRaw("DELETE FROM op_checkpoints WHERE op='repair'");+ const stop = new AbortController();+ const { handler, applied } = stub(new Map());+ const apply = handler.apply.bind(handler);+ handler.apply = async (ctx, item, opts) => { const outcome = await apply(ctx, item, opts); if (item.cursor.id === 1) stop.abort('SIGTERM'); return outcome; };+ const scope = await resolveRepairScope(engine);+ const first = await runRepair(ctx(), handler, scope, { apply: true, expect: 'stub-hash', explicit: true, stop: stop.signal });+ expect(applied).toEqual([1]);+ expect(first).toMatchObject({ applied: 1, complete: false, stopped: { reason: 'interrupted' } });+ expect(first.stopped!.message).toBe(`Stopped before default:notes/p2: this process received SIGTERM (2 item(s) still pending; the items before it stay applied). Rerun \`${first.apply_command}\` to resume.`);+ const second = await runRepair(ctx(), handler, scope, { apply: true, expect: 'stub-hash', explicit: true });+ expect(applied).toEqual([1, 2, 3]);+ expect(second).toMatchObject({ applied: 2, complete: true });+ }, 60_000);+});diff --git a/test/repair-file-drift-provenance-gbra133.test.ts b/test/repair-file-drift-provenance-gbra133.test.tsnew file mode 100644index 0000000000..915a9dc5be--- /dev/null+++ b/test/repair-file-drift-provenance-gbra133.test.ts@@ -0,0 +1,146 @@+/**+ * GBRA-133: a held `file_gone` file names its provenance, and `gbrain repair file-drift --held --side deleted --state file_gone`+ * selects by it (`--provenance`):+ * - each previewed page names the newest commit of HEAD's full history that deleted its file (sha, author, date,+ * subject; a side branch's own deleting commit, not the merge that kept it), `never_committed` when no commit held it,+ * or `deletion_uncommitted` when HEAD still holds it; the preview counts each provenance;+ * - `--provenance never_committed --prefer database` keeps each page database-only: the apply writes no file, the page+ * forgets its recorded path (`database_only_reason=detached`) and the hold is cleared, and the next sync, incremental and+ * full, holds nothing again and keeps the page live; `--prefer file` with it is refused (the page holds the only copy);+ * - `--provenance deleted_by_commit --prefer file` accepts the deletion (soft-deletes exactly those pages).+ * Before: every held gone file looked alike, so one --prefer recreated culled pages or deleted the only copy of others.+ * Real PGLite (and Postgres when DATABASE_URL is set), a real managed sync and real Git; the committed deletion's hold is+ * written as sync writes it (a page changed since its import), the never-committed one by sync itself.+ */+import { describe, expect, test } from 'bun:test';+import { execFileSync } from 'node:child_process';+import { existsSync, mkdirSync, mkdtempSync, rmSync, writeFileSync } from 'node:fs';+import { tmpdir } from 'node:os';+import { join } from 'node:path';+import type { BrainEngine } from '../src/core/engine.ts';+import { OperationError } from '../src/core/ops/contract.ts';+import { performManagedSync } from '../src/core/persistence/sync-run.ts';+import { RECOVERY_VERSION } from '../src/core/markdown.ts';+import { writeGitHold } from '../src/core/persistence/sync-holds.ts';+import { readDeletionProvenance } from '../src/core/persistence/sync-origin-evidence.ts';+import { repairRunner } from '../src/core/repair/registry.ts';+import { resolveRepairScope } from '../src/core/repair/core.ts';+import { managedBrain } from './helpers/managed-brain.ts';+import { requirePostgresTestDatabase, testBackends } from './helpers/test-backends.ts';++const logger = { info() {}, warn() {}, error() {} };+const git = (root: string, ...args: string[]) => execFileSync('git', ['-C', root, '-c', 'user.name=Example', '-c', '[email protected]',+ '-c', 'commit.gpgsign=false', ...args], { encoding: 'utf8', stdio: ['ignore', 'pipe', 'pipe'] }).trim();+const commit = (root: string, message: string) => { git(root, 'add', '-A'); git(root, 'commit', '-qm', message); };+const note = (title: string, body: string) => `---\ntype: concept\ntitle: ${title}\n---\n\n${body}\n`;+const OPTS = { sourceId: 'default', noPull: true, noEmbed: true, noExtract: true };+async function holds(engine: BrainEngine): Promise<Record<string, { code: string; meta: Record<string, unknown> }>> {+ const rows = await engine.executeRaw<{ fingerprint: string; record: { code: string; meta: Record<string, unknown> } }>(+ "SELECT fingerprint, completed_keys->0 AS record FROM op_checkpoints WHERE op='sync-hold' ORDER BY fingerprint");+ return Object.fromEntries(rows.map(row => [row.fingerprint.split(':').slice(2).join(':'), row.record]));+}+const pageRow = async (engine: BrainEngine, slug: string) => (await engine.executeRaw<{ deleted_at: unknown; source_path: string | null; database_only_reason: string | null }>(+ "SELECT deleted_at, source_path, database_only_reason FROM pages WHERE source_id='default' AND slug=$1", [slug]))[0];+const refusal = async (promise: Promise<unknown>) => { try { await promise; } catch (error) { return error as OperationError; } throw new Error('expected a refusal'); };++describe('GBRA-133: readDeletionProvenance', () => {+ test('a side branch\'s deleting commit, a merge that dropped a file, a worktree-only deletion, a never-committed file, and an unborn checkout', async () => {+ const dir = mkdtempSync(join(tmpdir(), 'gbrain-provenance-'));+ try {+ const root = join(dir, 'repo'); mkdirSync(join(root, 'notes'), { recursive: true });+ git(root, 'init', '-q', '-b', 'main');+ expect([...(await readDeletionProvenance(root, ['notes/x.md']))]).toEqual([['notes/x.md', { kind: 'never_committed' }]]);+ for (const name of ['a', 'b', 'c d', 'm']) writeFileSync(join(root, `notes/${name}.md`), `${name}\n`);+ commit(root, 'init');+ git(root, 'checkout', '-qb', 'side'); git(root, 'rm', '-q', 'notes/b.md'); git(root, 'commit', '-qm', 'cull b');+ git(root, 'checkout', '-q', 'main'); writeFileSync(join(root, 'x.md'), 'x\n'); commit(root, 'x'); git(root, 'merge', '-q', '--no-edit', 'side');+ git(root, 'checkout', '-qb', 'side2'); writeFileSync(join(root, 'notes/m.md'), 'm2\n'); commit(root, 'edit m');+ git(root, 'checkout', '-q', 'main'); writeFileSync(join(root, 'z.md'), 'z\n'); commit(root, 'z');+ try { git(root, 'merge', '-q', '--no-commit', 'side2'); } catch { /* stopped before committing */ }+ git(root, 'rm', '-qf', 'notes/m.md'); git(root, 'commit', '-qm', 'merge side2 dropping m');+ git(root, 'rm', '-q', 'notes/c d.md'); git(root, 'commit', '-qm', 'move c');+ rmSync(join(root, 'notes/a.md'));+ const read = await readDeletionProvenance(root, ['notes/a.md', 'notes/b.md', 'notes/c d.md', 'notes/m.md', 'notes/never.md']);+ const subject = (path: string) => { const found = read.get(path)!; return found.kind === 'deleted_by_commit' ? found.subject : found.kind; };+ expect(['notes/a.md', 'notes/b.md', 'notes/c d.md', 'notes/m.md', 'notes/never.md'].map(subject))+ .toEqual(['deletion_uncommitted', 'cull b', 'move c', 'merge side2 dropping m', 'never_committed']);+ expect(read.get('notes/b.md')).toMatchObject({ kind: 'deleted_by_commit', author: expect.any(String), date: expect.any(String), commit: git(root, 'log', '-1', '--format=%H', 'side', '--', 'notes/b.md') });+ // Read from a directory inside the work tree, paths relative to it.+ const inner = await readDeletionProvenance(join(root, 'notes'), ['b.md', 'never.md']);+ expect([inner.get('b.md')!.kind, inner.get('never.md')!.kind]).toEqual(['deleted_by_commit', 'never_committed']);+ expect((await readDeletionProvenance(dir, ['repo/notes/a.md'])).get('repo/notes/a.md')).toEqual({ kind: 'unknown' });+ } finally { rmSync(dir, { recursive: true, force: true }); }+ });+});++for (const backend of testBackends()) describe(`[${backend}] GBRA-133: held gone files by provenance`, () => {+ const databaseUrl = backend === 'postgres' ? requirePostgresTestDatabase() : undefined;+ const setup = ({ root }: { root: string }) => {+ mkdirSync(join(root, 'notes'), { recursive: true }); git(root, 'init', '-q');+ for (const name of ['a', 'b']) writeFileSync(join(root, `notes/${name}.md`), note(`notes/${name}`, `The committed body of notes/${name}.`));+ commit(root, 'notes');+ };++ test('never_committed keeps the page database-only and the next sync holds nothing; deleted_by_commit --prefer file accepts the deletion', () => managedBrain(async ({ engine, ctx, root }) => {+ expect((await performManagedSync(engine, OPTS)).status).toBe('first_sync');+ // A working-tree page no commit ever held, then removed from the disk.+ await engine.setConfig('sync.include_working_tree', 'true');+ writeFileSync(join(root, 'notes/w.md'), note('notes/w', 'An untracked note only the brain holds.'));+ expect((await performManagedSync(engine, OPTS)).status).toBe('synced');+ await engine.setConfig('sync.include_working_tree', 'false');+ rmSync(join(root, 'notes/w.md'));+ await performManagedSync(engine, OPTS);+ expect((await holds(engine))['notes/w.md']).toMatchObject({ code: 'file_drift', meta: { side: 'deleted', state: 'file_gone', reason: 'never_committed' } });+ // A committed page removed by a commit, held as the file_gone Decision (as sync holds one whose page changed since its import).+ git(root, 'rm', '-q', 'notes/b.md'); git(root, 'commit', '-qm', 'cull b');+ const b = (await engine.readPageSnapshot('notes/b', { sourceId: 'default' }))!;+ const [source] = await engine.executeRaw<{ incarnation: string }>("SELECT incarnation::text AS incarnation FROM sources WHERE id='default'");+ await engine.transaction(tx => writeGitHold(tx, { source_id: 'default', incarnation: source!.incarnation, path: 'notes/b.md', source_path: 'notes/b.md', slug: 'notes/b',+ page_id: Number(b.page.id), code: 'file_drift', message: 'notes/b.md is held: file drift (deleted file_gone)', upstream_version: null,+ observed_at: new Date().toISOString(), run_id: null, mode: 'managed', meta: { recovery_version: RECOVERY_VERSION, side: 'deleted', state: 'file_gone', page_revision: b.revision } }));++ const run = async (opts: { prefer: 'file' | 'database'; provenance?: string; expect?: string }) =>+ (await repairRunner(engine, { apply: opts.expect !== undefined, logger })).run('file-drift', await resolveRepairScope(engine, 'default'),+ { explicit: true, sourceFlag: 'default', prefer: opts.prefer, held: true, side: 'deleted', state: 'file_gone',+ ...(opts.provenance ? { provenance: opts.provenance } : {}), ...(opts.expect ? { expect: opts.expect } : {}) });+ type Page = { slug: string; action?: string; provenance?: { kind: string; subject?: string; commit?: string } };+ const pages = (result: Awaited<ReturnType<typeof run>>) => result.details!.pages as Page[];++ const all = await run({ prefer: 'database' });+ expect(all.preview_hash).toBeTruthy();+ expect(all.details!.provenance).toEqual({ deleted_by_commit: 1, never_committed: 1 });+ expect(pages(all).map(page => [page.slug, page.provenance?.kind, page.provenance?.subject])).toEqual([['notes/b', 'deleted_by_commit', 'cull b'], ['notes/w', 'never_committed', undefined]]);+ expect(pages(all).find(page => page.slug === 'notes/b')!.provenance!.commit).toBe(git(root, 'rev-parse', 'HEAD'));+ expect(all.listing!.find(entry => entry.item === 'default:notes/b')!.detail).toContain(`deleted by commit ${git(root, 'rev-parse', 'HEAD').slice(0, 12)}`);+ expect(all.listing!.find(entry => entry.item === 'default:notes/w')!.detail).toContain('never committed');++ const unsafe = await refusal(run({ prefer: 'file', provenance: 'never_committed' }));+ expect(unsafe.code).toBe('invalid_params');+ expect(unsafe.suggestion).toContain('each page holds the only copy');+ const unknownKind = await refusal(run({ prefer: 'database', provenance: 'deleted' }));+ expect(unknownKind.code).toBe('invalid_params');++ const accept = await run({ prefer: 'file', provenance: 'deleted_by_commit' });+ expect(pages(accept).map(page => [page.slug, page.action])).toEqual([['notes/b', 'soft_delete']]);+ expect(accept.residuals).toMatchObject({ other_provenance: 1 });+ const accepted = await run({ prefer: 'file', provenance: 'deleted_by_commit', expect: accept.preview_hash! });+ expect(accepted.outcomes).toEqual({ repaired: 1 });+ expect((await pageRow(engine, 'notes/b'))!.deleted_at).not.toBeNull();++ const keep = await run({ prefer: 'database', provenance: 'never_committed' });+ expect(pages(keep).map(page => [page.slug, page.action])).toEqual([['notes/w', 'detach_page']]);+ expect(keep.apply_command).toContain('--provenance never_committed --prefer database --apply --expect');+ const kept = await run({ prefer: 'database', provenance: 'never_committed', expect: keep.preview_hash! });+ expect(kept.outcomes).toEqual({ repaired: 1 });+ expect(existsSync(join(root, 'notes/w.md'))).toBe(false);+ expect(await pageRow(engine, 'notes/w')).toMatchObject({ deleted_at: null, source_path: null, database_only_reason: 'detached' });+ expect((await holds(engine))['notes/w.md']).toBeUndefined();+ // The next sync, incremental and full, holds nothing again and keeps the page.+ await performManagedSync(engine, OPTS);+ await performManagedSync(engine, { ...OPTS, full: true });+ expect((await holds(engine))['notes/w.md']).toBeUndefined();+ expect(await pageRow(engine, 'notes/w')).toMatchObject({ deleted_at: null, database_only_reason: 'detached' });+ expect((await engine.readPageSnapshot('notes/w', { sourceId: 'default' }))!.page.compiled_truth).toContain('only the brain holds');++ }, { databaseUrl, setup }), 300_000);+});