Garry's Opinionated OpenClaw/Hermes Agent Brain
TypeScript
GBRA-161 PR 1a (wip): repair generations
garrytanf54e39632923
diff --git a/src/commands/repair.ts b/src/commands/repair.tsindex 30fb3de4fe..d663dd4642 100644--- a/src/commands/repair.ts+++ b/src/commands/repair.ts@@ -24,6 +24,7 @@ import { readFix } from '../core/ops/op-fix.ts';import { shellQuote } from '../core/agent-output.ts';import { OLDER_THAN_RE } from '../cli/strict-args.ts';import { parseSince } from '../core/since.ts';+import { generationsSelectionArgv, generationsSelectionRefusal, type GenerationMode, type GenerationsSelection } from '../core/generations/repair.ts';import { REPAIR_KINDS, resolveRepairScope, type RepairKind, type RepairResult, type RepairScope } from '../core/repair/core.ts';import { consentGate, engineConsentEnv } from '../core/consent-cli.ts';import { AUTO_REPAIR_REGISTRY, EXPLICIT_REPAIR_REGISTRY, LLM_REPAIR_REGISTRY, PREVIEW_BOUND_REPAIR_REGISTRY, REPAIR_REGISTRY, explicitRepairNotices, repairMayEmbed, repairMaySpend,@@ -77,6 +78,8 @@ export const REPAIR_HELP = `Usage: gbrain repair [<kind>] [--apply] [--source <igbrain repair ghost-pages --source <id> [--apply --expect <preview-hash> --yes] [--json]gbrain repair legacy-twins --source <id> [--apply --expect <preview-hash> --yes] [--json]gbrain repair uncommitted-deletions --source <id> [--after <page-id>] [--include-ambiguous] [--apply --expect <preview-hash> --yes] [--json]+ gbrain repair generations --kind <kind> [--mode restore|release-held] (--run <id> | --since <ISO-8601|7d> | --key <owner> | --generation <id> | --held)+ [--source <id>] [--apply --expect <preview-hash> --yes] [--json]gbrain repair url-clone-fences [--source <id>] [--apply --expect <preview-hash> --yes] [--json]gbrain repair rename-identity --source <id> [--slug <new-slug> [--from <old-slug>] [--close][--apply --expect <preview-hash> --yes]] [--json]@@ -137,7 +140,10 @@ Options:--after <page-id>uncommitted-deletions: preview the next window, below the next_after page id the previous preview printed;the hash and the apply command carry it.- --yes frontmatter, conversation-labels, stuck-recovery, ghost-pages, legacy-twins, rename-identity, url-clone-fences, uncommitted-deletions --apply: the user agreed+ --kind <kind> [--mode restore|release-held] (--run <id> | --since <ISO-8601|7d> | --key <owner> | --generation <id> | --held)+ generations: the ledger kind and the operation (one of --run, --since, --key, --generation+ or --held is required; --mode defaults to restore); the hash and the apply command carry them.+ --yes frontmatter, conversation-labels, stuck-recovery, ghost-pages, legacy-twins, rename-identity, url-clone-fences, uncommitted-deletions, generations --apply: the user agreedto the previewed changes (destructive consent; without it a terminal asks, and a non-interactive run exits 3 with the consent payload).--json Machine-readable output with a stable shape (frontmatter: every per-file diff).@@ -154,19 +160,21 @@ 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']);+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', '--kind', '--mode', '--run', '--key', '--generation']);/** Flags only some kinds accept, with the kinds that do. */const KIND_FLAGS: Record<string, readonly string[]> = {'--only': ['frontmatter', 'fences', 'slug-conflicts', 'file-drift', CONTENT_LANE], '--skip': ['frontmatter', 'fences', 'slug-conflicts', 'file-drift', CONTENT_LANE], '--diff': ['frontmatter', 'fences', 'slug-conflicts', CONTENT_LANE], '--yes': ['frontmatter', 'conversation-labels', 'stuck-recovery', 'ghost-pages', 'legacy-twins', 'rename-identity', 'url-clone-fences'],- '--slug': ['fences', 'file-drift', 'rename-identity', 'overwritten-edits', 'origin-twins'], '--from': ['rename-identity'], '--close': ['rename-identity'], '--prefer': ['file-drift'], '--request': ['file-drift'], '--all-drifted': ['file-drift'], '--class': ['file-drift'], '--since': ['file-drift'],- '--held': ['file-drift'], '--side': ['file-drift'], '--state': ['file-drift'],+ '--slug': ['fences', 'file-drift', 'rename-identity', 'overwritten-edits', 'origin-twins'], '--from': ['rename-identity'], '--close': ['rename-identity'], '--prefer': ['file-drift'], '--request': ['file-drift'], '--all-drifted': ['file-drift'], '--class': ['file-drift'], '--since': ['file-drift', 'generations'],+ '--held': ['file-drift', 'generations'], '--side': ['file-drift'], '--state': ['file-drift'],'--keep': ['stuck-recovery'], '--request-id': ['stuck-recovery'],'--older-than': ['receipt-compaction'], '--include-failures': ['receipt-compaction'], '--force': ['receipt-compaction'],'--after': ['uncommitted-deletions'],+ '--kind': ['generations'], '--mode': ['generations'], '--run': ['generations'], '--key': ['generations'], '--generation': ['generations'],};const VALUE_EXAMPLES: Record<string, string> = { '--source': 'default', '--limit': '50', '--expect': 'PLAN_HASH', '--only': 'notes/a.md', '--skip': 'notes/a.md','--slug': 'notes/a', '--max-usd': '0.50', '--prefer': 'file', '--request': 'REQUEST_UUID', '--class': 'review_required', '--since': '7d', '--side': 'deleted', '--state': 'tombstone_edited', '--keep': 'prior',- '--request-id': '123e4567-e89b-42d3-a456-426614174000', '--older-than': '30d', '--from': 'notes/old', '--after': '1200' };+ '--request-id': '123e4567-e89b-42d3-a456-426614174000', '--older-than': '30d', '--from': 'notes/old', '--after': '1200',+ '--kind': 'atom', '--mode': 'restore', '--run': 'RUN_ID', '--key': 'page:notes/a', '--generation': '42' };/** 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 }) });@@ -175,7 +183,8 @@ interface RepairArgs { kind?: string; apply: boolean; all: boolean; json: booleanoLlm: boolean; source?: string; limit?: string; expect?: string; maxUsd?: number; only: string[]; skip: string[]; slugs: string[];allDrifted: boolean; prefer?: 'file' | 'database'; requests: string[]; driftClass?: string; since?: string;held: boolean; side?: string; state?: string;- keep?: 'prior' | 'disk' | 'withdrawn'; requestId?: string; olderThan?: string; includeFailures: boolean; force: boolean; from?: string; close: boolean; afterPage?: number }+ keep?: 'prior' | 'disk' | 'withdrawn'; requestId?: string; olderThan?: string; includeFailures: boolean; force: boolean; from?: string; close: boolean; afterPage?: number;+ generationKind?: string; generationMode?: string; run?: string; key?: string; generation?: number }/** `--max-usd` on a kind that never calls a paid model: the cap belongs to the doctor remediation run. */function maxUsdRefusal(flag: string, cap: string | undefined, kind: string | undefined): OperationError {@@ -276,6 +285,15 @@ export function parseRepairArgs(args: string[]): RepairArgs {['gbrain', 'repair', 'uncommitted-deletions', ...(parsed.source ? ['--source', parsed.source] : []), '--json']);parsed.afterPage = Number(value);}+ else if (flag === '--kind') parsed.generationKind = value;+ else if (flag === '--mode') parsed.generationMode = value;+ else if (flag === '--run') parsed.run = value;+ else if (flag === '--key') parsed.key = value;+ else if (flag === '--generation') {+ if (!/^[1-9]\d{0,15}$/.test(value)) throw invalid(`--generation takes the generation id a preview printed (got "${value}").`, 'Pass the generation id from the preview, e.g. --generation 42.',+ ['gbrain', 'repair', 'generations', ...(parsed.generationKind ? ['--kind', parsed.generationKind] : []), '--json']);+ parsed.generation = Number(value);+ }else if (flag === '--keep') keepText = value;else if (flag === '--request-id') {if (!/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i.test(value)) throw invalid(`--request-id must be a request UUID (got "${value}").`,@@ -366,7 +384,14 @@ export function renderRepairResult(result: RepairResult, opts: { diff: boolean }export async function runRepairCommand(engine: BrainEngine, args: string[]): Promise<void> {if (args.includes('--help') || args.includes('-h')) { console.log(REPAIR_HELP); return; }const { kind, apply, all, json, noEmbed, includeAmbiguous, source, expect, only, skip, slugs, diff, noLlm, maxUsd, limit: limitText,- prefer, requests, allDrifted, driftClass, since, held, side, state, keep, requestId, olderThan, includeFailures, force, from, close, afterPage } = parseRepairArgs(args);+ prefer, requests, allDrifted, driftClass, since, held, side, state, keep, requestId, olderThan, includeFailures, force, from, close, afterPage,+ generationKind, generationMode, run, key, generation } = parseRepairArgs(args);+ const generations: GenerationsSelection | undefined = kind === 'generations' ? { kind: generationKind ?? '', mode: (generationMode ?? 'restore') as GenerationMode,+ ...(run ? { run } : {}), ...(since ? { since } : {}), ...(key ? { key } : {}), ...(generation !== undefined ? { generation } : {}), ...(held ? { held } : {}) } : undefined;+ if (generations) {+ const refusal = generationsSelectionRefusal({ ...generations, kind: generationKind });+ if (refusal) throw refusal;+ }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).@@ -393,7 +418,8 @@ export async function runRepairCommand(engine: BrainEngine, args: string[]): Pro...(olderThan ? ['--older-than', olderThan] : []), ...(includeFailures ? ['--include-failures'] : []), ...(force ? ['--force'] : []),...(afterPage !== undefined ? ['--after', String(afterPage)] : []),...(kind === 'rename-identity' ? [...slugs.flatMap(slug => ['--slug', slug]), ...(from ? ['--from', from] : []), ...(close ? ['--close'] : [])] : []),- ...(kind === 'origin-twins' ? slugs.flatMap(slug => ['--slug', slug]) : [])];+ ...(kind === 'origin-twins' ? slugs.flatMap(slug => ['--slug', slug]) : []),+ ...(generations ? generationsSelectionArgv(generations) : [])];const custom = repairSpec(kind as RepairKind).consentText;const text = custom ? { ...custom, why: `Preview ${expect}: ${custom.why}`, user_message: `${custom.user_message} (preview ${expect.slice(0, 12)}${keep ? `, keep ${keep}` : ''})` } : {what: `Rewrite the previewed ${kind} changes on disk and import them`,@@ -411,7 +437,8 @@ export async function runRepairCommand(engine: BrainEngine, args: string[]): Pro...(k === kind && k === 'file-drift' ? { prefer, requests, allDrifted, driftClass, since, ...(held ? { held } : {}), ...(side ? { side } : {}), ...(state ? { state } : {}) } : {}),...(k === kind && keep ? { keep } : {}), ...(k === kind && requestId ? { requestId } : {}),...(k === kind && k === 'receipt-compaction' ? { olderThan, includeFailures, force } : {}),- ...(k === kind && k === 'rename-identity' ? { from, close } : {}), ...(k === kind && afterPage !== undefined ? { afterPage } : {}) }));+ ...(k === kind && k === 'rename-identity' ? { from, close } : {}), ...(k === kind && afterPage !== undefined ? { afterPage } : {}),+ ...(k === kind && generations ? { generations } : {}) }));if (apply) clearHealthMemo(engine);const paidKinds = results.filter(r => r.paid).map(r => r.kind);if (json) {diff --git a/src/core/cli-flag-registry.generated.ts b/src/core/cli-flag-registry.generated.tsindex 15310461fe..cf6355b45f 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', '--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', '--generation', '--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', '--key', '--kind', '--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', '--run', '--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'],'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'],@@ -109,7 +109,7 @@ export const CLI_FLAG_REGISTRY: Record<string, readonly string[]> = {'reindex-search-vector': ['--accept-pending', '--background', '--brain', '--dry-run', '--explain', '--follow', '--help', '--json', '--no-accept-pending', '--progress-interval', '--progress-json', '--quiet', '--resume', '--source', '--timeout', '--timings', '--wait', '--yes'],'reinit-pglite': ['--abbrev-ref', '--acknowledge-managed', '--all', '--allow-create-db', '--allow-docker', '--allow-empty', '--apply', '--body', '--brain', '--break-lock', '--cached', '--chat-model', '--check', '--concurrency', '--confirm-destructive', '--content-root', '--db-only', '--detail', '--diff-filter', '--dim', '--embedding-dimensions', '--embedding-model', '--empty', '--exclude', '--exclude-standard', '--expansion-model', '--expect', '--filters', '--fix', '--force', '--force-break-lock', '--format', '--full', '--full-history', '--git', '--grant-types', '--hard-deadline', '--help', '--http', '--include-gitignored', '--include-hidden', '--interval', '--is-ancestor', '--is-shallow-repository', '--issuer-url', '--json', '--key', '--lanes', '--local-postgres', '--max-age', '--max-cost', '--max-sources', '--max-usd', '--mcp-only', '--mcp-url', '--migrate-only', '--missing-path', '--model', '--name-only', '--no-auto-embed', '--no-bulk', '--no-delegate', '--no-embed', '--no-embedding', '--no-extract', '--no-git', '--no-gpg-sign', '--no-hard-deadline', '--no-lanes', '--no-llm', '--no-migrate', '--no-pull', '--no-renames', '--no-repair', '--no-schema-pack', '--no-sync', '--no-verify', '--non-interactive', '--oauth-client-id', '--oauth-client-secret', '--others', '--parallel', '--path', '--pglite', '--plan', '--prefer', '--prefer-postgres', '--preview', '--priority', '--provenance', '--query', '--quiet', '--redact-paths', '--repo', '--reset-checkpoint', '--retry-failed', '--retry-held', '--schema-pack', '--scopes', '--search-mode', '--serial', '--show-toplevel', '--skip-embed-check', '--skip-failed', '--slugs', '--source', '--source-id', '--src-subpath', '--stale', '--status', '--strategy', '--supabase', '--surface', '--timeout', '--to', '--trust', '--url', '--verify', '--version', '--watch', '--workers', '--working-tree', '--yes'],'remote': ['--brain', '--help', '--json', '--mcp-only', '--only', '--remediation-plan', '--request-id', '--scopes', '--source', '--timeout'],- 'repair': ['--acknowledge-managed', '--after', '--all', '--all-drifted', '--apply', '--brain', '--break-lock', '--class', '--client', '--close', '--diff', '--expect', '--ff-only', '--force', '--force-break-lock', '--from', '--full', '--held', '--help', '--id', '--include-ambiguous', '--include-failures', '--include-repairs', '--json', '--keep', '--limit', '--max-cost', '--max-cost-usd', '--max-usd', '--no-delegate', '--no-embed', '--no-llm', '--older-than', '--only', '--prefer', '--probe', '--remediate', '--remediation-plan', '--request', '--request-id', '--reset-checkpoint', '--retry-failed', '--scopes', '--side', '--since', '--skip', '--skip-failed', '--slug', '--slugs', '--source', '--stale', '--state', '--url', '--yes'],+ 'repair': ['--acknowledge-managed', '--after', '--all', '--all-drifted', '--apply', '--brain', '--break-lock', '--class', '--client', '--close', '--diff', '--expect', '--ff-only', '--force', '--force-break-lock', '--from', '--full', '--generation', '--held', '--help', '--id', '--include-ambiguous', '--include-failures', '--include-repairs', '--json', '--keep', '--key', '--kind', '--limit', '--max-cost', '--max-cost-usd', '--max-usd', '--mode', '--no-delegate', '--no-embed', '--no-llm', '--older-than', '--only', '--prefer', '--probe', '--remediate', '--remediation-plan', '--request', '--request-id', '--reset-checkpoint', '--retry-failed', '--run', '--scopes', '--side', '--since', '--skip', '--skip-failed', '--slug', '--slugs', '--source', '--stale', '--state', '--url', '--yes'],'repair-jsonb': ['--accept-pending', '--background', '--brain', '--dry-run', '--explain', '--follow', '--help', '--json', '--no-accept-pending', '--probe', '--progress-interval', '--progress-json', '--quiet', '--source', '--supabase', '--timeout', '--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/generations/repair.ts b/src/core/generations/repair.tsnew file mode 100644index 0000000000..2b0adf7dba--- /dev/null+++ b/src/core/generations/repair.ts@@ -0,0 +1,259 @@+/**+ * GBRA-161 PR 1a: `gbrain repair generations`, the preview-first undo and release path of the generation ledger. `--kind`+ * names the ledger kind and `--mode` the operation (default restore); one selector (`--run`, `--since`, `--key`,+ * `--generation`, or `--held` for release-held) bounds the set.+ *+ * - restore: republishes the item set the selected live generation replaced, as a new generation (`restore_of`): items it+ * retired come back from their ledger preimages, items it overwrote return to their earlier content, and items it added+ * are versioned and retired (`retired_by: generation-restore`). A key with an item edited since the generation, or one+ * with no stored preimage, is refused whole and the apply exits incomplete; nothing of that key changes.+ * - release-held: publishes a held result once (shrunk, valve, attempts_exhausted; oversize after the operator raised+ * `generations.max_items`). no_proof, fence_absent and segmented_unsupported are refused: releasing them would+ * manufacture the proof they lack.+ * - cleanup: the synthesis unmatched-predecessor retire (PR 4); no kind in this release has it.+ *+ * Explicit-only, preview-bound, destructive consent: the preview saves the set under its hash and `--apply --expect <hash>+ * --yes` applies exactly that set, rechecking each key under its locks (`changed_since_preview` otherwise).+ */+import type { BrainEngine } from '../engine.ts';+import { opError, OperationError, type OperationContext } from '../ops/contract.ts';+import { readFix } from '../ops/op-fix.ts';+import { maintenanceTransaction } from '../persistence/attribution.ts';+import { stableJson } from '../persistence/digest.ts';+import { clearApprovedSet, loadApprovedSet, previewChangedError, previewHash, saveApprovedSet } from '../persistence/preview-approval.ts';+import { afterCursor, type RepairHandler, type RepairItem, type RepairItemOutcome, type RepairPlan, type RepairScope } from '../repair/core.ts';+import { generationAdapter, generationKinds } from './adapters/index.ts';+import { readGenerationsConfig, restoreDaysHint } from './config.ts';+import { RELEASABLE_HELD_REASONS, type GenerationAdapter, type GenerationKey, type HeldReason, type ProposedItem } from './contract.ts';+import { activateGeneration, assertItemsLive, itemSetHash, lockGeneration, publishGeneration, readLiveGeneration, type LedgerItem } from './publish.ts';++export const GENERATION_MODES = ['restore', 'release-held', 'cleanup'] as const;+export type GenerationMode = typeof GENERATION_MODES[number];++/** What one run selects: the kind, the mode and the selectors the operator passed (`since` is a concrete ISO instant). */+export interface GenerationsSelection { kind: string; mode: GenerationMode; run?: string; since?: string; key?: string; generation?: number; held?: boolean }++/** The argv that selects this set again (preview, apply and consent replay share it). */+export function generationsSelectionArgv(selection: GenerationsSelection): string[] {+ return ['--kind', selection.kind, '--mode', selection.mode, ...(selection.run ? ['--run', selection.run] : []), ...(selection.key ? ['--key', selection.key] : []),+ ...(selection.generation !== undefined ? ['--generation', String(selection.generation)] : []), ...(selection.since ? ['--since', selection.since] : []),+ ...(selection.held ? ['--held'] : [])];+}++/** The read-only preview a notice prints for a kind (and optionally one key): the restore window, or the held set. */+export function generationsPreviewArgv(target: { kind: string; ownerKey?: string; sourceId?: string }, mode: 'restore' | 'release-held' = 'restore'): string[] {+ return ['gbrain', 'repair', 'generations', '--kind', target.kind, '--mode', mode, ...(target.sourceId ? ['--source', target.sourceId] : []),+ ...(target.ownerKey ? ['--key', target.ownerKey] : mode === 'release-held' ? ['--held'] : ['--since', `${restoreDaysHint()}d`]), '--json'];+}++const usage = (message: string, suggestion: string, selection: Partial<GenerationsSelection>) => opError('invalid_params', message, suggestion,+ { fix: readFix('Previews the generations repair; without --apply it writes nothing.', { argv: generationsPreviewArgv({ kind: selection.kind && generationAdapter(selection.kind) ? selection.kind : generationKinds()[0] ?? 'atom' },+ selection.mode === 'release-held' ? 'release-held' : 'restore') }) });++/** The usage refusal for an incomplete or contradictory selection, or null when it can run. */+export function generationsSelectionRefusal(selection: Partial<GenerationsSelection>): OperationError | null {+ const kinds = generationKinds().join(', ');+ const example = (mode: 'restore' | 'release-held' = 'restore') => generationsPreviewArgv({ kind: selection.kind && generationAdapter(selection.kind) ? selection.kind : generationKinds()[0] ?? 'atom' }, mode).slice(0, -1).join(' ');+ if (!selection.kind) return usage('gbrain repair generations needs --kind.', `Name the ledger kind (${kinds}), e.g. ${example()}.`, selection);+ if (!generationAdapter(selection.kind)) return usage(`--kind ${selection.kind} is not a generation kind this brain publishes (${kinds}).`, `Pass --kind ${generationKinds()[0] ?? 'atom'}.`, selection);+ if (!selection.mode || !GENERATION_MODES.includes(selection.mode)) {+ return usage(`--mode must be restore, release-held or cleanup (got "${selection.mode ?? ''}").`,+ 'restore republishes the generation a key replaced; release-held publishes a held result once.', selection);+ }+ if (selection.mode === 'cleanup') return usage(`--mode cleanup retires unmatched synthesis predecessors; --kind ${selection.kind} has none.`, 'Use --mode restore or --mode release-held for this kind.', selection);+ if (!selection.run && !selection.since && !selection.key && selection.generation === undefined && !selection.held) {+ return usage('gbrain repair generations needs a selector: --run, --since, --key, --generation or --held.', `Bound the set, e.g. ${example(selection.mode === 'release-held' ? 'release-held' : 'restore')}.`, selection);+ }+ if (selection.held && selection.mode !== 'release-held') return usage('--held selects held results, which only --mode release-held publishes.', `Run ${example('release-held')}.`, selection);+ return null;+}++interface RestoreEntry {+ mode: 'restore'; id: number; source_id: string; owner_key: string; generation: number; restore_to: number; restore_to_id: number;+ revive: string[]; retire: string[]; refused: string[];+}+interface ReleaseEntry {+ mode: 'release-held'; id: number; source_id: string; owner_key: string; reason: HeldReason; hold_id: string; input_pin: string | null;+ attempts: number; proposal_bytes: number | null; items: number; refused: string[];+}+type Entry = RestoreEntry | ReleaseEntry;+interface EntryItem extends RepairItem { entry: Entry; hash: string; last: boolean; selection: GenerationsSelection }++function selectorSql(selection: GenerationsSelection, params: unknown[], alias: string): string {+ const parts: string[] = [];+ const add = (sql: string, value: unknown) => { params.push(value); parts.push(sql.replace('?', `$${params.length}`)); };+ if (selection.run) add(`${alias}.run_id = ?`, selection.run);+ if (selection.since) add(`${alias}.created_at >= ?::timestamptz`, selection.since);+ if (selection.key) add(`${alias}.owner_key = ?`, selection.key);+ if (selection.generation !== undefined) add(`${alias}.id = ?`, selection.generation);+ return parts.length ? ` AND ${parts.join(' AND ')}` : '';+}++const keyOf = (kind: string, sourceId: string, ownerKey: string): GenerationKey => ({ kind, sourceId, ownerKey });++/** What restoring the live generation `liveId` of `key` to its predecessor would do, read now. */+async function planRestore(db: BrainEngine, adapter: GenerationAdapter<unknown>, key: GenerationKey, liveId: number, prevId: number) {+ const items = await db.executeRaw<{ generation_id: number; item_key: string; identity_hash: string; action: string; preimage: Record<string, unknown> | null }>(+ 'SELECT generation_id, item_key, identity_hash, action, preimage FROM derived_generation_items WHERE generation_id = ANY($1::bigint[])', [[liveId, prevId]]);+ const owned = (id: number) => new Map(items.filter(item => Number(item.generation_id) === id && item.action !== 'retired').map(item => [item.item_key, item.identity_hash]));+ const target = owned(prevId);+ const current = owned(liveId);+ const liveRecords = new Map(items.filter(item => Number(item.generation_id) === liveId).map(item => [item.item_key, item]));+ const rows = await adapter.readItems(db, key, [...new Set([...target.keys(), ...current.keys()])]);+ const revive: string[] = []; const retire: string[] = []; const refused: string[] = [];+ const preimages = new Map<string, Record<string, unknown>>();+ for (const [itemKey, identity] of target) {+ const row = rows.get(itemKey);+ if (row?.live && row.identityHash === identity) continue;+ const record = liveRecords.get(itemKey);+ const expectedNow = record?.action === 'retired' ? (row ? !row.live : false) : (row?.live === true && row.identityHash === record?.identity_hash);+ if (!record?.preimage || adapter.preimageIdentity(record.preimage) !== identity) { refused.push(`${itemKey}: no_preimage`); continue; }+ if (!expectedNow) { refused.push(`${itemKey}: edited_since`); continue; }+ revive.push(itemKey); preimages.set(itemKey, record.preimage);+ }+ for (const [itemKey, identity] of current) {+ if (target.has(itemKey)) continue;+ const row = rows.get(itemKey);+ if (!row?.live) continue;+ if (row.identityHash !== identity) refused.push(`${itemKey}: edited_since`);+ else retire.push(itemKey);+ }+ return { target, revive: revive.sort(), retire: retire.sort(), refused: refused.sort(), preimages, rows };+}++async function selectEntries(db: BrainEngine, adapter: GenerationAdapter<unknown>, sources: string[], selection: GenerationsSelection, id?: number): Promise<Entry[]> {+ const params: unknown[] = [sources, adapter.kind];+ if (selection.mode === 'restore') {+ const where = id === undefined ? selectorSql(selection, params, 'g') : (params.push(id), ` AND g.id = $${params.length}`);+ const rows = await db.executeRaw<{ id: number; source_id: string; owner_key: string; generation: number; prev_id: number; prev_generation: number }>(+ `SELECT g.id, g.source_id, g.owner_key, g.generation, p.id AS prev_id, p.generation AS prev_generation+ FROM derived_generations g JOIN derived_generations p ON p.superseded_by = g.id AND p.state = 'superseded'+ WHERE g.source_id = ANY($1::text[]) AND g.kind = $2 AND g.state = 'live'${where} ORDER BY g.id`, params);+ const entries: Entry[] = [];+ for (const row of rows) {+ const plan = await planRestore(db, adapter, keyOf(adapter.kind, row.source_id, row.owner_key), Number(row.id), Number(row.prev_id));+ if (!plan.revive.length && !plan.retire.length && !plan.refused.length) continue;+ entries.push({ mode: 'restore', id: Number(row.id), source_id: row.source_id, owner_key: row.owner_key, generation: Number(row.generation),+ restore_to: Number(row.prev_generation), restore_to_id: Number(row.prev_id), revive: plan.revive, retire: plan.retire, refused: plan.refused });+ }+ return entries;+ }+ const where = id === undefined ? selectorSql(selection, params, 'g') : (params.push(id), ` AND g.id = $${params.length}`);+ const config = await readGenerationsConfig(db);+ const rows = await db.executeRaw<{ id: number; source_id: string; owner_key: string; held_reason: HeldReason; hold_id: string; input_pin: string | null;+ attempts: number; proposal_bytes: number | null; items: number | null }>(+ `SELECT g.id, g.source_id, g.owner_key, g.held_reason, g.hold_id, g.input_pin, g.attempts, g.proposal_bytes, jsonb_array_length(g.proposal) AS items+ FROM derived_generations g WHERE g.source_id = ANY($1::text[]) AND g.kind = $2 AND g.state = 'held'${where} ORDER BY g.id`, params);+ return rows.map(row => {+ const refused = !RELEASABLE_HELD_REASONS.has(row.held_reason) ? [`${row.owner_key}: ${row.held_reason} is not releasable`]+ : row.items === null ? [`${row.owner_key}: no retained proposal`]+ : row.held_reason === 'oversize' && Number(row.items) > config.maxItems ? [`${row.owner_key}: oversize until generations.max_items is raised`] : [];+ return { mode: 'release-held' as const, id: Number(row.id), source_id: row.source_id, owner_key: row.owner_key, reason: row.held_reason, hold_id: row.hold_id,+ input_pin: row.input_pin, attempts: Number(row.attempts), proposal_bytes: row.proposal_bytes === null ? null : Number(row.proposal_bytes), items: Number(row.items ?? 0), refused };+ });+}++function describeEntry(entry: Entry): string {+ const refused = entry.refused.length ? `; refused: ${entry.refused.join(', ')}` : '';+ if (entry.mode === 'release-held') return `held ${entry.reason}, ${entry.items} item(s), ${entry.attempts} attempt(s)${refused}`;+ return `generation ${entry.generation} back to ${entry.restore_to}: revive ${entry.revive.length}, retire ${entry.retire.length}${refused}`;+}++async function hashParts(engine: BrainEngine, scope: RepairScope, selection: GenerationsSelection, entries: Entry[]) {+ const sources = await engine.executeRaw<{ id: string; incarnation: string }>('SELECT id, incarnation::text AS incarnation FROM sources WHERE id=ANY($1::text[]) ORDER BY id', [scope.source_ids]);+ return { kind: 'generations-v1', brain_id: scope.brain_id, sources, selection, entries };+}++function previewCommand(scope: RepairScope, selection: GenerationsSelection): string {+ return ['gbrain', 'repair', 'generations', ...(scope.source_ids.length === 1 ? ['--source', scope.source_ids[0]!] : []), ...generationsSelectionArgv(selection)].join(' ');+}++function requireAdapter(selection: GenerationsSelection | undefined): { adapter: GenerationAdapter<unknown>; selection: GenerationsSelection } {+ const refusal = generationsSelectionRefusal(selection ?? {});+ if (refusal) throw refusal;+ return { adapter: generationAdapter(selection!.kind)!, selection: selection! };+}++type Approved = Entry & { selection: GenerationsSelection; sources: string[] };++export const generationsRepair: RepairHandler = {+ kind: 'generations',+ embeds: true,+ outcomeItemsLimit: 1000,+ async plan(engine, scope, after, opts): Promise<RepairPlan> {+ const { adapter, selection } = requireAdapter(opts?.generations);+ const command = previewCommand(scope, selection);+ const item = (entry: Entry, hash: string, last: boolean): EntryItem => ({ cursor: { phase: entry.mode === 'restore' ? 1 : 2, id: entry.id }, source_id: entry.source_id,+ slug: entry.owner_key, chars: 0, action: entry.mode === 'restore' ? 'restore' : 'release', entry, hash, last, selection });+ if (!opts?.apply) {+ const entries = await selectEntries(engine, adapter, scope.source_ids, selection);+ const hash = previewHash(await hashParts(engine, scope, selection, entries));+ if (entries.length) await saveApprovedSet<Approved>(engine, { command: 'generations', hash }, entries.map(entry => ({ ...entry, selection, sources: scope.source_ids })));+ return { items: entries.map((entry, index) => item(entry, hash, index === entries.length - 1)), preview_hash: hash,+ residuals: { keys: entries.length, refused: entries.filter(entry => entry.refused.length).length },+ listing: entries.map(entry => ({ item: `${entry.source_id}:${entry.owner_key}`, class: entry.refused.length ? 'refused' : entry.mode, detail: describeEntry(entry) })) };+ }+ if (!opts.expect) {+ throw new OperationError('invalid_params', 'gbrain repair generations --apply applies only the set a preview printed.',+ `Preview first: ${command} — then run the apply command it prints: ${command} --apply --expect <preview-hash> --yes`, 'docs/guides/repair.md#generations');+ }+ const approved = await loadApprovedSet<Approved>(engine, { command: 'generations', hash: opts.expect, previewCommand: command,+ emptyHash: async () => previewHash(await hashParts(engine, scope, selection, [])) });+ if (approved.items.some(entry => stableJson(entry.selection) !== stableJson(selection) || stableJson(entry.sources) !== stableJson(scope.source_ids))) {+ throw previewChangedError(opts.expect, command);+ }+ const items = approved.items.map(({ selection: _s, sources: _src, ...entry }, index) => item(entry, opts.expect!, index === approved.items.length - 1));+ return { items: items.filter(entry => afterCursor(entry.cursor, after)), preview_hash: opts.expect, residuals: {} };+ },+ async apply(ctx, raw): Promise<RepairItemOutcome> {+ const { entry, hash, last, selection } = raw as EntryItem;+ const adapter = generationAdapter(selection.kind)!;+ const outcome = await applyEntry(ctx, adapter, entry, selection);+ if (last) await clearApprovedSet(ctx.engine, { command: 'generations', hash });+ return outcome;+ },+ async report(_ctx, _scope, result, opts) {+ const refused = (result.outcome_items ?? []).filter(item => item.outcome === 'refused');+ if (result.mode !== 'apply' || !refused.length || !opts.generations) return {};+ return { stopped: { reason: 'incomplete', message: `${refused.length} key(s) were refused and left unchanged: ${refused.map(item => item.reason).join('; ')}`,+ fix: readFix('Previews the generations repair again, read-only.', { argv: ['gbrain', 'repair', 'generations', ...generationsSelectionArgv(opts.generations), '--json'] }) } };+ },+};++async function applyEntry(ctx: OperationContext, adapter: GenerationAdapter<unknown>, approved: Entry, selection: GenerationsSelection): Promise<RepairItemOutcome> {+ const changed = (reason: string): RepairItemOutcome => ({ applied: false, outcome: 'changed_since_preview', reason });+ if (approved.refused.length) return { applied: false, outcome: 'refused', reason: approved.refused.join(', ') };+ const key = keyOf(adapter.kind, approved.source_id, approved.owner_key);+ if (approved.mode === 'release-held') {+ const [row] = await ctx.engine.executeRaw<{ proposal: ProposedItem[] | null; hold_id: string }>(+ `SELECT proposal, hold_id FROM derived_generations WHERE id=$1 AND state='held'`, [approved.id]);+ if (!row || row.hold_id !== approved.hold_id || !row.proposal) return changed('the held result changed or was released since the preview');+ const outcome = await publishGeneration(ctx.engine, adapter, { key, items: row.proposal, runId: `release:${approved.hold_id}`, release: { holdId: approved.hold_id, reason: approved.reason } });+ if (outcome.state === 'held') return { applied: false, outcome: 'refused', reason: `${approved.owner_key}: still held (${outcome.reason})` };+ return { applied: true, outcome: 'released', detail: { generation: outcome.generation, ...(outcome.state === 'published' ? { retired: outcome.retired.length } : {}) } };+ }+ const restored = await maintenanceTransaction(ctx.engine, async tx => {+ const live = await readLiveGeneration(tx, key);+ const plan0 = live?.id === approved.id ? await planRestore(tx, adapter, key, approved.id, approved.restore_to_id) : null;+ await lockGeneration(tx, adapter, key, plan0 ? [...plan0.target.keys(), ...plan0.retire] : []);+ if (!plan0 || (await readLiveGeneration(tx, key))?.id !== approved.id) return 'changed' as const;+ const plan = await planRestore(tx, adapter, key, approved.id, approved.restore_to_id);+ if (stableJson([plan.revive, plan.retire, plan.refused]) !== stableJson([approved.revive, approved.retire, approved.refused])) return 'changed' as const;+ if (plan.refused.length) return plan.refused;+ for (const itemKey of plan.revive) await adapter.restoreItem(tx, key, itemKey, plan.preimages.get(itemKey)!);+ await adapter.retireItems(tx, key, plan.retire, 'generation-restore');+ await assertItemsLive(tx, adapter, key, plan.target);+ const items: LedgerItem[] = [+ ...[...plan.target].map(([itemKey, identity]) => ({ key: itemKey, identityHash: identity, action: plan.revive.includes(itemKey) ? 'revived' as const : 'kept' as const,+ ...(plan.revive.includes(itemKey) && plan.rows.get(itemKey)?.live ? { preimage: plan.rows.get(itemKey)!.preimage() } : {}) })),+ ...plan.retire.map(itemKey => ({ key: itemKey, identityHash: plan.rows.get(itemKey)!.identityHash, action: 'retired' as const, preimage: plan.rows.get(itemKey)!.preimage() })),+ ];+ const setHash = itemSetHash([...plan.target].map(([itemKey, identityHash]) => ({ key: itemKey, identityHash })));+ const activated = await activateGeneration(tx, key, live, { operationId: `restore:${approved.id}:${approved.restore_to_id}`, input: await adapter.readInput(tx, key, undefined),+ setHash, completeness: { complete: true, restore: approved.restore_to }, restoreOf: approved.restore_to_id }, items);+ return activated;+ });+ if (restored === 'changed') return changed('the live generation or its items changed since the preview');+ if (Array.isArray(restored)) return { applied: false, outcome: 'refused', reason: restored.join(', ') };+ return { applied: true, outcome: 'restored', detail: { generation: restored.generation, restore_of: approved.restore_to, revived: approved.revive.length, retired: approved.retire.length } };+}diff --git a/src/core/persistence/preview-approval.ts b/src/core/persistence/preview-approval.tsindex f39f2a71c7..7858509d21 100644--- a/src/core/persistence/preview-approval.ts+++ b/src/core/persistence/preview-approval.ts@@ -40,7 +40,7 @@ export const PREVIEW_APPROVAL_OP = 'repair-approval';/** The default `purgeStaleCheckpoints` TTL; an older approved set may already be gone. */export const APPROVAL_MAX_AGE_DAYS = 7;-export type PreviewApprovalCommand = 'authorize-legacy' | 'jobs-cancel' | 'stale-atoms' | 'atoms-restore' | 'extractor-facts' | 'conversation-labels' | 'captured-facts' | 'redacted-facts' | 'loop-facts' | 'ontology-facts' | 'facts-rehome' | 'consolidate-ties' | 'failed-writes' | 'split-facts' | 'frontmatter' | 'fences' | 'slug-conflicts' | 'managed-sync-orphans' | 'frontmatter-keys' | 'file-drift' | 'stuck-recovery' | 'ghost-pages' | 'origin-twins' | 'receipt-compaction' | 'accepted-takes' | 'rename-identity' | 'overwritten-edits' | 'legacy-twins' | 'missing-tables' | 'segmented-mirror' | 'uncommitted-deletions';+export type PreviewApprovalCommand = 'authorize-legacy' | 'jobs-cancel' | 'stale-atoms' | 'atoms-restore' | 'extractor-facts' | 'conversation-labels' | 'captured-facts' | 'redacted-facts' | 'loop-facts' | 'ontology-facts' | 'facts-rehome' | 'consolidate-ties' | 'failed-writes' | 'split-facts' | 'frontmatter' | 'fences' | 'slug-conflicts' | 'managed-sync-orphans' | 'frontmatter-keys' | 'file-drift' | 'stuck-recovery' | 'ghost-pages' | 'origin-twins' | 'receipt-compaction' | 'accepted-takes' | 'rename-identity' | 'overwritten-edits' | 'legacy-twins' | 'missing-tables' | 'segmented-mirror' | 'uncommitted-deletions' | 'generations';export interface ApprovedSetKey {command: PreviewApprovalCommand;diff --git a/src/core/repair/core.ts b/src/core/repair/core.tsindex a8c3beec79..04cfcb90bc 100644--- a/src/core/repair/core.ts+++ b/src/core/repair/core.ts@@ -48,8 +48,9 @@ import { repairAdmissionWindow, repairPublicationOwner, settleRepairReceipts, tyimport { RECEIPT_RESERVATION_FLOOR } from '../persistence/receipt-bytes.ts';import { readFix } from '../ops/op-fix.ts';import { ItemRun, type ItemFailure } from '../item-failure.ts';+import type { GenerationsSelection } from '../generations/repair.ts';-export const REPAIR_KINDS = ['timeline', 'visibility', 'safe-chunks', 'contextual-mode', 'connector-checkpoints', 'request-indexes', 'connector-fences', 'take-supersession', 'accepted-takes', 'orphan-bindings', 'embedding-effects', 'attribution-backfill', 'planner-stats', 'google-file-modes', 'stale-atoms', 'atoms-restore', 'extractor-facts', 'conversation-labels', 'captured-facts', 'redacted-facts', 'loop-facts', 'ontology-facts', 'facts-rehome', 'consolidate-ties', 'orphan-children', 'failed-writes', 'split-facts', 'frontmatter', 'fences', 'slug-conflicts', 'timeline-comments', 'managed-sync-orphans', 'content-receipt-root', 'frontmatter-keys', 'file-drift', 'stuck-recovery', 'ghost-pages', 'origin-twins', 'receipt-compaction', 'aliases', 'rename-identity', 'overwritten-edits', 'legacy-twins', 'missing-tables', 'url-clone-fences', 'segmented-mirror', 'uncommitted-deletions'] as const;+export 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', 'generations'] as const;export type RepairKind = typeof REPAIR_KINDS[number];export interface RepairScope { brain_id: string; source_ids: string[] }@@ -114,7 +115,9 @@ export interface RepairPlanOptions { apply: boolean; expect?: string; includeAmb/** `rename-identity` (#6729): the old slug that disambiguates a pair (`--from`), and the close disposition (`--close`). */from?: string; close?: boolean;/** `uncommitted-deletions` (#7130): the preview window starts below this page id (`--after`). */- afterPage?: number }+ afterPage?: number;+ /** `generations` (GBRA-161): the ledger kind, mode and selectors (`--kind`, `--mode`, `--run`/`--since`/`--key`/`--generation`/`--held`). */+ generations?: GenerationsSelection }export interface RepairHandler {kind: RepairKind;@@ -310,7 +313,7 @@ export async function runRepair(ctx: OperationContext, handler: RepairHandler, sopts: { apply: boolean; limit?: number; embeddingModel?: string; sourceFlag?: string; embed?: boolean; applyArgs?: string[];explicit?: boolean; expect?: string; includeAmbiguous?: boolean; only?: string[]; skip?: string[]; slugs?: string[]; noLlm?: boolean;prefer?: 'file' | 'database'; requests?: string[]; allDrifted?: boolean; driftClass?: string; since?: string; held?: boolean; side?: string; state?: string;- keep?: 'prior' | 'disk' | 'withdrawn'; requestId?: string; olderThan?: string; includeFailures?: boolean; force?: boolean; from?: string; close?: boolean; afterPage?: number;+ keep?: 'prior' | 'disk' | 'withdrawn'; requestId?: string; olderThan?: string; includeFailures?: boolean; force?: boolean; from?: string; close?: boolean; afterPage?: number; generations?: GenerationsSelection;spec?: Pick<RepairKindSpec, 'explicit_only' | 'consent' | 'spends'>; maxLlmUsd?: number; deadline?: number; now?: () => number;/** Test seam: who publishes this run's admissions (default: this process's consumer, else a live full one on this host). */publicationOwner?: () => Promise<{ alive: boolean; owner: string }> }): Promise<RepairResult> {@@ -334,7 +337,8 @@ async function runRepairScoped(ctx: OperationContext, handler: RepairHandler, sc...(opts.held ? { held: true } : {}), ...(opts.side ? { side: opts.side } : {}), ...(opts.state ? { state: opts.state } : {}),...(opts.keep ? { keep: opts.keep } : {}), ...(opts.requestId ? { requestId: opts.requestId } : {}),...(opts.olderThan ? { olderThan: opts.olderThan } : {}), ...(opts.includeFailures ? { includeFailures: true } : {}), ...(opts.force ? { force: true } : {}),- ...(opts.from ? { from: opts.from } : {}), ...(opts.close ? { close: true } : {}), ...(opts.afterPage !== undefined ? { afterPage: opts.afterPage } : {}) };+ ...(opts.from ? { from: opts.from } : {}), ...(opts.close ? { close: true } : {}), ...(opts.afterPage !== undefined ? { afterPage: opts.afterPage } : {}),+ ...(opts.generations ? { generations: opts.generations } : {}) };const plan = await handler.plan(ctx.engine, scope, resumed, planOpts);const pending = opts.limit !== undefined ? plan.items.slice(0, opts.limit) : plan.items;const counters = await capacity(ctx);diff --git a/src/core/repair/registry.ts b/src/core/repair/registry.tsindex e73a2a3a1f..19d97a304c 100644--- a/src/core/repair/registry.ts+++ b/src/core/repair/registry.ts@@ -81,6 +81,8 @@ import { missingTablesRepair } from './missing-tables.ts';import { urlCloneFencesRepair } from './url-clone-fences.ts';import { segmentedMirrorRepair } from './segmented-mirror.ts';import { uncommittedDeletionsRepair, UNCOMMITTED_DELETIONS_CONSENT_TEXT } from './uncommitted-deletions.ts';+import { generationsRepair, generationsSelectionArgv, type GenerationsSelection } from '../generations/repair.ts';+import { restoreDaysHint } from '../generations/config.ts';import { ERROR_CATALOGUE, catalogueError } from '../error-catalogue.ts';import type { OperationError } from '../ops/contract.ts';@@ -501,6 +503,21 @@ const SPECS: Record<RepairKind, Omit<RepairKindSpec, 'kind'>> = {+ 'never deletes it again. Pages already purged cannot be restored by this command; only a backup (pg_dump, or gbrain backup create) can bring them back. '+ 'Runs only when named; never on upgrade.',},+ 'generations': {+ handler: generationsRepair, embeds: 'effect', checks: ['generation_retirements', 'generation_held'], explicit_only: true, preview_bound: true, consent: 'destructive',+ consentText: {+ what: 'Apply the previewed generations repair: restore each listed key to the generation it replaced, or publish each listed held result once',+ why: 'The preview listed each key with what it revives, retires or publishes; the apply changes exactly that set and refuses a key that changed since.',+ risk: 'A restore versions and retires the items the restored-from generation added (retired_by generation-restore, restorable for generations.restore_days) and revives the items it retired from their ledger preimages; a release publishes the held result, retiring what it no longer has the same way.',+ user_message: 'Apply the previewed generations repair? Each listed key changes exactly as the preview showed',+ },+ summary: 'Undo or release a derived generation (GBRA-161): --kind <kind> names the ledger kind, --mode restore (default) republishes the item set the '+ + 'selected live generation replaced from its ledger preimages and retires what it added, --mode release-held publishes a held result once '+ + '(shrunk, valve, attempts_exhausted; oversize after raising generations.max_items; no_proof, fence_absent and segmented_unsupported are refused). '+ + 'One selector bounds the set: --run <id>, --since <ISO-8601|7d>, --key <owner>, --generation <id>, or --held (release-held). The preview lists each key '+ + 'and saves the set under its hash; --apply --expect <hash> --yes applies exactly that set, refusing a key edited since or with no stored preimage. '+ + 'Runs only when named; never on upgrade.',+ },};export const REPAIR_REGISTRY: readonly RepairKindSpec[] = REPAIR_KINDS.map(kind => ({ kind, ...SPECS[kind] }));@@ -534,7 +551,7 @@ export function repairSpec(kind: RepairKind, registry: readonly RepairKindSpec[]/** `gbrain repair <kind> [--source <id>]`, the read-only preview of one kind. */export function repairPreviewCommand(kind: RepairKind, opts: { source?: string } = {}): string {- return `gbrain repair ${kind}${opts.source ? ` --source ${opts.source}` : ''}`;+ return `gbrain repair ${kind}${opts.source ? ` --source ${opts.source}` : ''}${kind === 'generations' ? ` --kind atom --since ${restoreDaysHint()}d` : ''}`;}/** How `--all`, the remediation plan and the banner report an explicit-only kind instead of running it. */@@ -585,16 +602,16 @@ export async function repairRunner(engine: BrainEngine, opts: { apply: boolean;async run(kind: RepairKind, scope: RepairScope, run: { limit?: number; sourceFlag?: string; explicit?: boolean; expect?: string; includeAmbiguous?: boolean; only?: string[]; skip?: string[];slugs?: string[]; noLlm?: boolean; maxLlmUsd?: number; deadline?: number;prefer?: 'file' | 'database'; requests?: string[]; allDrifted?: boolean; driftClass?: string; since?: string; held?: boolean; side?: string; state?: string;- keep?: 'prior' | 'disk' | 'withdrawn'; requestId?: string; olderThan?: string; includeFailures?: boolean; force?: boolean; from?: string; close?: boolean; afterPage?: number } = {}): Promise<RepairResult> {+ keep?: 'prior' | 'disk' | 'withdrawn'; requestId?: string; olderThan?: string; includeFailures?: boolean; force?: boolean; from?: string; close?: boolean; afterPage?: number; generations?: GenerationsSelection } = {}): Promise<RepairResult> {const ctx = { engine, config, logger, dryRun: !opts.apply, remote: false, sourceId: scope.source_ids[0], writeWaitMs } as OperationContext;const spec = repairSpec(kind, opts.registry);return runRepair(ctx, spec.handler, scope, { apply: opts.apply, limit: run.limit, embeddingModel, sourceFlag: run.sourceFlag, spec,embed: !opts.noEmbed && embeddingModel !== undefined, applyArgs: [...(opts.noEmbed && spec.embeds === 'inline' ? ['--no-embed'] : []),...(run.olderThan ? ['--older-than', run.olderThan] : []), ...(run.includeFailures ? ['--include-failures'] : []), ...(run.force ? ['--force'] : []),- ...(run.afterPage !== undefined ? ['--after', String(run.afterPage)] : [])],+ ...(run.afterPage !== undefined ? ['--after', String(run.afterPage)] : []), ...(run.generations ? generationsSelectionArgv(run.generations) : [])],explicit: run.explicit, expect: run.expect, includeAmbiguous: run.includeAmbiguous, only: run.only, skip: run.skip, slugs: run.slugs, noLlm: run.noLlm,maxLlmUsd: run.maxLlmUsd, deadline: run.deadline, prefer: run.prefer, requests: run.requests, allDrifted: run.allDrifted, driftClass: run.driftClass, since: run.since,- held: run.held, side: run.side, state: run.state, keep: run.keep, requestId: run.requestId, olderThan: run.olderThan, includeFailures: run.includeFailures, force: run.force, from: run.from, close: run.close, afterPage: run.afterPage });+ held: run.held, side: run.side, state: run.state, keep: run.keep, requestId: run.requestId, olderThan: run.olderThan, includeFailures: run.includeFailures, force: run.force, from: run.from, close: run.close, afterPage: run.afterPage, generations: run.generations });},};}