Garry's Opinionated OpenClaw/Hermes Agent Brain
TypeScript
feat(repair): content lane runner, gbrain repair content, content_repair cycle phase, sync unblock repairs, docs (#6377 lane C + integration)
garrytand0521f8b1a1b
diff --cc docs/architecture/key-files/core-persistence-continued.mdindex 13b7620efb,edd66b3df7..a196c20937--- a/docs/architecture/key-files/core-persistence-continued.md+++ b/docs/architecture/key-files/core-persistence-continued.md@@@ -15,9 -16,10 +15,10 @@@ Managed connector ingestion, connector- `src/core/fence-repair/hold-fix.ts` — #6188 (D16, D17, E35, Codex CEO #7) what an `invalid_fence` sync hold tells an agent (the OWNER list routes `owner_unavailable`, `owner_cli_required` and the #6278 owner conditions `host_mismatch`, `transfer_in_progress`, `clone_in_progress`, `incarnation_changed`, `local_path_missing`, `coordination_path_missing` to state `owner`). `readFenceAutoRepair` (two reads: `fences.repair.enabled`, `fences.repair.llm` and `autopilot.last_global_at` from `config`, plus the last completed `autopilot-global-maintenance` job) says whether the maintenance run repairs fences by itself (active within `FENCE_MAINTENANCE_ACTIVE_MS`, 24 h). `fenceHoldStatus` derives the state from the reason table and `meta.fence_repair`: `auto` (no action needed, the read-only preview), `apply` (preview, then apply), `manual` (manual-only reason, gate rejection or a model failure the run does not retry: the preview names the edit, then the sync), `paid` (`budget_exhausted`, `llm_disabled`, `no_pricing`: the exact config or `pricing set` command with consent `paid`), `owner` (the owner-host command, actor `host_admin`). `fenceHoldFix` is the local fix (`gbrain repair fences --source <id> --only <path>`), `fenceHoldRelay` the remote one (`tell_user_to_run`, no path), `fenceHoldLocation` the D16 object, `fenceFileLine` the file line of a section line. Location only. Tests: `test/fence-hold-surfaces.test.ts`, `test/sync-hold-surfaces.test.ts`.- `src/core/fence-repair/{census,census-store}.ts` — #6188 the fence census: discovery only, nothing repairs. `runFenceCensus(engine, { sourceIds, deadline, now })` advances per source (an even share of the deadline each): the stored-page scan (a one-time keyset backfill over `pages.id`, then incremental passes over `updated_at >= watermark`, where each new watermark is the previous pass's start minus the oldest open writer transaction in `pg_stat_activity` and `LATE_COMMIT_GRACE_MS`, so a transaction that committed after a later pass is still read) and, for a checkout, the working-tree walk (a full first walk of `isFrontmatterScannablePath` files via `collectGitVisibleFiles`/`walkDir`, then only `git diff <walked commit>` files, untracked files newer than the last walk, mtime for non-Git sources, and every stored file candidate). Both resume from cursors saved after every batch; a deadline leaves the census `partial`. `judgeFences` runs the coordinated `fenceStep` (normalization on): `deterministic` when Tier 1 fixes it, else the highest `FENCE_REASONS` tier of its residual reasons (`reasonTier`; manual-only or page-dependent counts as manual). `listFenceCandidates` dedupes by page slug across `invalid_fence` holds, stored pages and files (bucket hold > page > file; held-file tier from the walked file, else the hold reason), each bound to the judged bytes (page sha256/`updated_at`/`content_hash`, file sha256/mtime, hold `upstream_version`); `summarizeFenceCensus` counts per source by bucket and tier with the oldest hold and scan state. `census-store.ts`: `op_checkpoints` rows `fence-candidate` (one per source incarnation and slug, `page`/`file` parts), `fence-scan` (cursors and last census) and `fence-trend` (one row per sync run, keyed by run id: a managed run's total is rewritten in the same transaction as each cursor step that changes it, so the trend never differs from the cursor, and a legacy run writes its total when it ends; plus one row per normalized page write via `recordPublicationFenceTrend`, which the coordinator and group publication call inside the publication transaction and which skips per-file sync outcomes); candidate and scan rows survive the 7-day purge while their incarnation lives, trend rows age out. Location only: tiers, reasons, rows, columns, slugs and paths, never a cell value. Tests: `test/fence-census.test.ts` (+ `test/e2e/fence-census-postgres.test.ts`), `test/doctor-fence-integrity.test.ts`.- `src/core/fence-repair/{llm,repair-tiers}.ts` — #6188 Tier 2 and Tier 3 for one candidate. `analyzeFences`: Tier 1 (`safeNormalizeFences`, stored rows loaded only for `renumber`), Tier 2 (`resolveStrictEntityReference` without the same-name arm per `holder_unresolved` cell, only `people/`/`companies/` slugs, private pages excluded on a world page; hits feed `verifiedHolders`), then `proposal` (validated by gates (a)-(g) and a fixed point), `llm` (only `TIER3_REASONS` residuals left; a fence with stray text lines or no end marker is not eligible) or `manual`. `llm.ts`: `tier3Requests` (per fence: the header line and the residual rows, every row for a fence-level issue), `buildTier3Prompt` (schema, vocabulary, reason codes, page visibility, and rule 8: answer `HOLD` when a row has more than one reasonable reading; pinned by a prompt-bytes digest and `FENCE_REPAIR_PROMPT_VERSION`, 2), the layout (wide when the header names a wide column or, headerless, a row as written is wider than the narrow layout), `tier3TokenBudget` (the table's size plus `TIER3_REASONING_TOKENS` for a model whose reasoning the call cannot switch off, raised to the gateway's thinking headroom where the route has no switch: the estimate reserves what the gateway sends), `callTier3` (gateway `chat`, no tools, no fallback, thinking off; `llm_unavailable` when the provider throws, `llm_refused`, `llm_truncated` for any stop but a normal end, `llm_declined` for HOLD, `llm_malformed`/`llm_empty` from `extractSingleTable`, a wrong row count is a gate (e) failure), `spliceTier3` (rebuilds only that fence: canonical header, then every row in order with the sent rows replaced). `runTier3` claims the attempt (a rejected memo returns its verdict), checks the per-page cap and the run allowance, reserves on the daily ledger before each call (a refusal stops the run), settles actual tokens (an answerless call at its estimate), normalizes and validates the spliced page against the bytes as read, and re-asks once with the failed gate letter and rows only after a structural failure (gate (a) or (e)); any other gate or a HOLD is final and consumes the memo. `TIER3_REASONS` is the reason table's screen reasons of tier `llm`. Tests: `test/fence-repair-llm.test.ts`, `test/repair-fences.test.ts`.+ - `src/core/fence-repair/llm-tail.ts` — #6377 (Lane A3) the Tier 3 request kind `tail`: when a fence has no end marker and lines follow its last row on a world-visible page, the model sees only the fence's begin line, header, every row and the trailing lines to the section end (never the rest of the page) and answers one JSON object `{"tail": "prose" | "rows" | "unsure"}` through the same gateway call, caps, daily ledger and attempt memo as the row requests (memo key: the fence region's sha256 + model + prompt version, so an unchanged tail never costs twice and a transient `llm_unavailable` does not consume it). `prose` makes the close previewable under the `tail_exposure_approval` reason (the preview prints the exact exposed lines and the hash binds them; unattended runs record `needs_human` with the paragraph and the `gbrain repair content --only <path> --apply --expect <hash>` command); `rows` and `unsure` render `unclosed_ambiguous_tail` (manual, the exact edit). On a private page the model is never called: `structure.ts` closes the fence after the last row deterministically (`trailing_lines` on the receipt), because the privacy boundary hides nothing from anyone there. Tests: `test/fence-repair-llm.test.ts`.- `src/core/fence-repair/stray-cells.ts` — #6188 Tier 1 `stray_empty_cell` (`strayCellPass`, run by `normalizeFences` after the structural pass): in a balanced primary fence with a canonical header, a row with more cells than the layout loses empty cells (slot removed, every other byte kept) only when exactly one distinct deletion leaves every validated column valid; otherwise it stays `extra_cells`, now manual. In a fence with no header, `headerlessMisfit` reads a row that starts with a row number by position: a `kind` cell that is not a kind word is `claim_split`, a row wider than any layout with an invalid validated column is `extra_cells` (after the same empty-cell removal), and `content.ts` holds both as manual, so a claim an unescaped `|` cut never reaches Tier 3. `rules.ts` `kindWord` keeps facts `kind_map` to a kind word (at most three words, no sentence punctuation, link or strikethrough); other text is `claim_split` (manual), never a kind note. Tests: `test/fence-repair-normalize.test.ts`.- `src/core/fence-repair/{measured,model}.ts` — #6188 the Tier 3 eval's verdicts and the model they pick. `measured.ts`: `FENCE_REPAIR_MEASURED_MODELS` (the models that met the preregistered rule, best first) and `FENCE_REPAIR_MEASURED` (the behavior notice's accuracy sentence), updated together by the next eval. `model.ts`: `resolveFenceRepairModel(WithSource)`: an explicit `models.fence_repair` always (any model, priced or not); unset, the first measured model whose provider key the merged env has; else null (`no_measured_model`, a paid hold whose fix is `gbrain config set models.fence_repair <model>`). `gbrain models` reports the row through it (`measured default`). Tests: `test/repair-fences.test.ts`.-- `src/core/fence-repair/{repair-io,receipt,uncommitted}.ts` — #6188 fence repair I/O. `loadFenceSource(engine, sourceId, { remote })`: managed owner root, or the `OwnerRefusal` row (`persistence/owner-refusal.ts`) that says why this host may not write it (a remote caller's row names no local path), legacy checkout, mirror flag, and the `RepairBusySet` (`persistence/repair-busy.ts`: in-flight writes plus the not-yet-admitted entries of every unfinished sync cursor, failing closed); an unfinished sync no longer marks the whole source busy. `writeFenceRepair` turns a `sync_in_progress` raised at the write's admission into `{ ok: false, reason: 'sync_in_progress' }`. `readFenceTarget`: a held or walked file from the checkout (UTF-8 only, confined, slug from the page by origin, hold or path) or the stored page; `spliceFileSections` puts the repaired sections back into the file by locating each changed line range with the fewest unique context lines and refuses unless the result parses back to exactly those sections. `writeFenceRepair`: managed → `submitManagedFileRepair` (bytes bound to the before-hash, page revision and publication digest; refused imports and canonical overlays are not written); legacy → confined path re-hashed (`changed_since_read`), backed up under `~/.gbrain/backups/fences/<run>/`, written, `importFromFile` (restored from the backup if it refuses), hold cleared, and an "uncommitted fence repair" notice (`uncommitted.ts`, op `fence-repair-uncommitted`, purge-exempt) with the exact `git add`/`git commit` step, dropped on read once the path is committed; db and mirror → a revision-bound `put_page` (mirror: database-only, hold cleared). Every write carries a `FenceRepairReceipt` (`receipt.ts`: actor `fence-repair`, tier, classes, rows, columns, model, before/after sha256, cost; `parseFenceRepairReceipt` rejects anything malformed) and clears the census parts of the key. Tests: `test/repair-fences.test.ts`.+- `src/core/fence-repair/{repair-io,receipt,uncommitted}.ts` — #6188 fence repair I/O. `loadFenceSource(engine, sourceId, { remote })`: managed owner root, or the `OwnerRefusal` row (`persistence/owner-refusal.ts`) that says why this host may not write it (a remote caller's row names no local path), legacy checkout, mirror flag, and the `RepairBusySet` (`persistence/repair-busy.ts`: in-flight writes plus the not-yet-admitted entries of every unfinished sync cursor, failing closed); an unfinished sync no longer marks the whole source busy. `writeFenceRepair` turns a `sync_in_progress` raised at the write's admission into `{ ok: false, reason: 'sync_in_progress' }`. `readFenceTarget`: a held or walked file from the checkout (UTF-8 only, confined, slug from the page by origin, hold or path) or the stored page; `spliceFileSections` puts the repaired sections back into the file by locating each changed line range with the fewest unique context lines and refuses unless the result parses back to exactly those sections. `writeFenceRepair`: managed → `submitManagedFileRepair` (bytes bound to the before-hash, page revision and publication digest; refused imports and canonical overlays are not written); legacy → confined path re-hashed (`changed_since_read`), backed up under `~/.gbrain/backups/fences/<run>/`, written, `importFromFile` (restored from the backup if it refuses), hold cleared, and an "uncommitted fence repair" notice (`uncommitted.ts`, op `fence-repair-uncommitted`, purge-exempt) with the exact `git add`/`git commit` step, dropped on read once the path is committed; db and mirror → a revision-bound `put_page` (mirror: database-only, hold cleared). Every write carries a `FenceRepairReceipt` (`receipt.ts`: actor `fence-repair`, tier, classes, rows, columns, model, before/after sha256, cost, and for a `merge_fences` repair `merged`: per merged fence and section the fence count and every before row as `{occurrence, from_fence, kept_as | duplicate_of}`, at most `MERGED_ROWS_MAX` rows, built by `mergedReceipt`; `parseFenceRepairReceipt` rejects anything malformed) and clears the census parts of the key. Tests: `test/repair-fences.test.ts`.- `src/core/fence-repair/attempts.ts` — #6188 attempt claims and the attempt memo for paid (Tier 3) fence repairs, one `op_checkpoints` row per candidate (op `fence-repair-attempt`) changed only by compare-and-swap on a record version: `claimed` → `dispatched` → `settled` → `published` | `rejected` | `transient`, at most one paid call plus one corrective re-ask per claim. A rejected or published memo (content sha256, model, fence rules version, prompt version) is not claimed again until one changes; transient failures do not consume it; an expired lease is taken over (a stale dispatch counts a crash, two reject the memo). Records carry location and reason codes and their source incarnation, so the purge keeps them while it lives. Tests: `test/fence-repair-attempts.test.ts` (+ Postgres e2e).- `src/core/persistence/{types,params,preconditions,verb-errors}.ts` — public mutation receipt states, error reasons and revision/idempotency parameter contracts. Receipt serialization explicitly selects public fields; queued content and execution credentials stay internal. `frozenVerbWriteError` uses MEMORY_VERBS v1's existing error enum with additive `write_request`/`write_error`; `committedVerbOutcome` refuses pending or failed receipts. `OperationError` and the thin MCP client preserve this metadata, including when a timeout races an already-received receipt. The registry-safe parameter/schema leaf never imports operation values. Pinned by `test/persistence-write-contracts.test.ts`, `test/mcp-client-hardening.test.ts` and a real HTTP envelope in `test/mcp-client.test.ts`.- `src/core/persistence/{database-write,manual-links}.ts` — `coordinatedDatabaseWrite` is the managed path for rows with no canonical file; `coordinatedManualLinkWrite` (`add_link` / `remove_link`) and `ontology_propose` (one entity page key) use it. On a managed brain it checks the caller's durable write authority for the authority page (`submissionAuthority`, then `authorizeWrite` FOR SHARE inside the transaction), revalidates the source incarnation and commits inside `withCoordinatedWrite` holding the given page keys (both link endpoints). Unmanaged brains keep the engine calls. Manual edges (`link_source` `manual` or a custom tag) survive re-derivation and republication because automatic reconciliation only replaces derived provenances. Tests: `test/managed-writers-w3.test.ts`, `test/managed-ontology-propose.test.ts`.diff --cc src/commands/doctor/wave-checks.tsindex 8d966569be,8d966569be..260113cce2--- a/src/commands/doctor/wave-checks.ts+++ b/src/commands/doctor/wave-checks.ts@@@ -47,10 -47,10 +47,11 @@@ export interface WaveCheckSpec/*** #6188 (D7): what clears malformed fences, from a check's `auto_repair` detail: the next maintenance run while-- * one is active and `fences.repair.enabled` is on, otherwise `gbrain repair fences` (whose preview prints the apply command).++ * one is active and `fences.repair.enabled` is on, otherwise the preview `command`: the content lane for held files (#6377), `gbrain repair fences`++ * for malformed fences stored pages carry (whose preview prints the apply command).*/--function fenceRepairHow(details: Record<string, any>, source?: string): string {-- const preview = `preview with: gbrain repair fences${source ? ` --source ${source}` : ''}`;++function fenceRepairHow(details: Record<string, any>, source: string | undefined, command: 'fences' | 'content'): string {++ const preview = `preview with: gbrain repair ${command}${source ? ` --source ${source}` : ''}`;const auto = details.auto_repair as { active?: boolean; enabled?: boolean } | undefined;if (auto && auto.active === false) return `not repaired automatically (${auto.enabled === false ? 'fences.repair.enabled is false' : 'no maintenance run is active'}); ${preview}`;const manual = Array.isArray(details.sources) ? details.sources.reduce((sum: number, c: { by_tier?: { manual?: number } }) => sum + Number(c.by_tier?.manual ?? 0), 0) : 0;@@@ -138,14 -138,14 +139,14 @@@ export const WAVE_CHECKS: readonly WavehostOnly: 'Held file paths are host-local; remote callers see held counts on sync results, get_page and search.',count: d => Number(d.held ?? 0),impact: 'Some Git source files are held instead of imported, so their pages are missing or keep an older revision',-- bannerHow: (d, how, source) => !d.fences ? how : d.fences >= Number(d.held ?? 0) ? `fence holds: ${fenceRepairHow(d, source)}` : `${how}; fence holds: ${fenceRepairHow(d, source)}`,++ bannerHow: (d, how, source) => !d.fences ? how : d.fences >= Number(d.held ?? 0) ? `fence holds: ${fenceRepairHow(d, source, 'content')}` : `${how}; fence holds: ${fenceRepairHow(d, source, 'content')}`,run: async (engine, scope) => (await import('./checks/git-holds.ts')).gitHeldFilesCheck(engine, scope.sourceIds),},{id: 'fence_integrity', resolution: 'repair', registration: 'doctor.ts',count: d => Number(d.total ?? 0),impact: 'Some facts or takes fences are malformed and wait for repair; none of them blocks a sync',-- bannerHow: (d, _how, source) => fenceRepairHow(d, source),++ bannerHow: (d, _how, source) => fenceRepairHow(d, source, 'fences'),run: async (engine, scope) => (await import('./checks/fence-integrity.ts')).fenceIntegrityCheck(engine, scope.sourceIds),},{diff --cc src/commands/repair.tsindex bc718e129c,d4366344d6..f67491e52b--- a/src/commands/repair.ts+++ b/src/commands/repair.ts@@@ -66,13 -87,13 +87,13 @@@ Options--include-ambiguousExplicit-only kinds: widen the preview to ambiguous items (its hash covers them).--only <path>, --skip <path>- frontmatter, fences, slug-conflicts: select source-relative files (repeatable); the hash covers the selection.- frontmatter, fences, content: select source-relative files (repeatable); the hash covers the selection.++ frontmatter, fences, slug-conflicts, content: select source-relative files (repeatable); the hash covers the selection.--slug <slug> fences: select a database page by slug (repeatable); the hash covers the selection.- --diff frontmatter, fences, slug-conflicts: print every per-file diff, not one sample per class or tier.- --no-llm Kinds that may call a paid model (${llmKinds}): use only the free tiers; model-tier- items stay held with llm_disabled.- --max-usd <n> Kinds that may call a paid model (${llmKinds}): spend at most n USD on the model in this- run. It only lowers the cap (the daily fences.repair cap still applies); never raises it.- --diff frontmatter, fences, content: print every per-file diff, not one sample per class or tier.++ --diff frontmatter, fences, slug-conflicts, content: print every per-file diff, not one sample per class or tier.+ --no-llm Kinds that may call a paid model (${llmKinds}) and the content lane: use only the free tiers;+ model-tier items stay held with llm_disabled.+ --max-usd <n> Kinds that may call a paid model (${llmKinds}) and the content lane: spend at most n USD on the+ model in this run. It only lowers the cap (the daily fences.repair cap still applies); never raises it.--yes frontmatter, conversation-labels --apply: the user agreed to the previewed changes (destructiveconsent; 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).@@@ -88,7 -109,7 +109,7 @@@ const BOOLEAN_FLAGS = new Set(['--applyconst VALUE_FLAGS = new Set(['--source', '--limit', '--expect', '--only', '--skip', '--slug', '--max-usd']);/** Flags only some kinds accept, with the kinds that do. */const KIND_FLAGS: Record<string, readonly string[]> = {- '--only': ['frontmatter', 'fences', 'slug-conflicts'], '--skip': ['frontmatter', 'fences', 'slug-conflicts'], '--diff': ['frontmatter', 'fences', 'slug-conflicts'], '--yes': ['frontmatter', 'conversation-labels'],- '--only': ['frontmatter', 'fences', CONTENT_LANE], '--skip': ['frontmatter', 'fences', CONTENT_LANE], '--diff': ['frontmatter', 'fences', CONTENT_LANE], '--yes': ['frontmatter', 'conversation-labels'],++ '--only': ['frontmatter', 'fences', 'slug-conflicts', CONTENT_LANE], '--skip': ['frontmatter', 'fences', 'slug-conflicts', CONTENT_LANE], '--diff': ['frontmatter', 'fences', 'slug-conflicts', CONTENT_LANE], '--yes': ['frontmatter', 'conversation-labels'],'--slug': ['fences'],};const VALUE_EXAMPLES: Record<string, string> = { '--source': 'default', '--limit': '50', '--expect': 'PLAN_HASH', '--only': 'notes/a.md', '--skip': 'notes/a.md',diff --cc src/core/persistence/sync-holds.tsindex 058f6f6300,0a3c408387..ec724db499--- a/src/core/persistence/sync-holds.ts+++ b/src/core/persistence/sync-holds.ts@@@ -21,15 -21,10 +21,16 @@@* frontmatter value. #6188 `invalid_fence` holds carry the fence, section,* reason, parsed row numbers and the file line, never a cell value; the* summary also counts them (`fences`) so every surface can route a source to- * the right repair (`holdRepairSteps`, D6): `gbrain repair fences` for fence- * holds, `gbrain repair frontmatter` for the rest. A fence hold's own fix- * depends on its state (`fence-repair/hold-fix.ts`, D17). #6377+ * the right repair (`holdRepairSteps`, D6): the content-repair lane+ * (`gbrain repair content`, #6377) for fence and slug-conflict holds,+ * `gbrain repair frontmatter` for the rest. A fence hold's own fix depends on- * its state (`fence-repair/hold-fix.ts`, D17).++ * its state (`fence-repair/hold-fix.ts`, D17). #6377+ * `frontmatter_slug_conflict` holds carry the content-repair lane's last+ * verdict (`meta.content_repair`: action, reason code, slugs, model, when it+ * is tried again; never the model's prose), written by+ * `recordContentHoldRepair` and kept across a re-screen of the same bytes;+ * their fix is that file's `gbrain repair content --only <path>` preview and,+ * for a recommended merge or an undecidable pair, a paragraph for a person.*/import type { BrainEngine } from '../engine.ts';import type { Action } from '../agent-output.ts';diff --cc src/core/persistence/sync-status.tsindex bc4c6baf13,d84435066d..8ae53d8317--- a/src/core/persistence/sync-status.ts+++ b/src/core/persistence/sync-status.ts@@@ -76,11 -87,30 +87,31 @@@ async function cursorHeader(engine: Brareturn rows[0]?.header ?? null;}- function holdStatus(record: GitHoldRecord): SyncStatusHold {+ /**+ * #6377: the verdict of a repair-class hold follows its stored repair state. A fence hold whose state is `manual` (a+ * manual-only reason, a gate rejection, a model failure the run does not retry) or `paid` (spend only the user raises),+ * and a slug-conflict hold the lane decided a person must settle (`merge_recommended`, `content_repair_needs_human`),+ * is `needs_human`: the lane will not act on it again until the file changes. `detail` lets the fault table name the+ * paragraph for the lane's codes when it knows them; otherwise the hold's own code decides.+ */+ function holdVerdict(record: GitHoldRecord, auto: FenceAutoRepair | undefined): SyncFaultVerdict {+ const attempts = record.meta.attempts ?? 1;++ const content = record.meta.content_repair ? { content_repair: { ...record.meta.content_repair, path: record.path, slug: record.slug } } : {};+ const disposition = contentHoldDisposition(record, auto);- if (disposition.action !== 'listed' || disposition.state === 'owner') return classifySyncFault({ code: record.code, attempts });- const verdict = classifySyncFault({ code: record.code, attempts, detail: disposition.reason });++ if (disposition.action !== 'listed' || disposition.state === 'owner') return classifySyncFault({ code: record.code, attempts, ...content });++ const verdict = classifySyncFault({ code: record.code, attempts, detail: disposition.reason, ...content });+ if (verdict.needs_human) return verdict;+ const reason = disposition.state === 'paid'+ ? `Model repair of ${record.path} waits on a setting only the user changes (${disposition.reason}); the hold's fix names it.`+ : `gbrain will not repair ${record.path} by itself (${disposition.reason}); the hold's fix names the exact edit or decision.`;+ return { ...verdict, safe_actions: ['none'], needs_human: true, human_reason: reason };+ }++ function holdStatus(record: GitHoldRecord, auto?: FenceAutoRepair): SyncStatusHold {const attempts = record.meta.attempts ?? 1;- const verdict = classifySyncFault({ code: record.code, attempts, ...(record.meta.content_repair ? { content_repair: { ...record.meta.content_repair, path: record.path, slug: record.slug } } : {}) });+ const verdict = holdVerdict(record, auto);return { code: record.code, slug: record.slug, path: record.path, attempts, held_since: record.held_at, ...verdict,- retry_after: verdict.safe_actions[0] === 'retry' || verdict.safe_actions[0] === 'retry_when_clean' ? null : 'after the named step', fix: gitHoldFix(record) };+ retry_after: verdict.safe_actions[0] === 'retry' || verdict.safe_actions[0] === 'retry_when_clean' ? null : 'after the named step', fix: gitHoldFix(record, auto) };}export async function readSyncStatus(engine: BrainEngine, sourceId: string): Promise<SyncStatus> {diff --cc src/core/repair/content-lane.tsindex 0000000000,6ef6093140..f439fe2cb8mode 000000,100644..100644--- a/src/core/repair/content-lane.ts+++ b/src/core/repair/content-lane.ts@@@ -1,0 -1,177 +1,173 @@@+ /**+ * The content-repair lane (#6377): the repair kinds that clear managed-sync+ * content holds, run as one bounded pass under one paid-model allowance.+ *+ * `CONTENT_REPAIR_KINDS` is the lane in dependency order; `gbrain repair+ * content`, the `content_repair` maintenance phase (src/core/cycle/+ * content-repair.ts) and `gbrain sync unblock --apply` all read it, so a new+ * kind plugs in with one entry here. Today it holds `fences`; the GBRA-72+ * integration appends `slug-conflicts` (Lane B, src/core/repair/+ * slug-conflicts.ts). `CONTENT_REPAIR_HOLD_KINDS` maps a hold code to the kind+ * that clears it (`null`: no kind yet, the surfaces keep today's refusal text).+ *+ * `runContentLane` has no rule logic of its own: it runs each kind through+ * the shared trusted `repairRunner`, so every kind keeps its own census, owner+ * checks, caps, ledger, memo and gates. What the lane adds is the contract+ * between kinds: the run's paid allowance (`maxLlmUsd`) flows from one kind to+ * the next minus what the earlier kinds spent (read from each result's+ * `cost.llm_usd`; the daily ledger is shared by every kind, `FENCE_REPAIR_LEDGER`),+ * and one absolute deadline bounds the whole pass. A preview builds every+ * component plan before any mutation and returns each kind's own preview+ * hash; `--apply --expect <h1>[,<h2>]` applies exactly those sets, one hash+ * per kind in lane order, so the operator's approval binds both concrete plans+ * (Codex #10). There is no combined hash. A bare apply (the cycle, `sync+ * unblock`, `--apply` alone) applies each kind's current plan the way+ * `gbrain repair <kind> --apply` does: the kind plans and applies in one run,+ * each item bound to the bytes its plan read (`changed_since_read`), and+ * records on every hold it leaves why (a preview records nothing).+ *+ * `contentHoldDisposition` is the one place that reads a hold's stored repair+ * state (a fence hold's `fenceHoldStatus`, a slug-conflict hold's+ * `meta.content_repair.action`) to say whether unattended surfaces may run the+ * kind on it or must list it for a person. Output is counts, codes, hashes+ * and paths only: never a claim, a cell or a frontmatter value.+ */+ import type { BrainEngine } from '../engine.ts';+ import type { OperationContext } from '../ops/contract.ts';+ import { opError } from '../ops/contract.ts';+ import { readFix } from '../ops/op-fix.ts';+ import { shellQuote } from '../agent-output.ts';+ import { fenceHoldStatus, type FenceAutoRepair } from '../fence-repair/hold-fix.ts';+ import type { GitHoldRecord } from '../persistence/sync-holds.ts';+ import type { RepairKind, RepairResult, RepairScope } from './core.ts';+ import { repairRunner, type RepairKindSpec } from './registry.ts';+-/** The lane, in run order. GBRA-72 integration appends 'slug-conflicts' (Lane B). */-export const CONTENT_REPAIR_KINDS: readonly RepairKind[] = ['fences'];++/** The lane, in run order: fences first (a merged or closed fence can change what a slug conflict's page looks like), then slug conflicts. */++export const CONTENT_REPAIR_KINDS: readonly RepairKind[] = ['fences', 'slug-conflicts'];+-/**- * Which lane kind clears a hold code. `null` keeps today's behaviour for the- * code (unblock refuses it with the fix it names); Lane B sets- * `frontmatter_slug_conflict` to 'slug-conflicts'.- */++/** Which lane kind clears a hold code; a code with `null` is refused by `sync unblock` with the fix it names. */+ export const CONTENT_REPAIR_HOLD_KINDS: Readonly<Partial<Record<GitHoldRecord['code'], RepairKind | null>>> = {+ invalid_fence: 'fences',- frontmatter_slug_conflict: null,++ frontmatter_slug_conflict: 'slug-conflicts',+ };++ /** A hold's stored repair decision, when the lane recorded one (Lane B writes it; read loosely so either lane lands first). */+ function storedContentAction(meta: GitHoldRecord['meta']): string | undefined {+ const action = (meta as { content_repair?: { action?: unknown } }).content_repair?.action;+ return typeof action === 'string' ? action : undefined;+ }++ export type ContentHoldDisposition =+ /** An unattended run may run `kind` on this hold now. */+ | { action: 'repair'; kind: RepairKind }+ /** The hold waits on a person (`needs_human`), the user's spend decision (`paid`) or the owner host (`owner`); list it, never retry it. */+ | { action: 'listed'; kind: RepairKind; state: 'needs_human' | 'paid' | 'owner'; reason: string }+ /** No lane kind clears this code yet. */+ | { action: 'unsupported' };++ /**+ * What an unattended surface (`sync unblock --apply`, the cycle) may do with+ * one hold. `auto` is what the caller read about the maintenance run+ * (`fenceAutoRepairFor`); it decides a fence hold's state exactly as the+ * hold's own fix does.+ */+ export function contentHoldDisposition(record: Pick<GitHoldRecord, 'code' | 'meta'>, auto?: FenceAutoRepair): ContentHoldDisposition {+ const kind = CONTENT_REPAIR_HOLD_KINDS[record.code];+ if (!kind) return { action: 'unsupported' };+ if (record.code === 'invalid_fence') {+ const status = fenceHoldStatus(record.meta, auto);- if (status.state === 'manual') return { action: 'listed', kind, state: 'needs_human', reason: status.reason };++ if (status.state === 'manual' || status.state === 'approval') return { action: 'listed', kind, state: 'needs_human', reason: status.reason };+ if (status.state === 'paid' || status.state === 'owner') return { action: 'listed', kind, state: status.state, reason: status.reason };+ return { action: 'repair', kind };+ }+ const stored = storedContentAction(record.meta);+ if (stored === 'merge_into') return { action: 'listed', kind, state: 'needs_human', reason: 'merge_recommended' };+ if (stored === 'needs_human') return { action: 'listed', kind, state: 'needs_human', reason: 'content_repair_needs_human' };+ return { action: 'repair', kind };+ }++ export interface ContentLaneOptions {+ apply: boolean;+ /** The kinds to run, in order (default: the whole lane). */+ kinds?: readonly RepairKind[];+ /** Source-relative file selection, handed to every kind (its hash covers it). */+ only?: string[];+ skip?: string[];+ /** One preview hash per kind in `kinds` order; the apply binds each kind to exactly that set. */+ expect?: readonly string[];+ /** Free tiers only, for every kind. */+ noLlm?: boolean;+ /** The run's paid-model allowance in USD for the whole lane; what one kind spends is gone for the next. */+ maxLlmUsd?: number;+ /** Absolute deadline (epoch ms) for the whole lane; a kind stopped `time_budget` ends the pass. */+ deadline?: number;+ limit?: number;+ noEmbed?: boolean;+ /** `--source <id>` as the operator wrote it, for the printed commands. */+ sourceFlag?: string;+ /** Replaces the registered kinds (tests pass stub specs). */+ registry?: readonly RepairKindSpec[];+ logger?: OperationContext['logger'];+ }++ export interface ContentLaneResult {+ mode: 'dry_run' | 'apply';+ scope: RepairScope;+ /** The kinds the lane ran, in order; one `results` entry each. */+ kinds: RepairKind[];+ results: RepairResult[];+ /** Each kind's own preview hash on a dry run, the hash each apply was bound to with `expect` (null: the kind printed none, or a bare apply). */+ preview_hashes: Partial<Record<RepairKind, string | null>>;+ /** Paid-model spend across the lane: the estimate on a dry run, the actual spend on an apply; the allowance left under `maxLlmUsd` (null: no run cap). */+ cost: { llm_usd: number; llm_allowance_remaining_usd: number | null };+ /** Every kind that stopped, with its reason (`time_budget` ends the lane; the rest let the next kind run). */+ stopped: Array<{ kind: RepairKind } & NonNullable<RepairResult['stopped']>>;+ /** The command that applies exactly these plans (dry run), or reruns the lane (apply). */+ apply_command: string;+ }++ /** `gbrain repair content [--source <id>] [--only <p>]... [--skip <p>]... [--no-llm] [--max-usd <n>] [--apply [--expect <h1>,<h2>]]`. */+ export function contentLaneArgv(opts: { source?: string; only?: readonly string[]; skip?: readonly string[]; noLlm?: boolean; maxLlmUsd?: number; apply?: boolean; expect?: readonly string[] }): string[] {+ return ['gbrain', 'repair', 'content', ...(opts.source ? ['--source', opts.source] : []), ...(opts.only ?? []).flatMap(path => ['--only', path]),+ ...(opts.skip ?? []).flatMap(path => ['--skip', path]), ...(opts.noLlm ? ['--no-llm'] : []), ...(opts.maxLlmUsd !== undefined ? ['--max-usd', String(opts.maxLlmUsd)] : []),+ ...(opts.apply ? ['--apply'] : []), ...(opts.expect?.length ? ['--expect', opts.expect.join(',')] : [])];+ }++ /**+ * `--expect <h1>[,<h2>]` → one hash per kind, in order. Refuses a count that+ * does not match the kinds the lane runs: the operator previewed a different+ * lane, so no hash can be matched to a kind.+ */+ export function parseContentLaneExpect(text: string, kinds: readonly RepairKind[], previewArgv: string[]): string[] {+ const hashes = text.split(',').map(hash => hash.trim()).filter(Boolean);+ if (hashes.length === kinds.length) return hashes;+ throw opError('invalid_params', `--expect takes one preview hash per kind of the content lane, comma-separated in lane order (${kinds.join(', ')}); got ${hashes.length} hash(es) for ${kinds.length} kind(s), so nothing ran.`,+ `Preview the lane again and pass the hashes it prints: ${shellQuote(previewArgv)} prints each kind's own hash and the exact apply command.`,+ { fix: readFix('Previews every lane kind; it writes nothing and calls no model.', { argv: previewArgv }) });+ }++ export async function runContentLane(engine: BrainEngine, scope: RepairScope, opts: ContentLaneOptions): Promise<ContentLaneResult> {+ const kinds = [...(opts.kinds ?? CONTENT_REPAIR_KINDS)];+ const previewArgv = contentLaneArgv({ source: opts.sourceFlag, only: opts.only, skip: opts.skip, noLlm: opts.noLlm, maxLlmUsd: opts.maxLlmUsd });+ if (opts.expect && opts.expect.length !== kinds.length) parseContentLaneExpect(opts.expect.join(','), kinds, previewArgv);+ const runner = await repairRunner(engine, { apply: opts.apply, noEmbed: opts.noEmbed, ...(opts.logger ? { logger: opts.logger } : {}), ...(opts.registry ? { registry: opts.registry } : {}) });+ const hashes: ContentLaneResult['preview_hashes'] = {};+ const stopped: ContentLaneResult['stopped'] = [];+ const results: RepairResult[] = [];+ let spent = 0;+ const allowance = () => opts.maxLlmUsd === undefined ? undefined : Math.max(0, opts.maxLlmUsd - spent);+ for (const [index, kind] of kinds.entries()) {+ const expect = opts.expect?.[index];+ const result = await runner.run(kind, scope, { explicit: true, limit: opts.limit, sourceFlag: opts.sourceFlag, only: opts.only, skip: opts.skip, noLlm: opts.noLlm,+ maxLlmUsd: allowance(), deadline: opts.deadline, ...(expect ? { expect } : {}) });+ hashes[kind] = expect ?? result.preview_hash ?? null;+ spent += result.cost.llm_usd ?? 0;+ results.push(result);+ if (result.stopped) stopped.push({ kind, ...result.stopped });+ if (result.stopped?.reason === 'time_budget') break;+ }+ const expect = kinds.map(kind => hashes[kind] ?? null);+ return { mode: opts.apply ? 'apply' : 'dry_run', scope, kinds, results, preview_hashes: hashes, cost: { llm_usd: spent, llm_allowance_remaining_usd: allowance() ?? null }, stopped,+ apply_command: shellQuote(contentLaneArgv({ source: opts.sourceFlag, only: opts.only, skip: opts.skip, noLlm: opts.noLlm, maxLlmUsd: opts.maxLlmUsd, apply: true,+ expect: expect.every((hash): hash is string => hash !== null) ? expect : undefined })) };+ }diff --cc src/core/repair/fences.tsindex b2463e537e,109af92834..e98d9809db--- a/src/core/repair/fences.ts+++ b/src/core/repair/fences.ts@@@ -233,6 -232,6 +233,13 @@@ function ownerReason(owner: OwnerRefusaconst previewFix = (sourceId: string, path: string | null, slug: string): Action => ({ argv: ['gbrain', 'repair', 'fences', '--source', sourceId, ...(path ? ['--only', path] : ['--slug', slug])],consent: [], actor: 'agent', requires_exclusive: false, why: 'Previews this fence repair again from the bytes as they are now; nothing is written.' });++++/** The hash a preview of this selection prints when it finds nothing to repair. */++async function emptyPlanHash(engine: BrainEngine, scope: RepairScope, selection: Selection): Promise<string> {++ const sourcesRows = await engine.executeRaw<{ id: string; incarnation: string }>('SELECT id, incarnation::text AS incarnation FROM sources WHERE id=ANY($1::text[]) ORDER BY id', [scope.source_ids]);++ return previewHash({ kind: 'fences-v1', brain_id: scope.brain_id, sources: sourcesRows, selection, items: [] });++}++export const fencesRepair: RepairHandler = {kind: 'fences',outcomeItemsLimit: 1000,@@@ -241,6 -240,6 +248,8 @@@slugs: [...(opts?.slugs ?? [])].sort(), no_llm: opts?.noLlm === true };const preview = previewArgv(scope, selection);if (opts?.apply && opts.expect) {++ // #6377: a preview that found nothing saved no set; its hash still binds "nothing to apply" (the content lane passes one hash per kind).++ if (opts.expect === await emptyPlanHash(engine, scope, selection)) return { items: [], preview_hash: opts.expect, residuals: {}, llm: { usd: 0, cap_remaining_usd: null } };const approved = await loadApprovedSet<ApprovedSetItem>(engine, { command: 'fences', hash: opts.expect, previewCommand: shellQuote(preview) });if (approved.items.some(entry => digestOf(entry.selection) !== digestOf(selection))) throw previewChangedError(opts.expect, shellQuote(preview));const items = approved.items.map(({ selection: _chosen, ...entry }, index) => item(entry, index, opts.expect!, index === approved.items.length - 1, false));diff --cc src/core/repair/slug-conflicts.tsindex d319805092,0000000000..7b8f3fe636mode 100644,000000..100644--- a/src/core/repair/slug-conflicts.ts+++ b/src/core/repair/slug-conflicts.ts@@@ -1,636 -1,0 +1,645 @@@+/**+ * `gbrain repair slug-conflicts` (#6377, Lane B): clears+ * `frontmatter_slug_conflict` sync holds (a file whose frontmatter `slug:`+ * names a page other than the one its path names) without a person, or+ * says exactly why a person is needed. `gbrain repair content` runs it after+ * `fences` for the same selection; the maintenance cycle and+ * `sync unblock --apply` run it with a bare `--apply`.+ *+ * Candidates: every `frontmatter_slug_conflict` hold of the sources in scope+ * (`--only <path>` / `--skip <path>` select, and `--only` also reaches an+ * unheld file that screens as a slug conflict now). Identity is resolved,+ * not textual (Codex #8): the declared slug is normalized the way the screen+ * does (`slugifyPath`), resolved through `slug_aliases`+ * (`readPageSnapshot` with `resolveAlias`) to a page in the same source; a+ * slug that resolves to the held file's own page is `already_exempt` and+ * never a candidate; a held file with no page yet (`page_id: null`) is a+ * normal candidate.+ *+ * Deterministic tier (confidence `high`, no model): `remove_slug` when the+ * named slug resolves to no page and names no file in the checkout (a stray+ * line from a template or a rename; nothing to merge into), or when the+ * named page has a different `type` and shares no title token with the held+ * file. The edit is exactly the `slug:` line (`autoFixFrontmatter` with the+ * file path, as `repair frontmatter` proposes it), and the result must+ * strict-parse with no hold. Everything else is `ambiguous` and goes to the+ * model at apply time (content-repair/llm.ts): the preview calls no model+ * and lists `model decides`, the estimated cost and the cap left.+ *+ * Model outcomes: `remove_slug` applies as above (confidence `medium`);+ * `merge_into` and `needs_human` write nothing: the hold records the verdict+ * as codes and slugs (`recordContentHoldRepair`, `merge_recommended` /+ * `content_repair_needs_human`) and `sync status` renders a paragraph for a+ * person. The model's `why` sentence appears in the run output only.+ * `--no-llm` (or `fences.repair.llm false`) holds model-tier candidates+ * `llm_disabled`; the per-page and daily caps, the run allowance and the+ * attempt memo work as the fence repair's (one lane, one budget).+ *+ * Publication: managed sources go through `prepareRepairPublication` and+ * `submitManagedFileRepair` with a `ContentRepairReceipt` (exact bytes bound+ * to the sha256 the plan read, import, hold clear and Git target effect in+ * one coordinated write; the commit reads `gbrain: repair frontmatter slug+ * in <path>` with the `gbrain-repair:` trailer); legacy sources back up,+ * write, import, clear the hold and print the commit step. Every candidate+ * passes the owner check and the `repairBusy` admission re-read, at plan,+ * at apply and again at the write (file-repair.ts). Messages carry paths,+ * slugs, codes and amounts only.+ */+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 { OperationError, type OperationContext } from '../ops/contract.ts';+import { trustedCliRequired } from '../ops/op-fix.ts';+import { shellQuote, type Action } from '../agent-output.ts';+import { autoFixFrontmatter, createFrontmatterBackup, makeFrontmatterBackupRunId } from '../brain-writer.ts';+import { classifyImportHold, parseMarkdown, serializePageToMarkdown } from '../markdown.ts';+import { MAX_FILE_SIZE } from '../import-screen.ts';+import { importFromFile } from '../import-file.ts';+import { resolveSlugForPath, slugifyPath } from '../sync.ts';+import { isReservedSkillBundlePath } from '../skill-reserved-paths.ts';+import { gbrainPath } from '../config.ts';+import { loadPricingOverrides } from '../budget/budget-tracker.ts';+import { dailyLedger, FENCE_REPAIR_LEDGER, nextUtcMidnight } from '../budget/daily-ledger.ts';+import { pricingSetCommand } from '../budget/no-pricing.ts';+import type { CapSource } from '../consent.ts';+import { sha256 } from '../persistence/digest.ts';+import { clearApprovedSet, loadApprovedSet, previewChangedError, previewHash, saveApprovedSet } from '../persistence/preview-approval.ts';+import { clearGitHold, readGitHold, readGitSourceHolds, recordContentHoldRepair, type ContentHoldRepairState, type GitHoldRecord } from '../persistence/sync-holds.ts';+import { confinedRepairTarget, prepareRepairPublication, repairScreenConfig, submitManagedFileRepair } from '../persistence/file-repair.ts';+import { repairBusy, repairBusyMessage } from '../persistence/repair-busy.ts';+import type { PageSnapshot } from '../page-state/types.ts';+import { attemptStore } from '../fence-repair/attempts.ts';+import { fenceRepairLlmEnabled, readFenceRepairCaps } from '../fence-repair/config.ts';+import { loadFenceSource, type FenceSource } from '../fence-repair/repair-io.ts';+import { judgmentParticipant, type JudgmentInput, type JudgmentVerdict } from '../content-repair/judgment.ts';+import { callJudgment, CONTENT_REPAIR_MODEL_KEY, judgmentEstimate, judgmentMemoReason, resolveContentRepairModel } from '../content-repair/llm.ts';+import { CONTENT_REPAIR_MEASURED_MODELS } from '../content-repair/measured.ts';+import { CONTENT_REPAIR_ACTOR, CONTENT_REPAIR_HOLD_CODE, contentRepairCommitSubject, contentRepairTrailer, type ContentRepairReceipt } from '../content-repair/receipt.ts';+import { contentPreviewArgv } from '../content-repair/hold-fix.ts';+import { lineDiff } from './frontmatter.ts';+import { repairRequestId, type RepairHandler, type RepairItem, type RepairItemOutcome, type RepairListing, type RepairPlan, type RepairPlanOptions, type RepairResult, type RepairScope } from './core.ts';++type Tier = 'deterministic' | 'llm';+type DeterministicRule = 'absent_page' | 'different_type';+interface Selection { source_ids: string[]; only: string[]; skip: string[]; no_llm: boolean }++/** One previewed candidate: everything the hash binds (location, hashes, tier), never a frontmatter value. */+interface ApprovedConflict {+ source_id: string; path: string; source_path: string; slug: string; mode: 'managed' | 'legacy';+ page_id: number | null; revision: string | null; before: string; upstream_version: string | null; held: boolean;+ /** The slug the `slug:` line resolves to (alias followed), and that page's id and content hash; null when no page has it. */+ named: string | null; named_page_id: number | null; named_sha256: string | null;+ tier: Tier;+ /** Deterministic: the rule and the sha256 of the edited bytes; null for the model tier (decided at apply time). */+ rule: DeterministicRule | null; after: string | null;+ estimate_usd: number;+ /** Model items from this one to the end of the plan (the pages a budget stop leaves waiting). */+ llm_waiting: number;+}+interface ApprovedSetItem extends ApprovedConflict { selection: Selection }+interface ConflictItem extends RepairItem { entry: ApprovedConflict; hash: string | null; last: boolean }++interface HeldEntry { item: string; reason: string; tier: Tier | 'manual'; resolution: string }+export interface SlugConflictsPreviewDetails {+ counts: { deterministic: number; llm: number; held: number; skipped: number };+ model: string | null;+ llm_enabled: boolean;+ diffs: Array<{ item: string; rule: DeterministicRule; diff: string }>;+ llm_items: Array<{ item: string; named: string | null; estimate_usd: number }>;+ held: HeldEntry[];+ skipped: Array<{ item: string; reason: string }>;+ caps: { max_usd_per_page: number; max_usd_per_day: number; day_remaining_usd: number | null; run_max_usd: number | null };+ next_actions: Action[];+}++/** The slug-conflicts result's `verification` (report hook). */+export interface SlugConflictsVerification {+ candidates: number;+ repaired_by_tier: Record<Tier, number>;+ held_by_reason: Record<string, number>;+ oldest_hold_at: string | null;+ llm_judgments: number;+ llm_usd: number;+}++const CALL_TIMEOUT_MS = () => { const n = parseInt(process.env.GBRAIN_CONTENT_REPAIR_CALL_TIMEOUT_MS ?? process.env.GBRAIN_FENCE_REPAIR_CALL_TIMEOUT_MS ?? '', 10); return Number.isFinite(n) && n > 0 ? n : 90_000; };+/** How long a transient model failure waits before the maintenance run tries the candidate again. */+const RETRY_AFTER_MS = 24 * 3_600_000;+const TRANSIENT: ReadonlySet<string> = new Set(['llm_unavailable', 'ledger_unavailable', 'sync_in_progress', 'claimed_elsewhere', 'changed_since_read']);+const STOPWORDS: ReadonlySet<string> = new Set(['a', 'an', 'the', 'of', 'and', 'or', 'for', 'to', 'in', 'on', 'at', 'by', 'with', 'from', 'inc', 'llc', 'ltd', 'co', 'corp', 'company', 'mr', 'ms', 'dr']);++const itemName = (entry: Pick<ApprovedConflict, 'source_id' | 'path'>) => `${entry.source_id}:${entry.path}`;++function previewArgv(scope: RepairScope, selection: Selection): string[] {+ return ['gbrain', 'repair', 'slug-conflicts', ...(scope.source_ids.length === 1 ? ['--source', scope.source_ids[0]!] : []),+ ...selection.only.flatMap(path => ['--only', path]), ...selection.skip.flatMap(path => ['--skip', path]), ...(selection.no_llm ? ['--no-llm'] : [])];+}++/** Slugified title words, stopwords removed. */+export function titleTokens(title: string): Set<string> {+ return new Set(title.toLowerCase().normalize('NFKD').replace(/[\u0300-\u036f]/g, '').split(/[^a-z0-9]+/).filter(word => word.length > 1 && !STOPWORDS.has(word)));+}++/** Git-visible Markdown under the root (tracked and untracked, ignored files excluded); a plain walk outside Git. */+function checkoutSlugs(root: string): Set<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('/'));+ }+ const out = new Set<string>();+ for (const path of paths) {+ if (!/\.mdx?$/i.test(path) || path.split('/').some(part => part.startsWith('.')) || isReservedSkillBundlePath(path)) continue;+ out.add(slugifyPath(path)); out.add(resolveSlugForPath(path));+ }+ return out;+}++/** The declared `slug:` value of a file as written, or null when the frontmatter has none. */+function declaredSlug(content: string): string | null {+ const block = /^\uFEFF?---[ \t]*\r?\n([\s\S]*?)\r?\n---[ \t]*(?:\r?\n|$)/.exec(content)?.[1];+ const line = block?.split(/\r?\n/).find(l => /^slug:\s*\S/.test(l));+ return line ? line.replace(/^slug:\s*/, '').trim().replace(/^["']|["']$/g, '') : null;+}++/** The slug a declared value is looked up by: as written, then as the screen normalizes it. */+function lookupSlugs(declared: string): string[] {+ return [...new Set([declared, slugifyPath(declared)])].filter(Boolean);+}++/**+ * The exact edit: the `slug:` line removed (with its line break) and nothing else. `autoFixFrontmatter` with the+ * file path decides that this is the one fix the file needs, as `repair frontmatter` proposes it; null when the+ * file needs other frontmatter changes too, or the result still fails to strict-parse or earns a hold.+ */+export function removeSlugLine(content: string, sourcePath: string, path: string, activePack?: FenceSource['activePack']): string | null {+ const fixed = autoFixFrontmatter(content, { filePath: sourcePath });+ if (fixed.fixes.length !== 1 || fixed.fixes[0]!.code !== 'SLUG_MISMATCH' || fixed.content === content) return null;+ const block = /^(\uFEFF?---[ \t]*(\r?\n))([\s\S]*?)(\r?\n---[ \t]*(?:\r?\n|$))/.exec(content);+ if (!block) return null;+ const newline = block[2]!;+ const lines = block[3]!.split(/\r?\n/);+ const at = lines.findIndex(line => /^slug:\s*\S/.test(line));+ if (at < 0) return null;+ const after = `${block[1]}${[...lines.slice(0, at), ...lines.slice(at + 1)].join(newline)}${block[4]}${content.slice(block[0].length)}`;+ const parsed = parseMarkdown(after, path, { validate: true, ...(activePack ? { activePack } : {}) });+ if (parsed.errors?.some(error => error.code === 'YAML_PARSE')) return null;+ if (classifyImportHold(parsed, { expectedSlug: resolveSlugForPath(sourcePath), byteLength: Buffer.byteLength(after), maxBytes: MAX_FILE_SIZE })) return null;+ return after;+}++/** A stored page as the judgment shows it: serialized with its frontmatter, so both sides read alike. */+function pageContent(snapshot: PageSnapshot): string {+ return serializePageToMarkdown(snapshot.page, snapshot.tags);+}++interface Settings {+ llmEnabled: boolean; model: string | null; overrides: Awaited<ReturnType<typeof loadPricingOverrides>>; capSource: CapSource;+ perPageUsd: number; perDayUsd: number; dayRemaining: number | null; runMaxUsd: number | null;+}++async function settings(engine: BrainEngine, opts: Pick<RepairPlanOptions, 'noLlm' | 'maxLlmUsd'>): Promise<Settings> {+ const caps = await readFenceRepairCaps(engine);+ const day = await dailyLedger(engine, FENCE_REPAIR_LEDGER).readDay().catch(() => null);+ return { llmEnabled: !opts.noLlm && await fenceRepairLlmEnabled(engine), model: await resolveContentRepairModel(engine), overrides: await loadPricingOverrides(engine),+ capSource: caps.perPageSource === 'user' || caps.perDaySource === 'user' || opts.maxLlmUsd !== undefined ? 'user' : 'default',+ perPageUsd: caps.perPageUsd, perDayUsd: caps.perDayUsd, dayRemaining: day ? Math.max(0, caps.perDayUsd - day.committedUsd - day.reservedUsd) : null, runMaxUsd: opts.maxLlmUsd ?? null };+}++/** Held because no measured model has a key: the exact choice the user makes. */+function noMeasuredModel(path: string): string {+ return `No model measured for the slug-conflict judgment has a provider key here (${CONTENT_REPAIR_MEASURED_MODELS.join(', ')}) and ${CONTENT_REPAIR_MODEL_KEY} is unset, so ${path} stays held. `+ + `Decide the slug by hand, or ask the user which model to trust, then: gbrain config set ${CONTENT_REPAIR_MODEL_KEY} <provider:model>.`;+}++/** One candidate's current state, read from the checkout and the page store. */+interface Candidate {+ src: FenceSource; path: string; sourcePath: string; slug: string; hold: GitHoldRecord | null; content: string; before: string;+ snapshot: PageSnapshot | null; declared: string; named: PageSnapshot | null; namedSlug: string | null;+}++type Analysis =+ | { status: 'skip'; reason: 'already_exempt' | 'already_clean' | 'gone' | 'unsafe_path' | 'not_utf8'; message: string }+ | { status: 'deterministic'; rule: DeterministicRule; after: string }+ | { status: 'llm'; input: JudgmentInput }+ | { status: 'held'; reason: string; message: string };++async function readCandidate(engine: BrainEngine, src: FenceSource, path: string): Promise<{ ok: true; cand: Candidate } | { ok: false; reason: 'gone' | 'unsafe_path' | 'not_utf8' | 'no_checkout' }> {+ if (!src.root) return { ok: false, reason: 'no_checkout' };+ const abs = join(src.root, path);+ if (!existsSync(abs)) return { ok: false, reason: 'gone' };+ try { confinedRepairTarget(src.root, path, src.id, 'content'); } catch (error) {+ if (error instanceof OperationError) return { ok: false, reason: 'unsafe_path' };+ throw error;+ }+ const bytes = readFileSync(abs);+ const content = bytes.toString('utf8');+ if (!Buffer.from(content, 'utf8').equals(bytes)) return { ok: false, reason: 'not_utf8' };+ const hold = await readGitHold(engine, src.id, src.incarnation, path);+ const sourcePath = hold?.source_path ?? path;+ const [byOrigin] = await engine.executeRaw<{ slug: string }>('SELECT slug FROM pages WHERE source_id=$1 AND source_path=$2 AND deleted_at IS NULL LIMIT 1', [src.id, sourcePath]);+ const slug = byOrigin?.slug ?? hold?.slug ?? resolveSlugForPath(sourcePath);+ const snapshot = await engine.readPageSnapshot(slug, { sourceId: src.id, includeDeleted: true });+ const declared = declaredSlug(content) ?? '';+ let named: PageSnapshot | null = null;+ for (const lookup of lookupSlugs(declared)) {+ named = await engine.readPageSnapshot(lookup, { sourceId: src.id, resolveAlias: true });+ if (named) break;+ }+ return { ok: true, cand: { src, path, sourcePath, slug, hold, content, before: sha256(bytes), snapshot: snapshot && !snapshot.page.deleted_at ? snapshot : null, declared,+ named, namedSlug: named?.page.slug ?? null } };+}++/** The free tier over a candidate: exempt, clean, a deterministic edit, or the model's question. */+function analyze(cand: Candidate, slugsInCheckout: () => Set<string>): Analysis {+ const expected = resolveSlugForPath(cand.sourcePath);+ if (!cand.declared || cand.declared === expected || slugifyPath(cand.declared) === expected) {+ return { status: 'skip', reason: 'already_clean', message: `${cand.path} no longer declares a conflicting slug; the next gbrain sync --source ${cand.src.id} --no-pull clears its hold.` };+ }+ const own = cand.named && ((cand.hold?.page_id !== null && cand.hold?.page_id !== undefined && cand.named.page.id === cand.hold.page_id)+ || (cand.named.page.source_path != null && cand.named.page.source_path === cand.sourcePath) || (cand.snapshot !== null && cand.named.page.id === cand.snapshot.page.id));+ if (own) return { status: 'skip', reason: 'already_exempt', message: `The slug: line of ${cand.path} resolves to the file's own page (${cand.named!.page.slug}); nothing to repair.` };+ const after = () => removeSlugLine(cand.content, cand.sourcePath, cand.path, cand.src.activePack);+ if (!cand.named) {+ const inCheckout = lookupSlugs(cand.declared).some(slug => slugsInCheckout().has(slug));+ if (!inCheckout) {+ const edited = after();+ return edited === null ? { status: 'held', reason: 'still_invalid', message: `Removing the slug: line of ${cand.path} alone does not make it importable (the frontmatter needs other changes too); preview gbrain repair frontmatter --source ${cand.src.id} --only ${cand.path} --include-ambiguous.` }+ : { status: 'deterministic', rule: 'absent_page', after: edited };+ }+ } else {+ const parsed = parseMarkdown(cand.content, cand.path, cand.src.activePack ? { activePack: cand.src.activePack } : undefined);+ const shared = [...titleTokens(parsed.title)].some(token => titleTokens(cand.named!.page.title ?? '').has(token));+ if (parsed.type !== cand.named.page.type && !shared) {+ const edited = after();+ return edited === null ? { status: 'held', reason: 'still_invalid', message: `Removing the slug: line of ${cand.path} alone does not make it importable (the frontmatter needs other changes too); preview gbrain repair frontmatter --source ${cand.src.id} --only ${cand.path} --include-ambiguous.` }+ : { status: 'deterministic', rule: 'different_type', after: edited };+ }+ }+ if (after() === null) return { status: 'held', reason: 'still_invalid', message: `Removing the slug: line of ${cand.path} alone would not make it importable, so no model is asked; preview gbrain repair frontmatter --source ${cand.src.id} --only ${cand.path} --include-ambiguous.` };+ const held = judgmentParticipant({ path: cand.path, slug: cand.slug, content: cand.content, otherSlug: cand.namedSlug });+ const named = cand.named ? judgmentParticipant({ path: cand.named.page.source_path ?? null, slug: cand.named.page.slug, content: pageContent(cand.named), otherSlug: cand.slug, type: cand.named.page.type }) : null;+ return { status: 'llm', input: { held, named, reason: 'frontmatter_slug_conflict' } };+}++const nextAttempt = (reason: string, resetsAt?: string): string | null => reason === 'budget_exhausted' ? resetsAt ?? nextUtcMidnight(new Date()) : TRANSIENT.has(reason) ? new Date(Date.now() + RETRY_AFTER_MS).toISOString() : null;++async function recordState(engine: BrainEngine, cand: Pick<Candidate, 'src' | 'path' | 'hold'>, state: Omit<ContentHoldRepairState, 'at'>): Promise<void> {+ if (!cand.hold) return;+ await recordContentHoldRepair(engine, { sourceId: cand.src.id, incarnation: cand.src.incarnation, path: cand.path, upstreamVersion: cand.hold.upstream_version,+ state: { ...state, at: new Date().toISOString() } }).catch(() => false);+}++function item(entry: ApprovedConflict, index: number, hash: string | null, last: boolean): ConflictItem {+ return { cursor: { phase: 1, id: index + 1 }, source_id: entry.source_id, slug: entry.path, chars: 0, action: `${entry.tier}:${entry.path}`,+ ...(entry.tier === 'llm' ? { llm_usd: entry.estimate_usd } : {}), entry, hash, last };+}++function digestOf(selection: Selection): string {+ return sha256(JSON.stringify([selection.source_ids, selection.only, selection.skip, selection.no_llm]));+}++/** The candidates of the selection: held paths, plus `--only` files that screen as a slug conflict now. */+async function candidatePaths(engine: BrainEngine, src: FenceSource, selection: Selection): Promise<{ paths: string[]; unknown: string[] }> {+ const holds = ((await readGitSourceHolds(engine, { sourceIds: [src.id] }))[0]?.holds ?? []).filter(hold => hold.code === 'frontmatter_slug_conflict').map(hold => hold.path);+ const paths = new Set(holds.filter(path => (!selection.only.length || selection.only.includes(path)) && !selection.skip.includes(path)));+ const unknown: string[] = [];+ for (const path of selection.only) {+ if (paths.has(path) || selection.skip.includes(path)) continue;+ const abs = src.root ? join(src.root, path) : null;+ if (!abs || !existsSync(abs) || !lstatSync(abs).isFile()) { unknown.push(path); continue; }+ const content = readFileSync(abs, 'utf8');+ const hold = classifyImportHold(parseMarkdown(content, path, { validate: true }), { expectedSlug: resolveSlugForPath(path), byteLength: Buffer.byteLength(content), maxBytes: MAX_FILE_SIZE });+ if (hold?.code === 'frontmatter_slug_conflict') paths.add(path); else unknown.push(path);+ }+ return { paths: [...paths].sort(), unknown };+}+++++/** The hash a preview of this selection prints when it finds nothing to repair. */++async function emptyPlanHash(engine: BrainEngine, scope: RepairScope, selection: Selection): Promise<string> {++ const sourcesRows = await engine.executeRaw<{ id: string; incarnation: string }>('SELECT id, incarnation::text AS incarnation FROM sources WHERE id=ANY($1::text[]) ORDER BY id', [scope.source_ids]);++ return previewHash({ kind: 'slug-conflicts-v1', brain_id: scope.brain_id, sources: sourcesRows, selection, items: [] });++}+++export const slugConflictsRepair: RepairHandler = {+ kind: 'slug-conflicts',+ outcomeItemsLimit: 1000,+ async plan(engine, scope, _after, opts): Promise<RepairPlan> {+ const selection: Selection = { source_ids: scope.source_ids, only: [...(opts?.only ?? [])].sort(), skip: [...(opts?.skip ?? [])].sort(), no_llm: opts?.noLlm === true };+ const preview = previewArgv(scope, selection);+ if (opts?.apply && opts.expect) {++ // #6377: a preview that found nothing saved no set; its hash still binds "nothing to apply" (the content lane passes one hash per kind).++ if (opts.expect === await emptyPlanHash(engine, scope, selection)) return { items: [], preview_hash: opts.expect, residuals: {}, llm: { usd: 0, cap_remaining_usd: null } };+ const approved = await loadApprovedSet<ApprovedSetItem>(engine, { command: 'slug-conflicts', hash: opts.expect, previewCommand: shellQuote(preview) });+ if (approved.items.some(entry => digestOf(entry.selection) !== digestOf(selection))) throw previewChangedError(opts.expect, shellQuote(preview));+ const items = approved.items.map(({ selection: _chosen, ...entry }, index) => item(entry, index, opts.expect!, index === approved.items.length - 1));+ const s = await settings(engine, opts);+ return { items, preview_hash: opts.expect, residuals: {}, llm: { usd: items.reduce((sum, i) => sum + (i.llm_usd ?? 0), 0), cap_remaining_usd: s.llmEnabled ? s.dayRemaining : 0 } };+ }+ const s = await settings(engine, opts ?? { noLlm: false });+ const residuals: Record<string, number> = {};+ const warnings: string[] = [];+ const approved: ApprovedConflict[] = [];+ const diffs: SlugConflictsPreviewDetails['diffs'] = [];+ const held: HeldEntry[] = [];+ const skipped: SlugConflictsPreviewDetails['skipped'] = [];+ const llmItems: SlugConflictsPreviewDetails['llm_items'] = [];+ let unpricedWarned = false;+ for (const sourceId of scope.source_ids) {+ const src = await loadFenceSource(engine, sourceId, { remote: opts?.remote !== false, work: 'content repair' });+ if (!src) continue;+ const { paths, unknown } = await candidatePaths(engine, src, selection);+ warnings.push(...unknown.map(path => `--only ${path}: no held or conflicting file at that path in ${sourceId}; check the source-relative path.`));+ let slugs: Set<string> | null = null;+ const slugsInCheckout = () => (slugs ??= src.root ? checkoutSlugs(src.root) : new Set<string>());+ for (const path of paths) {+ const name = `${sourceId}:${path}`;+ const keep = async (entry: Omit<HeldEntry, 'item'>, state?: Omit<ContentHoldRepairState, 'at'>) => {+ held.push({ item: name, ...entry }); residuals[entry.reason] = (residuals[entry.reason] ?? 0) + 1;+ if (opts?.apply && state) await recordState(engine, { src, path, hold: await readGitHold(engine, src.id, src.incarnation, path) }, state);+ };+ const skip = (reason: string) => { skipped.push({ item: name, reason }); residuals[reason] = (residuals[reason] ?? 0) + 1; };+ if (src.owner) { await keep({ reason: src.owner.reason, tier: 'manual', resolution: `${src.owner.message} ${src.owner.why}` }); continue; }+ if (src.mirror) { await keep({ reason: 'mirror_read_only', tier: 'manual', resolution: `${path} belongs to a read-only mirror, so gbrain does not edit its file; remove the slug: line where the source is written.` }); continue; }+ if (repairBusy(src.busy, { path })) { await keep({ reason: 'sync_in_progress', tier: 'manual', resolution: repairBusyMessage(src.busy, src.id, path) }); continue; }+ const read = await readCandidate(engine, src, path);+ if (!read.ok) {+ if (read.reason === 'gone' || read.reason === 'no_checkout') { skip(read.reason === 'gone' ? 'gone' : 'local_path_missing'); continue; }+ await keep({ reason: read.reason, tier: 'manual', resolution: read.reason === 'unsafe_path'+ ? `${path} is a symlink, sits under one, or resolves outside the source root; gbrain never writes through one. Replace it with the real file.`+ : `${path} is not valid UTF-8; re-save it as UTF-8 and preview again.` });+ continue;+ }+ const cand = read.cand;+ const analysis = analyze(cand, slugsInCheckout);+ if (analysis.status === 'skip') { skip(analysis.reason); continue; }+ if (analysis.status === 'held') { await keep({ reason: analysis.reason, tier: 'manual', resolution: analysis.message }, { action: 'remove_slug', reason: analysis.reason, next_attempt_after: null }); continue; }+ const base: Omit<ApprovedConflict, 'tier' | 'rule' | 'after' | 'estimate_usd' | 'llm_waiting'> = { source_id: src.id, path, source_path: cand.sourcePath, slug: cand.slug, mode: src.managed ? 'managed' : 'legacy',+ page_id: cand.snapshot?.page.id ?? null, revision: cand.snapshot?.revision ?? null, before: cand.before, upstream_version: cand.hold?.upstream_version ?? null, held: cand.hold !== null,+ named: cand.namedSlug, named_page_id: cand.named?.page.id ?? null, named_sha256: cand.named ? sha256(pageContent(cand.named)) : null };+ if (analysis.status === 'deterministic') {+ approved.push({ ...base, tier: 'deterministic', rule: analysis.rule, after: sha256(Buffer.from(analysis.after, 'utf8')), estimate_usd: 0, llm_waiting: 0 });+ diffs.push({ item: name, rule: analysis.rule, diff: lineDiff(path, cand.content, analysis.after) });+ continue;+ }+ const pending = (reason: string, resolution: string, next: string | null = null) => keep({ reason, tier: 'llm', resolution }, { action: 'pending', reason, ...(cand.namedSlug ? { named: cand.namedSlug } : {}),+ ...(s.model ? { model: s.model } : {}), next_attempt_after: next });+ if (!s.llmEnabled) {+ await pending('llm_disabled', `Model repair is off (${selection.no_llm ? '--no-llm' : 'fences.repair.llm false'}), so ${path} stays held: whether it and ${cand.namedSlug ?? 'the page its slug: line names'} are the same page needs a judgment. `+ + 'Decide by hand, or ask the user before turning model repair on: gbrain config set fences.repair.llm true.');+ continue;+ }+ if (!s.model) { await pending('no_measured_model', noMeasuredModel(path)); continue; }+ const estimate = judgmentEstimate(analysis.input, { model: s.model, overrides: s.overrides, capSource: s.capSource });+ if (!estimate.ok) { await pending('no_pricing', `A spend cap is set but gbrain has no price for ${s.model}. ${estimate.guidance.lookup} Register it with: ${estimate.guidance.register_command}`); continue; }+ if (estimate.estimated && !unpricedWarned) {+ unpricedWarned = true;+ warnings.push(`gbrain has no price for the content-repair model ${s.model}; the judgment runs under the default caps and is metered at an estimated ceiling (the highest chat rate gbrain knows). Make it exact with: ${pricingSetCommand(s.model, 'chat')}`);+ }+ if (s.perPageUsd === 0 || s.perDayUsd === 0) {+ const key = s.perPageUsd === 0 ? 'page' : 'day';+ await pending('budget_exhausted', `Model repair spend is set to 0 (fences.repair.max_usd_per_${key}), so ${path} stays held. Raising it is the user's call: gbrain config set fences.repair.max_usd_per_${key} <usd>.`, nextUtcMidnight(new Date()));+ continue;+ }+ if (estimate.usd > s.perPageUsd + 1e-9) {+ await pending('budget_exhausted', `The estimated judgment cost ($${estimate.usd.toFixed(4)}) exceeds fences.repair.max_usd_per_page ($${s.perPageUsd.toFixed(2)}). Raising it is the user's call: gbrain config set fences.repair.max_usd_per_page <usd>.`);+ continue;+ }+ approved.push({ ...base, tier: 'llm', rule: null, after: null, estimate_usd: estimate.usd, llm_waiting: 0 });+ llmItems.push({ item: name, named: cand.namedSlug, estimate_usd: estimate.usd });+ }+ }+ let waiting = 0;+ for (const entry of [...approved].reverse()) { if (entry.tier === 'llm') waiting++; entry.llm_waiting = entry.tier === 'llm' ? waiting : 0; }+ const sourcesRows = 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 hash = previewHash({ kind: 'slug-conflicts-v1', brain_id: scope.brain_id, sources: sourcesRows, selection, items: approved });+ if (approved.length && !opts?.apply) await saveApprovedSet<ApprovedSetItem>(engine, { command: 'slug-conflicts', hash }, approved.map(entry => ({ ...entry, selection })));+ const listing: RepairListing[] = [+ ...approved.map(entry => ({ item: itemName(entry), class: entry.tier, detail: entry.tier === 'deterministic' ? `remove_slug (${entry.rule}): the slug: line is removed; the path decides the slug`+ : `model decides (${s.model}) at apply time: remove_slug, merge_into ${entry.named ?? '?'} or needs_human; est. $${entry.estimate_usd.toFixed(4)}` })),+ ...held.map(entry => ({ item: entry.item, class: entry.reason, detail: entry.resolution })),+ ...skipped.map(entry => ({ item: entry.item, class: entry.reason })),+ ];+ const llmUsd = approved.reduce((sum, entry) => sum + entry.estimate_usd, 0);+ const apply = [...preview, ...(s.runMaxUsd !== null ? ['--max-usd', String(s.runMaxUsd)] : []), '--apply', '--expect', hash];+ const next_actions: Action[] = approved.length ? [{ argv: apply, consent: [], actor: 'agent', requires_exclusive: false, plan_hash: hash, preview_argv: preview,+ why: `Applies exactly the ${approved.length} previewed slug-conflict repair(s)${llmItems.length ? `, ${llmItems.length} of them judged by the model (estimated $${llmUsd.toFixed(4)}; a recommended merge or an undecidable pair writes nothing and is recorded on the hold)` : ''}; a file that changed since this preview is skipped.`,+ verify: { argv: ['gbrain', 'sources', 'status', ...(scope.source_ids.length === 1 ? [scope.source_ids[0]!] : []), '--json'] } }] : [];+ const counts = { deterministic: approved.filter(e => e.tier === 'deterministic').length, llm: llmItems.length, held: held.length, skipped: skipped.length };+ const details: SlugConflictsPreviewDetails = { counts, model: s.llmEnabled ? s.model : null, llm_enabled: s.llmEnabled, diffs, llm_items: llmItems, held, skipped,+ caps: { max_usd_per_page: s.perPageUsd, max_usd_per_day: s.perDayUsd, day_remaining_usd: s.dayRemaining, run_max_usd: s.runMaxUsd }, next_actions };+ return { items: approved.map((entry, index) => item(entry, index, null, index === approved.length - 1)), preview_hash: hash, residuals, listing,+ ...(warnings.length ? { warnings } : {}), details: details as unknown as Record<string, unknown>, llm: { usd: llmUsd, cap_remaining_usd: s.llmEnabled ? s.dayRemaining : 0 } };+ },+ async apply(ctx, raw, opts): Promise<RepairItemOutcome> {+ if (ctx.remote !== false) throw trustedCliRequired('gbrain repair slug-conflicts writes files and may call a paid model, so it runs only from the trusted local CLI or the maintenance job on the brain host.');+ const { entry, hash, last } = raw as ConflictItem;+ try {+ return await applyConflict(ctx, entry, { embed: opts?.embed === true, expect: hash, allowanceUsd: opts?.llmAllowanceUsd, deadline: opts?.deadline, noLlm: opts?.noLlm === true });+ } finally {+ if (hash && last) await clearApprovedSet(ctx.engine, { command: 'slug-conflicts', hash });+ }+ },+ render(details, opts) {+ const d = details as unknown as SlugConflictsPreviewDetails;+ const lines = [` tiers: deterministic=${d.counts.deterministic}, model=${d.counts.llm}, held=${d.counts.held}, skipped=${d.counts.skipped}${d.llm_enabled ? `; model ${d.model}` : '; model repair off'}`];+ if (d.counts.llm || d.held.some(h => h.tier === 'llm')) {+ lines.push(` model caps: $${d.caps.max_usd_per_page.toFixed(2)}/page, $${d.caps.max_usd_per_day.toFixed(2)}/day${d.caps.day_remaining_usd !== null ? ` ($${d.caps.day_remaining_usd.toFixed(4)} left today)` : ''}`+ + `${d.caps.run_max_usd !== null ? `; this run at most $${d.caps.run_max_usd.toFixed(4)}` : ''}`);+ }+ const shown = opts.diff ? d.diffs : d.diffs.slice(0, 1);+ for (const diff of shown) lines.push(` deterministic: ${diff.item} (remove_slug, ${diff.rule})`, ...diff.diff.split('\n').map(line => ` ${line}`));+ if (!opts.diff && d.diffs.length > shown.length) lines.push(` (one sample diff; --diff or --json shows all ${d.diffs.length})`);+ for (const llm of d.llm_items) lines.push(` model decides: ${llm.item}${llm.named ? ` vs page ${llm.named}` : ' (no page has the named slug)'}: remove_slug, merge_into or needs_human at apply time; est. $${llm.estimate_usd.toFixed(4)}`);+ for (const h of d.held) lines.push(` held ${h.item} [${h.reason}]: ${h.resolution}`);+ for (const s of d.skipped) lines.push(` skipped ${s.item} [${s.reason}]`);+ for (const action of d.next_actions) lines.push(` next: ${shellQuote(action.argv!)}`);+ return lines;+ },+ async report(ctx, scope, result) {+ return reportConflicts(ctx, scope, result);+ },+};++interface ApplyOptions { embed: boolean; expect: string | null; allowanceUsd?: number; deadline?: number; noLlm: boolean }++async function applyConflict(ctx: OperationContext, entry: ApprovedConflict, opts: ApplyOptions): Promise<RepairItemOutcome> {+ const engine = ctx.engine;+ const where = { path: entry.path, slug: entry.slug, mode: entry.mode, tier: entry.tier, ...(entry.named ? { named: entry.named } : {}) };+ const moved = opts.expect ? 'changed_since_preview' : 'changed_since_read';+ const skipped = (reason: string, message: string): RepairItemOutcome => ({ applied: false, outcome: 'skipped', reason, detail: { ...where, message } });+ const src = await loadFenceSource(engine, entry.source_id, { remote: false, work: 'content repair' });+ if (!src) return skipped(moved, `Source ${entry.source_id} is gone or archived.`);+ const hold = await readGitHold(engine, src.id, src.incarnation, entry.path);+ const held = async (reason: string, message: string, state: Omit<ContentHoldRepairState, 'at'> | null, extra: Record<string, unknown> = {}): Promise<RepairItemOutcome> => {+ if (state) await recordState(engine, { src, path: entry.path, hold }, state);+ return { applied: false, outcome: 'held', reason, detail: { ...where, message, ...extra } };+ };+ if (src.owner) {+ const out = skipped(src.owner.reason, src.owner.message);+ return { ...out, detail: { ...out.detail, why: src.owner.why, fix: src.owner.fix.argv, retryable: src.owner.retryable } };+ }+ if (src.mirror) return held('mirror_read_only', `${entry.path} belongs to a read-only mirror, so gbrain does not edit its file.`, null);+ // Re-checked here and again at the write's admission (file-repair.ts): a sync may have frozen this candidate since the plan.+ if (repairBusy(src.busy, { path: entry.path, slug: entry.slug })) {+ await recordState(engine, { src, path: entry.path, hold }, { action: 'pending', reason: 'sync_in_progress', next_attempt_after: nextAttempt('sync_in_progress') });+ return skipped('sync_in_progress', repairBusyMessage(src.busy, src.id, entry.path));+ }+ const read = await readCandidate(engine, src, entry.path);+ if (!read.ok) return skipped(moved, `${entry.path} is ${read.reason === 'gone' ? 'gone' : read.reason}.`);+ const cand = read.cand;+ if (cand.before !== entry.before || (cand.named ? sha256(pageContent(cand.named)) : null) !== entry.named_sha256 || (cand.named?.page.id ?? null) !== entry.named_page_id) {+ return skipped(moved, `${entry.path} or the page its slug: line names changed since it was ${opts.expect ? 'previewed' : 'read'}; preview again with ${shellQuote(contentPreviewArgv(src.id, entry.path))}.`);+ }+ let slugs: Set<string> | null = null;+ const analysis = analyze(cand, () => (slugs ??= src.root ? checkoutSlugs(src.root) : new Set<string>()));+ if (analysis.status === 'skip') return skipped(analysis.reason, analysis.message);+ if (analysis.status === 'held') return held(analysis.reason, analysis.message, { action: 'remove_slug', reason: analysis.reason, next_attempt_after: null });+ if (analysis.status === 'deterministic') {+ if (opts.expect && sha256(Buffer.from(analysis.after, 'utf8')) !== entry.after) return skipped('changed_since_preview', `The repair of ${entry.path} differs from the preview; preview again.`);+ return write(ctx, src, cand, analysis.after, { tier: 'deterministic', confidence: 'high', model: null, cost_usd: 0 }, opts, held, { rule: analysis.rule });+ }+ return judge(ctx, src, cand, analysis.input, entry, opts, held);+}++type HeldFn = (reason: string, message: string, state: Omit<ContentHoldRepairState, 'at'> | null, extra?: Record<string, unknown>) => Promise<RepairItemOutcome>;++/** Writes the edited file through the source's path with its receipt; the hold clears in the same write (managed) or right after the import (legacy). */+async function write(ctx: OperationContext, src: FenceSource, cand: Candidate, after: string, parts: Pick<ContentRepairReceipt, 'tier' | 'confidence' | 'model' | 'cost_usd'>, opts: ApplyOptions, held: HeldFn,+ extra: Record<string, unknown>): Promise<RepairItemOutcome> {+ const engine = ctx.engine;+ const local = { ...ctx, remote: false, sourceId: src.id } as OperationContext;+ const receipt: ContentRepairReceipt = { actor: CONTENT_REPAIR_ACTOR, hold_code: CONTENT_REPAIR_HOLD_CODE, action: 'remove_slug', ...parts, before_sha256: cand.before, after_sha256: sha256(Buffer.from(after, 'utf8')) };+ const detail = { path: cand.path, slug: cand.slug, action: 'remove_slug', tier: parts.tier, confidence: parts.confidence, ...(cand.namedSlug ? { named: cand.namedSlug } : {}), ...extra };+ const spend = parts.cost_usd ? { llm_usd: parts.cost_usd } : {};+ if (src.managed) {+ const config = await repairScreenConfig(engine, src.id);+ const publication = await prepareRepairPublication(engine, { sourceId: src.id, slug: cand.slug, sourcePath: cand.sourcePath, path: cand.path, root: src.root!, content: after,+ snapshot: cand.snapshot, base: cand.snapshot, ...config });+ if (publication.status === 'refused') return held(publication.refusal.code === 'frontmatter_slug_conflict' ? 'still_invalid' : publication.refusal.code, `Importing the repaired ${cand.path} would be refused (${publication.refusal.code}), so nothing was written.`,+ { action: 'remove_slug', reason: 'still_invalid', next_attempt_after: null }, spend);+ if (publication.status === 'overlay') return held('canonical_overlay', `Importing the repaired ${cand.path} would keep page data the file does not carry (tags added outside the file, a withdrawal or sanitized text), so nothing was written. `+ + `Edit the file by hand to carry them (gbrain get --source ${src.id} -- ${cand.slug} shows the page), remove the slug: line, and commit.`, { action: 'remove_slug', reason: 'canonical_overlay', next_attempt_after: null }, spend);+ try {+ const outcome = await submitManagedFileRepair(local, { sourceId: src.id, requestId: await repairRequestId(local, 'slug-conflicts', { source_id: src.id, slug: cand.slug }, `${receipt.before_sha256}:${receipt.after_sha256}`),+ slug: cand.slug, path: cand.path, sourcePath: cand.sourcePath, content: after, beforeHash: cand.before, resultDigest: publication.digest,+ ...(cand.snapshot ? { expected_revision: cand.snapshot.revision } : {}), noEmbed: !opts.embed, contentRepair: receipt });+ const persistence = outcome.persistence as { git_state?: string } | undefined;+ return { applied: true, outcome: 'repaired', detail: { ...detail, mode: 'managed', imported: outcome.status, hold_cleared: outcome.hold_cleared === true, committed: persistence?.git_state ?? 'not_requested' }, ...spend };+ } catch (error) {+ if (error instanceof OperationError && ['changed_since_preview', 'revision_conflict', 'page_identity_changed', 'source_changed'].includes(error.code)) {+ return { applied: false, outcome: 'skipped', reason: 'changed_since_read', detail: { ...detail, message: `${cand.path} changed while it was being repaired; the next run reads it again.` }, ...spend };+ }+ if (error instanceof OperationError && error.code === 'sync_in_progress') {+ await recordState(engine, { src, path: cand.path, hold: cand.hold }, { action: 'pending', reason: 'sync_in_progress', next_attempt_after: nextAttempt('sync_in_progress') });+ return { applied: false, outcome: 'skipped', reason: 'sync_in_progress', detail: { ...detail, message: error.message }, ...spend };+ }+ throw error;+ }+ }+ const root = src.root!;+ let abs: string;+ try { abs = confinedRepairTarget(root, cand.path, src.id, 'content'); } catch (error) {+ if (error instanceof OperationError) return held('unsafe_path', `${cand.path} is a symlink, sits under one, or resolves outside the source root; gbrain never writes through one.`, null, spend);+ throw error;+ }+ if (sha256(readFileSync(abs)) !== cand.before) return { applied: false, outcome: 'skipped', reason: 'changed_since_read', detail: { ...detail, message: `${cand.path} changed after the repair read it, so nothing was written.` }, ...spend };+ const backup = createFrontmatterBackup(abs, { sourcePath: root, backupRoot: gbrainPath('backups', 'content-repair', makeFrontmatterBackupRunId()) });+ writeFileSync(abs, after);+ const imported = await importFromFile(engine, abs, cand.sourcePath, { sourceId: src.id, noEmbed: !opts.embed });+ if (imported.status === 'error' || imported.refusal) {+ writeFileSync(abs, cand.content);+ return held('still_invalid', `The repaired ${cand.path} did not import (${imported.refusal?.code ?? 'error'}), so the file was restored from its backup.`, { action: 'remove_slug', reason: 'still_invalid', next_attempt_after: null }, spend);+ }+ const holdCleared = cand.hold ? await clearGitHold(engine, { sourceId: src.id, incarnation: src.incarnation, path: cand.path, observedAt: new Date().toISOString() }) : false;+ const commitStep = `git -C ${shellQuote([root])} add -- ${shellQuote([cand.path])} && git -C ${shellQuote([root])} commit -m ${shellQuote([contentRepairCommitSubject(cand.path)])} -m ${shellQuote([contentRepairTrailer(receipt)])} -- ${shellQuote([cand.path])}`;+ return { applied: true, outcome: 'repaired', detail: { ...detail, mode: 'legacy', backup, imported: imported.status, hold_cleared: holdCleared, content_repair: receipt, committed: 'commit_step', commit_step: commitStep }, ...spend };+}++/** The model tier for one candidate: the metered judgment, then the verdict's action. */+async function judge(ctx: OperationContext, src: FenceSource, cand: Candidate, input: JudgmentInput, entry: ApprovedConflict, opts: ApplyOptions, held: HeldFn): Promise<RepairItemOutcome> {+ const engine = ctx.engine;+ const s = await settings(engine, { noLlm: opts.noLlm, ...(opts.allowanceUsd !== undefined ? { maxLlmUsd: opts.allowanceUsd } : {}) });+ const named = cand.namedSlug ? { named: cand.namedSlug } : {};+ const pending = (reason: string, message: string, next: string | null, extra: Record<string, unknown> = {}) => held(reason, message, { action: 'pending', reason, ...named, ...(s.model ? { model: s.model } : {}), next_attempt_after: next }, extra);+ if (!s.llmEnabled) return pending('llm_disabled', `Model repair is off, so ${cand.path} stays held: whether it and ${cand.namedSlug ?? 'the page its slug: line names'} are the same page needs a judgment.`, null);+ const model = s.model;+ if (!model) return pending('no_measured_model', noMeasuredModel(cand.path), null);+ if (s.perPageUsd === 0 || s.perDayUsd === 0) return pending('budget_exhausted', 'Model repair spend is set to 0.', nextUtcMidnight(new Date()));+ const timeoutMs = Math.max(5_000, Math.min(CALL_TIMEOUT_MS(), opts.deadline !== undefined ? opts.deadline - Date.now() : Infinity));+ const result = await callJudgment(engine, model, input, { sourceId: src.id, incarnation: src.incarnation, path: cand.path,+ memo: { heldSha256: cand.before, namedSha256: entry.named_sha256, heldPageId: cand.snapshot?.page.id ?? null, namedPageId: entry.named_page_id },+ overrides: s.overrides, capSource: s.capSource, perPageUsd: s.perPageUsd, perDayUsd: s.perDayUsd, ...(opts.allowanceUsd !== undefined ? { allowanceUsd: opts.allowanceUsd } : {}), timeoutMs });+ const store = attemptStore(engine);+ if (!result.ok) {+ const spend = result.spentUsd ? { llm_usd: result.spentUsd } : {};+ if (result.reason === 'claimed_elsewhere') return { applied: false, outcome: 'skipped', reason: 'claimed_elsewhere', detail: { path: cand.path, slug: cand.slug, message: result.message }, ...spend };+ if (result.memoHit && result.reason === 'remove_slug') return write(ctx, src, cand, removeSlugLine(cand.content, cand.sourcePath, cand.path, src.activePack)!, { tier: 'llm', confidence: 'medium', model, cost_usd: 0 }, opts, held, { memo: 'judged_before' });+ if (result.memoHit) {+ const state = cand.hold?.meta.content_repair;+ const out = await held(result.reason, result.message, state && state.reason === result.reason ? null : { action: result.reason === 'merge_recommended' ? 'merge_into' : result.reason === 'content_repair_needs_human' ? 'needs_human' : 'pending',+ reason: result.reason, ...named, model, next_attempt_after: null }, { memo: 'judged_before' });+ return { ...out, ...spend };+ }+ const next = nextAttempt(result.reason, result.resetsAt);+ const out = await pending(result.reason, result.message, next, { ...(result.guidance ? { guidance: result.guidance } : {}) });+ if (!result.stop) return { ...out, ...spend };+ const day = await dailyLedger(engine, FENCE_REPAIR_LEDGER).readDay().catch(() => null);+ const resets = result.resetsAt ?? nextUtcMidnight(new Date());+ const message = opts.allowanceUsd !== undefined && !result.resetsAt+ ? `Stopped: ${result.message} ${entry.llm_waiting} file(s) wait for the model. Rerun with a larger --max-usd, or leave them to the maintenance run.`+ : `Stopped: the daily content-repair budget is spent ($${(day?.committedUsd ?? 0).toFixed(4)} of $${s.perDayUsd.toFixed(2)} today). It resets at ${resets}; `+ + `${entry.llm_waiting} file(s) wait for the model and the next run after that judges them. Raising the cap is the user's call: gbrain config set fences.repair.max_usd_per_day <usd>.`;+ return { ...out, ...spend, stop: { reason: 'budget_exhausted', message, fix: { argv: ['gbrain', 'config', 'set', 'fences.repair.max_usd_per_day', '<usd>'], consent: ['paid'], actor: 'agent', requires_exclusive: false,+ why: `The content-repair lane stopped at the daily cap it shares with fence repair; ${entry.llm_waiting} file(s) wait until ${resets} unless the cap is raised.`,+ user_message: `The daily model budget for content repair ($${s.perDayUsd.toFixed(2)}) is spent and ${entry.llm_waiting} file(s) still wait. Raise it for today, or let them repair after ${resets}?`,+ inputs: [{ name: 'usd', how: 'The new daily cap in USD the user agrees to; it must exceed what is already spent today.' }],+ verify: { argv: ['gbrain', 'sources', 'status', src.id, '--json'] } } } };+ }+ const verdict: JudgmentVerdict = result.verdict;+ const spend = result.spentUsd ? { llm_usd: result.spentUsd } : {};+ const why = verdict.why ? { why: verdict.why } : {};+ if (verdict.action === 'remove_slug') {+ const after = removeSlugLine(cand.content, cand.sourcePath, cand.path, src.activePack);+ if (after === null) { await store.reject(result.claim, { reason: 'still_invalid' }); return held('still_invalid', `The model chose remove_slug for ${cand.path}, but removing the line alone does not make it importable.`, { action: 'remove_slug', reason: 'still_invalid', model, next_attempt_after: null }, { ...why, ...spend }); }+ const written = await write(ctx, src, cand, after, { tier: 'llm', confidence: 'medium', model, cost_usd: result.spentUsd }, opts, held, why);+ if (written.applied) await store.publish(result.claim);+ else if (written.reason === 'changed_since_read' || written.reason === 'sync_in_progress') await store.transient(result.claim, written.reason);+ else await store.reject(result.claim, { reason: written.reason ?? 'still_invalid' });+ return written;+ }+ const reason = judgmentMemoReason(verdict);+ await store.reject(result.claim, { reason });+ const type = verdict.action === 'merge_into' ? cand.named?.page.type ?? parseMarkdown(cand.content, cand.path).type : undefined;+ const state: Omit<ContentHoldRepairState, 'at'> = { action: verdict.action, reason, ...(verdict.action === 'merge_into' ? { canonical: verdict.canonical } : {}), ...named, ...(type ? { type } : {}), model, next_attempt_after: null };+ const message = verdict.action === 'merge_into'+ ? `The model judged ${cand.path} and page ${cand.namedSlug ?? verdict.canonical} to be the same page; ${verdict.canonical} keeps the slug. gbrain does not merge pages by itself yet, so nothing was written; a person merges them (gbrain sources status ${src.id} shows the paragraph).`+ : `The model could not decide whether ${cand.path} and ${cand.namedSlug ?? 'the page its slug: line names'} are the same page, so nothing was written; a person decides which keeps the slug.`;+ return { ...await held(reason, message, state, { action: verdict.action, ...(verdict.action === 'merge_into' ? { canonical: verdict.canonical } : {}), ...why, tier: 'llm' }), ...spend };+}++async function reportConflicts(ctx: OperationContext, scope: RepairScope, result: RepairResult) {+ const repairedByTier: Record<Tier, number> = { deterministic: 0, llm: 0 };+ const remaining: Record<string, number> = {};+ const skips = new Set(['already_clean', 'already_exempt', 'gone']);+ for (const [reason, count] of Object.entries(result.residuals)) if (!skips.has(reason)) remaining[reason] = (remaining[reason] ?? 0) + count;+ const repaired = result.mode === 'apply' ? result.outcomes?.repaired ?? 0 : 0;+ let judgments = 0;+ if (result.mode === 'apply') {+ for (const outcome of result.outcome_items ?? []) {+ if (outcome.outcome === 'repaired') { const tier = outcome.detail?.tier as Tier | undefined; if (tier) repairedByTier[tier]++; if (tier === 'llm') judgments++; }+ else if (outcome.reason && !skips.has(outcome.reason)) { remaining[outcome.reason] = (remaining[outcome.reason] ?? 0) + 1; if (outcome.detail?.tier === 'llm') judgments++; }+ }+ const unattempted = result.affected - result.applied - result.skipped;+ if (unattempted > 0 && result.stopped) remaining[result.stopped.reason] = (remaining[result.stopped.reason] ?? 0) + unattempted;+ } else if (result.affected) remaining.pending_repair = result.affected;+ const [oldest] = await ctx.engine.executeRaw<{ held_at: string | null }>(`SELECT min(completed_keys->0->>'held_at') AS held_at FROM op_checkpoints+ WHERE op='sync-hold' AND completed_keys->0->>'code'='frontmatter_slug_conflict' AND completed_keys->0->>'source_id'=ANY($1::text[])`, [scope.source_ids]).catch(() => [{ held_at: null }]);+ const verification: SlugConflictsVerification = { candidates: result.affected + Object.entries(result.residuals).filter(([reason]) => !skips.has(reason)).reduce((a, [, b]) => a + b, 0),+ repaired_by_tier: repairedByTier, held_by_reason: Object.fromEntries(Object.entries(remaining).filter(([reason]) => reason !== 'pending_repair')), oldest_hold_at: oldest?.held_at ?? null,+ llm_judgments: judgments, llm_usd: typeof result.cost.llm_usd === 'number' ? result.cost.llm_usd : 0 };+ return { repaired, remaining, verification: verification as unknown as Record<string, unknown> };+}diff --cc test/cycle-content-repair.test.tsindex 0000000000,7ea24c14a0..ef2a3c3a4cmode 000000,100644..100644--- a/test/cycle-content-repair.test.ts+++ b/test/cycle-content-repair.test.ts@@@ -1,0 -1,269 +1,269 @@@+ /**+ * #6377 `content_repair` maintenance phase (src/core/cycle/content-repair.ts)+ * and the content lane it runs (src/core/repair/content-lane.ts).+ *+ * Protects: the global maintenance lane runs the rest of the content-repair+ * lane by itself, bounded and honest. With `CONTENT_REPAIR_KINDS` holding only+ * `fences` the phase runs nothing and says so (`no_kinds`); a kind handed to+ * it runs through the shared repair runner with the lane's deadline+ * (min(120 s, a third of the job's remaining time)); `fences.repair.enabled`+ * false pauses it without calling the kind; the report carries counts by+ * outcome and reason, the lane's spend and the oldest hold's age; a non-time+ * stop or an internal error reports `warn` with the next step and no error+ * text; the phase is brain-global, right after `fence_repair`, and never in a+ * per-source payload. The lane itself: every component plan is built before+ * the first mutation and each kind applies against its own hash; the paid+ * allowance flows minus the earlier kind's spend; `--expect` needs one hash+ * per kind.+ * Fails when: the enabled gate is dropped, the budget formula changes, the+ * phase hides a kind's stop, an error fails the cycle or leaks its message,+ * the lane applies before planning, or the allowance stops flowing.+ * Why new: the fence_repair test covers one kind's wrapper; nothing covered a+ * lane of kinds sharing one allowance, nor the plan-first apply.+ * Seams: the repair runner's `registry` stub-spec seam, passed through the+ * lane and the phase; `kinds` names the stub kind the phase should run.+ */+ import { afterAll, beforeAll, beforeEach, describe, expect, test } from 'bun:test';+ import { PGLiteEngine } from '../src/core/pglite-engine.ts';+ import { resetPgliteState } from './helpers/reset-pglite.ts';+ import { ALL_PHASES, GLOBAL_PHASES, MAINTENANCE_PHASES, PHASE_SCOPE, SOURCE_FRESHNESS_PHASES, SOURCE_PHASES, normalizeQueuedSourcePhases } from '../src/core/cycle.ts';+ import { CONNECTOR_SOURCE_PHASES } from '../src/core/cycle/phase-scope.ts';+ import { MANAGED_PHASE_TABLE } from '../src/core/cycle/phase-table.ts';+ import { CONTENT_REPAIR_PHASE_BUDGET_MS, contentRepairPhaseKinds, runContentRepairPhase } from '../src/core/cycle/content-repair.ts';+ import { CONTENT_REPAIR_HOLD_KINDS, CONTENT_REPAIR_KINDS, contentHoldDisposition, parseContentLaneExpect, runContentLane } from '../src/core/repair/content-lane.ts';+ import { afterCursor, resolveRepairScope, type RepairCursor, type RepairHandler, type RepairItem, type RepairItemOutcome, type RepairKind, type RepairPlanOptions } from '../src/core/repair/core.ts';+ import type { RepairKindSpec } from '../src/core/repair/registry.ts';+ import { OperationError } from '../src/core/ops/contract.ts';+ import { RECOVERY_VERSION } from '../src/core/markdown.ts';++ let engine: PGLiteEngine;++ beforeAll(async () => {+ engine = new PGLiteEngine();+ await engine.connect({});+ await engine.initSchema();+ }, 60_000);++ afterAll(async () => { await engine.disconnect(); });+ beforeEach(async () => { await resetPgliteState(engine); });++ interface Stub {+ spec: RepairKindSpec;+ plans: Array<{ apply: boolean; after: RepairCursor | null; opts?: RepairPlanOptions }>;+ applied: Array<{ id: number; deadline?: number; allowance?: number; expect?: string }>;+ }++ /** A stub lane kind over `count` items: preview-bound (its hash binds the selection), spends on the model, honors the resume cursor. */+ function stubKind(kind: RepairKind, count: number, behavior: {+ onApply?: (item: RepairItem) => Partial<RepairItemOutcome> | void;+ plan?: () => never;+ llmUsdPerItem?: number;+ verification?: Record<string, unknown>;+ } = {}): Stub {+ const items: RepairItem[] = Array.from({ length: count }, (_, id) => ({ cursor: { phase: 0, id }, source_id: 'default', slug: `people/alice-example-${id}`, chars: 10, action: 'repair',+ ...(behavior.llmUsdPerItem ? { llm_usd: behavior.llmUsdPerItem } : {}) }));+ const stub: Stub = { plans: [], applied: [], spec: undefined as never };+ let repaired = 0;+ const handler: RepairHandler = {+ kind, publication: 'projection', embeds: false,+ async plan(_engine, _scope, after, opts) {+ stub.plans.push({ apply: opts?.apply === true, after, opts });+ behavior.plan?.();+ return { items: items.filter(item => afterCursor(item.cursor, after)), residuals: {}, preview_hash: `${kind}-hash-${count}`,+ llm: { usd: items.length * (behavior.llmUsdPerItem ?? 0), cap_remaining_usd: 1 }, scan: { fresh_at: null, partial: false } };+ },+ async apply(_ctx, item, opts) {+ stub.applied.push({ id: item.cursor.id, deadline: opts?.deadline, allowance: opts?.llmAllowanceUsd, expect: opts?.expect });+ const outcome: RepairItemOutcome = { applied: true, outcome: 'repaired', detail: { tier: 'deterministic', path: `${item.slug}.md` }, ...(behavior.llmUsdPerItem ? { llm_usd: behavior.llmUsdPerItem } : {}), ...behavior.onApply?.(item) };+ if (outcome.applied) repaired++;+ return outcome;+ },+ ...(behavior.verification ? { async report() { return { repaired, verification: behavior.verification }; } } : {}),+ };+ stub.spec = { kind, handler, summary: 'stub', embeds: 'none', checks: [], preview_bound: true, spends: 'llm' };+ return stub;+ }++ describe('the content lane', () => {- test('today it holds fences; the hold table maps invalid_fence to it and leaves frontmatter_slug_conflict for Lane B', () => {- expect(CONTENT_REPAIR_KINDS).toEqual(['fences']);++ test('the lane runs fences then slug-conflicts; the hold table maps each hold code to its kind', () => {++ expect(CONTENT_REPAIR_KINDS).toEqual(['fences', 'slug-conflicts']);+ expect(CONTENT_REPAIR_HOLD_KINDS.invalid_fence).toBe('fences');- expect(CONTENT_REPAIR_HOLD_KINDS.frontmatter_slug_conflict).toBeNull();- expect(contentRepairPhaseKinds()).toEqual([]);++ expect(CONTENT_REPAIR_HOLD_KINDS.frontmatter_slug_conflict).toBe('slug-conflicts');++ expect(contentRepairPhaseKinds()).toEqual(['slug-conflicts']);+ const meta = { recovery_version: RECOVERY_VERSION };- expect(contentHoldDisposition({ code: 'frontmatter_slug_conflict', meta })).toEqual({ action: 'unsupported' });++ expect(contentHoldDisposition({ code: 'frontmatter_slug_conflict', meta })).toEqual({ action: 'repair', kind: 'slug-conflicts' });+ expect(contentHoldDisposition({ code: 'invalid_frontmatter', meta })).toEqual({ action: 'unsupported' });+ expect(contentHoldDisposition({ code: 'invalid_fence', meta: { ...meta, reason: 'holder_unresolved' } })).toEqual({ action: 'repair', kind: 'fences' });+ expect(contentHoldDisposition({ code: 'invalid_fence', meta: { ...meta, reason: 'repeated_marker' } })).toEqual({ action: 'listed', kind: 'fences', state: 'needs_human', reason: 'repeated_marker' });+ expect(contentHoldDisposition({ code: 'invalid_fence', meta: { ...meta, reason: 'no_header', fence_repair: { reason: 'budget_exhausted', tier: 'llm', at: 't', next_attempt_after: 'u' } } }))+ .toEqual({ action: 'listed', kind: 'fences', state: 'paid', reason: 'budget_exhausted' });+ expect(contentHoldDisposition({ code: 'invalid_fence', meta: { ...meta, reason: 'no_header', fence_repair: { reason: 'host_mismatch', tier: 'llm', at: 't', next_attempt_after: null } } }))+ .toEqual({ action: 'listed', kind: 'fences', state: 'owner', reason: 'host_mismatch' });+ });++ test('a dry run plans every kind, prints each kind\'s own hash and writes nothing; the apply command carries one hash per kind', async () => {+ const a = stubKind('fences', 2, { llmUsdPerItem: 0.1 }), b = stubKind('connector-fences', 1, { llmUsdPerItem: 0.1 });+ const scope = await resolveRepairScope(engine);+ const lane = await runContentLane(engine, scope, { apply: false, kinds: ['fences', 'connector-fences'], registry: [a.spec, b.spec], maxLlmUsd: 0.5, sourceFlag: 'default' });+ expect(lane.mode).toBe('dry_run');+ expect(lane.kinds).toEqual(['fences', 'connector-fences']);+ expect(lane.preview_hashes).toEqual({ fences: 'fences-hash-2', 'connector-fences': 'connector-fences-hash-1' });+ expect(lane.results.map(r => [r.kind, r.mode, r.affected, r.preview_hash])).toEqual([['fences', 'dry_run', 2, 'fences-hash-2'], ['connector-fences', 'dry_run', 1, 'connector-fences-hash-1']]);+ expect(lane.cost.llm_usd).toBeCloseTo(0.3); expect(lane.cost.llm_allowance_remaining_usd).toBeCloseTo(0.2);+ expect(lane.apply_command).toBe('gbrain repair content --source default --max-usd 0.5 --apply --expect fences-hash-2,connector-fences-hash-1');+ expect(a.applied).toHaveLength(0); expect(b.applied).toHaveLength(0);+ // The second kind's plan was built with the allowance left after the first kind's estimate.+ expect(b.plans[0]?.opts?.maxLlmUsd).toBeCloseTo(0.3);+ });++ test('a bare apply runs each kind\'s current plan in order (its own plan, its own apply, as gbrain repair <kind> --apply); the allowance flows minus the earlier spend', async () => {+ const a = stubKind('fences', 2, { llmUsdPerItem: 0.1 });+ const b = stubKind('connector-fences', 2, { llmUsdPerItem: 0.1 });+ const lane = await runContentLane(engine, await resolveRepairScope(engine), { apply: true, kinds: ['fences', 'connector-fences'], registry: [a.spec, b.spec], maxLlmUsd: 0.35 });+ expect(lane.mode).toBe('apply');+ expect(a.plans.map(p => p.apply)).toEqual([true]);+ expect(b.plans.map(p => p.apply)).toEqual([true]);+ expect(a.applied.map(x => x.expect)).toEqual([undefined, undefined]);+ expect(a.applied[0]!.allowance).toBeCloseTo(0.35); expect(a.applied[1]!.allowance).toBeCloseTo(0.25);+ // fences spent 0.20; connector-fences gets 0.15, enough for one item, then stops before the second (budget_exhausted).+ expect(b.plans[0]?.opts?.maxLlmUsd).toBeCloseTo(0.15);+ expect(b.applied).toHaveLength(1);+ expect(b.applied[0]!.allowance).toBeCloseTo(0.15);+ expect(lane.preview_hashes).toEqual({ fences: null, 'connector-fences': null });+ expect(lane.stopped.map(s => [s.kind, s.reason])).toEqual([['connector-fences', 'budget_exhausted']]);+ expect(lane.cost.llm_usd).toBeCloseTo(0.3);+ expect(lane.cost.llm_allowance_remaining_usd).toBeCloseTo(0.05);+ });++ test('--expect binds each kind to the operator\'s hash in lane order, and a count that does not match the lane refuses before anything runs', async () => {+ const a = stubKind('fences', 1), b = stubKind('connector-fences', 1);+ const lane = await runContentLane(engine, await resolveRepairScope(engine), { apply: true, kinds: ['fences', 'connector-fences'], registry: [a.spec, b.spec], expect: ['h1', 'h2'] });+ expect(a.plans.map(p => p.apply)).toEqual([true]);+ expect(a.applied[0]?.expect).toBe('h1'); expect(b.applied[0]?.expect).toBe('h2');+ expect(lane.preview_hashes).toEqual({ fences: 'h1', 'connector-fences': 'h2' });+ const c = stubKind('fences', 1);+ await expect(runContentLane(engine, await resolveRepairScope(engine), { apply: true, kinds: ['fences', 'connector-fences'], registry: [c.spec, b.spec], expect: ['h1'] }))+ .rejects.toMatchObject({ code: 'invalid_params' });+ expect(c.plans).toHaveLength(0);+ expect(() => parseContentLaneExpect('h1', ['fences', 'connector-fences'], ['gbrain', 'repair', 'content'])).toThrow(OperationError);+ expect(parseContentLaneExpect('h1, h2', ['fences', 'connector-fences'], ['gbrain', 'repair', 'content'])).toEqual(['h1', 'h2']);+ });++ test('a time_budget stop in one kind ends the lane; the deadline reaches every kind', async () => {+ const t = Date.now();+ const a = stubKind('fences', 2, { onApply: item => ({ stop: item.cursor.id === 0 ? { reason: 'time_budget', message: 'out of time' } : undefined }) });+ const b = stubKind('connector-fences', 1);+ const lane = await runContentLane(engine, await resolveRepairScope(engine), { apply: true, kinds: ['fences', 'connector-fences'], registry: [a.spec, b.spec], deadline: t + 1000 });+ expect(a.applied).toHaveLength(1);+ expect(a.applied[0]?.deadline).toBe(t + 1000);+ expect(b.applied).toHaveLength(0);+ expect(lane.results.map(r => r.kind)).toEqual(['fences']);+ expect(lane.stopped.map(s => s.reason)).toEqual(['time_budget']);+ });+ });++ describe('content_repair phase gates and budget', () => {+ test('with no lane kind beyond fences the phase runs nothing and says so', async () => {- const result = await runContentRepairPhase(engine, { dryRun: false });++ const result = await runContentRepairPhase(engine, { dryRun: false, kinds: [] });+ expect(result).toMatchObject({ status: 'skipped', details: { reason: 'no_kinds', kinds: [] } });+ expect(result.summary).toContain('ran nothing');+ });++ test('fences.repair.enabled false skips the phase and never calls the kind', async () => {+ const stub = stubKind('connector-fences', 2);+ await engine.setConfig('fences.repair.enabled', 'false');+ const paused = await runContentRepairPhase(engine, { dryRun: false, kinds: ['connector-fences'], registry: [stub.spec] });+ expect(paused).toMatchObject({ status: 'skipped', details: { reason: 'disabled', kinds: ['connector-fences'] } });+ expect(paused.summary).toContain('gbrain config set fences.repair.enabled true');+ expect(paused.summary).toContain('gbrain repair content');+ expect(stub.plans).toHaveLength(0);+ await engine.setConfig('fences.repair.enabled', 'true');+ const resumed = await runContentRepairPhase(engine, { dryRun: false, kinds: ['connector-fences'], registry: [stub.spec] });+ expect(resumed.status).toBe('ok');+ expect(stub.applied.map(a => a.id)).toEqual([0, 1]);+ });++ test('the deadline is min(120 s, a third of the remaining job deadline), 120 s without a job deadline', async () => {+ const t = Date.now();+ const cases: Array<[number | null, number]> = [[t + 180_000, 60_000], [t + 3_600_000, CONTENT_REPAIR_PHASE_BUDGET_MS], [null, CONTENT_REPAIR_PHASE_BUDGET_MS]];+ for (const [deadlineAtMs, budget] of cases) {+ const stub = stubKind('connector-fences', 1);+ const result = await runContentRepairPhase(engine, { dryRun: false, deadlineAtMs, kinds: ['connector-fences'], registry: [stub.spec], now: () => t });+ expect(result.details.time_budget_ms).toBe(budget);+ expect(stub.plans[0]?.opts?.deadline).toBe(t + budget);+ expect(stub.applied[0]?.deadline).toBe(t + budget);+ }+ const stub = stubKind('connector-fences', 1);+ const late = await runContentRepairPhase(engine, { dryRun: false, deadlineAtMs: t, kinds: ['connector-fences'], registry: [stub.spec], now: () => t });+ expect(late).toMatchObject({ status: 'skipped', details: { reason: 'deadline' } });+ expect(stub.plans).toHaveLength(0);+ });++ test('a dry run previews the kind and writes nothing', async () => {+ const stub = stubKind('connector-fences', 2);+ const result = await runContentRepairPhase(engine, { dryRun: true, kinds: ['connector-fences'], registry: [stub.spec] });+ expect(result.details).toMatchObject({ mode: 'dry_run', candidates: 2, repaired: 0 });+ expect(result.summary).toContain('dry run: 2 content candidate(s) planned across connector-fences, nothing written');+ expect(stub.applied).toHaveLength(0);+ });+ });++ describe('content_repair phase report', () => {+ test('counts by kind, outcome and reason, the lane spend and the oldest hold age; needs_human holds point at sync status', async () => {+ const t = Date.now();+ const stub = stubKind('connector-fences', 3, {+ onApply: item => item.cursor.id === 0 ? { llm_usd: 0.02, detail: { tier: 'llm' } }+ : item.cursor.id === 1 ? { applied: false, outcome: 'held', reason: 'merge_recommended' } : { applied: false, outcome: 'skipped', reason: 'sync_in_progress' },+ verification: { oldest_hold_at: new Date(t - 30 * 3_600_000).toISOString() },+ });+ const result = await runContentRepairPhase(engine, { dryRun: false, kinds: ['connector-fences'], registry: [stub.spec], now: () => t });+ expect(result.status).toBe('ok');+ expect(result.details).toMatchObject({ mode: 'apply', kinds: ['connector-fences'], candidates: 3, repaired: 1, llm_usd: 0.02, oldest_hold_age_hours: 30, stopped_reason: null,+ held_by_reason: { merge_recommended: 1, sync_in_progress: 1 } });+ expect((result.details.by_kind as Record<string, { outcomes: Record<string, number> }>)['connector-fences']!.outcomes).toEqual({ repaired: 1, held: 1, skipped: 1 });+ expect(result.summary).toContain('repaired 1 of 3 content candidate(s) across connector-fences ($0.0200 on the model)');+ expect(result.summary).toContain('2 still held (merge_recommended 1, sync_in_progress 1)');+ expect(result.summary).toContain('the oldest unresolved hold is 30 h old');+ expect(result.summary).toContain('1 wait for a person: gbrain sync status');+ expect((result.details.fix as { argv?: string[] }).argv).toEqual(['gbrain', 'repair', 'content']);+ });++ test('a stop other than the time budget reports warn with the kind fix; a time-budget stop stays ok', async () => {+ const fix = { argv: ['gbrain', 'config', 'set', 'fences.repair.max_usd_per_day', '<n>'], consent: ['paid' as const], actor: 'user' as const, why: 'cap', requires_exclusive: false };+ const stub = stubKind('connector-fences', 3, { onApply: () => ({ stop: { reason: 'budget_exhausted', message: 'The daily content repair cap is spent.', fix } }) });+ const result = await runContentRepairPhase(engine, { dryRun: false, kinds: ['connector-fences'], registry: [stub.spec] });+ expect(result.status).toBe('warn');+ expect(result.details).toMatchObject({ stopped_reason: 'budget_exhausted', fix });+ expect(result.summary).toContain('Stopped (connector-fences: budget_exhausted): The daily content repair cap is spent.');+ const timed = stubKind('connector-fences', 2, { onApply: () => ({ stop: { reason: 'time_budget', message: 'out of time' } }) });+ const ok = await runContentRepairPhase(engine, { dryRun: false, kinds: ['connector-fences'], registry: [timed.spec] });+ expect(ok.status).toBe('ok');+ expect(ok.details.stopped_reason).toBe('time_budget');+ expect(ok.summary).toContain('the next maintenance run resumes');+ });++ test('an internal error is contained as warn without its message; an aborted cycle still propagates', async () => {+ const failing = stubKind('connector-fences', 1, { plan: () => { throw new OperationError('database_error' as never, 'boom SENTINEL-CELL-VALUE'); } });+ const result = await runContentRepairPhase(engine, { dryRun: false, kinds: ['connector-fences'], registry: [failing.spec] });+ expect(result).toMatchObject({ status: 'warn', details: { reason: 'error', code: 'database_error' } });+ expect(JSON.stringify(result)).not.toContain('SENTINEL-CELL-VALUE');+ expect(result.summary).toContain('gbrain repair content');+ const controller = new AbortController();+ controller.abort();+ await expect(runContentRepairPhase(engine, { dryRun: false, kinds: ['connector-fences'], registry: [failing.spec], signal: controller.signal })).rejects.toThrow('SENTINEL-CELL-VALUE');+ });+ });++ describe('content_repair scheduling lanes', () => {+ test('brain-global, right after fence_repair, classified writes, never a source or freshness phase', () => {+ expect(PHASE_SCOPE.content_repair).toBe('global');+ expect(ALL_PHASES.indexOf('content_repair')).toBe(ALL_PHASES.indexOf('fence_repair') + 1);+ expect(GLOBAL_PHASES).toContain('content_repair');+ expect(MAINTENANCE_PHASES).toContain('content_repair');+ expect(SOURCE_PHASES).not.toContain('content_repair');+ expect(SOURCE_FRESHNESS_PHASES).not.toContain('content_repair');+ expect(CONNECTOR_SOURCE_PHASES).not.toContain('content_repair');+ expect(MANAGED_PHASE_TABLE.content_repair.class).toBe('writes');+ expect(normalizeQueuedSourcePhases(['sync', 'content_repair'], 'repo-a')).toEqual({ phases: ['sync'], rejected: ['content_repair'] });+ });+ });diff --cc test/fixtures/goldens/exports/types.jsonindex faeb28590b,3ae7b03a79..1b9248ff6c--- a/test/fixtures/goldens/exports/types.json+++ b/test/fixtures/goldens/exports/types.json@@@ -5963,7 -5963,7 +5963,7 @@@{"kind": "class","members": [- "canonical?: \"unknown\" | \"keyword_candidates_incomplete\" | \"projection_pending\" | \"timeout\" | \"embedding_disabled\" | \"writer_lock_unavailable\" | \"writer_pool_capacity\" | \"owner_unavailable\" | \"recovery_required\" | \"queue_capacity\" | \"revision_required\" | \"revision_conflict\" | \"idempotency_conflict\" | \"source_changed\" | \"write_pending\" | \"storage_error\" | \"cancelled\" | \"permission_denied\" | \"scope_denied\" | \"invalid_params\" | \"not_found\" | \"page_not_found\" | \"page_identity_changed\" | \"write_claim_lost\" | \"request_too_large\" | \"response_too_large\" | \"writer_registration_required\" | \"writer_identity_invalid\" | \"writer_not_initialized\" | \"writer_coordinator_required\" | \"fact_already_expired\" | \"source_writeback_required\" | \"unsupported_mutation_protocol\" | \"writer_upgrade_required\" | \"writer_not_quiesced\" | \"skill_bundle_required\" | \"take_row_collision\" | \"invalid_source_uri\" | \"writer_admin_locked\" | \"connector_account_changed\" | \"connector_intent_outdated\" | \"checkpoint_validation_timeout\" | \"invalid_connector_text\" | \"connector_holds_exhausted\" | \"connector_fence_below_timeline\" | \"core_budget_exceeded\" | \"core_mark_owner_only\" | \"core_remote_edit_refused\" | \"core_delete_owner_only\" | \"timeline_rows_would_be_removed\" | \"preparation_stalled\" | \"fence_unrenderable\" | \"write_outcome_unknown\" | \"embedding_failed\" | \"bucket_not_found\" | \"database_error\" | \"unknown_transport\" | \"rate_limited\" | \"extraction_failed\" | \"fact_not_found\" | \"provenance_required\" | \"unavailable\" | \"budget_unsatisfiable\" | \"embedding_budget_below_worst_case\" | \"access_command_failed\" | \"access_denied_test_user\" | \"access_env_missing\" | \"acknowledgment_unavailable\" | \"admin_policy_enforced\" | \"ambient_capture_off\" | \"ambiguous_id\" | \"ambiguous_ref\" | \"ambiguous_skill\" | \"answer_not_yours\" | \"answer_pending\" | \"answer_unavailable\" | \"api_not_enabled\" | \"approval_required\" | \"autopilot_job_owned_by_other_brain\" | \"budget_below_recent_runtime\" | \"benchmark_duplicate_task_id\" | \"benchmark_empty\" | \"benchmark_exists\" | \"benchmark_judge_llm_no_rubric\" | \"benchmark_judge_qrels_no_expected\" | \"benchmark_judge_rule_no_checks\" | \"benchmark_judge_unknown_kind\" | \"benchmark_malformed\" | \"benchmark_missing_judge\" | \"benchmark_missing_task\" | \"benchmark_missing_task_id\" | \"benchmark_not_found\" | \"benchmark_rule_check_bad_arg\" | \"benchmark_rule_check_malformed\" | \"benchmark_rule_check_unknown_op\" | \"bootstrap_empty\" | \"bootstrap_pending_review\" | \"bridge_ownership_conflict\" | \"cache_quota_exceeded\" | \"catalog_capacity_exceeded\" | \"catalog_unavailable\" | \"changed_since_preview\" | \"chronicle_skipped\" | \"no_pricing\" | \"checkpoint_missing\" | \"claim_already_used\" | \"client_json_unreadable\" | \"client_json_wrong_type\" | \"client_shape_invalid\" | \"code_callees_requires_symbol\" | \"code_callers_requires_symbol\" | \"code_def_requires_symbol\" | \"code_refs_requires_symbol\" | \"code_reused\" | \"colon_slug_windows_write_through\" | \"command_failed\" | \"concurrent_write\" | \"config_error\" | \"confirmation_required\" | \"conflicting_source_scope\" | \"connection_lost\" | \"consent_timeout\" | \"consumers_without_heartbeat\" | \"content_repair_needs_human\" | \"content_rejected\" | \"cost_cap_exceeded\" | \"cost_preview_requires_yes\" | \"cycle_failed\" | \"d_sel_too_small\" | \"delta_cursor_upgrade_required\" | \"demo_graph_failed\" | \"demo_import_failed\" | \"demo_verification_failed\" | \"derived_cap_exhausted\" | \"destination_not_ready\" | \"drain_stalled\" | \"managed_sync_not_moving\" | \"dream_breaker_tripped\" | \"dirty_tree\" | \"effect_not_failed\" | \"embedding_auth_failed\" | \"embedding_configuration\" | \"embedding_model_mismatch\" | \"embedding_plane_split\" | \"embedding_storage_unavailable\" | \"embedding_unavailable\" | \"embedding_unconfigured\" | \"embedding_width_mismatch\" | \"engine_graduated\" | \"eval_suite_unwired\" | \"export_limit\" | \"extractor_identity_mismatch\" | \"facts_absorb_write_refused\" | \"facts_backstop_skipped\" | \"facts_drain_deferred\" | \"facts_drain_job_failed\" | \"facts_payload_expired\" | \"feedback_disabled\" | \"feedback_not_authorized\" | \"fetch_failed\" | \"fix_not_writable\" | \"file_removed_during_scan\" | \"file_too_large\" | \"follow_approval_required\" | \"frontmatter_slug_conflict\" | \"full_resync_required\" | \"gate_failed\" | \"git_index_locked\" | \"git_index_stale\" | \"git_push_unavailable\" | \"git_target_unsafe\" | \"git_unavailable\" | \"graduation_drain_timeout\" | \"graduation_embedding_dimension_mismatch\" | \"graduation_foreign_host_binding\" | \"graduation_in_progress\" | \"graduation_interrupted\" | \"graduation_rollback_writes_lost\" | \"graduation_source_writer_held\" | \"graduation_split_brain\" | \"graduation_target_auth_failed\" | \"graduation_target_ddl_unreachable\" | \"graduation_target_not_empty\" | \"graduation_target_unsupported\" | \"graduation_unclassified_table\" | \"graduation_unsupported_platform\" | \"graduation_verify_failed\" | \"graph_incomplete\" | \"host_identity_mismatch\" | \"harness_hook_duplicates\" | \"harness_hook_unowned\" | \"held_out_overlaps_benchmark\" | \"held_out_required_for_bundled\" | \"independent_principal_required\" | \"insufficient_scope\" | \"internal\" | \"internal_error\" | \"interrupted\" | \"invalid_acknowledgment\" | \"invalid_client\" | \"invalid_fence\" | \"sync_in_progress\" | \"invalid_frontmatter\" | \"invalid_grant_clock_skew\" | \"invalid_grant_revoked\" | \"invalid_grant_testing_expiry\" | \"invalid_rating\" | \"invalid_receipt\" | \"invalid_receipt_transition\" | \"invalid_request\" | \"invalid_source\" | \"invalid_source_pin\" | \"invalid_token\" | \"invalid_write_wait\" | \"legacy_job_selection_invalid\" | \"legacy_jobs_active\" | \"local_conflict\" | \"lock_busy\" | \"maintenance_backpressure\" | \"maintenance_lock_busy\" | \"merge_recommended\" | \"managed_pull_skipped\" | \"manual_only_skipped\" | \"membership_inactive\" | \"membership_not_found\" | \"method_not_allowed\" | \"migration_lease_lost\" | \"migration_failed\" | \"migrations_pending\" | \"migrations_running\" | \"missing_source_scope\" | \"missing_source_value\" | \"models_strict_violation\" | \"no_refresh_token\" | \"no_routing_eval\" | \"no_skill_md\" | \"no_worker\" | \"no_worker_surface\" | \"not_a_git_repo\" | \"not_connected\" | \"no_brain\" | \"overlapping_path\" | \"page_projection_conflict\" | \"parse_error\" | \"parser_regression\" | \"pasted_wrong_url\" | \"payload_too_large\" | \"pattern_claims_pending\" | \"pending_writes\" | \"persistence_write_stall\" | \"pglite_busy\" | \"plan_output_failed\" | \"plan_stale\" | \"port_in_use\" | \"preview_changed\" | \"profile_incompatible\" | \"projection_owner_resident\" | \"publication_pending\" | \"receipt_conflict\" | \"receipt_fence_changed\" | \"receipt_fence_required\" | \"receipt_identity_mismatch\" | \"redirect_uri_mismatch\" | \"ref_not_in_answer\" | \"refresh_dirty\" | \"refresh_diverged\" | \"refresh_drain_timeout\" | \"refresh_no_upstream\" | \"refresh_not_managed\" | \"refresh_not_owner\" | \"refresh_source_changed\" | \"relay_disabled\" | \"relay_session_expired\" | \"relay_unreachable\" | \"rename_held\" | \"request_already_submitted\" | \"requirements_changed\" | \"requires_local_engine\" | \"resume_spec_mismatch\" | \"revision_unavailable\" | \"scope_missing\" | \"serve_port_in_use\" | \"serve_status_only\" | \"shared_skills_unavailable\" | \"shared_skills_unsupported\" | \"skill_asset_not_found\" | \"skill_candidate_invalid\" | \"skill_not_found\" | \"skill_retention_capacity\" | \"skill_unavailable\" | \"source_binding_required\" | \"source_id_taken\" | \"source_not_ready\" | \"source_profile_no_backfill\" | \"source_referenced\" | \"source_root_conflict\" | \"split_bad_ratio\" | \"split_unparseable\" | \"stale_unavailable\" | \"state_mismatch\" | \"sync_not_applicable\" | \"sync_parser_regression\" | \"target_escape\" | \"timeline_comment_markup\" | \"topology_change_required\" | \"transcript_secret_exposure\" | \"triage_unreliable_backoff\" | \"two_consumers_on_host\" | \"trusted_local_only\" | \"unexpected_file_bytes\" | \"unexpected_staging_bytes\" | \"unknown_command\" | \"unknown_flag\" | \"unknown_method\" | \"unknown_source\" | \"unknown_tool\" | \"unmanaged_path\" | \"unsupported_export_data\" | \"upstream\" | \"verification_failed\" | \"withdrawal_capacity\" | \"withdrawal_provenance\" | \"worktree_dirty\" | \"writer_admin_intent_required\" | \"writer_admin_state_changed\" | \"writer_busy\" | \"writer_identity_publish_failed\" | \"writer_manifest_mismatch\" | \"writer_manifest_rescope_required\" | \"writer_manifest_unsafe\" | \"writer_regrant_required\" | \"writer_transfer_conflict\" | \"writer_transfer_required\" | \"wrong_account_consented\" | undefined",- "canonical?: \"unknown\" | \"keyword_candidates_incomplete\" | \"projection_pending\" | \"timeout\" | \"embedding_disabled\" | \"writer_lock_unavailable\" | \"writer_pool_capacity\" | \"owner_unavailable\" | \"recovery_required\" | \"queue_capacity\" | \"revision_required\" | \"revision_conflict\" | \"idempotency_conflict\" | \"source_changed\" | \"write_pending\" | \"storage_error\" | \"cancelled\" | \"permission_denied\" | \"scope_denied\" | \"invalid_params\" | \"not_found\" | \"page_not_found\" | \"page_identity_changed\" | \"write_claim_lost\" | \"request_too_large\" | \"response_too_large\" | \"writer_registration_required\" | \"writer_identity_invalid\" | \"writer_not_initialized\" | \"writer_coordinator_required\" | \"fact_already_expired\" | \"source_writeback_required\" | \"unsupported_mutation_protocol\" | \"writer_upgrade_required\" | \"writer_not_quiesced\" | \"skill_bundle_required\" | \"take_row_collision\" | \"invalid_source_uri\" | \"writer_admin_locked\" | \"connector_account_changed\" | \"connector_intent_outdated\" | \"checkpoint_validation_timeout\" | \"invalid_connector_text\" | \"connector_holds_exhausted\" | \"connector_fence_below_timeline\" | \"core_budget_exceeded\" | \"core_mark_owner_only\" | \"core_remote_edit_refused\" | \"core_delete_owner_only\" | \"timeline_rows_would_be_removed\" | \"preparation_stalled\" | \"fence_unrenderable\" | \"write_outcome_unknown\" | \"embedding_failed\" | \"bucket_not_found\" | \"database_error\" | \"unknown_transport\" | \"rate_limited\" | \"extraction_failed\" | \"fact_not_found\" | \"provenance_required\" | \"unavailable\" | \"budget_unsatisfiable\" | \"embedding_budget_below_worst_case\" | \"access_command_failed\" | \"access_denied_test_user\" | \"access_env_missing\" | \"acknowledgment_unavailable\" | \"admin_policy_enforced\" | \"ambient_capture_off\" | \"ambiguous_id\" | \"ambiguous_ref\" | \"ambiguous_skill\" | \"answer_not_yours\" | \"answer_pending\" | \"answer_unavailable\" | \"api_not_enabled\" | \"approval_required\" | \"autopilot_job_owned_by_other_brain\" | \"budget_below_recent_runtime\" | \"benchmark_duplicate_task_id\" | \"benchmark_empty\" | \"benchmark_exists\" | \"benchmark_judge_llm_no_rubric\" | \"benchmark_judge_qrels_no_expected\" | \"benchmark_judge_rule_no_checks\" | \"benchmark_judge_unknown_kind\" | \"benchmark_malformed\" | \"benchmark_missing_judge\" | \"benchmark_missing_task\" | \"benchmark_missing_task_id\" | \"benchmark_not_found\" | \"benchmark_rule_check_bad_arg\" | \"benchmark_rule_check_malformed\" | \"benchmark_rule_check_unknown_op\" | \"bootstrap_empty\" | \"bootstrap_pending_review\" | \"bridge_ownership_conflict\" | \"cache_quota_exceeded\" | \"catalog_capacity_exceeded\" | \"catalog_unavailable\" | \"changed_since_preview\" | \"chronicle_skipped\" | \"no_pricing\" | \"checkpoint_missing\" | \"claim_already_used\" | \"client_json_unreadable\" | \"client_json_wrong_type\" | \"client_shape_invalid\" | \"code_callees_requires_symbol\" | \"code_callers_requires_symbol\" | \"code_def_requires_symbol\" | \"code_refs_requires_symbol\" | \"code_reused\" | \"colon_slug_windows_write_through\" | \"command_failed\" | \"concurrent_write\" | \"config_error\" | \"confirmation_required\" | \"conflicting_source_scope\" | \"connection_lost\" | \"consent_timeout\" | \"consumers_without_heartbeat\" | \"content_rejected\" | \"cost_cap_exceeded\" | \"cost_preview_requires_yes\" | \"cycle_failed\" | \"d_sel_too_small\" | \"delta_cursor_upgrade_required\" | \"demo_graph_failed\" | \"demo_import_failed\" | \"demo_verification_failed\" | \"derived_cap_exhausted\" | \"destination_not_ready\" | \"drain_stalled\" | \"managed_sync_not_moving\" | \"dream_breaker_tripped\" | \"dirty_tree\" | \"effect_not_failed\" | \"embedding_auth_failed\" | \"embedding_configuration\" | \"embedding_model_mismatch\" | \"embedding_plane_split\" | \"embedding_storage_unavailable\" | \"embedding_unavailable\" | \"embedding_unconfigured\" | \"embedding_width_mismatch\" | \"engine_graduated\" | \"eval_suite_unwired\" | \"export_limit\" | \"extractor_identity_mismatch\" | \"facts_absorb_write_refused\" | \"facts_backstop_skipped\" | \"facts_drain_deferred\" | \"facts_drain_job_failed\" | \"facts_payload_expired\" | \"feedback_disabled\" | \"feedback_not_authorized\" | \"fetch_failed\" | \"fix_not_writable\" | \"file_removed_during_scan\" | \"file_too_large\" | \"follow_approval_required\" | \"frontmatter_slug_conflict\" | \"full_resync_required\" | \"gate_failed\" | \"git_index_locked\" | \"git_index_stale\" | \"git_push_unavailable\" | \"git_target_unsafe\" | \"git_unavailable\" | \"graduation_drain_timeout\" | \"graduation_embedding_dimension_mismatch\" | \"graduation_foreign_host_binding\" | \"graduation_in_progress\" | \"graduation_interrupted\" | \"graduation_rollback_writes_lost\" | \"graduation_source_writer_held\" | \"graduation_split_brain\" | \"graduation_target_auth_failed\" | \"graduation_target_ddl_unreachable\" | \"graduation_target_not_empty\" | \"graduation_target_unsupported\" | \"graduation_unclassified_table\" | \"graduation_unsupported_platform\" | \"graduation_verify_failed\" | \"graph_incomplete\" | \"host_identity_mismatch\" | \"harness_hook_duplicates\" | \"harness_hook_unowned\" | \"held_out_overlaps_benchmark\" | \"held_out_required_for_bundled\" | \"independent_principal_required\" | \"insufficient_scope\" | \"internal\" | \"internal_error\" | \"interrupted\" | \"invalid_acknowledgment\" | \"invalid_client\" | \"invalid_fence\" | \"sync_in_progress\" | \"invalid_frontmatter\" | \"invalid_grant_clock_skew\" | \"invalid_grant_revoked\" | \"invalid_grant_testing_expiry\" | \"invalid_rating\" | \"invalid_receipt\" | \"invalid_receipt_transition\" | \"invalid_request\" | \"invalid_source\" | \"invalid_source_pin\" | \"invalid_token\" | \"invalid_write_wait\" | \"legacy_job_selection_invalid\" | \"legacy_jobs_active\" | \"local_conflict\" | \"lock_busy\" | \"maintenance_backpressure\" | \"maintenance_lock_busy\" | \"managed_pull_skipped\" | \"manual_only_skipped\" | \"membership_inactive\" | \"membership_not_found\" | \"method_not_allowed\" | \"migration_lease_lost\" | \"migration_failed\" | \"migrations_pending\" | \"migrations_running\" | \"missing_source_scope\" | \"missing_source_value\" | \"models_strict_violation\" | \"no_refresh_token\" | \"no_routing_eval\" | \"no_skill_md\" | \"no_worker\" | \"no_worker_surface\" | \"not_a_git_repo\" | \"not_connected\" | \"no_brain\" | \"overlapping_path\" | \"page_projection_conflict\" | \"parse_error\" | \"parser_regression\" | \"pasted_wrong_url\" | \"payload_too_large\" | \"pattern_claims_pending\" | \"pending_writes\" | \"persistence_write_stall\" | \"pglite_busy\" | \"plan_output_failed\" | \"plan_stale\" | \"port_in_use\" | \"preview_changed\" | \"profile_incompatible\" | \"projection_owner_resident\" | \"publication_pending\" | \"receipt_conflict\" | \"receipt_fence_changed\" | \"receipt_fence_required\" | \"receipt_identity_mismatch\" | \"redirect_uri_mismatch\" | \"ref_not_in_answer\" | \"refresh_dirty\" | \"refresh_diverged\" | \"refresh_drain_timeout\" | \"refresh_no_upstream\" | \"refresh_not_managed\" | \"refresh_not_owner\" | \"refresh_source_changed\" | \"relay_disabled\" | \"relay_session_expired\" | \"relay_unreachable\" | \"rename_held\" | \"request_already_submitted\" | \"requirements_changed\" | \"requires_local_engine\" | \"resume_spec_mismatch\" | \"revision_unavailable\" | \"scope_missing\" | \"serve_port_in_use\" | \"serve_status_only\" | \"shared_skills_unavailable\" | \"shared_skills_unsupported\" | \"skill_asset_not_found\" | \"skill_candidate_invalid\" | \"skill_not_found\" | \"skill_retention_capacity\" | \"skill_unavailable\" | \"source_binding_required\" | \"source_id_taken\" | \"source_not_ready\" | \"source_profile_no_backfill\" | \"source_referenced\" | \"source_root_conflict\" | \"split_bad_ratio\" | \"split_unparseable\" | \"stale_unavailable\" | \"state_mismatch\" | \"sync_not_applicable\" | \"sync_parser_regression\" | \"tail_exposure_approval\" | \"target_escape\" | \"timeline_comment_markup\" | \"topology_change_required\" | \"transcript_secret_exposure\" | \"triage_unreliable_backoff\" | \"two_consumers_on_host\" | \"trusted_local_only\" | \"unclosed_ambiguous_tail\" | \"unexpected_file_bytes\" | \"unexpected_staging_bytes\" | \"unknown_command\" | \"unknown_flag\" | \"unknown_method\" | \"unknown_source\" | \"unknown_tool\" | \"unmanaged_path\" | \"unsupported_export_data\" | \"upstream\" | \"verification_failed\" | \"withdrawal_capacity\" | \"withdrawal_provenance\" | \"worktree_dirty\" | \"writer_admin_intent_required\" | \"writer_admin_state_changed\" | \"writer_busy\" | \"writer_identity_publish_failed\" | \"writer_manifest_mismatch\" | \"writer_manifest_rescope_required\" | \"writer_manifest_unsafe\" | \"writer_regrant_required\" | \"writer_transfer_conflict\" | \"writer_transfer_required\" | \"wrong_account_consented\" | undefined",++ "canonical?: \"unknown\" | \"keyword_candidates_incomplete\" | \"projection_pending\" | \"timeout\" | \"embedding_disabled\" | \"writer_lock_unavailable\" | \"writer_pool_capacity\" | \"owner_unavailable\" | \"recovery_required\" | \"queue_capacity\" | \"revision_required\" | \"revision_conflict\" | \"idempotency_conflict\" | \"source_changed\" | \"write_pending\" | \"storage_error\" | \"cancelled\" | \"permission_denied\" | \"scope_denied\" | \"invalid_params\" | \"not_found\" | \"page_not_found\" | \"page_identity_changed\" | \"write_claim_lost\" | \"request_too_large\" | \"response_too_large\" | \"writer_registration_required\" | \"writer_identity_invalid\" | \"writer_not_initialized\" | \"writer_coordinator_required\" | \"fact_already_expired\" | \"source_writeback_required\" | \"unsupported_mutation_protocol\" | \"writer_upgrade_required\" | \"writer_not_quiesced\" | \"skill_bundle_required\" | \"take_row_collision\" | \"invalid_source_uri\" | \"writer_admin_locked\" | \"connector_account_changed\" | \"connector_intent_outdated\" | \"checkpoint_validation_timeout\" | \"invalid_connector_text\" | \"connector_holds_exhausted\" | \"connector_fence_below_timeline\" | \"core_budget_exceeded\" | \"core_mark_owner_only\" | \"core_remote_edit_refused\" | \"core_delete_owner_only\" | \"timeline_rows_would_be_removed\" | \"preparation_stalled\" | \"fence_unrenderable\" | \"write_outcome_unknown\" | \"embedding_failed\" | \"bucket_not_found\" | \"database_error\" | \"unknown_transport\" | \"rate_limited\" | \"extraction_failed\" | \"fact_not_found\" | \"provenance_required\" | \"unavailable\" | \"budget_unsatisfiable\" | \"embedding_budget_below_worst_case\" | \"access_command_failed\" | \"access_denied_test_user\" | \"access_env_missing\" | \"acknowledgment_unavailable\" | \"admin_policy_enforced\" | \"ambient_capture_off\" | \"ambiguous_id\" | \"ambiguous_ref\" | \"ambiguous_skill\" | \"answer_not_yours\" | \"answer_pending\" | \"answer_unavailable\" | \"api_not_enabled\" | \"approval_required\" | \"autopilot_job_owned_by_other_brain\" | \"budget_below_recent_runtime\" | \"benchmark_duplicate_task_id\" | \"benchmark_empty\" | \"benchmark_exists\" | \"benchmark_judge_llm_no_rubric\" | \"benchmark_judge_qrels_no_expected\" | \"benchmark_judge_rule_no_checks\" | \"benchmark_judge_unknown_kind\" | \"benchmark_malformed\" | \"benchmark_missing_judge\" | \"benchmark_missing_task\" | \"benchmark_missing_task_id\" | \"benchmark_not_found\" | \"benchmark_rule_check_bad_arg\" | \"benchmark_rule_check_malformed\" | \"benchmark_rule_check_unknown_op\" | \"bootstrap_empty\" | \"bootstrap_pending_review\" | \"bridge_ownership_conflict\" | \"cache_quota_exceeded\" | \"catalog_capacity_exceeded\" | \"catalog_unavailable\" | \"changed_since_preview\" | \"chronicle_skipped\" | \"no_pricing\" | \"checkpoint_missing\" | \"claim_already_used\" | \"client_json_unreadable\" | \"client_json_wrong_type\" | \"client_shape_invalid\" | \"code_callees_requires_symbol\" | \"code_callers_requires_symbol\" | \"code_def_requires_symbol\" | \"code_refs_requires_symbol\" | \"code_reused\" | \"colon_slug_windows_write_through\" | \"command_failed\" | \"concurrent_write\" | \"config_error\" | \"confirmation_required\" | \"conflicting_source_scope\" | \"connection_lost\" | \"consent_timeout\" | \"consumers_without_heartbeat\" | \"content_repair_needs_human\" | \"content_rejected\" | \"cost_cap_exceeded\" | \"cost_preview_requires_yes\" | \"cycle_failed\" | \"d_sel_too_small\" | \"delta_cursor_upgrade_required\" | \"demo_graph_failed\" | \"demo_import_failed\" | \"demo_verification_failed\" | \"derived_cap_exhausted\" | \"destination_not_ready\" | \"drain_stalled\" | \"managed_sync_not_moving\" | \"dream_breaker_tripped\" | \"dirty_tree\" | \"effect_not_failed\" | \"embedding_auth_failed\" | \"embedding_configuration\" | \"embedding_model_mismatch\" | \"embedding_plane_split\" | \"embedding_storage_unavailable\" | \"embedding_unavailable\" | \"embedding_unconfigured\" | \"embedding_width_mismatch\" | \"engine_graduated\" | \"eval_suite_unwired\" | \"export_limit\" | \"extractor_identity_mismatch\" | \"facts_absorb_write_refused\" | \"facts_backstop_skipped\" | \"facts_drain_deferred\" | \"facts_drain_job_failed\" | \"facts_payload_expired\" | \"feedback_disabled\" | \"feedback_not_authorized\" | \"fetch_failed\" | \"fix_not_writable\" | \"file_removed_during_scan\" | \"file_too_large\" | \"follow_approval_required\" | \"frontmatter_slug_conflict\" | \"full_resync_required\" | \"gate_failed\" | \"git_index_locked\" | \"git_index_stale\" | \"git_push_unavailable\" | \"git_target_unsafe\" | \"git_unavailable\" | \"graduation_drain_timeout\" | \"graduation_embedding_dimension_mismatch\" | \"graduation_foreign_host_binding\" | \"graduation_in_progress\" | \"graduation_interrupted\" | \"graduation_rollback_writes_lost\" | \"graduation_source_writer_held\" | \"graduation_split_brain\" | \"graduation_target_auth_failed\" | \"graduation_target_ddl_unreachable\" | \"graduation_target_not_empty\" | \"graduation_target_unsupported\" | \"graduation_unclassified_table\" | \"graduation_unsupported_platform\" | \"graduation_verify_failed\" | \"graph_incomplete\" | \"host_identity_mismatch\" | \"harness_hook_duplicates\" | \"harness_hook_unowned\" | \"held_out_overlaps_benchmark\" | \"held_out_required_for_bundled\" | \"independent_principal_required\" | \"insufficient_scope\" | \"internal\" | \"internal_error\" | \"interrupted\" | \"invalid_acknowledgment\" | \"invalid_client\" | \"invalid_fence\" | \"unclosed_ambiguous_tail\" | \"tail_exposure_approval\" | \"sync_in_progress\" | \"invalid_frontmatter\" | \"invalid_grant_clock_skew\" | \"invalid_grant_revoked\" | \"invalid_grant_testing_expiry\" | \"invalid_rating\" | \"invalid_receipt\" | \"invalid_receipt_transition\" | \"invalid_request\" | \"invalid_source\" | \"invalid_source_pin\" | \"invalid_token\" | \"invalid_write_wait\" | \"legacy_job_selection_invalid\" | \"legacy_jobs_active\" | \"local_conflict\" | \"lock_busy\" | \"maintenance_backpressure\" | \"maintenance_lock_busy\" | \"merge_recommended\" | \"managed_pull_skipped\" | \"manual_only_skipped\" | \"membership_inactive\" | \"membership_not_found\" | \"method_not_allowed\" | \"migration_lease_lost\" | \"migration_failed\" | \"migrations_pending\" | \"migrations_running\" | \"missing_source_scope\" | \"missing_source_value\" | \"models_strict_violation\" | \"no_refresh_token\" | \"no_routing_eval\" | \"no_skill_md\" | \"no_worker\" | \"no_worker_surface\" | \"not_a_git_repo\" | \"not_connected\" | \"no_brain\" | \"overlapping_path\" | \"page_projection_conflict\" | \"parse_error\" | \"parser_regression\" | \"pasted_wrong_url\" | \"payload_too_large\" | \"pattern_claims_pending\" | \"pending_writes\" | \"persistence_write_stall\" | \"pglite_busy\" | \"plan_output_failed\" | \"plan_stale\" | \"port_in_use\" | \"preview_changed\" | \"profile_incompatible\" | \"projection_owner_resident\" | \"publication_pending\" | \"receipt_conflict\" | \"receipt_fence_changed\" | \"receipt_fence_required\" | \"receipt_identity_mismatch\" | \"redirect_uri_mismatch\" | \"ref_not_in_answer\" | \"refresh_dirty\" | \"refresh_diverged\" | \"refresh_drain_timeout\" | \"refresh_no_upstream\" | \"refresh_not_managed\" | \"refresh_not_owner\" | \"refresh_source_changed\" | \"relay_disabled\" | \"relay_session_expired\" | \"relay_unreachable\" | \"rename_held\" | \"request_already_submitted\" | \"requirements_changed\" | \"requires_local_engine\" | \"resume_spec_mismatch\" | \"revision_unavailable\" | \"scope_missing\" | \"serve_port_in_use\" | \"serve_status_only\" | \"shared_skills_unavailable\" | \"shared_skills_unsupported\" | \"skill_asset_not_found\" | \"skill_candidate_invalid\" | \"skill_not_found\" | \"skill_retention_capacity\" | \"skill_unavailable\" | \"source_binding_required\" | \"source_id_taken\" | \"source_not_ready\" | \"source_profile_no_backfill\" | \"source_referenced\" | \"source_root_conflict\" | \"split_bad_ratio\" | \"split_unparseable\" | \"stale_unavailable\" | \"state_mismatch\" | \"sync_not_applicable\" | \"sync_parser_regression\" | \"target_escape\" | \"timeline_comment_markup\" | \"topology_change_required\" | \"transcript_secret_exposure\" | \"triage_unreliable_backoff\" | \"two_consumers_on_host\" | \"trusted_local_only\" | \"unexpected_file_bytes\" | \"unexpected_staging_bytes\" | \"unknown_command\" | \"unknown_flag\" | \"unknown_method\" | \"unknown_source\" | \"unknown_tool\" | \"unmanaged_path\" | \"unsupported_export_data\" | \"upstream\" | \"verification_failed\" | \"withdrawal_capacity\" | \"withdrawal_provenance\" | \"worktree_dirty\" | \"writer_admin_intent_required\" | \"writer_admin_state_changed\" | \"writer_busy\" | \"writer_identity_publish_failed\" | \"writer_manifest_mismatch\" | \"writer_manifest_rescope_required\" | \"writer_manifest_unsafe\" | \"writer_regrant_required\" | \"writer_transfer_conflict\" | \"writer_transfer_required\" | \"wrong_account_consented\" | undefined","canonicalCode: string","cause?: unknown","code: ErrorCode",diff --cc test/repair-content.test.tsindex 0000000000,f6085debc6..d86756260dmode 000000,100644..100644--- a/test/repair-content.test.ts+++ b/test/repair-content.test.ts@@@ -1,0 -1,131 +1,136 @@@+ /**+ * #6377 `gbrain repair content` (src/commands/repair-content.ts), the+ * content-repair lane as one command.+ *+ * Protects: `content` is parsed like a kind but is a lane, never a RepairKind+ * (its flags are the lane's: --only/--skip, --no-llm, --max-usd, --expect with+ * one hash per kind, --apply, --json; --slug, --yes and --all refuse); the+ * preview runs every lane kind read-only over the same selection and prints+ * each kind's own hash plus the exact apply command; `--apply --expect <hash>`+ * applies exactly that set through the real `fences` kind on a managed source+ * (the held file is repaired, committed through the Git effect and its hold+ * cleared); a hash count that does not match the lane refuses before any kind+ * runs; the exit verdict follows a kind's stop. Sentinel text never reaches an+ * output line. The two-kind contract (allowance flow, per-kind hashes, the+ * time-budget stop) is pinned in test/cycle-content-repair.test.ts with stub+ * kinds, since the CLI runs the registered lane.+ */+ import { afterAll, beforeAll, beforeEach, expect, test } from 'bun:test';+ import { randomUUID } from 'node:crypto';+ import { execFileSync } from 'node:child_process';+ import { mkdirSync, mkdtempSync, readFileSync, rmSync, 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 { 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 { readGitHold } from '../src/core/persistence/sync-holds.ts';+ import { CONTENT_LANE, parseRepairArgs, runRepairCommand } from '../src/commands/repair.ts';+ import { _resetCliExitVerdictForTests, currentExitCode } from '../src/core/cli-force-exit.ts';+ import type { RepairResult } from '../src/core/repair/core.ts';+ import { withEnv } from './helpers/with-env.ts';++ const home = mkdtempSync(join(tmpdir(), 'gbrain-repair-content-'));+ let engine: BrainEngine;+ const env = { GBRAIN_HOME: home, GBRAIN_SYNC_FAILURES_DIR: home, GBRAIN_FENCE_REPAIR_SCAN_MS: '60000', OPENAI_API_KEY: undefined, ANTHROPIC_API_KEY: undefined, VOYAGE_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: string) => { git(root, 'add', '.'); git(root, '-c', 'user.name=Example', '-c', '[email protected]', 'commit', '-qm', message); return git(root, 'rev-parse', 'HEAD'); };+ const HOLDER = 'Alice Example', MCLAIM = 'Sentinelmanualrc77 opens an office';+ const FB = '<!--- gbrain:facts:begin -->', FBE = '<!--- gbrain:facts:end -->';+ const FH = '| # | claim | kind | confidence | visibility | notability | valid_from | valid_until | source | context |\n|---|---|---|---|---|---|---|---|---|---|';+ const T = '<!--- gbrain:takes:begin -->', TE = '<!--- gbrain:takes:end -->';+ const TH = '| # | claim | kind | who | weight | since | source |\n|---|---|---|---|---|---|---|';+ const md = (title: string, body: string) => `---\ntitle: ${title}\n---\nA synthetic page.\n\n${body}`;+ const holder = () => `${T}\n${TH}\n| 1 | Synthetic take | take | ${HOLDER} | 0.7 | 2026-01 | chat |\n${TE}\n`;+ const manual = () => `${FB}\n${FH}\n| 1 | ${MCLAIM} | fact | 0.9 | sideways | high | 2026-01-01 | | chat | ctx |\n${FBE}\n`;+ /** Claim text never reaches an output; the preview's per-file diff shows the holder cell to the operator by design (D14), so the holder is checked on the apply result only. */+ const expectNoSecrets = (text: string, secrets: string[] = ['Sentinelmanualrc77', HOLDER]) => { for (const secret of secrets) expect(text).not.toContain(secret); };++ async function fixture(files: Record<string, string>) {+ const id = `rc-${randomUUID().replace(/-/g, '').slice(0, 20)}`, root = join(home, id);+ mkdirSync(root); git(root, 'init', '-q');+ for (const [path, body] of Object.entries(files)) { mkdirSync(join(root, path, '..'), { recursive: true }); writeFileSync(join(root, path), body); }+ 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 { id, root, opts: { sourceId: id, noPull: true, noEmbed: true, noExtract: true } };+ }++ async function cli(args: string[]): Promise<string> {+ const out: string[] = [];+ const log = console.log;+ console.log = (...parts: unknown[]) => { out.push(parts.join(' ')); };+ try { await runRepairCommand(engine, args); } finally { console.log = log; }+ return out.join('\n');+ }++ interface LaneJson { lane: string; mode: string; kinds: string[]; results: RepairResult[]; preview_hashes: Record<string, string | null>; cost: { llm_usd: number; llm_allowance_remaining_usd: number | null }; stopped: unknown[]; apply_command: string }++ beforeAll(async () => { const lite = new PGLiteEngine(); await lite.connect({}); await lite.initSchema(); engine = lite; }, 60_000);+ beforeEach(() => { _resetCliExitVerdictForTests(); });+ afterAll(async () => { await withEnv(env, async () => { await disposePersistenceConsumer(engine); }); await engine.disconnect(); rmSync(home, { recursive: true, force: true }); });++ test('content parses like a kind but is a lane: its flags are accepted, the kind-only ones refuse', () => {+ expect(CONTENT_LANE).toBe('content');+ const parsed = parseRepairArgs(['content', '--source', 'notes', '--only', 'a.md', '--skip', 'b.md', '--no-llm', '--max-usd', '0.5', '--apply', '--expect', 'h1,h2', '--json', '--diff']);+ expect(parsed).toMatchObject({ kind: 'content', source: 'notes', only: ['a.md'], skip: ['b.md'], noLlm: true, maxUsd: 0.5, apply: true, expect: 'h1,h2', json: true, diff: true });+ expect(() => parseRepairArgs(['content', '--slug', 'people/a'])).toThrow(/--slug applies only to gbrain repair fences/);+ expect(() => parseRepairArgs(['content', '--yes'])).toThrow(/--yes/);+ expect(() => parseRepairArgs(['content', '--include-ambiguous'])).toThrow(/--include-ambiguous applies only/);+ expect(() => parseRepairArgs(['content', 'fences'])).toThrow(/at most one kind/);+ });++ test('preview runs the lane read-only and prints each kind\'s hash; --apply --expect <hash> repairs the held file through the fences kind and clears its hold; a wrong hash count refuses', async () => withEnv(env, async () => {+ const f = await fixture({ 'people/alice-example.md': md('Alice Example', 'A synthetic person.\n'), 'notes/a.md': md('A', 'Plain.\n') });+ expect((await performManagedSync(engine, f.opts)).status).toBe('first_sync');+ writeFileSync(join(f.root, 'people/holder.md'), md('Holder', holder()));+ writeFileSync(join(f.root, 'people/manual.md'), md('Manual', manual()));+ commit(f.root, 'two malformed fences');+ expect((await performManagedSync(engine, f.opts)).held?.map(hold => hold.path).sort()).toEqual(['people/holder.md', 'people/manual.md']);+ const [source] = await engine.executeRaw<{ incarnation: string }>('SELECT incarnation::text AS incarnation FROM sources WHERE id=$1', [f.id]);++ await expect(cli(['content', '--all'])).rejects.toMatchObject({ code: 'invalid_params' });- await expect(cli(['content', '--source', f.id, '--apply', '--expect', 'h1,h2'])).rejects.toMatchObject({ code: 'invalid_params' });++ await expect(cli(['content', '--source', f.id, '--apply', '--expect', 'h1,h2,h3'])).rejects.toMatchObject({ code: 'invalid_params' });+ expect(await readGitHold(engine, f.id, source.incarnation, 'people/holder.md')).not.toBeNull();++ const preview = JSON.parse(await cli(['content', '--source', f.id, '--json'])) as LaneJson;- expect(preview).toMatchObject({ lane: 'content', mode: 'dry_run', kinds: ['fences'], stopped: [] });++ expect(preview).toMatchObject({ lane: 'content', mode: 'dry_run', kinds: ['fences', 'slug-conflicts'], stopped: [] });+ const hash = preview.preview_hashes.fences!;++ const slugHash = preview.preview_hashes['slug-conflicts']!;+ expect(hash).toMatch(/^[0-9a-f]{16,}$/);++ expect(slugHash).toMatch(/^[0-9a-f]{16,}$/);++ expect(preview.results[1]).toMatchObject({ kind: 'slug-conflicts', mode: 'dry_run', affected: 0, listing: [] });++ const both = `${hash},${slugHash}`;+ const fences = preview.results[0]!;+ expect(fences.kind).toBe('fences');+ expect(fences.preview_hash).toBe(hash);+ expect(fences.listing!.map(entry => [entry.item, entry.class]).sort()).toEqual([[`${f.id}:people/holder.md`, 'resolver'], [`${f.id}:people/manual.md`, 'enum_unmapped']]);- expect(preview.apply_command).toBe(`gbrain repair content --source ${f.id} --apply --expect ${hash}`);++ expect(preview.apply_command).toBe(`gbrain repair content --source ${f.id} --apply --expect ${both}`);+ expect(fences.apply_command).toBe(`gbrain repair fences --source ${f.id} --apply --expect ${hash}`);+ expect(currentExitCode()).toBe(0);++ const human = await cli(['content', '--source', f.id]);- expect(human).toContain(`lane content (fences)`);++ expect(human).toContain(`lane content (fences, slug-conflicts)`);+ expect(human).toContain(`preview hashes: fences=${hash}`);- expect(human).toContain(`apply: gbrain repair content --source ${f.id} --apply --expect ${hash}`);++ expect(human).toContain(`slug-conflicts=${slugHash}`);++ expect(human).toContain(`apply: gbrain repair content --source ${f.id} --apply --expect ${both}`);+ expectNoSecrets(human, ['Sentinelmanualrc77']);+- const applied = JSON.parse(await cli(['content', '--source', f.id, '--apply', '--expect', hash, '--json'])) as LaneJson;- expect(applied).toMatchObject({ mode: 'apply', kinds: ['fences'], preview_hashes: { fences: hash }, stopped: [] });++ const applied = JSON.parse(await cli(['content', '--source', f.id, '--apply', '--expect', both, '--json'])) as LaneJson;++ expect(applied).toMatchObject({ mode: 'apply', kinds: ['fences', 'slug-conflicts'], preview_hashes: { fences: hash, 'slug-conflicts': slugHash }, stopped: [] });+ expect(applied.results[0]).toMatchObject({ mode: 'apply', applied: 1, outcomes: { repaired: 1 } });+ expect(applied.results[0]!.outcome_items![0]).toMatchObject({ outcome: 'repaired', detail: { tier: 'resolver', path: 'people/holder.md', hold_cleared: true } });+ expect(await readGitHold(engine, f.id, source.incarnation, 'people/holder.md')).toBeNull();+ expect(await readGitHold(engine, f.id, source.incarnation, 'people/manual.md')).not.toBeNull();+ expect(readFileSync(join(f.root, 'people/holder.md'), 'utf8')).toContain('people/alice-example');+ expectNoSecrets(JSON.stringify(applied));++ // The hash is spent: the same apply is preview_changed; a bare apply finds nothing left to repair but the manual hold.- await expect(cli(['content', '--source', f.id, '--apply', '--expect', hash, '--json'])).rejects.toMatchObject({ code: 'preview_changed' });++ await expect(cli(['content', '--source', f.id, '--apply', '--expect', both, '--json'])).rejects.toMatchObject({ code: 'preview_changed' });+ const again = JSON.parse(await cli(['content', '--source', f.id, '--apply', '--json'])) as LaneJson;+ expect(again.results[0]).toMatchObject({ mode: 'apply', applied: 0, residuals: { enum_unmapped: 1 } });+ }), 180_000);diff --cc test/sync-hold-surfaces.test.tsindex 68f3d89d7a,68f3d89d7a..8c7b7e5893--- a/test/sync-hold-surfaces.test.ts+++ b/test/sync-hold-surfaces.test.ts@@@ -346,10 -346,10 +346,11 @@@ describe('#6188 fence holds on every DBafterAll(async () => { await engine.disconnect(); rmSync(home, { recursive: true, force: true }); }, 60_000);const expectRoute = (text: string, kind: 'fences' | 'frontmatter' | 'mixed', sourceId: string) => {-- if (kind !== 'frontmatter') expect(text).toContain(`gbrain repair fences --source ${sourceId}`);++ // #6377: the source-level route for fence (and slug-conflict) holds is the content lane; a fence hold's own fix still names `repair fences --only`.++ if (kind !== 'frontmatter') expect(text).toContain(`gbrain repair content --source ${sourceId}`);if (kind !== 'fences') expect(text).toContain(`gbrain repair frontmatter --source ${sourceId}`);if (kind === 'fences') expect(text).not.toContain('repair frontmatter');-- if (kind === 'frontmatter') expect(text).not.toContain('repair fences');++ if (kind === 'frontmatter') expect(text).not.toContain('repair content');for (const secret of SECRETS) expect(text).not.toContain(secret);};const SOURCES = [['fences-only', 'fences'], ['frontmatter-only', 'frontmatter'], ['mixed-holds', 'mixed']] as const;@@@ -367,7 -367,7 +368,7 @@@expectRoute((await retryHeld(engine, sourceId, { dryRun: false })).next_action, kind, sourceId);const doctor = await gitHeldFilesCheck(engine, [sourceId]);expectRoute(doctor.message, kind, sourceId);-- expect(doctor.fix!.argv).toEqual(kind === 'fences' ? ['gbrain', 'repair', 'fences', '--source', sourceId] : ['gbrain', 'repair', 'frontmatter', '--source', sourceId]);++ expect(doctor.fix!.argv).toEqual(kind === 'fences' ? ['gbrain', 'repair', 'content', '--source', sourceId] : ['gbrain', 'repair', 'frontmatter', '--source', sourceId]);const banner = bannerFindingLine({ spec: WAVE_CHECKS.find(spec => spec.id === 'git_held_files')!, check: doctor, state: 'finding' });expectRoute(banner, kind, sourceId);const report = await buildHoldReport(engine, { sourceId, incarnation: await incarnationOf(engine, sourceId), runId: 'none', remote: false,