Garry's Opinionated OpenClaw/Hermes Agent Brain
TypeScript
feat(repair): gbrain repair frontmatter, preview-bound safe and interpretive file repair (#5988)
garrytan2c72a65eedb1
diff --git a/src/commands/repair.ts b/src/commands/repair.tsindex 1a4f7cebd1..66f90ecfcf 100644--- a/src/commands/repair.ts+++ b/src/commands/repair.ts@@ -15,6 +15,7 @@ import { setCliExitVerdict } from '../core/cli-force-exit.ts';import { clearHealthMemo } from '../core/health-memo.ts';import { OperationError } from '../core/ops/contract.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, repairMaySpend, repairPreviewCommand, repairRunner, repairSpec } from '../core/repair/registry.ts';function wrap(text: string, indent: number, width = 80): string {@@ -33,6 +34,8 @@ const explicitKinds = EXPLICIT_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]Repair residual damage that \`gbrain doctor\` reports. Dry run unless --apply.@@ -51,28 +54,37 @@ Options:Explicit-only kinds: apply exactly the set the preview printed under this hash.--include-ambiguousExplicit-only kinds: widen the preview to ambiguous items (its hash covers them).- --json Machine-readable output with a stable shape.+ --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.+ --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 embeddingwork, preview gbrain doctor --remediation-plan --json and, after the user agrees, rungbrain doctor --remediate --yes --include-repairs --max-usd <n> --expect <plan_hash>.With no kind, previews every kind. Run it on the brain host.`;-const BOOLEAN_FLAGS = new Set(['--apply', '--all', '--json', '--no-embed', '--include-ambiguous']);-const VALUE_FLAGS = new Set(['--source', '--limit', '--expect']);+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;-interface RepairArgs { kind?: string; apply: boolean; all: boolean; json: boolean; noEmbed: boolean; includeAmbiguous: boolean; source?: string; limit?: string; expect?: string }+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[] }/** 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 };+ const parsed: RepairArgs = { apply: false, all: false, json: false, noEmbed: false, includeAmbiguous: false, diff: false, yes: false, only: [], skip: [] };+ const used = new Set<string>();const positional: string[] = [];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 (flag === '--yes') throw new OperationError('invalid_params', '`--yes` is not accepted by gbrain repair; pass --apply to write.');+ if (FRONTMATTER_FLAGS.includes(flag as typeof FRONTMATTER_FLAGS[number])) used.add(flag);if (flag === '--max-usd' || 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.`,@@ -84,6 +96,8 @@ export function parseRepairArgs(args: string[]): RepairArgs {else if (flag === '--all') parsed.all = true;else if (flag === '--json') parsed.json = true;else if (flag === '--include-ambiguous') parsed.includeAmbiguous = true;+ else if (flag === '--diff') parsed.diff = true;+ else if (flag === '--yes') parsed.yes = true;else parsed.noEmbed = true;continue;}@@ -92,11 +106,17 @@ export function parseRepairArgs(args: string[]): RepairArgs {if (!value || value.startsWith('--')) throw new OperationError('invalid_params', `${flag} requires a value.`);if (flag === '--source') parsed.source = value;else if (flag === '--expect') parsed.expect = value;+ else if (flag === '--only') parsed.only.push(value);+ else if (flag === '--skip') parsed.skip.push(value);else parsed.limit = value;}if (positional.length > 1) throw new OperationError('invalid_params', `Unexpected argument '${positional[1]}'; gbrain repair takes at most one kind.`,`Kinds: ${REPAIR_KINDS.join(', ')}.`);parsed.kind = positional[0];+ if (used.has('--yes') && parsed.kind !== 'frontmatter') throw new OperationError('invalid_params', '`--yes` is not accepted by gbrain repair; pass --apply to write.');+ 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 --source <id>');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}).`,@@ -105,7 +125,7 @@ export function parseRepairArgs(args: string[]): RepairArgs {return parsed;}-function human(result: RepairResult): string {+function human(result: RepairResult, opts: { diff: boolean } = { diff: false }): string {const lines = [`${result.kind}: ${result.affected} item(s) ${result.mode === 'apply' ? 'pending before this run' : 'to repair'}`];for (const warning of result.warnings ?? []) lines.push(` WARNING: ${warning}`);if (result.sample.length) lines.push(` e.g. ${result.sample.join(', ')}`);@@ -118,14 +138,21 @@ function human(result: RepairResult): string {if (result.mode === 'apply') lines.push(` applied ${result.applied}, skipped ${result.skipped}${result.complete ? ', complete' : ''}`);if (result.stopped) lines.push(` STOPPED: ${result.stopped.message}`);for (const entry of result.listing ?? []) lines.push(` ${entry.class}: ${entry.item}${entry.detail ? ` (${entry.detail})` : ''}`);+ const render = repairSpec(result.kind).handler.render;+ if (result.details && render) lines.push(...render(result.details, opts));if (result.mode === 'apply' && result.outcomes) lines.push(` outcomes: ${Object.entries(result.outcomes).map(([k, v]) => `${k}=${v}`).join(', ')}`);+ for (const outcome of result.mode === 'apply' ? result.outcome_items ?? [] : []) {+ if (!outcome.detail) continue;+ lines.push(` ${outcome.outcome}: ${outcome.item} ${Object.entries(outcome.detail).filter(([key]) => key !== 'commit_step').map(([k, v]) => `${k}=${v}`).join(', ')}${outcome.reason ? ` (${outcome.reason})` : ''}`);+ if (typeof outcome.detail.commit_step === 'string') lines.push(` commit: ${outcome.detail.commit_step}`);+ }if (result.mode === 'dry_run' && result.affected) lines.push(` apply: ${result.apply_command}`);return lines.join('\n');}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, limit: limitText } = parseRepairArgs(args);+ const { kind, apply, all, json, noEmbed, includeAmbiguous, source, expect, only, skip, diff, limit: limitText } = parseRepairArgs(args);const limit = limitText === undefined ? undefined : Number(limitText);if (limit !== undefined && (!Number.isSafeInteger(limit) || limit < 1)) throw new OperationError('invalid_params', '--limit must be a positive integer.');if (kind && !REPAIR_KINDS.includes(kind as RepairKind)) {@@ -136,10 +163,21 @@ export async function runRepairCommand(engine: BrainEngine, args: string[]): Proconst kinds: RepairKind[] = kind ? [kind as RepairKind] : AUTO_REPAIR_REGISTRY.map(spec => spec.kind);const explicitKindsNotRun = kind ? [] : explicitRepairNotices({ source });const scope = await resolveRepairScope(engine, source);+ if (apply && kind && expect && repairSpec(kind as RepairKind).consent === 'destructive') {+ const preview = ['gbrain', 'repair', kind, ...(source ? ['--source', source] : []), ...only.flatMap(path => ['--only', path]), ...skip.flatMap(path => ['--skip', path]),+ ...(includeAmbiguous ? ['--include-ambiguous'] : [])];+ const auth = await consentGate({ command: `repair ${kind}`, effects: ['destructive'], actor: 'agent',+ what: `Rewrite the previewed ${kind} changes on disk and import them`,+ why: `The preview ${expect} listed each file change; applying it rewrites those files in place and publishes them.`,+ risk: 'Only the previewed lines change; a file that changed since the preview is skipped. Managed sources commit through the Git effect (undo with git revert); legacy sources keep a backup under ~/.gbrain/backups/frontmatter/.',+ user_message: `Apply the previewed ${kind} repair (preview ${expect.slice(0, 12)})? Each listed file is rewritten on disk exactly as the preview showed and imported again.`,+ argv: [...preview, '--apply', '--expect', expect, ...(json ? ['--json'] : [])], preview_argv: [...preview, '--json'], plan_hash: expect, args }, { json, env: engineConsentEnv(engine) });+ if (!auth) return;+ }const 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 });+ const result = await runner.run(k, scope, { limit, sourceFlag: source, explicit: k === kind, expect, includeAmbiguous, ...(k === 'frontmatter' ? { only, skip } : {}) });results.push({ ...result, paid: repairMaySpend(repairSpec(k), noEmbed) });if (result.stopped) break;}@@ -150,7 +188,7 @@ export async function runRepairCommand(engine: BrainEngine, args: string[]): Pro...(explicitKindsNotRun.length ? { explicit_kinds: explicitKindsNotRun } : {}) }, null, 2));} else {console.log(`Scope: brain ${scope.brain_id}; sources ${scope.source_ids.join(', ') || '(none)'}`);- for (const result of results) console.log(human(result));+ for (const result of results) console.log(human(result, { diff }));if (!apply && paidKinds.length) console.log(`Kinds that may queue paid embeddings: ${paidKinds.join(', ')} (pass --no-embed to skip; `+ 'page-write kinds are re-embedded by their publication either way; cap spend with gbrain doctor --remediate --yes --include-repairs --max-usd <n> --expect <plan_hash> from gbrain doctor --remediation-plan --json).');if (explicitKindsNotRun.length) console.log(`Explicit-only kinds (not run without their name; preview each): ${explicitKindsNotRun.map(n => n.preview_command).join('; ')}`);diff --git a/src/core/persistence/preview-approval.ts b/src/core/persistence/preview-approval.tsindex dab2eeb8a7..45a53e8cd5 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' | 'extractor-facts' | 'captured-facts' | 'loop-facts' | 'failed-writes';+export type PreviewApprovalCommand = 'authorize-legacy' | 'jobs-cancel' | 'stale-atoms' | 'extractor-facts' | 'captured-facts' | 'loop-facts' | 'failed-writes' | 'frontmatter';export interface ApprovedSetKey {command: PreviewApprovalCommand;diff --git a/src/core/repair/core.ts b/src/core/repair/core.tsindex 8020cd65c9..55c2a1bade 100644--- a/src/core/repair/core.ts+++ b/src/core/repair/core.ts@@ -22,8 +22,9 @@ 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';-export const REPAIR_KINDS = ['timeline', 'visibility', 'safe-chunks', 'contextual-mode', 'connector-checkpoints', 'request-indexes', 'connector-fences', 'orphan-bindings', 'embedding-effects', 'attribution-backfill', 'planner-stats', 'google-file-modes', 'stale-atoms', 'extractor-facts', 'captured-facts', 'loop-facts', 'orphan-children', 'failed-writes'] as const;+export const REPAIR_KINDS = ['timeline', 'visibility', 'safe-chunks', 'contextual-mode', 'connector-checkpoints', 'request-indexes', 'connector-fences', '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 type RepairKind = typeof REPAIR_KINDS[number];export interface RepairScope { brain_id: string; source_ids: string[] }@@ -47,12 +48,14 @@ export interface RepairPlan {preview_hash?: string;/** Preview-bound kinds: every previewed item with its class, all of which the hash covers. */listing?: RepairListing[];+ /** Kind-specific preview detail (per-file diffs, manual fixes, next actions), rendered by the handler's `render`. */+ details?: Record<string, unknown>;}export interface RepairListing { item: string; class: string; detail?: string }-/** What the run was asked to do; preview-bound (explicit-only) kinds read `expect` and `includeAmbiguous`. */-export interface RepairPlanOptions { apply: boolean; expect?: string; includeAmbiguous?: boolean }+/** 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[] }export interface RepairHandler {kind: RepairKind;@@ -68,10 +71,14 @@ export interface RepairHandler {* A kind with named per-item outcomes returns them instead of a boolean.*/apply(ctx: OperationContext, item: RepairItem, opts?: { embed: boolean; runId?: 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[];}/** A named per-item outcome; `applied` counts it as applied, otherwise skipped. */-export interface RepairItemOutcome { applied: boolean; outcome: string; reason?: string }+export interface RepairItemOutcome { applied: boolean; outcome: string; reason?: string; detail?: Record<string, unknown> }export interface RepairResult {kind: RepairKind;@@ -93,7 +100,9 @@ export interface RepairResult {listing?: RepairListing[];/** Per-outcome counts and the first items, for kinds that name outcomes. */outcomes?: Record<string, number>;- outcome_items?: Array<{ item: string; outcome: string; reason?: string }>;+ outcome_items?: Array<{ item: string; outcome: string; reason?: string; detail?: Record<string, unknown> }>;+ /** Kind-specific preview detail (see RepairPlan.details). */+ details?: Record<string, unknown>;}const RECEIPT_BYTES = 16_384;@@ -181,12 +190,12 @@ 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 }): Promise<RepairResult> {+ explicit?: boolean; expect?: string; includeAmbiguous?: boolean; only?: string[]; skip?: string[] }): Promise<RepairResult> {const { repairSpec, explicitKindRequired } = await import('./registry.ts');if (repairSpec(handler.kind)?.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 });+ 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 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;@@ -198,10 +207,13 @@ export async function runRepair(ctx: OperationContext, handler: RepairHandler, scapacity: 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.includeAmbiguous ? ' --include-ambiguous' : ''} --apply${plan.preview_hash ? ` --expect ${plan.preview_hash}` : ''}`,+ + `${[...(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}` : ''}`+ + `${repairSpec(handler.kind)?.consent === 'destructive' ? ' --yes' : ''}`,};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;}@@ -222,8 +234,9 @@ export async function runRepair(ctx: OperationContext, handler: RepairHandler, sconst applied = await handler.apply({ ...ctx, sourceId: item.source_id }, item, { embed: opts.embed === true, runId });if (typeof applied === 'object') {result.outcomes = { ...result.outcomes, [applied.outcome]: (result.outcomes?.[applied.outcome] ?? 0) + 1 };- if ((result.outcome_items ??= []).length < SAMPLE * 2) {- result.outcome_items.push({ item: `${item.source_id}:${item.slug}`, outcome: applied.outcome, ...(applied.reason ? { reason: applied.reason } : {}) });+ if ((result.outcome_items ??= []).length < (handler.outcomeItemsLimit ?? SAMPLE * 2)) {+ result.outcome_items.push({ item: `${item.source_id}:${item.slug}`, outcome: applied.outcome, ...(applied.reason ? { reason: applied.reason } : {}),+ ...(applied.detail ? { detail: applied.detail } : {}) });}}if (typeof applied === 'object' ? applied.applied : applied) result.applied++;diff --git a/src/core/repair/frontmatter.ts b/src/core/repair/frontmatter.tsnew file mode 100644index 0000000000..290f836a63--- /dev/null+++ b/src/core/repair/frontmatter.ts@@ -0,0 +1,511 @@+/**+ * `gbrain repair frontmatter` (#5988): finds every file and page a broken+ * frontmatter block left behind and fixes what it can without guessing.+ *+ * Scope: the Git-visible `.md`/`.mdx` files of each source plus every Git+ * hold row, and (database side) pages whose body begins with an embedded+ * frontmatter block or whose title was derived from the slug while the file+ * names one. Per file it proposes one minimal line-level change, in two+ * classes:+ *+ * - safe: quoting a value ingestion already reads (`recoverFrontmatter`+ * `quote`), stripping NUL bytes, swapping the outer quotes of a nested+ * quoted value. Every parsed value stays exactly what ingestion read.+ * - interpretive: folding unquoted continuation lines into a value,+ * resolving a duplicated key to the later line, quoting an unclosed+ * `[`/`{`, quoting a `#`-leading title, inserting a missing closing+ * fence, removing a frontmatter `slug:` that names another page,+ * re-importing a page from its canonical file, and re-binding a held+ * rename to the old page's current revision.+ *+ * The default set is safe only; `--include-ambiguous` adds interpretive+ * changes and changes the preview hash. `--only <path>` / `--skip <path>`+ * select files and are bound into the hash too. Every change must leave a+ * file that strict-parses with no hold, and its publication result (the+ * exact bytes plus the page fields an import would store, bound to the page+ * revision) is hashed; a file whose import would need a canonical overlay,+ * or that no rule fixes, is `needs_review` with the exact manual fix and is+ * never written.+ *+ * Explicit-only and preview-bound: `--apply --expect <hash>` (destructive+ * consent: `--yes`) re-derives each approved change from the file as it is+ * and applies it only when the file bytes, the proposal and the page still+ * match (`changed_since_preview` otherwise). Managed sources publish through+ * the owner-internal `managed_file_repair` intent (exact bytes, import, hold+ * clear and Git target effect in one coordinated write); legacy sources back+ * the file up, write it, import it, clear its hold, and print the commit+ * step. An apply refuses while an unfinished managed sync cursor still names+ * a selected file.+ */+import { execFileSync } from 'node:child_process';+import { existsSync, lstatSync, readdirSync, readFileSync, writeFileSync } from 'node:fs';+import { join } from 'node:path';+import type { BrainEngine } from '../engine.ts';+import { opError, OperationError, type OperationContext } from '../ops/contract.ts';+import { shellQuote, type Action } from '../agent-output.ts';+import { autoFixFrontmatter, createFrontmatterBackup, makeFrontmatterBackupRunId, repairRecoverableFrontmatter } from '../brain-writer.ts';+import { classifyImportHold, parseMarkdown, type ContentHold, type ParsedMarkdown } from '../markdown.ts';+import { MAX_FILE_SIZE, type ContentRefusal } from '../import-screen.ts';+import { importFromFile } from '../import-file.ts';+import { resolveSlugForPath } from '../sync.ts';+import { isReservedSkillBundlePath } from '../skill-reserved-paths.ts';+import { digest, sha256 } from '../persistence/digest.ts';+import { managedPersistenceEnabled } from '../persistence/ownership.ts';+import { clearGitHold, readGitSourceHolds, type GitHoldRecord } from '../persistence/sync-holds.ts';+import type { SyncRename } from '../persistence/sync-discovery.ts';+import { canonicalRepairFields, confinedRepairTarget, managedRepairRoot, prepareRepairPublication, repairScreenConfig, submitManagedFileRepair } from '../persistence/file-repair.ts';+import { clearApprovedSet, loadApprovedSet, previewChangedError, previewHash, saveApprovedSet } from '../persistence/preview-approval.ts';+import type { PageSnapshot } from '../page-state/types.ts';+import { afterCursor, repairRequestId, type RepairHandler, type RepairItem, type RepairItemOutcome, type RepairListing, type RepairPlan, type RepairScope } from './core.ts';++type Mode = 'managed' | 'legacy';+type RepairClass = 'safe' | 'interpretive';+interface Selection { source_ids: string[]; include_ambiguous: boolean; only: string[]; skip: string[] }+interface SourceRoot { sourceId: string; incarnation: string; mode: Mode; root: string }++/** One approved change: everything the hash binds, never a raw frontmatter value. */+interface ApprovedRepair {+ source_id: string; mode: Mode; path: string; source_path: string; slug: string; class: RepairClass; fixes: string[];+ before: string; after: string; chars: number; page_id: number | null; revision: string | null; result_digest: string; rename_from?: SyncRename;+}+interface ApprovedSetItem extends ApprovedRepair { selection: Selection }+interface FrontmatterItem extends RepairItem { repair: ApprovedRepair; selection: Selection; hash: string; last: boolean }++export interface NeedsReview {+ source_id: string; path: string; code: string; reason?: string; key?: string; line?: number;+ /** The exact manual fix: the line to edit, or what to do with the file. */+ resolution: string;+ /** `imported_before_hold`: a page exists from a gbrain that imported this file before it was held. */+ flag?: string;+}+interface FileDiff { source_id: string; path: string; class: RepairClass; fixes: string[]; diff: string; selected: boolean }+export interface FrontmatterPreviewDetails {+ counts: { safe: number; interpretive: number; interpretive_pending: number; needs_review: number };+ samples: Partial<Record<RepairClass, FileDiff>>;+ diffs: FileDiff[];+ needs_review: NeedsReview[];+ next_actions: Action[];+}++const REPAIRABLE = new Set(['YAML_PARSE', 'NULL_BYTES', 'NESTED_QUOTES', 'MISSING_CLOSE']);+const RESCUE_KEYS = new Set(['title', 'name', 'description', 'summary']);++function previewArgv(scope: RepairScope, selection: Pick<Selection, 'only' | 'skip'>, includeAmbiguous: boolean): string[] {+ return ['gbrain', 'repair', 'frontmatter', ...(scope.source_ids.length === 1 ? ['--source', scope.source_ids[0]!] : []),+ ...selection.only.flatMap(path => ['--only', path]), ...selection.skip.flatMap(path => ['--skip', path]), ...(includeAmbiguous ? ['--include-ambiguous'] : [])];+}++/** Single-hunk unified diff of the changed line range. */+export function lineDiff(path: string, before: string, after: string): string {+ const a = before.split('\n'), b = after.split('\n');+ let head = 0;+ while (head < a.length && head < b.length && a[head] === b[head]) head++;+ let tail = 0;+ while (tail < a.length - head && tail < b.length - head && a[a.length - 1 - tail] === b[b.length - 1 - tail]) tail++;+ const removed = a.slice(head, a.length - tail), added = b.slice(head, b.length - tail);+ return [`--- a/${path}`, `+++ b/${path}`, `@@ -${head + 1},${removed.length} +${head + 1},${added.length} @@`,+ ...removed.map(line => `-${line}`), ...added.map(line => `+${line}`)].join('\n');+}++/** What ingestion reads from the file: the values a safe change must keep (NUL bytes aside). */+function reading(content: string, path: string): string {+ const parsed = parseMarkdown(content.replace(/\x00/g, ''), path, { validate: true });+ return JSON.stringify([parsed.frontmatter, parsed.title, parsed.type, parsed.tags]);+}++interface SlugContext { expectedSlug: string; slugExempt: (declared: string) => boolean }++function inspect(content: string, path: string, ctx: SlugContext, byteLength: number): { parsed: ParsedMarkdown; errors: string[]; hold: ContentHold | null; recovered: number; comments: number } {+ const parsed = parseMarkdown(content, path, { validate: true });+ return { parsed, errors: [...new Set((parsed.errors ?? []).filter(error => REPAIRABLE.has(error.code)).map(error => error.code))],+ hold: classifyImportHold(parsed, { ...ctx, byteLength, maxBytes: MAX_FILE_SIZE }),+ recovered: (parsed.warnings ?? []).filter(w => w.code === 'FRONTMATTER_RECOVERED').length,+ comments: (parsed.warnings ?? []).filter(w => w.code === 'FRONTMATTER_COMMENT_VALUE' && RESCUE_KEYS.has(w.key)).length };+}++/** Strict-parses with no YAML error and earns no hold: the gate every change must pass. */+function clean(content: string, path: string, ctx: SlugContext): boolean {+ const found = inspect(content, path, ctx, Buffer.byteLength(content));+ return found.errors.length === 0 && found.hold === null;+}++interface Candidates { safe: { content: string; fixes: string[] } | null; interpretive: { content: string; fixes: string[] } | null }++/** The safe and the interpretive rewrite of one file, each kept only when it passes the gate. */+export function frontmatterCandidates(content: string, path: string, ctx: SlugContext): Candidates {+ const found = inspect(content, path, ctx, Buffer.byteLength(content));+ const has = (code: string) => found.errors.includes(code);+ let safe = content;+ const safeFixes: string[] = [];+ if (has('NULL_BYTES')) { safe = safe.replace(/\x00/g, ''); safeFixes.push('Stripped null bytes'); }+ if (has('NESTED_QUOTES') && !has('MISSING_CLOSE')) {+ const swapped = autoFixFrontmatter(safe);+ if (swapped.fixes.every(fix => fix.code === 'NESTED_QUOTES')) { safe = swapped.content; safeFixes.push(...swapped.fixes.map(fix => fix.description)); }+ }+ const quoted = repairRecoverableFrontmatter(safe);+ safe = quoted.content;+ safeFixes.push(...quoted.fixes.map(fix => fix.description));+ const safeOk = safe !== content && clean(safe, path, ctx) && reading(safe, path) === reading(content, path);+ let interpretive = content.replace(/\x00/g, '');+ const interpretiveFixes = has('NULL_BYTES') ? ['Stripped null bytes'] : [];+ const slugConflict = found.hold?.code === 'frontmatter_slug_conflict';+ if (has('NESTED_QUOTES') || has('MISSING_CLOSE') || slugConflict) {+ const fixed = autoFixFrontmatter(interpretive, slugConflict ? { filePath: path } : undefined);+ interpretive = fixed.content;+ interpretiveFixes.push(...fixed.fixes.map(fix => fix.description));+ }+ const rescued = repairRecoverableFrontmatter(interpretive, { includeAmbiguous: true });+ interpretive = rescued.content;+ interpretiveFixes.push(...rescued.fixes.map(fix => fix.description));+ const interpretiveOk = interpretive !== content && interpretive !== (safeOk ? safe : content) && clean(interpretive, path, ctx);+ return { safe: safeOk ? { content: safe, fixes: safeFixes } : null, interpretive: interpretiveOk ? { content: interpretive, fixes: interpretiveFixes } : null };+}++/** The exact manual fix for a file no rule repairs. */+function resolution(hold: Pick<ContentRefusal, 'code' | 'reason' | 'key' | 'line'> | null, path: string): string {+ if (!hold) return `Edit the frontmatter of ${path} by hand (one line per key, the whole value quoted), then preview again.`;+ const where = `${hold.line !== undefined ? `line ${hold.line}` : 'the frontmatter'}${hold.key ? ` (key "${hold.key}")` : ''} of ${path}`;+ switch (hold.code) {+ case 'file_too_large': return `Split ${path} into files under ${MAX_FILE_SIZE} bytes and commit, or leave it out of the source with sync.exclude.`;+ case 'frontmatter_slug_conflict': return `Remove the slug: line of ${path} (the path decides the slug), or move the file to the path its slug names.`;+ case 'content_rejected': return `Remove the junk the content-sanity gate matched in ${path}, or ask the user whether junk_disposition should stay reject.`;+ case 'rename_held': return `Re-run the preview with --include-ambiguous to re-bind the rename of ${path} to the current page, or restore the old file name.`;+ case 'parser_regression': return `This is a gbrain bug: report the gbrain version, ${path} and the code; upgrade or pin the last good version.`;+ default: return hold.reason === 'ambiguous_protected_key' ? `Write ${where} on one line with one quoted value; gbrain never guesses who may read a page or where it came from.`+ : hold.reason === 'ambiguous_identity_key' ? `Keep exactly one line for ${where}; gbrain never guesses which page a file is.`+ : `Fix ${where} by hand: one line per key, the whole value quoted on that line.`;+ }+}++/** The managed owner root, or the legacy checkout, of each source in scope; others are residuals. */+async function sourceRoots(engine: BrainEngine, scope: RepairScope, residuals: Record<string, number>, warnings: string[]): Promise<SourceRoot[]> {+ const managed = await managedPersistenceEnabled(engine);+ const rows = await engine.executeRaw<{ id: string; incarnation: string; local_path: string | null }>(+ 'SELECT id, incarnation::text AS incarnation, local_path FROM sources WHERE id = ANY($1::text[]) ORDER BY id', [scope.source_ids]);+ const roots: SourceRoot[] = [];+ for (const row of rows) {+ if (managed) {+ try { roots.push({ sourceId: row.id, incarnation: row.incarnation, mode: 'managed', root: (await managedRepairRoot(engine, row.id)).root }); }+ catch (error) {+ if (!(error instanceof OperationError)) throw error;+ residuals.owner_elsewhere = (residuals.owner_elsewhere ?? 0) + 1;+ warnings.push(`Source ${row.id}: this host is not its active canonical owner; run the preview on the owner host (gbrain sources writer status --source ${row.id}).`);+ }+ continue;+ }+ const root = row.local_path ?? (row.id === 'default' ? await engine.getConfig('sync.repo_path') : null);+ if (root && existsSync(root)) roots.push({ sourceId: row.id, incarnation: row.incarnation, mode: 'legacy', root });+ }+ return roots;+}++/** Git-visible Markdown under the root (tracked and untracked, ignored files excluded); a plain walk outside Git. */+function markdownFiles(root: string): string[] {+ let paths: string[];+ try {+ paths = execFileSync('git', ['-C', root, 'ls-files', '-z', '--cached', '--others', '--exclude-standard'], { encoding: 'utf8', maxBuffer: 1 << 30, stdio: ['ignore', 'pipe', 'ignore'] })+ .split('\0').filter(Boolean);+ } catch {+ paths = (readdirSync(root, { recursive: true }) as string[]).map(path => path.split('\\').join('/'));+ }+ return [...new Set(paths)].filter(path => /\.mdx?$/i.test(path) && !path.split('/').some(part => part.startsWith('.')) && !isReservedSkillBundlePath(path)).sort();+}++interface PageRow { id: number; slug: string; source_path: string; revision: string; title: string; head: string }++async function pagesByOrigin(engine: BrainEngine, sourceId: string): Promise<Map<string, PageRow>> {+ const rows = await engine.executeRaw<PageRow>(`SELECT id, slug, source_path, knowledge_revision::text AS revision, title, left(compiled_truth, 400) AS head+ FROM pages WHERE source_id=$1 AND deleted_at IS NULL AND source_path IS NOT NULL`, [sourceId]);+ return new Map(rows.map(row => [row.source_path, { ...row, id: Number(row.id) }]));+}++/** #4526: a body that begins with its own frontmatter block. */+const EMBEDDED_BLOCK = /^\s*---[ \t]*\r?\n(?:[\s\S]*?\r?\n)?[A-Za-z_][\w-]*:[\s\S]*?\r?\n---[ \t]*(?:\r?\n|$)/;++/** The title parseMarkdown falls back to when a file names none: the humanized slug. */+function slugTitle(slug: string): string {+ const name = slug.split('/').pop() ?? '';+ return name.replace(/[-_]/g, ' ').trim().replace(/\b\w/g, c => c.toUpperCase()) || 'Untitled';+}++/** Database-side damage worth a re-import from the canonical file. */+function pageDamage(page: PageRow | undefined, content: string): string | null {+ if (!page) return null;+ if (EMBEDDED_BLOCK.test(page.head)) return 'its stored body begins with an embedded frontmatter block';+ const titleLine = /^---[^\n]*\n[\s\S]*?^title:[ \t]*\S/m.test(content.replace(/^\uFEFF/, ''));+ if (titleLine && page.title === slugTitle(page.slug)) return 'its stored title was derived from the slug although the file names a title';+ return null;+}++interface Analysis {+ proposal?: { content: string; fixes: string[]; class: RepairClass; rename_from?: SyncRename; reimport?: string };+ pending?: { content: string; fixes: string[] };+ review?: NeedsReview;+}++interface FileContext { engine: BrainEngine; src: SourceRoot; includeAmbiguous: boolean; pages: Map<string, PageRow> }++/** One file's proposal, pending interpretation, or manual fix; null when it needs nothing. */+async function analyzeFile(ctx: FileContext, path: string, hold: GitHoldRecord | undefined): Promise<Analysis | null> {+ const { src, includeAmbiguous } = ctx;+ const abs = join(src.root, path);+ const review = (code: string, text: string, extra: Partial<NeedsReview> = {}): Analysis => ({ review: { source_id: src.sourceId, path, code, resolution: text, ...extra } });+ if (!existsSync(abs)) return hold ? review(hold.code, `${path} is gone; the next gbrain sync --source ${src.sourceId} --no-pull clears its hold.`) : null;+ if (lstatSync(abs).isSymbolicLink()) return hold ? review(hold.code, `${path} is a symlink; gbrain never writes through one. Replace it with the real file, then preview again.`) : null;+ const size = lstatSync(abs).size;+ if (size > MAX_FILE_SIZE) return review('file_too_large', resolution({ code: 'file_too_large' }, path));+ const content = readFileSync(abs, 'utf8');+ const sourcePath = hold?.source_path ?? path;+ const page = ctx.pages.get(sourcePath);+ const slugCtx: SlugContext = { expectedSlug: resolveSlugForPath(sourcePath), slugExempt: declared => page?.source_path === sourcePath && declared === page.slug };+ const found = inspect(content, path, slugCtx, size);+ const heldBefore = hold && hold.page_id !== null && ['ambiguous_protected_key', 'ambiguous_identity_key'].includes(hold.meta.reason ?? '')+ ? { flag: 'imported_before_hold' } : {};+ let renameFrom = hold?.meta.rename_from;+ let rebind = hold?.code === 'rename_held';+ if (renameFrom) {+ const old = await ctx.engine.readPageSnapshot(renameFrom.slug, { sourceId: src.sourceId });+ if (!old || old.page.id !== renameFrom.pageId) { renameFrom = undefined; rebind = false; }+ else if (old.revision !== renameFrom.revision) { renameFrom = { ...renameFrom, revision: old.revision }; rebind = true; }+ }+ const problem = found.errors.length > 0 || found.hold !== null || found.recovered > 0 || found.comments > 0;+ const damage = !problem && !hold ? pageDamage(page, content) : null;+ if (!problem && !hold && !damage) return null;+ if (damage) {+ const body = parseMarkdown(content, path).compiled_truth;+ if (EMBEDDED_BLOCK.test(body)) return review('embedded_frontmatter', `${path} itself carries a second frontmatter block at the top of its body; merge the two blocks by hand, then preview again.`);+ const reimport = { content, fixes: [`Re-import ${path}: ${damage}`], class: 'interpretive' as const, reimport: damage };+ return includeAmbiguous ? { proposal: reimport } : { pending: reimport };+ }+ const candidates = frontmatterCandidates(content, path, slugCtx);+ const unchanged = found.hold === null && !found.errors.length ? { content, fixes: [] as string[] } : null;+ if (rebind) {+ const base = candidates.interpretive ?? candidates.safe ?? unchanged;+ if (!base) return review(found.hold?.code ?? hold!.code, resolution(found.hold, path));+ const proposal = { content: base.content, fixes: [...base.fixes, `Re-bind the rename of ${path} to page ${renameFrom!.slug} at its current revision`], class: 'interpretive' as const, rename_from: renameFrom };+ return includeAmbiguous ? { proposal } : { pending: proposal };+ }+ const withRename = renameFrom ? { rename_from: renameFrom } : {};+ if (includeAmbiguous && candidates.interpretive) return { proposal: { ...candidates.interpretive, class: 'interpretive', ...withRename } };+ if (candidates.safe) return { proposal: { ...candidates.safe, class: 'safe', ...withRename }, ...(candidates.interpretive ? { pending: candidates.interpretive } : {}) };+ if (candidates.interpretive) return { pending: candidates.interpretive };+ if (hold && unchanged) return { proposal: { content, fixes: [`Import ${path} as it is now`], class: 'safe', ...withRename } };+ if (!found.hold && !hold && !found.errors.length) return null;+ const blocking = found.hold ?? (hold ? { code: hold.code as ContentHold['code'], reason: hold.meta.reason as ContentHold['reason'], key: hold.meta.key, line: hold.meta.line, message: hold.message } : null);+ return review(blocking?.code ?? 'invalid_frontmatter', resolution(blocking, path), {+ ...(blocking?.reason ? { reason: blocking.reason } : {}), ...(blocking?.key ? { key: blocking.key } : {}), ...(blocking?.line !== undefined ? { line: blocking.line } : {}), ...heldBefore });+}++interface Prepared { approved: ApprovedRepair; content: string; original: string }++/** Binds a proposal to its publication result; a refusal or an overlay makes it `needs_review`. */+async function bindProposal(ctx: FileContext, path: string, hold: GitHoldRecord | undefined, proposal: NonNullable<Analysis['proposal']>,+ screenConfig: Awaited<ReturnType<typeof repairScreenConfig>>): Promise<Prepared | NeedsReview> {+ const { engine, src } = ctx;+ const sourcePath = hold?.source_path ?? path;+ const page = ctx.pages.get(sourcePath);+ const slug = page?.slug ?? (proposal.rename_from ? resolveSlugForPath(sourcePath) : hold?.slug ?? resolveSlugForPath(sourcePath));+ const snapshot = await engine.readPageSnapshot(slug, { sourceId: src.sourceId, includeDeleted: true });+ const base: PageSnapshot | null = proposal.rename_from ? await engine.readPageSnapshot(proposal.rename_from.slug, { sourceId: src.sourceId, includeDeleted: true }) : snapshot;+ const publication = await prepareRepairPublication(engine, { sourceId: src.sourceId, slug, sourcePath, path, root: src.root, content: proposal.content,+ snapshot, base, ...screenConfig });+ if (publication.status === 'refused') return { source_id: src.sourceId, path, code: publication.refusal.code, ...(publication.refusal.reason ? { reason: publication.refusal.reason } : {}),+ ...(publication.refusal.line !== undefined ? { line: publication.refusal.line } : {}), resolution: resolution(publication.refusal, path) };+ if (publication.status === 'overlay') return { source_id: src.sourceId, path, code: 'canonical_overlay',+ resolution: `Importing the repaired ${path} would keep page data the file does not carry (tags added outside the file, a withdrawal or sanitized text), so it is not written. Edit the file by hand to carry them (gbrain get --source ${src.sourceId} -- ${slug} shows the page), then preview again.` };+ if (proposal.reimport && snapshot && digest(canonicalRepairFields(snapshot.page, snapshot.tags)) === publication.digest) {+ return { source_id: src.sourceId, path, code: 'embedded_frontmatter', resolution: `The page of ${path} already matches its file; nothing to re-import.` };+ }+ const original = readFileSync(join(src.root, path));+ return { content: proposal.content, original: original.toString('utf8'), approved: { source_id: src.sourceId, mode: src.mode, path, source_path: sourcePath, slug, class: proposal.class, fixes: proposal.fixes,+ before: sha256(original), after: sha256(Buffer.from(proposal.content, 'utf8')), chars: proposal.content.length, page_id: snapshot?.page.id ?? null, revision: snapshot?.revision ?? null,+ result_digest: publication.digest, ...(proposal.rename_from ? { rename_from: proposal.rename_from } : {}) } };+}++interface ScanResult { prepared: Prepared[]; pending: FileDiff[]; review: NeedsReview[]; unknownOnly: string[] }++/** Analyzes every selected file of every source and binds each proposal. */+async function scan(engine: BrainEngine, scope: RepairScope, selection: Selection, residuals: Record<string, number>, warnings: string[]): Promise<ScanResult> {+ const out: ScanResult = { prepared: [], pending: [], review: [], unknownOnly: [] };+ const seen = new Set<string>();+ for (const src of await sourceRoots(engine, scope, residuals, warnings)) {+ const holds = new Map(((await readGitSourceHolds(engine, { sourceIds: [src.sourceId] }))[0]?.holds ?? []).map(hold => [hold.path, hold]));+ const ctx: FileContext = { engine, src, includeAmbiguous: selection.include_ambiguous, pages: await pagesByOrigin(engine, src.sourceId) };+ const screenConfig = await repairScreenConfig(engine, src.sourceId);+ const paths = [...new Set([...markdownFiles(src.root), ...holds.keys()])].sort()+ .filter(path => (!selection.only.length || selection.only.includes(path)) && !selection.skip.includes(path));+ for (const path of paths) {+ seen.add(path);+ const hold = holds.get(path);+ const analysis = await analyzeFile(ctx, path, hold);+ if (!analysis) continue;+ if (analysis.review) out.review.push(analysis.review);+ if (analysis.pending) {+ const before = readFileSync(join(src.root, path), 'utf8');+ out.pending.push({ source_id: src.sourceId, path, class: 'interpretive', fixes: analysis.pending.fixes, diff: lineDiff(path, before, analysis.pending.content), selected: false });+ }+ if (!analysis.proposal) continue;+ const bound = await bindProposal(ctx, path, hold, analysis.proposal, screenConfig);+ if ('approved' in bound) out.prepared.push(bound);+ else out.review.push(bound);+ }+ }+ out.unknownOnly = selection.only.filter(path => !seen.has(path));+ return out;+}++/** E9: an unfinished managed sync cursor that still names one of these paths. */+async function unfinishedSyncPath(engine: BrainEngine, sourceId: string, paths: Set<string>): Promise<string | null> {+ const cursors = await engine.executeRaw<{ run_id: string; index: number | string | null }>(`SELECT completed_keys->0->>'runId' AS run_id, completed_keys->0->>'index' AS index+ FROM op_checkpoints WHERE op='managed-sync' AND COALESCE(completed_keys->0->>'done','false')<>'true' AND completed_keys->0->>'sourceId'=$1`, [sourceId]);+ for (const cursor of cursors) {+ const [manifest] = await engine.executeRaw<{ completed_keys: Array<{ path?: string; sourcePath?: string }> }>(+ "SELECT completed_keys FROM op_checkpoints WHERE op='managed-sync-manifest' AND fingerprint=$1", [cursor.run_id]);+ const named = (manifest?.completed_keys ?? []).slice(Number(cursor.index ?? 0)).find(entry => paths.has(entry.path ?? '') || paths.has(entry.sourcePath ?? ''));+ if (named) return named.path ?? named.sourcePath ?? null;+ }+ return null;+}++function item(repair: ApprovedRepair, selection: Selection, hash: string, index: number, last: boolean): FrontmatterItem {+ return { cursor: { phase: 1, id: index + 1 }, source_id: repair.source_id, slug: repair.slug, chars: repair.chars, action: `${repair.class}:${repair.path}`, repair, selection, hash, last };+}++function sameSelection(a: Selection, b: Selection): boolean {+ return digest(a) === digest(b);+}++export const frontmatterRepair: RepairHandler = {+ kind: 'frontmatter',+ outcomeItemsLimit: 1000,+ async plan(engine, scope, after, opts): Promise<RepairPlan> {+ const selection: Selection = { source_ids: scope.source_ids, include_ambiguous: opts?.includeAmbiguous === true, only: [...(opts?.only ?? [])].sort(), skip: [...(opts?.skip ?? [])].sort() };+ const preview = previewArgv(scope, selection, selection.include_ambiguous);+ if (opts?.apply) {+ if (!opts.expect) {+ throw opError('invalid_params', 'gbrain repair frontmatter --apply writes only the set a preview printed.',+ `Preview first: ${shellQuote(preview)} — show the user the per-file diffs, then run the apply command it prints (with --yes --expect <preview-hash>).`);+ }+ const approved = await loadApprovedSet<ApprovedSetItem>(engine, { command: 'frontmatter', hash: opts.expect, previewCommand: shellQuote(preview) });+ if (approved.items.some(entry => !sameSelection(entry.selection, selection))) throw previewChangedError(opts.expect, shellQuote(preview));+ for (const sourceId of new Set(approved.items.map(entry => entry.source_id))) {+ const named = await unfinishedSyncPath(engine, sourceId, new Set(approved.items.filter(entry => entry.source_id === sourceId).flatMap(entry => [entry.path, entry.source_path])));+ if (named) throw opError('sync_in_progress', `Source ${sourceId} has an unfinished managed sync that still names ${named}, so the repair wrote nothing.`,+ `Finish that sync first: gbrain sync --source ${sourceId} --no-pull — then preview the repair again (${shellQuote(preview)}) and approve its new hash.`,+ { fix: { argv: ['gbrain', 'sync', '--source', sourceId, '--no-pull'], consent: [], actor: 'agent', requires_exclusive: false,+ why: `Finishes source ${sourceId}'s unfinished sync cursor, which would otherwise race the repair of a file it still names.` } });+ }+ const items = approved.items.map(({ selection: chosen, ...repair }, index) => item(repair, chosen, opts.expect!, index, index === approved.items.length - 1));+ return { items: items.filter(entry => afterCursor(entry.cursor, after)), preview_hash: opts.expect, residuals: {} };+ }+ const residuals: Record<string, number> = {};+ const warnings: string[] = [];+ const found = await scan(engine, scope, selection, residuals, warnings);+ for (const path of found.unknownOnly) warnings.push(`--only ${path}: no such Markdown file or hold in scope; check the source-relative path.`);+ 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]);+ const approvedItems = found.prepared.map(entry => entry.approved);+ const hash = previewHash({ kind: 'frontmatter-v1', brain_id: scope.brain_id, sources, selection, items: approvedItems });+ if (approvedItems.length) await saveApprovedSet<ApprovedSetItem>(engine, { command: 'frontmatter', hash }, approvedItems.map(entry => ({ ...entry, selection })));+ const diffs: FileDiff[] = [+ ...found.prepared.map(entry => ({ source_id: entry.approved.source_id, path: entry.approved.path, class: entry.approved.class, fixes: entry.approved.fixes,+ diff: lineDiff(entry.approved.path, entry.original, entry.content), selected: true })),+ ...found.pending,+ ];+ const counts = { safe: approvedItems.filter(entry => entry.class === 'safe').length, interpretive: approvedItems.filter(entry => entry.class === 'interpretive').length,+ interpretive_pending: diffs.filter(entry => !entry.selected).length, needs_review: found.review.length };+ for (const review of found.review) residuals[`needs_review:${review.code}`] = (residuals[`needs_review:${review.code}`] ?? 0) + 1;+ if (counts.interpretive_pending) residuals.interpretive_pending = counts.interpretive_pending;+ const listing: RepairListing[] = [+ ...diffs.map(entry => ({ item: `${entry.source_id}:${entry.path}`, class: entry.selected ? entry.class : 'interpretive_pending', detail: entry.fixes.join('; ') })),+ ...found.review.map(entry => ({ item: `${entry.source_id}:${entry.path}`, class: 'needs_review', detail: `${entry.code}${entry.reason ? `/${entry.reason}` : ''}: ${entry.resolution}` })),+ ];+ const applyArgv = [...preview, '--apply', '--expect', hash, '--yes'];+ const next_actions: Action[] = [];+ if (approvedItems.length) next_actions.push({ argv: applyArgv, consent: ['destructive'], actor: 'agent', requires_exclusive: false, plan_hash: hash, preview_argv: preview,+ why: `Writes exactly the ${approvedItems.length} previewed file change(s) (${counts.safe} safe, ${counts.interpretive} interpretive) and imports them; a file that changed since this preview is skipped.`,+ user_message: `Repair the frontmatter of ${approvedItems.length} file(s) exactly as the preview showed? Each file is rewritten on disk (only the lines shown change) and imported again.`,+ verify: { argv: ['gbrain', 'sources', 'status', ...(scope.source_ids.length === 1 ? [scope.source_ids[0]!] : []), '--json'] } });+ if (!selection.include_ambiguous && counts.interpretive_pending) next_actions.push({ argv: previewArgv(scope, selection, true), consent: [], actor: 'agent', requires_exclusive: false,+ why: `${counts.interpretive_pending} file(s) need an interpretation (folded lines, duplicate keys, a #-leading title, a slug line, a re-import or a rename re-bind); this preview shows each exact proposal for approval and writes nothing.` });+ const details: FrontmatterPreviewDetails = { counts, samples: Object.fromEntries((['safe', 'interpretive'] as const).flatMap(cls => {+ const sample = diffs.find(entry => entry.class === cls && (entry.selected || cls === 'interpretive'));+ return sample ? [[cls, sample]] : [];+ })), diffs, needs_review: found.review, next_actions };+ return { items: approvedItems.map((repair, index) => item(repair, selection, hash, index, index === approvedItems.length - 1)), preview_hash: hash, residuals, listing,+ ...(warnings.length ? { warnings } : {}), details: details as unknown as Record<string, unknown> };+ },+ async apply(ctx, entry, opts): Promise<RepairItemOutcome> {+ const { repair, selection, hash, last } = entry as FrontmatterItem;+ try { return await applyRepair(ctx, repair, selection, opts?.embed === true); }+ finally { if (last) await clearApprovedSet(ctx.engine, { command: 'frontmatter', hash }); }+ },+ render(details, opts) {+ const d = details as unknown as FrontmatterPreviewDetails;+ const lines = [` classes: safe=${d.counts.safe}, interpretive=${d.counts.interpretive}, interpretive (needs --include-ambiguous)=${d.counts.interpretive_pending}, needs_review=${d.counts.needs_review}`];+ const shown = opts.diff ? d.diffs : Object.values(d.samples);+ for (const diff of shown) lines.push(` ${diff.selected ? diff.class : 'interpretive, not selected'}: ${diff.source_id}:${diff.path}`, ...diff.diff.split('\n').map(line => ` ${line}`));+ if (!opts.diff && d.diffs.length > shown.length) lines.push(` (one sample diff per class; --diff or --json shows all ${d.diffs.length})`);+ for (const review of d.needs_review) lines.push(` needs_review ${review.source_id}:${review.path} [${review.code}${review.reason ? `/${review.reason}` : ''}${review.line !== undefined ? ` line ${review.line}` : ''}]${review.flag ? ` (${review.flag})` : ''}: ${review.resolution}`);+ for (const action of d.next_actions) lines.push(` next: ${shellQuote(action.argv!)}${action.consent.length ? ' (asks the user first: destructive)' : ''}`);+ return lines;+ },+};++async function rootFor(engine: BrainEngine, repair: ApprovedRepair): Promise<string> {+ if (repair.mode === 'managed') return (await managedRepairRoot(engine, repair.source_id)).root;+ const [row] = await engine.executeRaw<{ local_path: string | null }>('SELECT local_path FROM sources WHERE id=$1', [repair.source_id]);+ const root = row?.local_path ?? (repair.source_id === 'default' ? await engine.getConfig('sync.repo_path') : null);+ if (!root) throw opError('source_changed', `Source ${repair.source_id} has no local checkout any more, so nothing was written.`, 'Preview the repair again on the host that holds the checkout.');+ return root;+}++/** Re-derives one approved change from the file as it is and applies it only when everything still matches. */+async function applyRepair(ctx: OperationContext, repair: ApprovedRepair, selection: Selection, embed: boolean): Promise<RepairItemOutcome> {+ const changed = (reason: string): RepairItemOutcome => ({ applied: false, outcome: 'changed_since_preview', reason, detail: { path: repair.path } });+ const root = await rootFor(ctx.engine, repair);+ const target = join(root, repair.path);+ if (!existsSync(target) || sha256(readFileSync(target)) !== repair.before) return changed(`${repair.path} changed on disk since the preview`);+ const src: SourceRoot = { sourceId: repair.source_id, incarnation: '', mode: repair.mode, root };+ const holds = (await readGitSourceHolds(ctx.engine, { sourceIds: [repair.source_id] }))[0]?.holds ?? [];+ const hold = holds.find(entry => entry.path === repair.path);+ const fileCtx: FileContext = { engine: ctx.engine, src, includeAmbiguous: selection.include_ambiguous, pages: await pagesByOrigin(ctx.engine, repair.source_id) };+ const analysis = await analyzeFile(fileCtx, repair.path, hold);+ if (!analysis?.proposal) return changed('the file no longer needs this change');+ const bound = await bindProposal(fileCtx, repair.path, hold, analysis.proposal, await repairScreenConfig(ctx.engine, repair.source_id));+ if (!('approved' in bound)) return { applied: false, outcome: 'needs_review', reason: bound.resolution, detail: { path: repair.path, code: bound.code } };+ const now = bound.approved;+ if (now.after !== repair.after || now.class !== repair.class || now.revision !== repair.revision || now.result_digest !== repair.result_digest || now.slug !== repair.slug) {+ return changed('the proposal or the page it publishes differs from the preview');+ }+ if (repair.mode === 'managed') {+ try {+ const outcome = await submitManagedFileRepair({ ...ctx, remote: false }, { sourceId: repair.source_id, requestId: await repairRequestId(ctx, 'frontmatter', repair, `${repair.before}:${repair.after}`),+ slug: repair.slug, path: repair.path, sourcePath: repair.source_path, content: bound.content, beforeHash: repair.before, resultDigest: repair.result_digest,+ ...(repair.revision ? { expected_revision: repair.revision } : {}), ...(repair.rename_from ? { renameFrom: repair.rename_from } : {}), noEmbed: !embed });+ const persistence = outcome.persistence as { git_state?: string } | undefined;+ return { applied: true, outcome: 'repaired', detail: { path: repair.path, written: repair.before !== repair.after, imported: outcome.status, hold_cleared: outcome.hold_cleared === true,+ committed: persistence?.git_state ?? 'not_requested' } };+ } catch (error) {+ if (error instanceof OperationError && ['changed_since_preview', 'revision_conflict', 'page_identity_changed'].includes(error.code)) return changed(error.message);+ if (error instanceof OperationError && error.code === 'source_changed') return { applied: false, outcome: 'refused', reason: error.message, detail: { path: repair.path } };+ throw error;+ }+ }+ confinedRepairTarget(root, repair.path, repair.source_id);+ let backup: string | undefined;+ if (repair.before !== repair.after) {+ backup = createFrontmatterBackup(target, { sourcePath: root, runId: makeFrontmatterBackupRunId() });+ writeFileSync(target, bound.content);+ }+ if (repair.rename_from) {+ const moved = await ctx.engine.updateSlug(repair.rename_from.slug, repair.slug, { sourceId: repair.source_id });+ if (moved === 1) await ctx.engine.executeRaw('UPDATE pages SET source_path=$1 WHERE id=$2 AND source_id=$3', [repair.source_path, repair.rename_from.pageId, repair.source_id]);+ }+ const imported = await importFromFile(ctx.engine, target, repair.source_path, { sourceId: repair.source_id, noEmbed: !embed });+ const ok = imported.status !== 'error' && !imported.refusal;+ const holdCleared = ok && await clearGitHold(ctx.engine, { sourceId: repair.source_id, incarnation: (await ctx.engine.executeRaw<{ incarnation: string }>(+ 'SELECT incarnation::text AS incarnation FROM sources WHERE id=$1', [repair.source_id]))[0]!.incarnation, path: repair.path, observedAt: new Date().toISOString() });+ return { applied: ok, outcome: ok ? 'repaired' : 'import_refused', ...(ok ? {} : { reason: imported.error ?? 'the import refused the repaired file' }),+ detail: { path: repair.path, written: repair.before !== repair.after, ...(backup ? { backup } : {}), imported: imported.status, hold_cleared: holdCleared,+ committed: 'commit_step', commit_step: `git -C ${shellQuote([root])} add -- ${shellQuote([repair.path])} && git -C ${shellQuote([root])} commit -m ${shellQuote([`fix(frontmatter): repair ${repair.path}`])}` } };+}diff --git a/src/core/repair/registry.ts b/src/core/repair/registry.tsindex 288d8aa1da..5a67806c6c 100644--- a/src/core/repair/registry.ts+++ b/src/core/repair/registry.ts@@ -38,6 +38,7 @@ import { capturedFactsRepair } from './captured-facts.ts';import { loopFactsRepair } from './loop-facts.ts';import { orphanChildrenRepair } from './orphan-children.ts';import { failedWritesRepair } from './failed-writes.ts';+import { frontmatterRepair } from './frontmatter.ts';import { attributionBackfillRepair } from './attribution-backfill.ts';import { plannerStatsRepair } from './planner-stats.ts';import { ERROR_CATALOGUE, catalogueError } from '../error-catalogue.ts';@@ -54,6 +55,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;+ /** `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';}const SPECS: Record<RepairKind, Omit<RepairKindSpec, 'kind'>> = {@@ -156,6 +159,14 @@ const SPECS: Record<RepairKind, Omit<RepairKindSpec, 'kind'>> = {+ 'reconcile, relink, maintenance) are counted with the command that produces them again. Preview-bound: --apply --expect <hash> replays exactly '+ 'the previewed set under new request ids, after re-checking each write\'s original authority; the failed receipts stay as history.',},+ frontmatter: {+ handler: frontmatterRepair, embeds: 'effect', checks: ['git_held_files', 'frontmatter_repairable'], explicit_only: true, consent: 'destructive',+ summary: 'Fix files whose YAML frontmatter gbrain holds or reads only by guessing (#5988), and pages an older import stored wrong: per file the minimal '+ + 'line change (safe: quoting a value as gbrain already reads it, NUL bytes, nested quotes; interpretive with --include-ambiguous: folded lines, '+ + 'duplicate keys, #-leading titles, a missing closing fence, a conflicting slug line, re-imports and rename re-binds). --only/--skip <path> '+ + '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.',+ },'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), '@@ -223,12 +234,12 @@ export async function repairRunner(engine: BrainEngine, opts: { apply: boolean;return {embeddingModel,/** `explicit`: the operator named `kind`; required for explicit-only kinds. */- async run(kind: RepairKind, scope: RepairScope, run: { limit?: number; sourceFlag?: string; explicit?: boolean; expect?: string; includeAmbiguous?: boolean } = {}): Promise<RepairResult> {+ async run(kind: RepairKind, scope: RepairScope, run: { limit?: number; sourceFlag?: string; explicit?: boolean; expect?: string; includeAmbiguous?: boolean; only?: string[]; skip?: string[] } = {}): Promise<RepairResult> {const ctx = { engine, config, logger, dryRun: !opts.apply, remote: false, sourceId: scope.source_ids[0] } as OperationContext;const spec = repairSpec(kind);return runRepair(ctx, spec.handler, scope, { apply: opts.apply, limit: run.limit, embeddingModel, sourceFlag: run.sourceFlag,embed: !opts.noEmbed && embeddingModel !== undefined, applyArgs: opts.noEmbed && spec.embeds === 'inline' ? ['--no-embed'] : [],- explicit: run.explicit, expect: run.expect, includeAmbiguous: run.includeAmbiguous });+ explicit: run.explicit, expect: run.expect, includeAmbiguous: run.includeAmbiguous, only: run.only, skip: run.skip });},};}diff --git a/test/fix-wave-5-integration.test.ts b/test/fix-wave-5-integration.test.tsindex 4e3cb08935..95445c1857 100644--- a/test/fix-wave-5-integration.test.ts+++ b/test/fix-wave-5-integration.test.ts@@ -194,7 +194,8 @@ for (const backend of testBackends()) {const activeFacts = async () => (await engine.executeRaw<{ n: number }>("SELECT count(*)::int AS n FROM facts WHERE source_markdown_slug='conversations/expired' AND expired_at IS NULL"))[0].n;const untouched = async () => { expect(await liveAtoms()).toBe(30); expect(await activeFacts()).toBe(0); };const previews = { 'google-file-modes': 'gbrain repair google-file-modes', 'stale-atoms': 'gbrain repair stale-atoms', 'extractor-facts': 'gbrain repair extractor-facts',- 'captured-facts': 'gbrain repair captured-facts', 'loop-facts': 'gbrain repair loop-facts', 'orphan-children': 'gbrain repair orphan-children', 'failed-writes': 'gbrain repair failed-writes' };+ 'captured-facts': 'gbrain repair captured-facts', 'loop-facts': 'gbrain repair loop-facts', 'orphan-children': 'gbrain repair orphan-children', 'failed-writes': 'gbrain repair failed-writes',+ frontmatter: 'gbrain repair frontmatter' };// The post-upgrade banner names both findings with the kind's read-only preview.const banner = await postUpgradeRecoveryBanner(engine, 'host');diff --git a/test/repair-explicit-only.test.ts b/test/repair-explicit-only.test.tsindex fdc46f7cc2..3dbaec1fac 100644--- a/test/repair-explicit-only.test.ts+++ b/test/repair-explicit-only.test.ts@@ -24,7 +24,7 @@ import { REPAIR_HELP, parseRepairArgs, runRepairCommand } from '../src/commands/import { _resetCliExitVerdictForTests, currentExitCode } from '../src/core/cli-force-exit.ts';import { withEnv } from './helpers/with-env.ts';-const EXPLICIT: RepairKind[] = ['google-file-modes', 'stale-atoms', 'extractor-facts', 'captured-facts', 'loop-facts', 'orphan-children', 'failed-writes'];+const EXPLICIT: RepairKind[] = ['google-file-modes', 'stale-atoms', 'extractor-facts', 'captured-facts', 'loop-facts', 'orphan-children', 'failed-writes', 'frontmatter'];let engine: PGLiteEngine;const home = mkdtempSync(join(tmpdir(), 'gbrain-repair-explicit-'));diff --git a/test/repair-frontmatter.test.ts b/test/repair-frontmatter.test.tsnew file mode 100644index 0000000000..520dc4003f--- /dev/null+++ b/test/repair-frontmatter.test.ts@@ -0,0 +1,410 @@+/**+ * #5988 Lane 3: `gbrain repair frontmatter`. One previewed, hash-bound repair+ * per file: safe quoting by default, interpretations only with+ * --include-ambiguous, --only/--skip bound into the hash, needs_review never+ * written, and managed publication through `managed_file_repair` (exact+ * bytes, import, hold clear and Git effect in one coordinated write).+ */+import { afterAll, beforeAll, expect, test } from 'bun:test';+import { execFileSync } from 'node:child_process';+import { randomUUID } from 'node:crypto';+import { chmodSync, existsSync, mkdirSync, mkdtempSync, readFileSync, readdirSync, rmSync, symlinkSync, writeFileSync } from 'node:fs';+import { tmpdir } from 'node:os';+import { join } from 'node:path';+import type { BrainEngine } from '../src/core/engine.ts';+import { PGLiteEngine } from '../src/core/pglite-engine.ts';+import { OperationError, type OperationContext } from '../src/core/ops/contract.ts';+import { claimWorktree } from '../src/core/persistence/ownership.ts';+import { disposePersistenceConsumer } from '../src/core/persistence/service.ts';+import { performManagedSync } from '../src/core/persistence/sync-run.ts';+import { sha256 } from '../src/core/persistence/digest.ts';+import { localHostId } from '../src/core/persistence/identity.ts';+import { runPersistenceEffects } from '../src/core/persistence/effects.ts';+import { readGitSourceHolds } from '../src/core/persistence/sync-holds.ts';+import { submitPageMutation } from '../src/core/persistence/page-mutations.ts';+import { confinedRepairTarget, submitManagedFileRepair } from '../src/core/persistence/file-repair.ts';+import { resolveRepairScope, type RepairResult } from '../src/core/repair/core.ts';+import { repairRunner } from '../src/core/repair/registry.ts';+import type { FrontmatterPreviewDetails } from '../src/core/repair/frontmatter.ts';+import { runRepairCommand } from '../src/commands/repair.ts';+import { _resetCliExitVerdictForTests, currentExitCode } from '../src/core/cli-force-exit.ts';+import { isolatedPersistencePostgres } from './helpers/persistence-postgres.ts';+import { testBackends } from './helpers/test-backends.ts';+import { withEnv } from './helpers/with-env.ts';++const backends = testBackends();+const home = mkdtempSync(join(tmpdir(), 'gbrain-repair-frontmatter-'));+const engines: BrainEngine[] = [];+let closePostgres: (() => Promise<void>) | undefined;+const env = { GBRAIN_HOME: home, GBRAIN_SYNC_FAILURES_DIR: home, OPENAI_API_KEY: undefined, VOYAGE_API_KEY: undefined, ANTHROPIC_API_KEY: undefined };+const git = (root: string, ...args: string[]) => execFileSync('git', ['-C', root, ...args], { encoding: 'utf8', stdio: ['ignore', 'pipe', 'pipe'] }).trim();+const commit = (root: string, message = 'content') => { git(root, 'add', '-A'); git(root, '-c', 'user.name=Example', '-c', '[email protected]', 'commit', '-qm', message); return git(root, 'rev-parse', 'HEAD'); };+const note = (title: string, body = 'A synthetic observation.') => `---\ntitle: ${title}\n---\n${body}\n`;+/** Imports today only after quoting: the safe class. */+const QUOTABLE = '---\ntitle: Payments roundup\nauthor: alice-example (citing acme-example) (original: https://example.invalid/a)\n---\nA synthetic roundup.\n';+/** Unquoted continuation lines: held as needs_interpretation, folded only under --include-ambiguous. */+const folded = (n: number) => `---\ntitle: alice-example post ${n}\nsecond line of post ${n}\n---\nA synthetic post.\n`;+/** Mis-indented mapping entry: no rule, so needs_review. */+const UNFIXABLE = '---\ntitle: Broken\n author: nobody\n tags: [a\n---\nBody.\n';+const LONG = Array.from({ length: 40 }, (_, i) => `Line ${i} of a long synthetic observation that keeps Git rename detection certain.`).join('\n');+const long = (title: string) => `---\ntitle: ${title}\n---\n${LONG}\n`;+const longBroken = `---\ntitle: alice-example first line\nalice-example second line\n---\n${LONG}\n`;++beforeAll(async () => {+ if (backends.includes('pglite')) { const engine = new PGLiteEngine(); await engine.connect({}); await engine.initSchema(); engines.push(engine); }+ if (backends.includes('postgres')) { const pg = await isolatedPersistencePostgres(process.env.DATABASE_URL!); engines.push(pg.engine); closePostgres = pg.close; }+}, 120_000);++afterAll(async () => {+ await withEnv(env, async () => { for (const engine of engines) { await disposePersistenceConsumer(engine); await engine.disconnect(); } });+ await closePostgres?.(); rmSync(home, { recursive: true, force: true });+});++const quiet = { info() {}, warn() {}, error() {} };++async function managed(engine: BrainEngine, files: Record<string, string>) {+ const id = `fm-${randomUUID().replace(/-/g, '').slice(0, 20)}`, root = join(home, id);+ mkdirSync(root, { recursive: true }); git(root, 'init', '-q');+ git(root, 'config', 'user.name', 'Example'); git(root, 'config', 'user.email', '[email protected]');+ // Git target effects commit only in a durability-hardened checkout.+ writeFileSync(join(root, '.git', 'hooks', 'post-commit'), '#!/bin/sh\n# gbrain brain-durability post-commit hook (v0.42.44+)\n'); chmodSync(join(root, '.git', 'hooks', 'post-commit'), 0o755);+ const write = (path: string, content: string) => { mkdirSync(join(root, path, '..'), { recursive: true }); writeFileSync(join(root, path), content); };+ for (const [path, content] of Object.entries(files)) write(path, content);+ commit(root, 'fixture');+ await engine.executeRaw('UPDATE persistence_brain SET enabled=false WHERE singleton=1');+ await engine.executeRaw("INSERT INTO sources(id,name,local_path,config) VALUES($1,$1,$2,'{}')", [id, root]);+ await claimWorktree(engine, id, root);+ await engine.executeRaw('UPDATE persistence_brain SET enabled=true WHERE singleton=1');+ return fixture(engine, id, root, write);+}++function fixture(engine: BrainEngine, id: string, root: string, write: (path: string, content: string) => void) {+ const sync = () => performManagedSync(engine, { sourceId: id, noPull: true, noEmbed: true, noExtract: true });+ const holds = async () => (await readGitSourceHolds(engine, { sourceIds: [id] }))[0]?.holds ?? [];+ const run = async (opts: { apply?: boolean; expect?: string; includeAmbiguous?: boolean; only?: string[]; skip?: string[] } = {}) => {+ const runner = await repairRunner(engine, { apply: opts.apply === true, noEmbed: true, logger: quiet });+ return runner.run('frontmatter', await resolveRepairScope(engine, id), { explicit: true, sourceFlag: id, expect: opts.expect,+ includeAmbiguous: opts.includeAmbiguous, only: opts.only, skip: opts.skip });+ };+ const read = (path: string) => readFileSync(join(root, path), 'utf8');+ return { id, root, sync, holds, run, read, write };+}++/** Runs queued effects here and waits for the consumer's, until no Git effect of the source is open. */+async function gitEffectsSettled(engine: BrainEngine, sourceId: string) {+ for (let i = 0; i < 100; i++) {+ await runPersistenceEffects(engine, { engine: engine.kind }, { hostId: localHostId(), limit: 10 });+ const open = await engine.executeRaw("SELECT 1 FROM persistence_effects WHERE source_id=$1 AND kind='git' AND state<>'committed'", [sourceId]);+ if (!open.length) return engine.executeRaw<{ outcome: Record<string, unknown> }>("SELECT outcome FROM persistence_effects WHERE source_id=$1 AND kind='git' ORDER BY id", [sourceId]);+ await Bun.sleep(100);+ }+ throw new Error('git effects did not settle');+}++const details = (result: RepairResult) => result.details as unknown as FrontmatterPreviewDetails;++async function each(run: (engine: BrainEngine) => Promise<void>) {+ await withEnv(env, async () => {+ for (const engine of engines) {+ try { await run(engine); } finally { await disposePersistenceConsumer(engine); }+ }+ });+}++async function refusal(run: () => Promise<unknown>): Promise<OperationError> {+ try { await run(); } catch (error) { if (error instanceof OperationError) return error; throw error; }+ throw new Error('expected a refusal');+}++test('safe preview quotes only, hashes its set, and the apply writes exactly the previewed bytes', () => each(async engine => {+ const s = await managed(engine, { 'notes/roundup.md': QUOTABLE, 'notes/ok.md': note('Ok') });+ await s.sync();+ const before = await engine.getPage('notes/roundup', { sourceId: s.id });+ expect(before?.frontmatter.author).toBe('alice-example (citing acme-example) (original: https://example.invalid/a)');+ const preview = await s.run();+ expect(preview).toMatchObject({ mode: 'dry_run', affected: 1 });+ expect(details(preview).counts).toMatchObject({ safe: 1, interpretive: 0, needs_review: 0 });+ expect(details(preview).samples.safe!.diff).toContain('+author: "alice-example (citing acme-example) (original: https://example.invalid/a)"');+ const hash = preview.apply_command.split('--expect ')[1]!.split(' ')[0]!;+ expect(preview.apply_command).toBe(`gbrain repair frontmatter --source ${s.id} --apply --expect ${hash} --yes`);+ expect((await s.run()).apply_command).toBe(preview.apply_command);+ expect(s.read('notes/roundup.md')).toBe(QUOTABLE);+ expect((await refusal(() => s.run({ apply: true, expect: 'f'.repeat(64) }))).code).toBe('preview_changed');+ const applied = await s.run({ apply: true, expect: hash });+ expect(applied).toMatchObject({ applied: 1, outcomes: { repaired: 1 } });+ const expected = QUOTABLE.replace('author: alice-example (citing acme-example) (original: https://example.invalid/a)',+ 'author: "alice-example (citing acme-example) (original: https://example.invalid/a)"');+ expect(s.read('notes/roundup.md')).toBe(expected);+ expect(applied.outcome_items![0]!.detail).toMatchObject({ path: 'notes/roundup.md', written: true, committed: 'queued' });+ const page = await engine.getPage('notes/roundup', { sourceId: s.id });+ expect(page?.id).toBe(before!.id);+ expect(page?.frontmatter.author).toBe(before!.frontmatter.author);+ // The Git target effect commits the repaired file like any coordinated page write.+ await gitEffectsSettled(engine, s.id);+ expect(git(s.root, 'status', '--porcelain', '--', 'notes/roundup.md')).toBe('');+ expect(git(s.root, 'show', 'HEAD:notes/roundup.md')).toBe(expected.trimEnd());+}), 180_000);++test('interpretations wait for --include-ambiguous (two-pass next_action), which changes the hash; --only approves one file and leaves the other held', () => each(async engine => {+ const s = await managed(engine, { 'notes/a.md': folded(1), 'notes/b.md': folded(2), 'notes/roundup.md': QUOTABLE });+ expect((await s.sync()).held_count).toBe(2);+ const safe = await s.run();+ expect(details(safe).counts).toMatchObject({ safe: 1, interpretive: 0, interpretive_pending: 2 });+ const safeHash = safe.apply_command.split('--expect ')[1]!.split(' ')[0]!;+ expect(details(safe).next_actions.map(action => action.argv)).toEqual([+ ['gbrain', 'repair', 'frontmatter', '--source', s.id, '--apply', '--expect', safeHash, '--yes'],+ ['gbrain', 'repair', 'frontmatter', '--source', s.id, '--include-ambiguous'],+ ]);+ expect(details(safe).next_actions[0]).toMatchObject({ consent: ['destructive'], plan_hash: safeHash });+ const wide = await s.run({ includeAmbiguous: true });+ expect(details(wide).counts).toMatchObject({ safe: 1, interpretive: 2, interpretive_pending: 0 });+ expect(wide.apply_command).not.toContain(safeHash);+ expect(details(wide).diffs.find(diff => diff.path === 'notes/a.md')!.diff).toContain('+title: "alice-example post 1\\nsecond line of post 1"');+ // The safe apply never writes an interpretive change.+ expect(await s.run({ apply: true, expect: safeHash })).toMatchObject({ applied: 1 });+ expect(s.read('notes/a.md')).toBe(folded(1));+ const one = await s.run({ includeAmbiguous: true, only: ['notes/a.md'] });+ expect(details(one).counts).toMatchObject({ interpretive: 1 });+ const oneHash = one.apply_command.split('--expect ')[1]!.split(' ')[0]!;+ expect(one.apply_command).toBe(`gbrain repair frontmatter --source ${s.id} --only notes/a.md --include-ambiguous --apply --expect ${oneHash} --yes`);+ expect((await refusal(() => s.run({ apply: true, expect: oneHash, includeAmbiguous: true }))).code).toBe('preview_changed');+ const applied = await s.run({ apply: true, expect: oneHash, includeAmbiguous: true, only: ['notes/a.md'] });+ expect(applied.outcome_items?.[0]?.detail).toMatchObject({ path: 'notes/a.md', imported: 'created', hold_cleared: true });+ expect((await engine.getPage('notes/a', { sourceId: s.id }))?.title).toBe('alice-example post 1\nsecond line of post 1');+ expect(s.read('notes/b.md')).toBe(folded(2));+ expect((await s.holds()).map(hold => hold.path)).toEqual(['notes/b.md']);+ expect(await engine.getPage('notes/b', { sourceId: s.id })).toBeNull();+}), 180_000);++test('a file edited after the preview is changed_since_preview and keeps its new bytes; needs_review files are listed with the manual fix and never written', () => each(async engine => {+ const s = await managed(engine, { 'notes/roundup.md': QUOTABLE, 'notes/broken.md': UNFIXABLE });+ await s.sync();+ const preview = await s.run({ includeAmbiguous: true });+ expect(details(preview).needs_review).toEqual([expect.objectContaining({ path: 'notes/broken.md', code: 'invalid_frontmatter' })]);+ expect(details(preview).needs_review[0]!.resolution).toContain('notes/broken.md');+ expect(preview.affected).toBe(1);+ const edited = QUOTABLE.replace('A synthetic roundup.', 'An edited roundup.');+ s.write('notes/roundup.md', edited);+ const hash = preview.apply_command.split('--expect ')[1]!.split(' ')[0]!;+ const applied = await s.run({ apply: true, expect: hash, includeAmbiguous: true });+ expect(applied).toMatchObject({ applied: 0, outcomes: { changed_since_preview: 1 } });+ expect(s.read('notes/roundup.md')).toBe(edited);+ expect(s.read('notes/broken.md')).toBe(UNFIXABLE);+}), 180_000);++const localCtx = (engine: BrainEngine, sourceId: string, remote = false) =>+ ({ engine, config: { engine: engine.kind }, logger: quiet, dryRun: false, remote, sourceId }) as unknown as OperationContext;++test('a held modified file: put_page stays refused for drift, the repair writes the exact bytes under its hash and updates the page', () => each(async engine => {+ const s = await managed(engine, { 'notes/post.md': note('Original') });+ await s.sync();+ const page = (await engine.getPage('notes/post', { sourceId: s.id }))!;+ s.write('notes/post.md', folded(7)); commit(s.root, 'broken edit');+ expect((await s.sync()).held?.[0]).toMatchObject({ path: 'notes/post.md', stale: true });+ const revision = (await engine.readPageSnapshot('notes/post', { sourceId: s.id }))!.revision;+ const drift = await refusal(() => submitPageMutation(localCtx(engine, s.id), { operation: 'put_page',+ params: { slug: 'notes/post', content: note('Agent write'), source_id: s.id, expected_revision: revision } }));+ expect(drift.detail).toBe('file_database_drift');+ const preview = await s.run({ includeAmbiguous: true });+ const hash = preview.apply_command.split('--expect ')[1]!.split(' ')[0]!;+ const proposed = details(preview).diffs[0]!;+ expect(proposed).toMatchObject({ path: 'notes/post.md', class: 'interpretive', selected: true });+ const applied = await s.run({ apply: true, expect: hash, includeAmbiguous: true });+ expect(applied.outcome_items?.[0]?.detail).toMatchObject({ imported: 'updated', hold_cleared: true, written: true });+ expect(s.read('notes/post.md')).toBe('---\ntitle: "alice-example post 7\\nsecond line of post 7"\n---\nA synthetic post.\n');+ const after = (await engine.getPage('notes/post', { sourceId: s.id }))!;+ expect(after.id).toBe(page.id);+ expect(after.title).toBe('alice-example post 7\nsecond line of post 7');+ expect(await s.holds()).toEqual([]);+ // A later sync of the committed repair imports nothing new and holds nothing.+ await gitEffectsSettled(engine, s.id);+ expect((await s.sync()).held_count ?? 0).toBe(0);+}), 180_000);++test('a repaired file whose import would keep a database-only tag is needs_review (canonical overlay), never written', () => each(async engine => {+ const s = await managed(engine, { 'notes/post.md': note('Original') });+ await s.sync();+ await engine.executeRaw('UPDATE persistence_brain SET enabled=false WHERE singleton=1');+ await engine.addTag('notes/post', 'kept-in-db', { sourceId: s.id });+ await engine.executeRaw('UPDATE persistence_brain SET enabled=true WHERE singleton=1');+ s.write('notes/post.md', folded(3)); commit(s.root, 'broken edit');+ await s.sync();+ const preview = await s.run({ includeAmbiguous: true });+ expect(preview.affected).toBe(0);+ expect(details(preview).needs_review).toEqual([expect.objectContaining({ path: 'notes/post.md', code: 'canonical_overlay' })]);+ expect(s.read('notes/post.md')).toBe(folded(3));+}), 180_000);++test('apply refuses while an unfinished managed sync cursor still names a selected file, and names the sync to finish', () => each(async engine => {+ const s = await managed(engine, { 'notes/roundup.md': QUOTABLE });+ await s.sync();+ const preview = await s.run();+ const hash = preview.apply_command.split('--expect ')[1]!.split(' ')[0]!;+ const runId = randomUUID();+ await engine.executeRaw(`INSERT INTO op_checkpoints(op,fingerprint,completed_keys) VALUES('managed-sync',$1,$2::text::jsonb)`,+ [`fixture-${runId}`, JSON.stringify([{ sourceId: s.id, runId, index: 0, total: 1 }])]);+ await engine.executeRaw(`INSERT INTO op_checkpoints(op,fingerprint,completed_keys) VALUES('managed-sync-manifest',$1,$2::text::jsonb)`,+ [runId, JSON.stringify([{ path: 'notes/roundup.md', sourcePath: 'notes/roundup.md', action: 'import', working: false }])]);+ try {+ const error = await refusal(() => s.run({ apply: true, expect: hash }));+ expect(error.code).toBe('sync_in_progress');+ expect(error.suggestion).toContain(`gbrain sync --source ${s.id} --no-pull`);+ expect(s.read('notes/roundup.md')).toBe(QUOTABLE);+ } finally {+ await engine.executeRaw("DELETE FROM op_checkpoints WHERE (op='managed-sync' AND fingerprint=$1) OR (op='managed-sync-manifest' AND fingerprint=$2)", [`fixture-${runId}`, runId]);+ }+}), 180_000);++test('managed_file_repair is trusted-local only: MCP put_page cannot name it and a remote caller is refused before admission', () => each(async engine => {+ const s = await managed(engine, { 'notes/roundup.md': QUOTABLE });+ await s.sync();+ const params = { slug: 'notes/roundup', source_id: s.id, kind: 'managed_file_repair', content: note('Injected'), path: 'notes/roundup.md', sourcePath: 'notes/roundup.md' };+ const viaMcp = await refusal(() => submitPageMutation(localCtx(engine, s.id, true), { operation: 'put_page', params }));+ expect(viaMcp.code).toBe('invalid_params');+ const viaLocalPut = await refusal(() => submitPageMutation(localCtx(engine, s.id), { operation: 'put_page', params }));+ expect(viaLocalPut.code).toBe('invalid_params');+ const remote = await refusal(() => submitManagedFileRepair(localCtx(engine, s.id, true), { sourceId: s.id, requestId: randomUUID(), slug: 'notes/roundup',+ path: 'notes/roundup.md', sourcePath: 'notes/roundup.md', content: note('Injected'), beforeHash: sha256(QUOTABLE), resultDigest: 'x', noEmbed: true }));+ expect(remote).toMatchObject({ code: 'permission_denied', reason: 'trusted_cli_required' });+ expect(s.read('notes/roundup.md')).toBe(QUOTABLE);+}), 180_000);++test('repair paths are confined: climbing, absolute and symlinked paths are refused before anything is written', () => {+ const root = mkdtempSync(join(home, 'confine-'));+ const outside = mkdtempSync(join(home, 'outside-'));+ writeFileSync(join(outside, 'secret.md'), note('Outside'));+ mkdirSync(join(root, 'notes'));+ writeFileSync(join(root, 'notes', 'ok.md'), note('Ok'));+ symlinkSync(outside, join(root, 'linked'));+ symlinkSync(join(outside, 'secret.md'), join(root, 'notes', 'link.md'));+ expect(confinedRepairTarget(root, 'notes/ok.md', 'src')).toBe(join(root, 'notes', 'ok.md'));+ for (const path of ['../outside/secret.md', join(outside, 'secret.md'), 'linked/secret.md', 'notes/link.md', 'notes/missing.md']) {+ let error: unknown;+ try { confinedRepairTarget(root, path, 'src'); } catch (caught) { error = caught; }+ expect(error).toBeInstanceOf(OperationError);+ expect((error as OperationError).code).toBe('source_changed');+ }+});++test('a held renamed file: the repair moves the old page with its id instead of creating a second page', () => each(async engine => {+ const s = await managed(engine, { 'notes/old.md': long('Old') });+ await s.sync();+ const page = (await engine.getPage('notes/old', { sourceId: s.id }))!;+ git(s.root, 'mv', 'notes/old.md', 'notes/new.md'); s.write('notes/new.md', longBroken); commit(s.root, 'rename to broken');+ await s.sync();+ expect((await s.holds())[0]).toMatchObject({ path: 'notes/new.md', meta: { rename_from: { slug: 'notes/old', pageId: page.id } } });+ const preview = await s.run({ includeAmbiguous: true });+ const hash = preview.apply_command.split('--expect ')[1]!.split(' ')[0]!;+ const applied = await s.run({ apply: true, expect: hash, includeAmbiguous: true });+ expect(applied.outcome_items?.[0]?.detail).toMatchObject({ imported: 'renamed', hold_cleared: true });+ expect((await engine.getPage('notes/new', { sourceId: s.id }))?.id).toBe(page.id);+ expect(await engine.getPage('notes/old', { sourceId: s.id })).toBeNull();+ const [{ count }] = await engine.executeRaw<{ count: number }>('SELECT count(*)::int AS count FROM pages WHERE source_id=$1 AND deleted_at IS NULL', [s.id]);+ expect(Number(count)).toBe(1);+}), 180_000);++test('a rename held because the old page changed is re-bound to its current revision only under --include-ambiguous', () => each(async engine => {+ const s = await managed(engine, { 'notes/x.md': long('X') });+ await s.sync();+ const x = (await engine.getPage('notes/x', { sourceId: s.id }))!;+ git(s.root, 'mv', 'notes/x.md', 'notes/y.md'); s.write('notes/y.md', longBroken); commit(s.root, 'x to y broken');+ await s.sync();+ await engine.executeRaw('UPDATE persistence_brain SET enabled=false WHERE singleton=1');+ await engine.executeRaw('UPDATE pages SET knowledge_revision=gen_random_uuid() WHERE id=$1', [x.id]);+ await engine.executeRaw('UPDATE persistence_brain SET enabled=true WHERE singleton=1');+ s.write('notes/y.md', long('Y')); commit(s.root, 'fix y');+ await s.sync();+ expect((await s.holds())[0]).toMatchObject({ path: 'notes/y.md', code: 'rename_held' });+ const safe = await s.run();+ expect(details(safe).counts).toMatchObject({ safe: 0, interpretive_pending: 1 });+ const preview = await s.run({ includeAmbiguous: true });+ expect(details(preview).diffs[0]!.fixes.join(' ')).toContain('Re-bind the rename of notes/y.md to page notes/x');+ const hash = preview.apply_command.split('--expect ')[1]!.split(' ')[0]!;+ const applied = await s.run({ apply: true, expect: hash, includeAmbiguous: true });+ expect(applied.outcome_items?.[0]?.detail).toMatchObject({ imported: 'renamed', hold_cleared: true, written: false });+ expect((await engine.getPage('notes/y', { sourceId: s.id }))).toMatchObject({ id: x.id, title: 'Y' });+ expect(await s.holds()).toEqual([]);+}), 180_000);++test('database side: a page whose body begins with its own frontmatter block is re-imported from its clean file under --include-ambiguous', () => each(async engine => {+ const s = await managed(engine, { 'notes/fact.md': note('Real title', 'The real body.'), 'notes/twice.md': `---\ntitle: Outer\n---\n---\ntitle: Inner\n---\nBody.\n` });+ await s.sync();+ await engine.executeRaw('UPDATE persistence_brain SET enabled=false WHERE singleton=1');+ await engine.executeRaw("UPDATE pages SET compiled_truth=$2, title='Fact' WHERE source_id=$1 AND slug='notes/fact'", [s.id, '---\ntitle: Real title\n---\nThe real body.']);+ await engine.executeRaw("UPDATE pages SET title='Twice' WHERE source_id=$1 AND slug='notes/twice'", [s.id]);+ await engine.executeRaw('UPDATE persistence_brain SET enabled=true WHERE singleton=1');+ const safe = await s.run();+ expect(details(safe).counts.interpretive_pending).toBe(1);+ const preview = await s.run({ includeAmbiguous: true });+ expect(details(preview).diffs).toEqual([expect.objectContaining({ path: 'notes/fact.md', class: 'interpretive' })]);+ expect(details(preview).needs_review).toEqual([expect.objectContaining({ path: 'notes/twice.md', code: 'embedded_frontmatter' })]);+ const hash = preview.apply_command.split('--expect ')[1]!.split(' ')[0]!;+ const applied = await s.run({ apply: true, expect: hash, includeAmbiguous: true });+ expect(applied.outcome_items?.[0]?.detail).toMatchObject({ imported: 'updated', written: false });+ const fixed = (await engine.getPage('notes/fact', { sourceId: s.id }))!;+ expect(fixed.title).toBe('Real title');+ expect(fixed.compiled_truth.trim()).toBe('The real body.');+ expect(s.read('notes/fact.md')).toBe(note('Real title', 'The real body.'));+}), 180_000);++test('legacy brain: the apply backs the file up, writes it, imports it, clears its hold and prints the commit step', async () => {+ const engine = new PGLiteEngine(); await engine.connect({}); await engine.initSchema();+ try {+ await withEnv(env, async () => {+ await engine.executeRaw('UPDATE persistence_brain SET enabled=false WHERE singleton=1');+ const id = 'legacy-fm', root = join(home, id);+ mkdirSync(join(root, 'notes'), { recursive: true });+ writeFileSync(join(root, 'notes', 'roundup.md'), QUOTABLE);+ await engine.executeRaw("INSERT INTO sources(id,name,local_path,config) VALUES($1,$1,$2,'{}')", [id, root]);+ const s = fixture(engine, id, root, (path, content) => writeFileSync(join(root, path), content));+ const preview = await s.run();+ expect(details(preview).counts.safe).toBe(1);+ const hash = preview.apply_command.split('--expect ')[1]!.split(' ')[0]!;+ const applied = await s.run({ apply: true, expect: hash });+ const detail = applied.outcome_items![0]!.detail!;+ expect(detail).toMatchObject({ path: 'notes/roundup.md', written: true, imported: 'imported', committed: 'commit_step' });+ expect(String(detail.commit_step)).toContain(`git -C ${root} add -- notes/roundup.md`);+ expect(readFileSync(String(detail.backup), 'utf8')).toBe(QUOTABLE);+ expect(s.read('notes/roundup.md')).toContain('author: "alice-example');+ expect((await engine.getPage('notes/roundup', { sourceId: id }))?.frontmatter.author).toBe('alice-example (citing acme-example) (original: https://example.invalid/a)');+ });+ } finally { await engine.disconnect(); }+}, 120_000);++test('the CLI apply asks for destructive consent: without --yes a non-interactive run exits 3 and writes nothing', () => each(async engine => {+ const s = await managed(engine, { 'notes/roundup.md': QUOTABLE });+ await s.sync();+ const hash = (await s.run()).apply_command.split('--expect ')[1]!.split(' ')[0]!;+ _resetCliExitVerdictForTests();+ let printed = '';+ const original = console.log, write = process.stdout.write;+ console.log = (...parts: unknown[]) => { printed += parts.map(String).join(' '); };+ process.stdout.write = ((chunk: string | Uint8Array) => { printed += String(chunk); return true; }) as typeof process.stdout.write;+ try { await withEnv({ GBRAIN_INTERACTIVE: '0', CI: '1' }, () => runRepairCommand(engine, ['frontmatter', '--source', s.id, '--apply', '--expect', hash, '--json'])); }+ finally { console.log = original; process.stdout.write = write; }+ expect(currentExitCode()).toBe(3);+ expect(JSON.parse(printed)).toMatchObject({ code: 'confirmation_required', effects: ['destructive'] });+ expect(s.read('notes/roundup.md')).toBe(QUOTABLE);+ _resetCliExitVerdictForTests();+ console.log = () => {};+ try { await runRepairCommand(engine, ['frontmatter', '--source', s.id, '--apply', '--expect', hash, '--yes', '--json']); } finally { console.log = original; }+ expect(currentExitCode()).toBe(0);+ expect(s.read('notes/roundup.md')).toContain('author: "alice-example');+}), 180_000);++test('database side: a slug-derived title under a file that names one is re-imported; a page whose file now holds a protected key is flagged', () => each(async engine => {+ const s = await managed(engine, { 'notes/launch-plan.md': note('The real launch plan'), 'notes/private.md': note('Private') });+ await s.sync();+ await engine.executeRaw('UPDATE persistence_brain SET enabled=false WHERE singleton=1');+ await engine.executeRaw("UPDATE pages SET title='Launch Plan' WHERE source_id=$1 AND slug='notes/launch-plan'", [s.id]);+ await engine.executeRaw('UPDATE persistence_brain SET enabled=true WHERE singleton=1');+ s.write('notes/private.md', '---\ntitle: Private\nvisibility: private # note: x\n---\nBody.\n'); commit(s.root, 'protected key');+ expect((await s.sync()).held?.[0]).toMatchObject({ path: 'notes/private.md', reason: 'ambiguous_protected_key', stale: true });+ const preview = await s.run({ includeAmbiguous: true });+ expect(details(preview).diffs).toEqual([expect.objectContaining({ path: 'notes/launch-plan.md', class: 'interpretive' })]);+ expect(details(preview).diffs[0]!.fixes[0]).toContain('title was derived from the slug');+ expect(details(preview).needs_review).toEqual([expect.objectContaining({ path: 'notes/private.md', reason: 'ambiguous_protected_key', key: 'visibility', flag: 'imported_before_hold' })]);+ const hash = preview.apply_command.split('--expect ')[1]!.split(' ')[0]!;+ await s.run({ apply: true, expect: hash, includeAmbiguous: true });+ expect((await engine.getPage('notes/launch-plan', { sourceId: s.id }))?.title).toBe('The real launch plan');+}), 180_000);