Garry's Opinionated OpenClaw/Hermes Agent Brain
TypeScript
feat(repair): register the fences kind skeleton, preview-bound --expect, --max-usd for paid-model kinds, fences.repair switches and models.fence_repair (#6188)
garrytanebc74a98dd1f
diff --git a/src/commands/models.ts b/src/commands/models.tsindex 4b3563c781..8c0c585211 100644--- a/src/commands/models.ts+++ b/src/commands/models.ts@@ -102,6 +102,7 @@ const PER_TASK_KEYS: PerTaskModelRoute[] = [{ key: 'models.drift', tier: 'reasoning', description: 'Drift LLM judge (v0.29 scaffold)' },{ key: 'models.auto_think', tier: 'deep', description: 'Auto-think question answering' },{ key: 'models.think', tier: 'deep', description: '`gbrain think` synthesis op' },+ { key: 'models.fence_repair', tier: 'deep', description: 'Model repair (Tier 3) of malformed facts/takes fence rows' },{ key: 'models.subagent', tier: 'subagent', description: '`gbrain agent run` subagent loop' },{ key: 'facts.extraction_model', tier: 'reasoning', description: 'Real-time facts extraction during sync' },{ key: 'models.eval.longmemeval', tier: 'reasoning', description: 'LongMemEval benchmark answer-gen' },diff --git a/src/commands/repair.ts b/src/commands/repair.tsindex 3efbd3738a..0d35bb2026 100644--- a/src/commands/repair.ts+++ b/src/commands/repair.ts@@ -7,8 +7,11 @@* that takes no admission), resumes after an interruption, and stops before* crossing 90% of a cumulative journal cap. Thin clients refuse (cli.ts).* Explicit-only kinds run only when named; `--all` and the no-kind preview- * list them with their preview command instead, and only they accept- * `--expect <hash>` and `--include-ambiguous` (their preview-bound apply).+ * list them with their preview command instead. Explicit-only and+ * preview-bound kinds accept `--expect <hash>` (their preview-bound apply);+ * only explicit-only kinds accept `--include-ambiguous`. `--max-usd <n>` is+ * accepted only for kinds that may call a paid chat model, and only lowers+ * their cap for this run.*/import type { BrainEngine } from '../core/engine.ts';import { setCliExitVerdict } from '../core/cli-force-exit.ts';@@ -17,7 +20,8 @@ import { OperationError, opError } from '../core/ops/contract.ts';import { readFix } from '../core/ops/op-fix.ts';import { REPAIR_KINDS, resolveRepairScope, type RepairKind, type RepairResult } from '../core/repair/core.ts';import { consentGate, engineConsentEnv } from '../core/consent-cli.ts';-import { AUTO_REPAIR_REGISTRY, EXPLICIT_REPAIR_REGISTRY, REPAIR_REGISTRY, explicitRepairNotices, repairMayEmbed, repairMaySpend, repairPreviewCommand, repairRunner, repairSpec } from '../core/repair/registry.ts';+import { AUTO_REPAIR_REGISTRY, EXPLICIT_REPAIR_REGISTRY, LLM_REPAIR_REGISTRY, PREVIEW_BOUND_REPAIR_REGISTRY, REPAIR_REGISTRY, explicitRepairNotices, repairMayEmbed, repairMaySpend,+ repairPreviewCommand, repairRunner, repairSpec } from '../core/repair/registry.ts';function wrap(text: string, indent: number, width = 80): string {const lines: string[] = [];@@ -31,12 +35,16 @@ function wrap(text: string, indent: number, width = 80): string {}const explicitKinds = EXPLICIT_REPAIR_REGISTRY.map(spec => spec.kind).join(', ');+const previewBoundKinds = PREVIEW_BOUND_REPAIR_REGISTRY.map(spec => spec.kind).join(', ');+const llmKinds = LLM_REPAIR_REGISTRY.map(spec => spec.kind).join(', ');export const REPAIR_HELP = `Usage: gbrain repair [<kind>] [--apply] [--source <id>] [--limit <n>] [--no-embed] [--json]gbrain repair --all [--apply] [--source <id>] [--json]gbrain repair <explicit-only kind> [--include-ambiguous] [--apply --expect <preview-hash>] [--source <id>] [--json]gbrain repair frontmatter [--source <id>] [--include-ambiguous] [--only <path>]... [--skip <path>]... [--diff][--apply --expect <preview-hash> --yes] [--json]+ gbrain repair fences [--source <id>] [--only <path>]... [--skip <path>]... [--slug <slug>]... [--diff]+ [--no-llm] [--max-usd <n>] [--apply [--expect <preview-hash>]] [--limit <n>] [--json]Repair residual damage that \`gbrain doctor\` reports. Dry run unless --apply.@@ -52,49 +60,70 @@ Options:--all Run every kind in order (${AUTO_REPAIR_REGISTRY.map(spec => spec.kind).join(', ')}).Explicit-only kinds (${explicitKinds}) never run here; name each one.--expect <hash>- Explicit-only kinds: apply exactly the set the preview printed under this hash.+ Explicit-only and preview-bound kinds (${previewBoundKinds}): apply exactly the set the+ preview printed under this hash.--include-ambiguousExplicit-only kinds: widen the preview to ambiguous items (its hash covers them).--only <path>, --skip <path>- frontmatter: select source-relative files (repeatable); the hash covers the selection.- --diff frontmatter: print every per-file diff, not one sample per class.+ frontmatter, fences: select source-relative files (repeatable); the hash covers the selection.+ --slug <slug> fences: select a database page by slug (repeatable); the hash covers the selection.+ --diff frontmatter, fences: print every per-file diff, not one sample per class or tier.+ --no-llm Kinds that may call a paid model (${llmKinds}): use only the free tiers; model-tier+ items stay held with llm_disabled.+ --max-usd <n> Kinds that may call a paid model (${llmKinds}): spend at most n USD on the model in this+ run. It only lowers the cap (the daily fences.repair cap still applies); never raises it.--yes frontmatter --apply: the user agreed to the previewed file 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).-Any other option is refused. There is no --max-usd here: to cap paid embedding-work, preview gbrain doctor --remediation-plan --json and, after the user agrees, run-gbrain doctor --remediate --yes --include-repairs --max-usd <n> --expect <plan_hash>.+Any other option is refused. --max-usd caps only a paid-model kind's model spend; to cap+paid embedding work, preview gbrain doctor --remediation-plan --json and, after the user agrees,+run gbrain doctor --remediate --yes --include-repairs --max-usd <n> --expect <plan_hash>.With no kind, previews every kind. Run it on the brain host.-Held files (two-pass frontmatter repair with real output): docs/guides/repair.md#held-files.`;+Held files (two-pass frontmatter repair with real output): docs/guides/repair.md#held-files.+Malformed facts/takes fences (preview, apply, undo): docs/guides/repair.md#fences.`;-const BOOLEAN_FLAGS = new Set(['--apply', '--all', '--json', '--no-embed', '--include-ambiguous', '--diff', '--yes']);-const VALUE_FLAGS = new Set(['--source', '--limit', '--expect', '--only', '--skip']);-/** Flags only `gbrain repair frontmatter` accepts. */-const FRONTMATTER_FLAGS = ['--only', '--skip', '--diff', '--yes'] as const;-const VALUE_EXAMPLES: Record<string, string> = { '--source': 'default', '--limit': '50', '--expect': 'PLAN_HASH', '--only': 'notes/a.md', '--skip': 'notes/a.md' };+const BOOLEAN_FLAGS = new Set(['--apply', '--all', '--json', '--no-embed', '--include-ambiguous', '--diff', '--yes', '--no-llm']);+const VALUE_FLAGS = new Set(['--source', '--limit', '--expect', '--only', '--skip', '--slug', '--max-usd']);+/** Flags only some kinds accept, with the kinds that do. */+const KIND_FLAGS: Record<string, readonly string[]> = {+ '--only': ['frontmatter', 'fences'], '--skip': ['frontmatter', 'fences'], '--diff': ['frontmatter', 'fences'], '--yes': ['frontmatter'],+ '--slug': ['fences'],+};+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' };/** 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 }) });interface RepairArgs { kind?: string; apply: boolean; all: boolean; json: boolean; noEmbed: boolean; includeAmbiguous: boolean; diff: boolean; yes: boolean;- source?: string; limit?: string; expect?: string; only: string[]; skip: string[] }+ noLlm: boolean; source?: string; limit?: string; expect?: string; maxUsd?: number; only: string[]; skip: string[]; slugs: string[] }++/** `--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 {+ const value = cap && !cap.startsWith('-') ? cap : '<n>';+ return new OperationError('invalid_params', `${flag} applies only to a kind that may call a paid model (${llmKinds}); `+ + `${kind ? `gbrain repair ${kind} never does` : 'name that kind'}, so the repair did not run.`,+ `To cap paid repair work, preview gbrain doctor --remediation-plan --json, then after the user agrees run: gbrain doctor --remediate --yes --include-repairs --max-usd ${value} --expect <plan_hash> (plan_hash from the preview)`);+}/** Strict parse: every flag is known, value flags carry a value, at most one kind. */export function parseRepairArgs(args: string[]): RepairArgs {- const parsed: RepairArgs = { apply: false, all: false, json: false, noEmbed: false, includeAmbiguous: false, diff: false, yes: false, only: [], skip: [] };+ const parsed: RepairArgs = { apply: false, all: false, json: false, noEmbed: false, includeAmbiguous: false, diff: false, yes: false, noLlm: false, only: [], skip: [], slugs: [] };const used = new Set<string>();const positional: string[] = [];+ let maxUsdText: string | undefined;+ let maxUsdFlag: string | undefined;for (let i = 0; i < args.length; i++) {const token = args[i]!;if (!token.startsWith('-')) { positional.push(token); continue; }const equal = token.indexOf('=');const flag = equal < 0 ? token : token.slice(0, equal);- if (FRONTMATTER_FLAGS.includes(flag as typeof FRONTMATTER_FLAGS[number])) used.add(flag);- if (flag === '--max-usd' || flag === '--max-cost') {+ if (KIND_FLAGS[flag]) used.add(flag);+ if (flag === '--max-cost') {const cap = equal < 0 ? args[i + 1] : token.slice(equal + 1);throw new OperationError('invalid_params', `${flag} is not a gbrain repair option; the repair did not run.`,- `To cap paid repair work, preview gbrain doctor --remediation-plan --json, then after the user agrees run: gbrain doctor --remediate --yes --include-repairs --max-usd ${cap && !cap.startsWith('-') ? cap : '<n>'} --expect <plan_hash> (plan_hash from the preview)`);+ `A paid-model kind takes --max-usd <n>. To cap paid repair work across kinds, preview gbrain doctor --remediation-plan --json, then after the user agrees run: gbrain doctor --remediate --yes --include-repairs --max-usd ${cap && !cap.startsWith('-') ? cap : '<n>'} --expect <plan_hash> (plan_hash from the preview)`);}if (BOOLEAN_FLAGS.has(flag)) {if (equal >= 0) throw invalid(`${flag} does not accept a value.`, `Write ${flag} on its own, without =value; leave it out to keep it off.`);@@ -104,6 +133,7 @@ export function parseRepairArgs(args: string[]): RepairArgs {else if (flag === '--include-ambiguous') parsed.includeAmbiguous = true;else if (flag === '--diff') parsed.diff = true;else if (flag === '--yes') parsed.yes = true;+ else if (flag === '--no-llm') parsed.noLlm = true;else parsed.noEmbed = true;continue;}@@ -114,6 +144,8 @@ export function parseRepairArgs(args: string[]): RepairArgs {else if (flag === '--expect') parsed.expect = value;else if (flag === '--only') parsed.only.push(value);else if (flag === '--skip') parsed.skip.push(value);+ else if (flag === '--slug') parsed.slugs.push(value);+ else if (flag === '--max-usd') { maxUsdText = value; maxUsdFlag = flag; }else parsed.limit = value;}if (positional.length > 1) throw new OperationError('invalid_params', `Unexpected argument '${positional[1]}'; gbrain repair takes at most one kind.`,@@ -122,12 +154,30 @@ export function parseRepairArgs(args: string[]): RepairArgs {if (used.has('--yes') && parsed.kind !== 'frontmatter') throw invalid('`--yes` is not accepted by gbrain repair; pass --apply to write.',`Preview first with gbrain repair${parsed.kind ? ` ${parsed.kind}` : ''}, then run the same command with --apply instead of --yes.`,['gbrain', 'repair', ...(parsed.kind ? [parsed.kind] : []), ...(parsed.source ? ['--source', parsed.source] : []), '--json']);- const frontmatterOnly = [...used].find(flag => flag !== '--yes');- if (frontmatterOnly && parsed.kind !== 'frontmatter') throw new OperationError('invalid_params', `${frontmatterOnly} applies only to gbrain repair frontmatter.`,- `Preview it by name: gbrain repair frontmatter${parsed.source ? ` --source ${parsed.source}` : ''}`);- const bound = parsed.expect !== undefined ? '--expect' : parsed.includeAmbiguous ? '--include-ambiguous' : undefined;- if (bound && !EXPLICIT_REPAIR_REGISTRY.some(spec => spec.kind === parsed.kind)) {- throw new OperationError('invalid_params', `${bound} applies only to an explicit-only kind named on the command line (${explicitKinds}).`,+ const kindOnly = [...used].find(flag => flag !== '--yes' && !KIND_FLAGS[flag]!.includes(parsed.kind ?? ''));+ if (kindOnly) {+ const kinds = KIND_FLAGS[kindOnly]!;+ throw new OperationError('invalid_params', `${kindOnly} applies only to gbrain repair ${kinds.join(' or ')}.`,+ `Preview it by name: gbrain repair ${kinds[kinds.length - 1]}${parsed.source ? ` --source ${parsed.source}` : ''}`);+ }+ const llmKind = LLM_REPAIR_REGISTRY.some(spec => spec.kind === parsed.kind);+ if (maxUsdFlag) {+ if (!llmKind) throw maxUsdRefusal(maxUsdFlag, maxUsdText, parsed.kind);+ const cap = Number(maxUsdText);+ if (!/^\d+(\.\d+)?$/.test(maxUsdText!.trim()) || !Number.isFinite(cap)) {+ throw invalid(`--max-usd must be a non-negative USD amount such as 0.50 (got "${maxUsdText}").`, 'Pass --max-usd as a decimal number of US dollars; 0 keeps the run to the free tiers.',+ ['gbrain', 'repair', parsed.kind!, ...(parsed.source ? ['--source', parsed.source] : []), '--json']);+ }+ parsed.maxUsd = cap;+ }+ if (parsed.noLlm && !llmKind) throw new OperationError('invalid_params', `--no-llm applies only to a kind that may call a paid model (${llmKinds}).`,+ `Preview it by name: gbrain repair ${LLM_REPAIR_REGISTRY[0]?.kind ?? 'fences'}${parsed.source ? ` --source ${parsed.source}` : ''}`);+ if (parsed.expect !== undefined && !PREVIEW_BOUND_REPAIR_REGISTRY.some(spec => spec.kind === parsed.kind)) {+ throw new OperationError('invalid_params', `--expect applies only to an explicit-only or preview-bound kind named on the command line (${previewBoundKinds}).`,+ `Preview one by name: ${repairPreviewCommand(PREVIEW_BOUND_REPAIR_REGISTRY[0]!.kind)}`);+ }+ if (parsed.includeAmbiguous && !EXPLICIT_REPAIR_REGISTRY.some(spec => spec.kind === parsed.kind)) {+ throw new OperationError('invalid_params', `--include-ambiguous applies only to an explicit-only kind named on the command line (${explicitKinds}).`,`Preview one by name: ${repairPreviewCommand(EXPLICIT_REPAIR_REGISTRY[0]!.kind)}`);}return parsed;@@ -163,7 +213,7 @@ function human(result: RepairResult, opts: { diff: boolean } = { diff: false }):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, diff, limit: limitText } = parseRepairArgs(args);+ const { kind, apply, all, json, noEmbed, includeAmbiguous, source, expect, only, skip, slugs, diff, noLlm, maxUsd, limit: limitText } = 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.');if (kind && !REPAIR_KINDS.includes(kind as RepairKind)) {@@ -191,7 +241,9 @@ export async function runRepairCommand(engine: BrainEngine, args: string[]): Proconst runner = await repairRunner(engine, { apply, noEmbed });const results: Array<RepairResult & { paid: boolean }> = [];for (const k of kinds) {- const result = await runner.run(k, scope, { limit, sourceFlag: source, explicit: k === kind, expect, includeAmbiguous, ...(k === 'frontmatter' ? { only, skip } : {}) });+ const result = await 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 } : {}) });results.push({ ...result, paid: repairMaySpend(repairSpec(k), noEmbed) });if (result.stopped) break;}diff --git a/src/core/cli-flag-registry.generated.ts b/src/core/cli-flag-registry.generated.tsindex 766fe38c0d..036144c853 100644--- a/src/core/cli-flag-registry.generated.ts+++ b/src/core/cli-flag-registry.generated.ts@@ -47,7 +47,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', '--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', '--locks', '--name', '--no-accept-pending', '--path', '--prefer-postgres', '--probe', '--progress-interval', '--progress-json', '--quiet', '--remediate', '--restart', '--skip-verify', '--source', '--supabase', '--timeout', '--undo-last-rewrite', '--url', '--version', '--wait', '--yes'],'decide': ['--all', '--all-from', '--apply', '--brain', '--call-site', '--dataset', '--dry-run', '--egress', '--embedding-dimensions', '--embedding-model', '--expect', '--from', '--help', '--include-withdrawals', '--input', '--json', '--limit', '--max-cost', '--max-usd', '--min', '--non-interactive', '--out', '--provenance', '--provider', '--query', '--recommended', '--shadow', '--since', '--slot', '--source', '--status', '--suite', '--target', '--threshold', '--trust', '--what-if-threshold', '--yes'],- 'doctor': ['--abandon', '--abbrev-ref', '--abort', '--accept-pending', '--admin-intent', '--adopt-columns', '--adopt-permissions', '--all', '--all-from', '--allow-old-serve', '--allow-shell-jobs', '--allow-unverified-remote', '--apply', '--apply-rewrites', '--auto', '--auto-fix', '--background', '--brain', '--branch', '--break-lock', '--budget-ms', '--by-mention', '--cached', '--call-site', '--catch-up', '--check', '--concurrency', '--confidence', '--confirm', '--content-audit', '--content-root', '--count', '--dataset', '--db-url', '--delete-brain', '--detach', '--diff-filter', '--dim', '--dir', '--drain', '--drain-timeout', '--dry-run', '--egress', '--embedding-dimensions', '--embedding-model', '--env', '--error-unmatch', '--exclude', '--exclude-standard', '--exit-code', '--expect', '--expected-epoch', '--expected-revision', '--expected-state', '--explain', '--facts', '--fast', '--federated-read', '--fetch-timeout-ms', '--ff-only', '--file', '--fix', '--follow', '--force', '--force-rechunk', '--force-retry', '--force-schema', '--format', '--fresh', '--from', '--from-pages', '--full', '--gbrain-bin', '--get', '--get-url', '--git-common-dir', '--git-dir', '--git-path', '--group', '--hard', '--harness', '--help', '--home', '--http', '--id', '--ignore-env-override', '--include-ambiguous', '--include-flagged', '--include-gitignored', '--include-hidden', '--include-pseudo', '--include-repairs', '--include-withdrawals', '--index-audit', '--init', '--input', '--install', '--is-ancestor', '--is-inside-work-tree', '--job-isolation', '--jq', '--json', '--lang', '--left-right', '--limit', '--link-source', '--link-type', '--local', '--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', '--min', '--mode', '--multimodal', '--name', '--name-only', '--nice', '--no-accept-pending', '--no-autopilot-install', '--no-capture', '--no-confirm', '--no-cron', '--no-edit', '--no-embed', '--no-embedding', '--no-extract', '--no-hooks', '--no-migrate', '--no-pull', '--no-renames', '--no-schema-pack', '--no-tags', '--no-verify', '--no-write-fetch-head', '--non-interactive', '--once', '--only', '--operations', '--others', '--out', '--output', '--overwrite', '--parallel', '--params', '--pat-file', '--path', '--path-format', '--pglite', '--phase', '--pid-file', '--plan', '--porcelain', '--port', '--prefer-postgres', '--preset', '--preview', '--probe', '--probe-pglite', '--progress-interval', '--progress-json', '--project', '--provider', '--prune-orphans', '--pure', '--push', '--push-only', '--query', '--queue', '--quiet', '--rate', '--reauth', '--rebase', '--recommended', '--reference-date', '--refresh', '--refresh-operations', '--refresh-skills', '--regenerate', '--reissue', '--relative', '--remediate', '--remediation-plan', '--remove', '--remove-core', '--repo', '--request-id', '--reranker', '--reset', '--reset-checkpoint', '--reset-default', '--restore-only', '--resume', '--retry-failed', '--reverse', '--review-lower', '--revision', '--rollback-to-source', '--scope', '--scopes', '--select', '--self-transfer', '--session', '--set', '--set-upstream-to', '--shadow', '--short', '--show-current', '--show-prefix', '--show-token', '--show-toplevel', '--since', '--skills', '--skills-dir', '--skip', '--skip-bare-tweet', '--skip-failed', '--skip-urls', '--skip-verify', '--slot', '--slugs', '--source', '--source-id', '--sources', '--src-subpath', '--staged', '--stale', '--status', '--strategy', '--strict', '--suite', '--supabase', '--surface', '--symbol-kind', '--symbolic-full-name', '--takes-holders', '--target', '--target-score', '--threshold', '--timeout', '--to', '--token', '--token-name', '--token-ttl', '--top-k', '--trust', '--type', '--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', '--yes'],+ 'doctor': ['--abandon', '--abbrev-ref', '--abort', '--accept-pending', '--admin-intent', '--adopt-columns', '--adopt-permissions', '--all', '--all-from', '--allow-old-serve', '--allow-shell-jobs', '--allow-unverified-remote', '--apply', '--apply-rewrites', '--auto', '--auto-fix', '--background', '--brain', '--branch', '--break-lock', '--budget-ms', '--by-mention', '--cached', '--call-site', '--catch-up', '--check', '--concurrency', '--confidence', '--confirm', '--content-audit', '--content-root', '--count', '--dataset', '--db-url', '--delete-brain', '--detach', '--diff-filter', '--dim', '--dir', '--drain', '--drain-timeout', '--dry-run', '--egress', '--embedding-dimensions', '--embedding-model', '--env', '--error-unmatch', '--exclude', '--exclude-standard', '--exit-code', '--expect', '--expected-epoch', '--expected-revision', '--expected-state', '--explain', '--facts', '--fast', '--federated-read', '--fetch-timeout-ms', '--ff-only', '--file', '--fix', '--follow', '--force', '--force-rechunk', '--force-retry', '--force-schema', '--format', '--fresh', '--from', '--from-pages', '--full', '--gbrain-bin', '--get', '--get-url', '--git-common-dir', '--git-dir', '--git-path', '--group', '--hard', '--harness', '--help', '--home', '--http', '--id', '--ignore-env-override', '--include-ambiguous', '--include-flagged', '--include-gitignored', '--include-hidden', '--include-pseudo', '--include-repairs', '--include-withdrawals', '--index-audit', '--init', '--input', '--install', '--is-ancestor', '--is-inside-work-tree', '--job-isolation', '--jq', '--json', '--lang', '--left-right', '--limit', '--link-source', '--link-type', '--local', '--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', '--min', '--mode', '--multimodal', '--name', '--name-only', '--nice', '--no-accept-pending', '--no-autopilot-install', '--no-capture', '--no-confirm', '--no-cron', '--no-edit', '--no-embed', '--no-embedding', '--no-extract', '--no-hooks', '--no-llm', '--no-migrate', '--no-pull', '--no-renames', '--no-schema-pack', '--no-tags', '--no-verify', '--no-write-fetch-head', '--non-interactive', '--once', '--only', '--operations', '--others', '--out', '--output', '--overwrite', '--parallel', '--params', '--pat-file', '--path', '--path-format', '--pglite', '--phase', '--pid-file', '--plan', '--porcelain', '--port', '--prefer-postgres', '--preset', '--preview', '--probe', '--probe-pglite', '--progress-interval', '--progress-json', '--project', '--provider', '--prune-orphans', '--pure', '--push', '--push-only', '--query', '--queue', '--quiet', '--rate', '--reauth', '--rebase', '--recommended', '--reference-date', '--refresh', '--refresh-operations', '--refresh-skills', '--regenerate', '--reissue', '--relative', '--remediate', '--remediation-plan', '--remove', '--remove-core', '--repo', '--request-id', '--reranker', '--reset', '--reset-checkpoint', '--reset-default', '--restore-only', '--resume', '--retry-failed', '--reverse', '--review-lower', '--revision', '--rollback-to-source', '--scope', '--scopes', '--select', '--self-transfer', '--session', '--set', '--set-upstream-to', '--shadow', '--short', '--show-current', '--show-prefix', '--show-token', '--show-toplevel', '--since', '--skills', '--skills-dir', '--skip', '--skip-bare-tweet', '--skip-failed', '--skip-urls', '--skip-verify', '--slot', '--slug', '--slugs', '--source', '--source-id', '--sources', '--src-subpath', '--staged', '--stale', '--status', '--strategy', '--strict', '--suite', '--supabase', '--surface', '--symbol-kind', '--symbolic-full-name', '--takes-holders', '--target', '--target-score', '--threshold', '--timeout', '--to', '--token', '--token-name', '--token-ttl', '--top-k', '--trust', '--type', '--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', '--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', '--pull', '--reconcile-queue', '--since', '--source', '--source-id', '--threshold', '--to', '--unsafe-bypass-dream-guard', '--window', '--yes'],'edge-proposals': ['--access', '--add', '--all-applied', '--allowed-operations', '--asof', '--bound-slug-prefixes', '--brain', '--client', '--date', '--dated-since', '--days', '--entities', '--federated-read', '--full', '--fuzzy', '--help', '--http', '--id', '--include-deleted', '--json', '--kind', '--limit', '--model', '--multimodal', '--no-autopilot-install', '--page', '--params', '--path', '--phase', '--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'],@@ -99,13 +99,13 @@ export const CLI_FLAG_REGISTRY: Record<string, readonly string[]> = {'quarantine': ['--apply', '--brain', '--force', '--force-rechunk', '--help', '--include-flagged', '--json', '--limit', '--no-embed', '--source', '--source-id', '--stale'],'recall': ['--accept-pending', '--access', '--add', '--allowed-operations', '--as-context', '--asof', '--background', '--bound-slug-prefixes', '--brain', '--budget-policy', '--budget-tokens', '--client', '--date', '--dated-since', '--days', '--entities', '--explain', '--federated-read', '--follow', '--full', '--fuzzy', '--grep', '--help', '--http', '--id', '--include-deleted', '--include-expired', '--json', '--kind', '--limit', '--mcp-only', '--model', '--multimodal', '--no-accept-pending', '--no-autopilot-install', '--page', '--params', '--path', '--pending', '--phase', '--progress-interval', '--progress-json', '--query', '--quiet', '--reason', '--recent', '--refresh-operations', '--request-id', '--rollup', '--row', '--scopes', '--session', '--session-id', '--since', '--since-last-run', '--slugs', '--source', '--source-id', '--sources', '--stale', '--supersessions', '--surface', '--timeout', '--to', '--today', '--updated-after', '--url', '--wait', '--watch', '--yes'],'reconcile-links': ['--accept-pending', '--background', '--brain', '--dry-run', '--explain', '--follow', '--help', '--json', '--no-accept-pending', '--progress-interval', '--progress-json', '--quiet', '--source', '--timeout', '--wait'],- 'reindex': ['--accept-pending', '--admin-intent', '--aliases', '--apply', '--background', '--brain', '--concurrency', '--cost-estimate', '--dim', '--dry-run', '--embedding-dimensions', '--embedding-model', '--expect', '--expected-epoch', '--expected-state', '--explain', '--follow', '--force', '--force-rechunk', '--help', '--include-ambiguous', '--json', '--limit', '--manifest', '--markdown', '--multimodal', '--no-accept-pending', '--no-embed', '--no-embedding', '--only', '--path', '--progress-interval', '--progress-json', '--quiet', '--repo', '--self-transfer', '--skip', '--source', '--stale', '--status', '--supabase', '--timeout', '--to', '--type', '--vectors', '--wait', '--workers', '--yes'],+ 'reindex': ['--accept-pending', '--admin-intent', '--aliases', '--apply', '--background', '--brain', '--concurrency', '--cost-estimate', '--dim', '--dry-run', '--embedding-dimensions', '--embedding-model', '--expect', '--expected-epoch', '--expected-state', '--explain', '--follow', '--force', '--force-rechunk', '--help', '--include-ambiguous', '--json', '--limit', '--manifest', '--markdown', '--max-usd', '--multimodal', '--no-accept-pending', '--no-embed', '--no-embedding', '--no-llm', '--only', '--path', '--progress-interval', '--progress-json', '--quiet', '--repo', '--self-transfer', '--skip', '--slug', '--source', '--stale', '--status', '--supabase', '--timeout', '--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', '--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', '--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', '--wait', '--yes'],'reinit-pglite': ['--abbrev-ref', '--all', '--allow-create-db', '--allow-docker', '--allow-empty', '--apply', '--brain', '--break-lock', '--cached', '--chat-model', '--concurrency', '--confirm-destructive', '--content-root', '--db-only', '--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-migrate', '--no-pull', '--no-renames', '--no-schema-pack', '--no-sync', '--no-verify', '--non-interactive', '--oauth-client-id', '--oauth-client-secret', '--others', '--parallel', '--path', '--pglite', '--plan', '--prefer-postgres', '--priority', '--provenance', '--query', '--quiet', '--repo', '--reset-checkpoint', '--retry-failed', '--retry-held', '--schema-pack', '--scopes', '--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', '--scopes', '--source', '--timeout'],- 'repair': ['--all', '--apply', '--brain', '--client', '--diff', '--expect', '--help', '--id', '--include-ambiguous', '--include-repairs', '--json', '--limit', '--max-cost', '--max-usd', '--no-embed', '--only', '--remediate', '--remediation-plan', '--scopes', '--skip', '--source', '--stale', '--yes'],+ 'repair': ['--all', '--apply', '--brain', '--client', '--diff', '--expect', '--help', '--id', '--include-ambiguous', '--include-repairs', '--json', '--limit', '--max-cost', '--max-usd', '--no-embed', '--no-llm', '--only', '--remediate', '--remediation-plan', '--scopes', '--skip', '--slug', '--source', '--stale', '--yes'],'repair-jsonb': ['--accept-pending', '--background', '--brain', '--dry-run', '--explain', '--follow', '--help', '--json', '--no-accept-pending', '--probe', '--progress-interval', '--progress-json', '--quiet', '--source', '--supabase', '--timeout', '--url', '--wait'],'report': ['--brain', '--content', '--dir', '--help', '--json', '--source', '--title', '--type'],'repos': ['--abandon', '--abbrev-ref', '--abort', '--accept-suggested', '--access', '--account', '--add', '--admin-intent', '--adopt-columns', '--adopt-permissions', '--after', '--all', '--all-new', '--allow-unverified-remote', '--allowed-operations', '--app-id', '--app-install', '--app-pem', '--apply', '--audit', '--auto-additive', '--backups', '--before', '--bound-brain', '--bound-max-concurrent', '--bound-slug-prefixes', '--bound-source', '--bound-tools', '--brain', '--branch', '--budget-usd-per-day', '--cached', '--calendar-id', '--classify', '--cleanup-dead-local-locks', '--clear', '--client', '--clone-dir', '--confirm-destructive', '--confirm-quiesced', '--count', '--days', '--decisions', '--delegated-namespace', '--delegated-slug-prefixes', '--detect', '--diff-filter', '--dir', '--dry-run', '--exclude', '--exit-code', '--expected-epoch', '--expected-incarnation', '--expected-state', '--federated', '--federated-read', '--fetch-timeout-ms', '--ff-only', '--file', '--fix', '--force', '--format', '--from', '--get', '--get-url', '--git-dir', '--git-path', '--github-repo', '--grant-types', '--help', '--history-days', '--http', '--id', '--if-version', '--include', '--include-warns', '--is-ancestor', '--is-inside-work-tree', '--json', '--keep-storage', '--kind', '--limit', '--local', '--manifest', '--max-cost-usd', '--message', '--migrate-legacy', '--migration', '--name', '--name-only', '--no-cron', '--no-embed', '--no-extract', '--no-federate', '--no-federated', '--no-harden', '--no-pull', '--no-schema-pack', '--no-tags', '--no-verify', '--no-write-fetch-head', '--operations', '--others', '--out', '--params', '--pat-file', '--path', '--plan', '--preview', '--probe', '--profile', '--push', '--push-only', '--quiet', '--read-sources', '--rebase', '--redirect-uri', '--refresh-operations', '--remove-backup', '--repair', '--replace', '--repos', '--request-id', '--reset-checkpoint', '--reset-default', '--resume', '--retry-failed', '--scope', '--scopes', '--secret', '--self-transfer', '--services', '--set', '--shared-skills', '--short', '--show-toplevel', '--slug-prefixes', '--source', '--source-id', '--source-ids', '--sources', '--stale', '--status', '--surface', '--takes-holders', '--token', '--token-command', '--token-endpoint-auth-method', '--token-env', '--token-ttl', '--unset-all', '--url', '--usage', '--wait-drain', '--yes'],diff --git a/src/core/config.ts b/src/core/config.tsindex 2af92f6751..a66592fbbd 100644--- a/src/core/config.ts+++ b/src/core/config.ts@@ -1412,6 +1412,7 @@ export const KNOWN_CONFIG_KEYS: readonly string[] = ['models.drift','models.auto_think','models.think',+ 'models.fence_repair', // #6188: Tier 3 fence repair model (fence-repair/llm.ts), tier deep'models.subagent','models.expansion','models.contextual_synopsis',@@ -1671,6 +1672,8 @@ export const KNOWN_CONFIG_KEYS: readonly string[] = ['sync.hold_escalate_pct','sync.parser_regression','fences.normalize', // #6188: inline Tier 1 fence normalization (fence-repair/config.ts); default on+ 'fences.repair.enabled', // #6188: the maintenance cycle's fence_repair phase (fence-repair/config.ts); default on+ 'fences.repair.llm', // #6188: Tier 3 model repair of residual fence rows; default on'fences.repair.max_usd_per_page', // #6188: Tier 3 fence repair caps (fence-repair/config.ts); 0 = no model spend'fences.repair.max_usd_per_day',// #2179: clamp window for DCR-requested per-client token TTLs. Read bydiff --git a/src/core/fence-repair/config.ts b/src/core/fence-repair/config.tsindex 3f13f235af..1ebefc415a 100644--- a/src/core/fence-repair/config.ts+++ b/src/core/fence-repair/config.ts@@ -5,6 +5,13 @@* importers). It is read only when a write actually has something to* normalize, so a clean write never pays the config read.*+ * `fences.repair.enabled` (default true, opt-out) lets the maintenance cycle's+ * `fence_repair` phase repair held and stored malformed fences; false pauses+ * it (an explicit `gbrain repair fences --apply` still runs).+ * `fences.repair.llm` (default true, opt-out) lets that repair send residual+ * fence rows to the configured chat model (Tier 3); false keeps it to the+ * free tiers everywhere and holds Tier 3 candidates with `llm_disabled`.+ ** `fences.repair.max_usd_per_page` (default $0.05) and* `fences.repair.max_usd_per_day` (default $1.00) cap model (Tier 3) fence* repair: per page, and per UTC day across every process through the daily@@ -15,6 +22,8 @@import type { BrainEngine } from '../engine.ts';export const FENCES_NORMALIZE_KEY = 'fences.normalize';+export const FENCE_REPAIR_ENABLED_KEY = 'fences.repair.enabled';+export const FENCE_REPAIR_LLM_KEY = 'fences.repair.llm';export const FENCE_REPAIR_MAX_USD_PER_PAGE_KEY = 'fences.repair.max_usd_per_page';export const FENCE_REPAIR_MAX_USD_PER_DAY_KEY = 'fences.repair.max_usd_per_day';/** Defaults of the Tier 3 caps (USD). */@@ -22,7 +31,7 @@ export const FENCE_REPAIR_DEFAULT_MAX_USD_PER_PAGE = 0.05;export const FENCE_REPAIR_DEFAULT_MAX_USD_PER_DAY = 1;const USD_KEYS: readonly string[] = [FENCE_REPAIR_MAX_USD_PER_PAGE_KEY, FENCE_REPAIR_MAX_USD_PER_DAY_KEY];/** Every `fences.*` key `gbrain config set` accepts. */-export const FENCE_CONFIG_KEYS: readonly string[] = [FENCES_NORMALIZE_KEY, ...USD_KEYS];+export const FENCE_CONFIG_KEYS: readonly string[] = [FENCES_NORMALIZE_KEY, FENCE_REPAIR_ENABLED_KEY, FENCE_REPAIR_LLM_KEY, ...USD_KEYS];const TRUE = /^(true|1|on|yes)$/i;const FALSE = /^(false|0|off|no)$/i;@@ -67,12 +76,27 @@ export async function readFenceRepairCaps(engine: Pick<BrainEngine, 'getConfig'>perPageSource: page === null ? 'default' : 'user', perDaySource: day === null ? 'default' : 'user' };}-/** The effective switch: on unless explicitly set false. A config read error keeps the default (on). */-export async function fencesNormalizeEnabled(engine: Pick<BrainEngine, 'getConfig'>): Promise<boolean> {+/** A boolean switch that is on unless explicitly set false; a config read error keeps it on. */+async function switchOn(engine: Pick<BrainEngine, 'getConfig'>, key: string): Promise<boolean> {try {- const value = await engine.getConfig(FENCES_NORMALIZE_KEY);+ const value = await engine.getConfig(key);return !(typeof value === 'string' && FALSE.test(value.trim()));} catch {return true;}}++/** The effective switch: on unless explicitly set false. A config read error keeps the default (on). */+export function fencesNormalizeEnabled(engine: Pick<BrainEngine, 'getConfig'>): Promise<boolean> {+ return switchOn(engine, FENCES_NORMALIZE_KEY);+}++/** `fences.repair.enabled`: the maintenance cycle repairs fences (default on). */+export function fenceRepairEnabled(engine: Pick<BrainEngine, 'getConfig'>): Promise<boolean> {+ return switchOn(engine, FENCE_REPAIR_ENABLED_KEY);+}++/** `fences.repair.llm`: fence repair may call the chat model (Tier 3; default on). */+export function fenceRepairLlmEnabled(engine: Pick<BrainEngine, 'getConfig'>): Promise<boolean> {+ return switchOn(engine, FENCE_REPAIR_LLM_KEY);+}diff --git a/src/core/fence-repair/receipt.ts b/src/core/fence-repair/receipt.tsnew file mode 100644index 0000000000..bfbea41fe9--- /dev/null+++ b/src/core/fence-repair/receipt.ts@@ -0,0 +1,52 @@+/**+ * #6188: what a fence repair (Tier 2 resolver or Tier 3 model) records about+ * one write, and the Git commit subject of a repaired file.+ *+ * The receipt rides the write's durable outcome (`fence_repair`): the actor+ * `fence-repair`, the tier, the fix classes with their rows and columns, the+ * model (Tier 3 only), the sha256 of the bytes before and after, and the+ * model spend. Location and hashes only: never a claim, holder or any other+ * cell value, so it is safe in receipts, results and commit messages.+ */+import type { FenceTier } from './types.ts';++export const FENCE_REPAIR_ACTOR = 'fence-repair';++export interface FenceRepairReceipt {+ actor: typeof FENCE_REPAIR_ACTOR;+ tier: Exclude<FenceTier, 'manual'>;+ /** Fix classes and Tier 3 residual reasons the write cleared, sorted. */+ classes: string[];+ rows: number[];+ columns: string[];+ /** The model that rewrote rows (Tier 3); null for the free tiers. */+ model: string | null;+ before_sha256: string;+ after_sha256: string;+ /** Model spend for this page (USD); 0 for the free tiers, null for an unpriced model. */+ cost_usd: number | null;+}++const CLASS = /^[a-z_]{1,40}$/;+const SHA = /^[0-9a-f]{64}$/;++/** A receipt as stored: well-formed or null, so a forged or damaged value never reaches a receipt or a commit message. */+export function parseFenceRepairReceipt(value: unknown): FenceRepairReceipt | null {+ if (!value || typeof value !== 'object') return null;+ const r = value as Record<string, unknown>;+ const tiers = ['deterministic', 'resolver', 'llm'];+ if (r.actor !== FENCE_REPAIR_ACTOR || !tiers.includes(String(r.tier))) return null;+ if (!Array.isArray(r.classes) || !r.classes.length || r.classes.length > 40 || !r.classes.every(c => typeof c === 'string' && CLASS.test(c))) return null;+ if (!Array.isArray(r.rows) || r.rows.length > 200 || !r.rows.every(n => Number.isSafeInteger(n) && (n as number) >= 0)) return null;+ if (!Array.isArray(r.columns) || r.columns.length > 40 || !r.columns.every(c => typeof c === 'string' && /^[#a-z_]{1,20}$/.test(c))) return null;+ if (r.model !== null && (typeof r.model !== 'string' || r.model.length > 200 || /[\r\n]/.test(r.model))) return null;+ if (typeof r.before_sha256 !== 'string' || !SHA.test(r.before_sha256) || typeof r.after_sha256 !== 'string' || !SHA.test(r.after_sha256)) return null;+ if (r.cost_usd !== null && (typeof r.cost_usd !== 'number' || !Number.isFinite(r.cost_usd) || r.cost_usd < 0)) return null;+ return { actor: FENCE_REPAIR_ACTOR, tier: r.tier as FenceRepairReceipt['tier'], classes: [...r.classes as string[]], rows: [...r.rows as number[]],+ columns: [...r.columns as string[]], model: r.model as string | null, before_sha256: r.before_sha256, after_sha256: r.after_sha256, cost_usd: r.cost_usd as number | null };+}++/** `gbrain: repair fence in <path> (<classes>)`, the subject of a repaired file's commit. */+export function fenceRepairCommitSubject(path: string, classes: readonly string[]): string {+ return `gbrain: repair fence in ${path.replace(/[\u0000-\u001f\u007f]/g, '?')} (${classes.join(', ')})`;+}diff --git a/src/core/repair/core.ts b/src/core/repair/core.tsindex 438f52c2b6..c9739e8c75 100644--- a/src/core/repair/core.ts+++ b/src/core/repair/core.ts@@ -22,10 +22,10 @@ import { isTerminal, principalKey } from '../persistence/model.ts';import { getWriteRequest } from '../persistence/journal.ts';import { initializeLocalPersistence, requestPrincipalForContext } from '../persistence/page-mutations.ts';import { lookupEmbeddingPrice, estimateCostFromChars } from '../embedding-pricing.ts';-import { shellQuote } from '../agent-output.ts';+import { shellQuote, type Action } from '../agent-output.ts';import type { RepairKindSpec } from './registry.ts';-export const REPAIR_KINDS = ['timeline', 'visibility', 'safe-chunks', 'contextual-mode', 'connector-checkpoints', 'request-indexes', 'connector-fences', 'take-supersession', 'orphan-bindings', 'embedding-effects', 'attribution-backfill', 'planner-stats', 'google-file-modes', 'stale-atoms', 'extractor-facts', 'captured-facts', 'loop-facts', 'orphan-children', 'failed-writes', 'frontmatter'] as const;+export const REPAIR_KINDS = ['timeline', 'visibility', 'safe-chunks', 'contextual-mode', 'connector-checkpoints', 'request-indexes', 'connector-fences', 'take-supersession', 'orphan-bindings', 'embedding-effects', 'attribution-backfill', 'planner-stats', 'google-file-modes', 'stale-atoms', 'extractor-facts', 'captured-facts', 'loop-facts', 'orphan-children', 'failed-writes', 'frontmatter', 'fences'] as const;export type RepairKind = typeof REPAIR_KINDS[number];export interface RepairScope { brain_id: string; source_ids: string[] }@@ -37,6 +37,12 @@ export interface RepairItem {cursor: RepairCursor; source_id: string; slug: string; chars: number; action: string;/** Kind-specific planned change, rechecked against the page before it is applied. */change?: { from: string | null; to: string };+ /**+ * `spends: 'llm'` kinds: this item's estimated paid-model spend (USD). A dry run sums it over the items it would+ * apply (so `--limit` lowers the estimate), and an apply stops before an item whose estimate exceeds what is left of+ * the run's allowance instead of starting a call the allowance cannot cover.+ */+ llm_usd?: number;}export interface RepairPlan {@@ -56,12 +62,19 @@ export interface RepairPlan {* user-set cap) and what is left under the kind's own daily cap (null when it has none).*/llm?: { usd: number | null; cap_remaining_usd: number | null };+ /** Discovery kinds: when the scan the plan read last finished (`fresh_at`) and whether it is still partial. */+ scan?: { fresh_at: string | null; partial: boolean };}export interface RepairListing { item: string; class: string; detail?: string }-/** What the run was asked to do; preview-bound (explicit-only) kinds read `expect`, `includeAmbiguous` and the `only`/`skip` path selection. */-export interface RepairPlanOptions { apply: boolean; expect?: string; includeAmbiguous?: boolean; only?: string[]; skip?: string[] }+/**+ * What the run was asked to do; preview-bound kinds read `expect`, `includeAmbiguous` and the `only`/`skip` path+ * selection (`slugs` names database pages). `noLlm` keeps a `spends: 'llm'` kind to its free tiers; `maxLlmUsd` is+ * the run's paid-model allowance (it only lowers the kind's own cap). `deadline` (epoch ms) bounds a discovery scan.+ */+export interface RepairPlanOptions { apply: boolean; expect?: string; includeAmbiguous?: boolean; only?: string[]; skip?: string[]; slugs?: string[];+ noLlm?: boolean; maxLlmUsd?: number; deadline?: number }export interface RepairHandler {kind: RepairKind;@@ -76,17 +89,28 @@ export interface RepairHandler {* under --no-embed. `runId` identifies this repair run and survives a resume.* A kind with named per-item outcomes returns them instead of a boolean.* `llmAllowanceUsd` (`spends: 'llm'` kinds): what is left of the run's paid-model allowance (undefined = no run- * cap), so the kind caps its own reservation at it.+ * cap), so the kind caps its own reservation at it. `deadline` (epoch ms) is when the run stops starting work; a+ * kind bounds its own provider calls by it. `noLlm` and `expect` repeat the run's options.*/- apply(ctx: OperationContext, item: RepairItem, opts?: { embed: boolean; runId?: string; llmAllowanceUsd?: number }): Promise<boolean | RepairItemOutcome>;+ apply(ctx: OperationContext, item: RepairItem, opts?: { embed: boolean; runId?: string; llmAllowanceUsd?: number; deadline?: number; noLlm?: boolean; expect?: string }): Promise<boolean | RepairItemOutcome>;/** How many per-item outcomes the result lists (default 20). */outcomeItemsLimit?: number;/** Human lines for the plan's `details`; `diff` asks for every per-item diff, not one sample per class. */render?(details: Record<string, unknown>, opts: { diff: boolean }): string[];+ /**+ * Kind-specific result fields, computed once the dry run or apply finished (for example a verification re-check+ * of the selected scope). Runs only when the run ended without an exception.+ */+ report?(ctx: OperationContext, scope: RepairScope, result: RepairResult, opts: RepairPlanOptions): Promise<Partial<Pick<RepairResult, 'repaired' | 'remaining' | 'verification'>>>;}-/** A named per-item outcome; `applied` counts it as applied, otherwise skipped. `llm_usd`: what the item actually spent on a paid chat model. */-export interface RepairItemOutcome { applied: boolean; outcome: string; reason?: string; detail?: Record<string, unknown>; llm_usd?: number }+/**+ * A named per-item outcome; `applied` counts it as applied, otherwise skipped. `llm_usd`: what the item actually spent+ * on a paid chat model. `stop`: the run stops after this item (for example the daily ledger refused the next call),+ * with the reason, message and fix the result reports.+ */+export interface RepairItemOutcome { applied: boolean; outcome: string; reason?: string; detail?: Record<string, unknown>; llm_usd?: number;+ stop?: { reason: string; message: string; fix?: Action } }export interface RepairResult {kind: RepairKind;@@ -106,8 +130,16 @@ export interface RepairResult {applied: number;skipped: number;complete: boolean;- stopped?: { reason: string; message: string };+ stopped?: { reason: string; message: string; fix?: Action };apply_command: string;+ /** Kinds with a report hook: items repaired by this run (dry run: 0). `complete` keeps its meaning (every pending item was attempted). */+ repaired?: number;+ /** Kinds with a report hook: what still needs repair after this run, counted by reason. */+ remaining?: Record<string, number>;+ /** Kinds with a report hook: the post-run re-check of the selected scope. */+ verification?: Record<string, unknown>;+ /** Discovery kinds: the scan the plan read (see RepairPlan.scan). */+ scan?: { fresh_at: string | null; partial: boolean };/** Preview-bound kinds' dry run: every item the preview hash covers. */listing?: RepairListing[];/** Per-outcome counts and the first items, for kinds that name outcomes. */@@ -209,14 +241,18 @@ function writerHeld(error: unknown): error is OperationError {*/export async function runRepair(ctx: OperationContext, handler: RepairHandler, scope: RepairScope,opts: { apply: boolean; limit?: number; embeddingModel?: string; sourceFlag?: string; embed?: boolean; applyArgs?: string[];- explicit?: boolean; expect?: string; includeAmbiguous?: boolean; only?: string[]; skip?: string[];- spec?: Pick<RepairKindSpec, 'explicit_only' | 'consent' | 'spends'>; maxLlmUsd?: number }): Promise<RepairResult> {+ explicit?: boolean; expect?: string; includeAmbiguous?: boolean; only?: string[]; skip?: string[]; slugs?: string[]; noLlm?: boolean;+ spec?: Pick<RepairKindSpec, 'explicit_only' | 'consent' | 'spends'>; maxLlmUsd?: number; deadline?: number; now?: () => number }): Promise<RepairResult> {const { repairSpec, explicitKindRequired } = await import('./registry.ts');const spec = opts.spec ?? repairSpec(handler.kind);if (spec?.explicit_only && opts.explicit !== true) throw explicitKindRequired(handler.kind);if (opts.apply) await initializeLocalPersistence(ctx);const { cursor: resumed, runId: storedRunId } = await readCursor(ctx.engine, handler.kind, scope, opts.apply ? opts.expect : undefined);- const plan = await handler.plan(ctx.engine, scope, resumed, { apply: opts.apply, expect: opts.expect, includeAmbiguous: opts.includeAmbiguous, only: opts.only, skip: opts.skip });+ const now = opts.now ?? Date.now;+ const planOpts: RepairPlanOptions = { apply: opts.apply, expect: opts.expect, includeAmbiguous: opts.includeAmbiguous, only: opts.only, skip: opts.skip,+ ...(opts.slugs?.length ? { slugs: opts.slugs } : {}), ...(opts.noLlm ? { noLlm: true } : {}), ...(opts.maxLlmUsd !== undefined ? { maxLlmUsd: opts.maxLlmUsd } : {}),+ ...(opts.deadline !== undefined ? { deadline: opts.deadline } : {}) };+ 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);const admits = (handler.publication ?? 'coordinated') === 'coordinated' ? pending.length : 0;@@ -230,19 +266,27 @@ export async function runRepair(ctx: OperationContext, handler: RepairHandler, ssample: plan.items.slice(0, SAMPLE).map(item => `${item.source_id}:${item.slug}`), residuals: plan.residuals,cost: { lifetime_ids: admits, receipt_bytes: admits * RECEIPT_BYTES, embedding_pages: handler.embeds === false ? 0 : pending.length,embedding_usd: embeddingUsd(pending.reduce((sum, item) => sum + item.chars, 0), opts.embeddingModel),- ...(llm ? { llm_usd: opts.apply || !plan.llm ? 0 : plan.llm.usd, llm_cap_remaining_usd: llmLeft(0) } : {}) },+ ...(llm ? { llm_usd: opts.apply || !plan.llm ? 0 : plan.llm.usd === null ? null+ : pending.some(item => item.llm_usd !== undefined) ? pending.reduce((sum, item) => sum + (item.llm_usd ?? 0), 0) : plan.llm.usd,+ llm_cap_remaining_usd: llmLeft(0) } : {}) },capacity: counters.map(({ scope: key, resource, used, limit, stop_at }) => ({ scope: key, resource, used, limit, stop_at })),resumed_from: resumed, applied: 0, skipped: 0, complete: false, ...(plan.warnings?.length ? { warnings: plan.warnings } : {}),apply_command: `gbrain repair ${handler.kind}${opts.sourceFlag ? ` --source ${opts.sourceFlag}` : ''}${(opts.applyArgs ?? []).map(arg => ` ${arg}`).join('')}`- + `${[...(opts.only ?? []).flatMap(path => ['--only', path]), ...(opts.skip ?? []).flatMap(path => ['--skip', path])].map(arg => ` ${shellQuote([arg])}`).join('')}`- + `${opts.includeAmbiguous ? ' --include-ambiguous' : ''} --apply${plan.preview_hash ? ` --expect ${plan.preview_hash}` : ''}`- + `${spec?.consent === 'destructive' ? ' --yes' : ''}`,+ + `${[...(opts.only ?? []).flatMap(path => ['--only', path]), ...(opts.skip ?? []).flatMap(path => ['--skip', path]),+ ...(opts.slugs ?? []).flatMap(slug => ['--slug', slug])].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' : ''}`,+ ...(plan.scan ? { scan: plan.scan } : {}),+ };+ const finish = async (): Promise<RepairResult> => {+ if (handler.report) Object.assign(result, await handler.report(ctx, scope, result, planOpts));+ return result;};if (!opts.apply) {if (plan.listing) result.listing = plan.listing;if (plan.details) result.details = plan.details;result.complete = pending.length === plan.items.length;- return result;+ return finish();}// A resumed run keeps its id, so work it authorized is replayed, not authorized twice.const runId = storedRunId ?? randomUUID();@@ -250,10 +294,17 @@ export async function runRepair(ctx: OperationContext, handler: RepairHandler, slet llmSpent = 0;for (const [index, item] of pending.entries()) {const remaining = pending.length - index;- if (llm && opts.maxLlmUsd !== undefined && llmSpent >= opts.maxLlmUsd) {- result.stopped = { reason: 'budget_exhausted', message: `Stopped before ${item.source_id}:${item.slug}: this run's paid-model allowance is used up `- + `($${llmSpent.toFixed(4)} spent of $${opts.maxLlmUsd.toFixed(4)}; ${remaining} item(s) still pending). Rerun \`${result.apply_command}\` to resume.` };- return result;+ if (opts.deadline !== undefined && now() >= opts.deadline) {+ result.stopped = { 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.` };+ return finish();+ }+ const allowanceLeft = opts.maxLlmUsd !== undefined ? opts.maxLlmUsd - llmSpent : undefined;+ if (llm && allowanceLeft !== undefined && (llmSpent >= opts.maxLlmUsd! || (item.llm_usd !== undefined && item.llm_usd > allowanceLeft + 1e-9))) {+ result.stopped = { reason: 'budget_exhausted', message: `Stopped before ${item.source_id}:${item.slug}: this run's paid-model allowance `+ + `${llmSpent >= opts.maxLlmUsd! ? 'is used up' : `cannot cover its estimate ($${item.llm_usd!.toFixed(4)})`} `+ + `($${llmSpent.toFixed(4)} spent of $${opts.maxLlmUsd!.toFixed(4)}; ${remaining} item(s) still pending). Rerun \`${result.apply_command}\` to resume.` };+ return finish();}const full = admits ? (await capacity(ctx)).find(c => c.used + (c.resource === 'lifetime_ids' ? 1 : RECEIPT_BYTES) > c.stop_at) : undefined;if (full) {@@ -261,11 +312,12 @@ export async function runRepair(ctx: OperationContext, handler: RepairHandler, sconst needed = Math.ceil((full.used + remaining * perItem) / STOP_RATIO) + 1;result.stopped = { reason: 'capacity', message: `Stopped before crossing 90% of ${full.scope} ${full.resource} (${full.used} of ${full.limit} used; `+ `${remaining} item(s) still need ${remaining * perItem} more). Run: gbrain config set ${full.config_key} ${needed} — then rerun \`${result.apply_command}\` to resume.` };- return result;+ return finish();}try {const applied = await handler.apply({ ...ctx, sourceId: item.source_id }, item, { embed: opts.embed === true, runId,- ...(llm && opts.maxLlmUsd !== undefined ? { llmAllowanceUsd: opts.maxLlmUsd - llmSpent } : {}) });+ ...(llm && opts.maxLlmUsd !== undefined ? { llmAllowanceUsd: opts.maxLlmUsd - llmSpent } : {}),+ ...(opts.deadline !== undefined ? { deadline: opts.deadline } : {}), ...(opts.noLlm ? { noLlm: true } : {}), ...(opts.expect ? { expect: opts.expect } : {}) });if (llm && typeof applied === 'object' && applied.llm_usd) {llmSpent += applied.llm_usd;result.cost = { ...result.cost, llm_usd: llmSpent, llm_cap_remaining_usd: llmLeft(llmSpent) };@@ -279,24 +331,29 @@ export async function runRepair(ctx: OperationContext, handler: RepairHandler, s}if (typeof applied === 'object' ? applied.applied : applied) result.applied++;else result.skipped++;+ if (typeof applied === 'object' && applied.stop) {+ await writeCursor(ctx.engine, handler.kind, scope, item.cursor, runId, opts.expect);+ result.stopped = applied.stop;+ return finish();+ }} catch (error) {// A page edited since planning is left for the next full scan.if (error instanceof OperationError && error.code === 'revision_conflict') { result.skipped++; continue; }if (error instanceof OperationError && error.code === 'write_pending') {result.stopped = { reason: 'write_pending', message: `The repair of ${item.source_id}:${item.slug} was accepted and is still pending publication. `+ `Rerun \`${result.apply_command}\` to resume; the same request is replayed.` };- return result;+ return finish();}if (!writerHeld(error)) throw error;result.stopped = { 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.` };- return result;+ return finish();}await writeCursor(ctx.engine, handler.kind, scope, item.cursor, runId, opts.expect);}result.complete = pending.length === plan.items.length;if (result.complete) await writeCursor(ctx.engine, handler.kind, scope, null, null, opts.expect);- return result;+ return finish();}/** Cursor order shared by the kinds' SQL: (phase, id) strictly after `after`. */diff --git a/src/core/repair/fences.ts b/src/core/repair/fences.tsnew file mode 100644index 0000000000..fa99f76d30--- /dev/null+++ b/src/core/repair/fences.ts@@ -0,0 +1,17 @@+/**+ * `gbrain repair fences` (#6188): repairs malformed facts and takes fences.+ * Skeleton: the kind is registered so the CLI, the cycle phase and the+ * surfaces can wire to it; the plan and apply land next.+ */+import type { RepairHandler, RepairPlan } from './core.ts';++export const fencesRepair: RepairHandler = {+ kind: 'fences',+ outcomeItemsLimit: 200,+ async plan(): Promise<RepairPlan> {+ return { items: [], residuals: {}, llm: { usd: 0, cap_remaining_usd: null }, scan: { fresh_at: null, partial: true } };+ },+ async apply() {+ return false;+ },+};diff --git a/src/core/repair/registry.ts b/src/core/repair/registry.tsindex 80e7ea1dea..862c3f51d5 100644--- a/src/core/repair/registry.ts+++ b/src/core/repair/registry.ts@@ -17,6 +17,12 @@* `est_usd_cost`) includes that spend, and `repairRunner` passes a run's* remaining allowance through as `maxLlmUsd`.*+ * `preview_bound` kinds print a preview hash, and `--apply --expect <hash>`+ * applies exactly the previewed set (`changed_since_preview` for anything that+ * moved); it is independent of `explicit_only`, so a preview-bound kind that+ * is not explicit-only also runs from `--all`, the remediation plan and the+ * maintenance cycle with a bare `--apply` (the current plan).+ ** `explicit_only` kinds run only when the operator names them* (`gbrain repair <kind>`): `--all`, the remediation plan and run, and the* post-upgrade banner list them with their preview command@@ -47,6 +53,7 @@ import { failedWritesRepair } from './failed-writes.ts';import { frontmatterRepair } from './frontmatter.ts';import { attributionBackfillRepair } from './attribution-backfill.ts';import { plannerStatsRepair } from './planner-stats.ts';+import { fencesRepair } from './fences.ts';import { ERROR_CATALOGUE, catalogueError } from '../error-catalogue.ts';import type { OperationError } from '../ops/contract.ts';@@ -61,6 +68,8 @@ export interface RepairKindSpec {checks: string[];/** Runs only when named on the command line; never from `--all`, the remediation plan or a supplied step. */explicit_only?: true;+ /** The preview prints a hash and `--apply --expect <hash>` applies exactly that set (accepted with or without `explicit_only`). */+ preview_bound?: true;/** `destructive`: the apply rewrites user files, so it also needs the user's consent (`--yes` with the preview hash, or a terminal prompt). */consent?: 'destructive';/** `llm`: the kind may call a paid chat model; its spend is metered by the daily USD ledger and reported in `cost.llm_usd`. */@@ -183,6 +192,15 @@ const SPECS: Record<RepairKind, Omit<RepairKindSpec, 'kind'>> = {+ 'select files. Preview-bound: --apply --expect <hash> --yes writes exactly the previewed bytes, imports them and clears the hold (managed '+ 'sources commit through the Git effect; legacy sources back up first and print the commit step). Files no rule fixes are listed with the exact manual fix.',},+ fences: {+ handler: fencesRepair, embeds: 'effect', checks: ['fence_integrity'], preview_bound: true, spends: 'llm',+ summary: 'Repair malformed facts and takes fences (#6188) that sync held or that pages store: per file or page the free tiers first (the lossless '+ + 'Tier 1 rules, then holder names verified against people/ and companies/ pages), then, for rows only a model can realign, the configured '+ + 'chat model (models.fence_repair) sees only the header and those rows under the fences.repair caps. Every proposal passes the validation gates '+ + '(a)-(g) and is a Tier 1 fixed point, or it is not written. Managed sources commit through the Git effect, legacy sources back up and print '+ + 'the commit step, database-only pages take a revision-bound write. --only/--skip <path> and --slug <slug> select; --no-llm keeps to the free '+ + 'tiers; --max-usd <n> lowers the model cap for this run. Preview-bound: --apply --expect <hash> applies exactly the previewed set.',+ },'planner-stats': {handler: plannerStatsRepair, embeds: 'none', checks: ['planner_stats_stale'],summary: 'ANALYZE the hot tables (pages, links, facts, takes, content_chunks, timeline_entries) whose planner statistics are stale (F4b), '@@ -209,6 +227,12 @@ export const AUTO_REPAIR_REGISTRY: readonly RepairKindSpec[] = REPAIR_REGISTRY.f/** The explicit-only kinds, listed by those surfaces with their preview command but never run by them. */export const EXPLICIT_REPAIR_REGISTRY: readonly RepairKindSpec[] = REPAIR_REGISTRY.filter(spec => spec.explicit_only);+/** The kinds whose `--apply` accepts `--expect <hash>`: explicit-only kinds and preview-bound ones. */+export const PREVIEW_BOUND_REPAIR_REGISTRY: readonly RepairKindSpec[] = REPAIR_REGISTRY.filter(spec => spec.explicit_only || spec.preview_bound);++/** The kinds that may call a paid chat model, the only ones `--max-usd` applies to. */+export const LLM_REPAIR_REGISTRY: readonly RepairKindSpec[] = REPAIR_REGISTRY.filter(spec => spec.spends === 'llm');+/** `registry`: the kinds to look in; production callers use the registered ones, tests pass stub specs. */export function repairSpec(kind: RepairKind, registry: readonly RepairKindSpec[] = REPAIR_REGISTRY): RepairKindSpec {return registry.find(spec => spec.kind === kind)!;@@ -261,12 +285,13 @@ 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[];- maxLlmUsd?: number } = {}): Promise<RepairResult> {+ slugs?: string[]; noLlm?: boolean; maxLlmUsd?: number; deadline?: number } = {}): Promise<RepairResult> {const ctx = { engine, config, logger, dryRun: !opts.apply, remote: false, sourceId: scope.source_ids[0] } 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'] : [],- explicit: run.explicit, expect: run.expect, includeAmbiguous: run.includeAmbiguous, only: run.only, skip: run.skip, maxLlmUsd: run.maxLlmUsd });+ 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 });},};}diff --git a/test/repair-explicit-only.test.ts b/test/repair-explicit-only.test.tsindex 3dbaec1fac..474e97245e 100644--- a/test/repair-explicit-only.test.ts+++ b/test/repair-explicit-only.test.ts@@ -132,8 +132,13 @@ describe('surfaces that list instead of run', () => {for (const kind of EXPLICIT) expect(allLine).not.toContain(kind);expect(parseRepairArgs(['stale-atoms', '--apply', '--expect', 'abc'])).toMatchObject({ kind: 'stale-atoms', apply: true, expect: 'abc' });expect(parseRepairArgs(['extractor-facts', '--include-ambiguous'])).toMatchObject({ includeAmbiguous: true });- for (const args of [['timeline', '--expect', 'abc'], ['--all', '--expect', 'abc'], ['visibility', '--include-ambiguous']]) {- expect(() => parseRepairArgs(args)).toThrow(/applies only to an explicit-only kind/);+ // #6188 (D8): a preview-bound kind that is not explicit-only (fences) accepts --expect, never --include-ambiguous.+ expect(parseRepairArgs(['fences', '--apply', '--expect', 'abc'])).toMatchObject({ kind: 'fences', apply: true, expect: 'abc' });+ for (const args of [['timeline', '--expect', 'abc'], ['--all', '--expect', 'abc']]) {+ expect(() => parseRepairArgs(args)).toThrow(/--expect applies only to an explicit-only or preview-bound kind/);+ }+ for (const args of [['visibility', '--include-ambiguous'], ['fences', '--include-ambiguous']]) {+ expect(() => parseRepairArgs(args)).toThrow(/--include-ambiguous applies only to an explicit-only kind/);}});diff --git a/test/repair-flags.test.ts b/test/repair-flags.test.tsindex 79f3ee99cc..cf0d70f5bb 100644--- a/test/repair-flags.test.ts+++ b/test/repair-flags.test.ts@@ -102,6 +102,6 @@ describe('gbrain repair flags', () => {const human = await captured(['--all']);expect(human).toContain("may queue paid embeddings: timeline, visibility, safe-chunks");const free = JSON.parse(await captured(["--all", "--json", "--no-embed"])) as { paid_kinds: string[] };- expect(free.paid_kinds).toEqual(["timeline", "visibility", "connector-fences", "take-supersession", "embedding-effects"]);+ expect(free.paid_kinds).toEqual(["timeline", "visibility", "connector-fences", "take-supersession", "embedding-effects", "fences"]);});});