Skip to content

Garry's Opinionated OpenClaw/Hermes Agent Brain

TypeScript

feat(repair): slug-conflicts kind with a judgment model tier, hold state and receipts (#6377 lane B)

garrytanac6e08682194
diff --git a/docs/guides/error-codes.md b/docs/guides/error-codes.md
index 02fe5d66a9..6b82fe05c6 100644
--- a/docs/guides/error-codes.md
+++ b/docs/guides/error-codes.md
@@ -610,6 +610,16 @@ More: [docs/guides/troubleshooting.md#consumers-without-heartbeat](../../docs/gu
|---|---|---|---|---|---|---|
| The content-sanity gate rejected the content because the operator set `content_sanity.junk_disposition` to `reject`. | A junk-pattern or operator-literal hit is refused instead of quarantined under that setting, so the page was not written. The same content refuses on every retry. | Remove the matched junk from the file, or switch `content_sanity.junk_disposition` back to `quarantine` (a user decision), then import it again. | agent | `repeat the read that failed` | 1 | no |
+### content_repair_needs_human
+
+<a id="content_repair_needs_human"></a>
+
+| Meaning | Why | Next step | Who acts · consent | Verify | Exit | Retryable |
+|---|---|---|---|---|---|---|
+| The content-repair model could not decide whether a held file and the page its frontmatter `slug:` names are the same page, so nothing was written and a person decides which keeps the slug. | A `frontmatter_slug_conflict` hold that the deterministic rules cannot clear (the named page exists and shares a type or a title word with the file) goes to the judgment model; `needs_human` is its answer when the shown frontmatter, headings, opening lines and cross-mentions do not decide identity. Removing the `slug:` line on a guess would mint a second page for the same thing, and merging on a guess would fold two different things together, so gbrain records the verdict on the hold as codes and slugs, retries nothing until the file changes, and the rest of the source keeps syncing. | Show the user the paragraph gbrain sources status <id> --json renders for the hold (the path and the two slugs). If the two differ, remove the slug: line of the file; if they are one page, merge the unique sections into the page that keeps the slug and delete the other file; then commit and run gbrain sync --source <id> --no-pull. Run: gbrain sources status '{source_id}' --json | user | `gbrain sources status '{source_id}' --json` | 1 | no |
+
+More: [docs/guides/write-refusals.md#content_repair_needs_human](../../docs/guides/write-refusals.md#content_repair_needs_human)
+
### core_budget_exceeded
<a id="core_budget_exceeded"></a>
@@ -1664,6 +1674,16 @@ More: [docs/guides/shared-brain-skills.md#membership-inactive-after-a-re-enrollm
More: [docs/guides/shared-brain-skills.md#troubleshoot-leave-and-recover](../../docs/guides/shared-brain-skills.md#troubleshoot-leave-and-recover)
+### merge_recommended
+
+<a id="merge_recommended"></a>
+
+| Meaning | Why | Next step | Who acts · consent | Verify | Exit | Retryable |
+|---|---|---|---|---|---|---|
+| The content-repair model judged a held file and the page its frontmatter `slug:` names to be the same page, so gbrain recommends merging them instead of removing the slug line; nothing was written. | A `frontmatter_slug_conflict` hold whose two sides describe the same person, company or topic is a duplicate, and the deterministic repair (delete the `slug:` line) would mint a second page for it. gbrain does not merge pages by itself yet (a lossless merge needs a coordinated two-page write with both revisions, withdrawal and metadata preservation; it ships separately), so the lane records the recommendation on the hold as codes and slugs (`meta.content_repair`: the canonical slug that keeps the page), `gbrain sync status` renders a paragraph for a person, and nothing retries it until the file changes. | Show the user the paragraph gbrain sources status <id> --json renders for the hold (the path, the canonical slug and the recommendation). After they agree, merge the unique sections of the duplicate into the canonical page, delete the duplicate file, commit, and run gbrain sync --source <id> --no-pull; the hold clears on that sync. Run: gbrain sources status '{source_id}' --json | user | `gbrain sources status '{source_id}' --json` | 1 | no |
+
+More: [docs/guides/write-refusals.md#merge_recommended](../../docs/guides/write-refusals.md#merge_recommended)
+
### method_not_allowed
<a id="method_not_allowed"></a>
diff --git a/docs/guides/write-refusals.md b/docs/guides/write-refusals.md
index ba274d6717..ffa316bedc 100644
--- a/docs/guides/write-refusals.md
+++ b/docs/guides/write-refusals.md
@@ -152,6 +152,8 @@ with each file and fix the ones that need no guessing."*
| <a id="invalid_frontmatter-ambiguous_identity_key"></a>`invalid_frontmatter` (`ambiguous_identity_key`) | `slug`, `type`, `id` or `source_id` appears twice, or its line was swallowed into another value, so gbrain cannot tell which page the file is. | Edit the file by hand: keep exactly one line for the key. The user decides which value is right. |
| <a id="invalid_frontmatter-ambiguous_protected_key"></a>`invalid_frontmatter` (`ambiguous_protected_key`) | A key that decides access or provenance (`visibility`, `derived_from`, …) is malformed, duplicated, swallowed into another value, rewritten by quoting, or inside an unclosed fence. gbrain never reads such a key as a broader value. | Edit the file by hand: write the key on one line with one quoted value. Ask the user which visibility is intended; never guess it. |
| <a id="frontmatter_slug_conflict"></a>`frontmatter_slug_conflict` | The file's frontmatter `slug:` names a different page than its path does (earlier releases reported this as `invalid_params`). The path decides the slug. | Remove the `slug:` line or make it match the path, or move the file to the path its slug names; `gbrain repair frontmatter --source <source> --include-ambiguous` proposes removing the line. Commit and sync. |
+| <a id="merge_recommended"></a>`frontmatter_slug_conflict` (`merge_recommended`) | The content-repair lane judged the held file and the page its `slug:` names to be the same page (#6377). Removing the slug line would mint a duplicate, and gbrain does not merge pages by itself yet, so the recommendation (the canonical slug) is recorded on the hold and nothing is written. | `gbrain sources status <source> --json` renders the paragraph; after the user agrees, merge the unique sections of the duplicate into the canonical page, delete the duplicate file, commit, and run `gbrain sync --source <source> --no-pull`. |
+| <a id="content_repair_needs_human"></a>`frontmatter_slug_conflict` (`content_repair_needs_human`) | The content-repair model could not decide whether the held file and the page its `slug:` names are the same page (#6377); nothing is written and nothing retries until the file changes. | `gbrain sources status <source> --json` names the path and both slugs. If they differ, remove the `slug:` line; if they are one page, merge them by hand and delete the duplicate; then commit and sync. |
| <a id="file_too_large"></a>`file_too_large` | Over the import size limit (5 MB for Markdown and code, 10 MiB for any sync read). The limit is fixed. | Split the file into smaller files and commit, or leave it out of the source: read `gbrain config get sync.exclude`, then `gbrain config set sync.exclude '<current list>,<path>'`. The next `gbrain sync --source <source> --no-pull` clears the hold. |
| <a id="managed_image_sync_unsupported"></a>`managed_image_sync_unsupported` | With multimodal embedding on (`embedding_multimodal` / `GBRAIN_EMBEDDING_MULTIMODAL`), sync admits image files, but managed sync has no image importer yet. Each image import is held instead of refusing the whole sync (#5493); deleting or renaming an image still reconciles its page. These holds count as missing coverage (the image is not searchable) but never escalate, because they are not a content fault. | Nothing is broken; keeping them held is fine. To stop holding images, leave them out of the source (`gbrain config get sync.exclude`, then `gbrain config set sync.exclude '<current list>,**/*.png'`) or turn multimodal embedding off; either clears the holds on the next `gbrain sync --source <source> --no-pull`. A held image is re-screened when it changes and on `gbrain sources retry-held <source>`. |
| <a id="content_rejected"></a>`content_rejected` | The content-sanity gate matched junk and the operator set `content_sanity.junk_disposition` to `reject`, so the file is never imported and always visible. | Remove the matched junk from the file, or ask the user whether `junk_disposition` should go back to `quarantine`; that setting is the user's decision. |
diff --git a/src/commands/models.ts b/src/commands/models.ts
index 46a00d748b..2af0958de5 100644
--- a/src/commands/models.ts
+++ b/src/commands/models.ts
@@ -44,6 +44,7 @@ import {
} from '../core/model-config.ts';
import { resolveExtractAtomsModelWithSource } from '../core/cycle/extract-atoms.ts';
import { resolveFenceRepairModelWithSource } from '../core/fence-repair/model.ts';
+import { resolveContentRepairModelWithSource } from '../core/content-repair/llm.ts';
import { resolveFactsExtractionModel } from '../core/facts/extract.ts';
import {
NIGHTLY_PROBE_EXTRACTOR_ROUTE,
@@ -110,6 +111,12 @@ const PER_TASK_KEYS: PerTaskModelRoute[] = [
description: 'Model repair (Tier 3) of malformed facts/takes fence rows; unset: the first measured model with a key, else none (off)',
narrowResolver: async engine => { const r = await resolveFenceRepairModelWithSource(engine); return { model: r.model ?? 'none', source: r.source }; },
},
+ {
+ key: 'models.content_repair',
+ tier: 'deep',
+ description: 'Slug-conflict judgment of the content-repair lane (#6377); unset: models.fence_repair, else the first measured model with a key, else none (off)',
+ narrowResolver: async engine => { const r = await resolveContentRepairModelWithSource(engine); return { model: r.model ?? 'none', source: r.source === 'measured' ? 'measured' : 'config' }; },
+ },
{ key: 'models.subagent', tier: 'subagent', description: '`gbrain agent run` subagent loop' },
{
key: 'facts.extraction_model',
diff --git a/src/commands/repair.ts b/src/commands/repair.ts
index 1495b96a7c..bc718e129c 100644
--- a/src/commands/repair.ts
+++ b/src/commands/repair.ts
@@ -66,9 +66,9 @@ Options:
--include-ambiguous
Explicit-only kinds: widen the preview to ambiguous items (its hash covers them).
--only <path>, --skip <path>
- frontmatter, fences: select source-relative files (repeatable); the hash covers the selection.
+ frontmatter, fences, slug-conflicts: select source-relative files (repeatable); the hash covers the selection.
--slug <slug> fences: select a database page by slug (repeatable); the hash covers the selection.
- --diff frontmatter, fences: print every per-file diff, not one sample per class or tier.
+ --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
@@ -88,7 +88,7 @@ const BOOLEAN_FLAGS = new Set(['--apply', '--all', '--json', '--no-embed', '--in
const VALUE_FLAGS = new Set(['--source', '--limit', '--expect', '--only', '--skip', '--slug', '--max-usd']);
/** Flags only some kinds accept, with the kinds that do. */
const KIND_FLAGS: Record<string, readonly string[]> = {
- '--only': ['frontmatter', 'fences'], '--skip': ['frontmatter', 'fences'], '--diff': ['frontmatter', 'fences'], '--yes': ['frontmatter', 'conversation-labels'],
+ '--only': ['frontmatter', 'fences', 'slug-conflicts'], '--skip': ['frontmatter', 'fences', 'slug-conflicts'], '--diff': ['frontmatter', 'fences', 'slug-conflicts'], '--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 --git a/src/core/content-repair/hold-fix.ts b/src/core/content-repair/hold-fix.ts
new file mode 100644
index 0000000000..179bb4ebcc
--- /dev/null
+++ b/src/core/content-repair/hold-fix.ts
@@ -0,0 +1,99 @@
+/**
+ * #6377: what a `frontmatter_slug_conflict` sync hold tells an agent, by the
+ * content-repair lane's recorded state (`meta.content_repair`, written by
+ * `recordContentHoldRepair`). The command is always that file's
+ * `gbrain repair content --source <id> --only <path>` (Lane C's lane runner:
+ * fences, then slug conflicts, for one selection); the step it calls for
+ * depends on the state:
+ *
+ * - no state: the lane has not judged it yet. gbrain repairs it by itself on
+ * the next maintenance run or on `sync unblock --apply`; the preview is
+ * read-only and calls no model.
+ * - `merge_into` (`merge_recommended`): a person merges the two pages; the
+ * fix is addressed to the user with the rendered paragraph
+ * (`contentRepairHumanReason`: codes and slugs, never model prose).
+ * - `needs_human` (`content_repair_needs_human`): the model could not decide;
+ * the user chooses which page keeps the slug.
+ * - `pending` on a paid reason (`llm_disabled`, `budget_exhausted`,
+ * `no_measured_model`, `no_pricing`): waits on spend the user controls; the
+ * fix names the setting with consent `paid`.
+ * - `pending` on a transient reason (`llm_unavailable`,
+ * `ledger_unavailable`, `sync_in_progress`, `claimed_elsewhere`): the next
+ * run retries after `next_attempt_after`.
+ * - `remove_slug` recorded (the edit could not be written: `canonical_overlay`,
+ * `still_invalid`, `changed_since_read`): the exact one-line edit by hand.
+ *
+ * Location only: path, slugs, codes and amounts.
+ */
+import type { Action, ActionInput, Effect } from '../agent-output.ts';
+import { CONTENT_REPAIR_MEASURED_MODELS } from './measured.ts';
+import type { ContentHoldRepairState } from '../persistence/sync-holds.ts';
+import { contentRepairHumanReason } from '../persistence/sync-fault-class.ts';
+
+const PAID: ReadonlySet<string> = new Set(['llm_disabled', 'budget_exhausted', 'no_measured_model', 'no_pricing']);
+
+/** The read-only preview of one held file's content repair. */
+export function contentPreviewArgv(sourceId: string, path?: string): string[] {
+ return ['gbrain', 'repair', 'content', '--source', sourceId, ...(path ? ['--only', path] : [])];
+}
+
+/** The docs anchor a judged hold points at (the hold code's own anchor otherwise). */
+export function contentHoldDocs(state: ContentHoldRepairState | undefined): string {
+ if (state?.action === 'merge_into') return 'docs/guides/write-refusals.md#merge_recommended';
+ if (state?.action === 'needs_human') return 'docs/guides/write-refusals.md#content_repair_needs_human';
+ return 'docs/guides/write-refusals.md#frontmatter_slug_conflict';
+}
+
+/** The paid setting a pending hold waits on, with the inputs a placeholder needs. */
+function paidStep(reason: string, model: string | undefined): { argv: string[]; inputs?: ActionInput[] } {
+ if (reason === 'llm_disabled') return { argv: ['gbrain', 'config', 'set', 'fences.repair.llm', 'true'] };
+ if (reason === 'no_measured_model') return { argv: ['gbrain', 'config', 'set', 'models.content_repair', '<model>'],
+ inputs: [{ name: 'model', how: `The provider:model the user chooses to trust with the slug-conflict judgment. Measured: ${CONTENT_REPAIR_MEASURED_MODELS.join(', ')}; each needs its provider's key.` }] };
+ if (reason === 'no_pricing') return { argv: ['gbrain', 'pricing', 'set', model ?? '<model>', '--input', '<usd>', '--output', '<usd>'],
+ inputs: [...(model ? [] : [{ name: 'model', how: 'The content-repair model: models.content_repair in gbrain models --json.' }]),
+ { name: 'usd', how: "The provider's price in USD per 1M input tokens after --input and per 1M output tokens after --output, from its pricing page." }] };
+ return { argv: ['gbrain', 'config', 'set', 'fences.repair.max_usd_per_day', '<usd>'],
+ inputs: [{ name: 'usd', how: 'The daily cap in USD the user agreed to; read the current one with gbrain config get fences.repair.max_usd_per_day.' }] };
+}
+
+export function contentHoldFix(record: { source_id: string; path: string; slug?: string | null; meta: { content_repair?: ContentHoldRepairState } }): Action {
+ const source = record.source_id;
+ const preview = contentPreviewArgv(source, record.path);
+ const verify = { argv: ['gbrain', 'sources', 'status', source, '--json'] };
+ const docs = contentHoldDocs(record.meta.content_repair);
+ const state = record.meta.content_repair;
+ const base = { argv: preview, consent: [] as Effect[], requires_exclusive: false, verify, docs };
+ if (!state) {
+ return { ...base, actor: 'agent',
+ why: `The frontmatter slug of ${record.path} names another page. gbrain repairs this itself on the next maintenance run or with gbrain sync unblock --source ${source} --apply: `
+ + 'a stray slug (no such page, or a page of another type with nothing in common) is removed deterministically; anything else is judged by the content-repair model under the fences.repair caps. '
+ + 'The preview is read-only and calls no model: it lists the planned action, the estimated model cost and the cap left, and prints the apply command.' };
+ }
+ const paragraph = contentRepairHumanReason({ ...state, path: record.path, slug: record.slug ?? null });
+ if (paragraph) {
+ return { ...base, actor: 'user', user_message: paragraph,
+ why: state.action === 'merge_into'
+ ? `The content-repair model judged ${record.path} and page ${state.canonical ?? state.named ?? '?'} to be the same page (merge_recommended). gbrain does not merge pages by itself yet, so a person merges them; nothing was written. `
+ + 'Removing the slug: line instead would mint a second page for the same thing, so the deterministic repair never applies here.'
+ : `The content-repair model could not decide whether ${record.path} and the page its slug: line names are the same page (content_repair_needs_human), so nothing was written and nothing retries it until the file changes. `
+ + 'A person decides which page keeps the slug.' };
+ }
+ if (state.action === 'pending' && PAID.has(state.reason)) {
+ return { ...base, actor: 'agent', consent: ['paid' as Effect], ...paidStep(state.reason, state.model),
+ why: `${record.path} waits for the content-repair model (${state.reason}): ${state.reason === 'llm_disabled' ? 'model repair is off (fences.repair.llm false)'
+ : state.reason === 'no_measured_model' ? 'no measured model has a provider key here and models.content_repair is unset'
+ : state.reason === 'no_pricing' ? `gbrain has no price for ${state.model ?? 'the model'} under a user-set cap` : 'the daily content-repair budget is spent'}. `
+ + `Spending is the user's call; ask before changing it. Until then the file stays held${state.next_attempt_after ? ` and the maintenance run tries again after ${state.next_attempt_after}` : ''}. `
+ + `Preview: ${preview.join(' ')}`,
+ user_message: `${record.path} has a frontmatter slug conflict only a model call can judge, and ${state.reason === 'llm_disabled' ? 'model repair is turned off' : state.reason === 'budget_exhausted' ? 'the daily model budget for content repair is spent'
+ : state.reason === 'no_pricing' ? 'gbrain has no price for the configured model' : 'no measured model has a key here'}. Allow the spend, or leave the file held?` };
+ }
+ if (state.action === 'pending') {
+ return { ...base, actor: 'agent',
+ why: `${record.path} is held until the content-repair model can judge it (${state.reason}); the maintenance run tries again${state.next_attempt_after ? ` after ${state.next_attempt_after}` : ''}. `
+ + `Run the preview now to retry immediately (read-only), then its apply command.` };
+ }
+ return { ...base, actor: 'agent',
+ why: `gbrain decided to remove the slug: line of ${record.path} but could not write it (${state.reason}); the preview shows the current state. `
+ + `By hand: delete the slug: line of ${record.path} (the path decides the slug), commit, and run gbrain sync --source ${source} --no-pull.` };
+}
diff --git a/src/core/content-repair/judgment.ts b/src/core/content-repair/judgment.ts
new file mode 100644
index 0000000000..7c645168ab
--- /dev/null
+++ b/src/core/content-repair/judgment.ts
@@ -0,0 +1,222 @@
+/**
+ * #6377 the slug-conflict judgment (Lane B3): what the content-repair model
+ * is shown about a held file and the page its frontmatter `slug:` names, and
+ * how its one-object answer is read back. Pure: no I/O, no engine, so the
+ * eval harness (evals/content-repair-judgment) builds the same prompt from
+ * fixture files and scores the same parser.
+ *
+ * What the model sees (both participants, nothing else of the brain): each
+ * side's path, slug and type, its frontmatter as `key: value` text exactly as
+ * the file carries it, its headings, the first JUDGMENT_HEAD_LINES body lines,
+ * and every later body line that mentions the other side's slug (identity
+ * evidence past line 60, Codex #7). The held side is the file sync refused;
+ * the named side is the page the `slug:` line resolves to, or none when no
+ * page has that slug.
+ *
+ * What it must return: exactly one JSON object and nothing else:
+ * `{"action":"remove_slug"}` (the two are different things; the stray line
+ * goes), `{"action":"merge_into","canonical":"<one of the two slugs>"}` (the
+ * same thing twice; the canonical slug keeps the page) or
+ * `{"action":"needs_human"}` (not decidable from the evidence), with an
+ * optional one-sentence `why`. The `why` is shown in the run's output only;
+ * holds and receipts carry codes and slugs (Codex #11). Failure classes
+ * mirror fence-repair/llm.ts: `llm_unavailable` (the provider threw;
+ * transient, the attempt memo is not consumed), `llm_empty`, `llm_refused`
+ * (a refusal or content-filter stop, or a prose refusal), `llm_malformed`
+ * (no single object, an unknown action, a canonical that is neither slug),
+ * `llm_truncated` (any stop other than a normal end) and `llm_declined` (the
+ * single word HOLD; the prompt asks for `needs_human` instead, but a model
+ * trained on the fence prompt may still say it).
+ */
+import type { ChatMessage, ChatResult } from '../ai/gateway.ts';
+import { parseMarkdown } from '../markdown.ts';
+
+/** Bump when the prompt text changes: it is part of the attempt-memo key, so a new prompt retries rejected pairs. */
+export const JUDGMENT_PROMPT_VERSION = 1;
+/** Body lines each participant shows from the top. */
+export const JUDGMENT_HEAD_LINES = 60;
+/** Mention lines kept per participant past the head (the longest pages stay bounded). */
+export const JUDGMENT_MAX_MENTIONS = 40;
+/** A line longer than this is cut (the model judges identity, not prose). */
+const MAX_LINE_CHARS = 400;
+/** The decline word the fence prompt taught; accepted here as `llm_declined`. */
+export const JUDGMENT_DECLINE = 'HOLD';
+
+export type JudgmentAction = 'remove_slug' | 'merge_into' | 'needs_human';
+export const JUDGMENT_ACTIONS: readonly JudgmentAction[] = ['remove_slug', 'merge_into', 'needs_human'];
+
+/** One side of the judgment, as text the file or page carries. */
+export interface JudgmentParticipant {
+ /** Source-relative file path; null for a database-only page. */
+ path: string | null;
+ slug: string;
+ type: string;
+ /** Frontmatter keys and values as text, as the file has them (no key is added). */
+ frontmatter: Record<string, string>;
+ headings: string[];
+ /** The first JUDGMENT_HEAD_LINES non-blank body lines. */
+ head_lines: string[];
+ /** Later body lines that mention the other participant's slug. */
+ mentions: string[];
+}
+
+export interface JudgmentInput {
+ held: JudgmentParticipant;
+ /** The page the held file's `slug:` resolves to; null when no page has that slug. */
+ named: JudgmentParticipant | null;
+ /** The hold's reason code (location-only). */
+ reason: string;
+}
+
+export type JudgmentVerdict =
+ | { ok: true; action: 'remove_slug'; why?: string }
+ | { ok: true; action: 'merge_into'; canonical: string; why?: string }
+ | { ok: true; action: 'needs_human'; why?: string };
+
+export type JudgmentFailureReason = 'llm_unavailable' | 'llm_empty' | 'llm_refused' | 'llm_malformed' | 'llm_truncated' | 'llm_declined';
+export interface JudgmentFailure { ok: false; reason: JudgmentFailureReason; text?: string; error?: string }
+
+const cut = (line: string) => (line.length > MAX_LINE_CHARS ? `${line.slice(0, MAX_LINE_CHARS)}…` : line);
+
+/** A frontmatter value as the prompt shows it: scalars as written, anything else as JSON. */
+function valueText(value: unknown): string {
+ if (value === null || value === undefined) return '';
+ if (typeof value === 'string') return value;
+ if (typeof value === 'number' || typeof value === 'boolean') return String(value);
+ if (value instanceof Date) return value.toISOString();
+ return JSON.stringify(value);
+}
+
+/** Whether a body line mentions a slug: the full slug, or its last segment as a word. */
+function mentions(line: string, slug: string): boolean {
+ if (line.includes(slug)) return true;
+ const leaf = slug.split('/').pop() ?? slug;
+ return leaf.length >= 3 && new RegExp(`(^|[^a-z0-9])${leaf.replace(/[.*+?^${}()|[\]\\]/g, '\\$&')}([^a-z0-9]|$)`, 'i').test(line);
+}
+
+/**
+ * The participant a Markdown file or stored page makes: `content` is the file
+ * as written (frontmatter included) or a page serialized the same way;
+ * `otherSlug` is the slug whose mentions are collected (null: none).
+ */
+export function judgmentParticipant(input: { path: string | null; slug: string; content: string; otherSlug: string | null; type?: string }): JudgmentParticipant {
+ const parsed = parseMarkdown(input.content, input.path ?? `${input.slug}.md`);
+ const raw = /^\uFEFF?---[ \t]*\r?\n([\s\S]*?)\r?\n---[ \t]*(?:\r?\n|$)/.exec(input.content)?.[1] ?? '';
+ const frontmatter: Record<string, string> = {};
+ for (const line of raw.split(/\r?\n/)) {
+ const m = /^([A-Za-z_][\w.-]*):\s*(.*)$/.exec(line);
+ if (m) frontmatter[m[1]!] = cut(m[2]!.trim());
+ }
+ if (!Object.keys(frontmatter).length) {
+ for (const [key, value] of Object.entries(parsed.frontmatter)) frontmatter[key] = cut(valueText(value));
+ if (parsed.title && !frontmatter.title) frontmatter.title = cut(parsed.title);
+ }
+ const body = [parsed.compiled_truth, parsed.timeline].filter(Boolean).join('\n').split(/\r?\n/);
+ const lines = body.map(line => line.trimEnd()).filter(line => line.trim());
+ const headings = lines.filter(line => /^#{1,6}\s/.test(line)).map(line => cut(line.replace(/^#{1,6}\s+/, '')));
+ const head = lines.slice(0, JUDGMENT_HEAD_LINES).map(cut);
+ const later = input.otherSlug ? lines.slice(JUDGMENT_HEAD_LINES).filter(line => mentions(line, input.otherSlug!)).slice(0, JUDGMENT_MAX_MENTIONS).map(cut) : [];
+ return { path: input.path, slug: input.slug, type: input.type ?? parsed.type, frontmatter, headings, head_lines: head, mentions: later };
+}
+
+function renderParticipant(label: string, p: JudgmentParticipant): string[] {
+ return [
+ `## ${label}`,
+ `path: ${p.path ?? '(no file; database page)'}`,
+ `slug: ${p.slug}`,
+ `type: ${p.type}`,
+ 'frontmatter:',
+ ...(Object.keys(p.frontmatter).length ? Object.entries(p.frontmatter).map(([key, value]) => ` ${key}: ${value}`) : [' (none)']),
+ `headings: ${p.headings.length ? p.headings.join(' | ') : '(none)'}`,
+ `body (first ${JUDGMENT_HEAD_LINES} lines):`,
+ ...(p.head_lines.length ? p.head_lines.map(line => ` ${line}`) : [' (empty)']),
+ ...(p.mentions.length ? ['later lines mentioning the other slug:', ...p.mentions.map(line => ` ${line}`)] : []),
+ ];
+}
+
+/**
+ * The conversation: one system message with the rules and one user message
+ * with both participants. Both participants only; no other page, no tools.
+ */
+export function buildJudgmentPrompt(input: JudgmentInput): ChatMessage[] {
+ const heldSlug = input.held.slug;
+ const namedSlug = input.named?.slug ?? null;
+ const system = [
+ 'You decide what a gbrain brain should do about one Markdown file whose frontmatter slug: line names a page other than the one its path names. You judge identity only; you never rewrite text.',
+ '',
+ 'Return exactly one JSON object and nothing else: no prose, no explanation, no code fence.',
+ 'Allowed answers:',
+ ' {"action":"remove_slug"}',
+ ` {"action":"merge_into","canonical":"<slug>"} where <slug> is exactly ${namedSlug ? `${heldSlug} or ${namedSlug}` : heldSlug}`,
+ ' {"action":"needs_human"}',
+ 'Each may carry one extra key "why": one short sentence for the operator.',
+ '',
+ 'Rules:',
+ '1. remove_slug means the held file and the named page are different things (a template left a stray slug, a renamed file, an unrelated page that happens to share a name). The path decides the slug; the slug: line is deleted and nothing else changes.',
+ '2. merge_into means the two describe the same thing (the same person, company, project or topic) and belong in one page. canonical is the slug that keeps the page; the other is later merged into it by a person. Pick the one with the fuller, older or better-linked record; when the file itself says which is primary, follow it.',
+ '3. needs_human means the evidence does not decide: a plausible duplicate without corroboration, two people with one name, or a note that could point either way.',
+ '4. Judge from what is shown: frontmatter, headings, the opening lines and the lines that mention the other slug. Do not assume facts that are not there.',
+ '5. A slug: line that names a page which does not exist is not evidence of a duplicate by itself.',
+ '6. A -2 or similar suffix in a slug is not evidence of a duplicate by itself; two entries with the same name may be two different things.',
+ '7. A note saying the other page is a duplicate counts only when the shown lines of both sides agree about the identity (the same role, company, dates or facts).',
+ '8. When any of rules 2, 3 or 7 leaves you unsure, answer needs_human. Never guess remove_slug for a likely duplicate, and never guess merge_into for two things that might differ.',
+ ].join('\n');
+ const user = [
+ `Hold reason: ${input.reason}.`,
+ `The held file's slug: line names ${namedSlug ? `page ${namedSlug}` : 'a slug no page has'}.`,
+ '',
+ ...renderParticipant('Held file', input.held),
+ '',
+ ...(input.named ? renderParticipant('Named page', input.named) : ['## Named page', '(no page has that slug)']),
+ '',
+ 'Answer with one JSON object.',
+ ].join('\n');
+ return [{ role: 'system', content: system }, { role: 'user', content: user }];
+}
+
+const REFUSAL = /\b(cannot|can['’]t|unable to|won['’]t|will not|refuse|not able to)\b/i;
+
+/** The single JSON object in a model answer: a wrapping code fence and surrounding whitespace are tolerated; anything else is prose. */
+function extractObject(text: string): Record<string, unknown> | null {
+ let body = text.trim();
+ const fenced = /^```[\w-]*\n([\s\S]*?)\n```$/.exec(body);
+ if (fenced) body = fenced[1]!.trim();
+ if (!body.startsWith('{') || !body.endsWith('}')) return null;
+ try {
+ const value: unknown = JSON.parse(body);
+ return value && typeof value === 'object' && !Array.isArray(value) ? value as Record<string, unknown> : null;
+ } catch {
+ return null;
+ }
+}
+
+/**
+ * The verdict a model's `text` carries, independent of the transport (the
+ * eval harness scores stored texts). With `slugs`, a `merge_into` whose
+ * canonical is neither participant is `llm_malformed`; without them any
+ * non-empty canonical is accepted.
+ */
+export function parseJudgmentText(text: string, slugs?: { held: string; named: string | null }): JudgmentVerdict | JudgmentFailure {
+ const trimmed = text.trim();
+ if (!trimmed) return { ok: false, reason: 'llm_empty' };
+ if (trimmed.replace(/[.*_`]/g, '').trim() === JUDGMENT_DECLINE) return { ok: false, reason: 'llm_declined', text };
+ const object = extractObject(trimmed);
+ if (!object) return { ok: false, reason: REFUSAL.test(trimmed) && !trimmed.startsWith('{') ? 'llm_refused' : 'llm_malformed', text };
+ const action = object.action;
+ const why = typeof object.why === 'string' && object.why.trim() ? { why: object.why.trim().slice(0, MAX_LINE_CHARS) } : {};
+ if (action === 'remove_slug') return { ok: true, action, ...why };
+ if (action === 'needs_human') return { ok: true, action, ...why };
+ if (action === 'merge_into') {
+ const canonical = object.canonical;
+ if (typeof canonical !== 'string' || !canonical.trim() || (slugs && canonical !== slugs.held && canonical !== slugs.named)) return { ok: false, reason: 'llm_malformed', text };
+ return { ok: true, action, canonical, ...why };
+ }
+ return { ok: false, reason: 'llm_malformed', text };
+}
+
+/** The verdict of one gateway result: the stop reason first, then the text. */
+export function parseJudgmentAnswer(result: ChatResult, slugs?: { held: string; named: string | null }): JudgmentVerdict | JudgmentFailure {
+ if (result.stopReason === 'refusal' || result.stopReason === 'content_filter') return { ok: false, reason: 'llm_refused', text: result.text };
+ if (result.stopReason !== 'end') return { ok: false, reason: result.text.trim() ? 'llm_truncated' : 'llm_empty', text: result.text };
+ return parseJudgmentText(result.text, slugs);
+}
diff --git a/src/core/content-repair/llm.ts b/src/core/content-repair/llm.ts
new file mode 100644
index 0000000000..17bbbc861f
--- /dev/null
+++ b/src/core/content-repair/llm.ts
@@ -0,0 +1,222 @@
+/**
+ * #6377 the paid tier of the content-repair lane: one metered judgment call
+ * per slug-conflict candidate, under the fence repair's caps and ledger.
+ *
+ * Model: `models.content_repair` when set (an explicit choice always runs,
+ * new and unpriced models included), else `models.fence_repair` when set,
+ * else the first model of `CONTENT_REPAIR_MEASURED_MODELS` the brain has a
+ * provider key for, else the fence repair's measured list the same way, else
+ * none (`no_measured_model`: the model tier stays off until the user picks).
+ *
+ * Spend (Codex #9): the lane is one budget. Every call reserves against the
+ * fence repair's daily ledger identity (`FENCE_REPAIR_LEDGER`, so a fences
+ * spend earlier today counts) under `fences.repair.max_usd_per_day`, is
+ * checked against `fences.repair.max_usd_per_page` and the run's own
+ * allowance (`--max-usd`), and uses the same thinking-off control and output
+ * ceiling as the fence tier: a short JSON answer plus a reasoning allowance
+ * for a model whose reasoning the call cannot switch off, so the estimate
+ * reserves what the gateway will send.
+ *
+ * Memo: the fence repair's attempt store (`fence-repair/attempts.ts`) under
+ * its own candidate key (`slug-conflict:<path>`, so it never overwrites a
+ * fence attempt of the same file) with a memo of sha256(held bytes),
+ * sha256(named page content or `none`), both page ids, the model and
+ * `JUDGMENT_PROMPT_VERSION`: a verdict already given for these exact inputs
+ * (rejected: `merge_into`, `needs_human`, an unusable answer) is returned at
+ * $0 until one of them changes; `llm_unavailable` is transient and does not
+ * consume it. A published `remove_slug` changes the bytes, so its memo never
+ * matches again.
+ *
+ * Messages carry reason codes, slugs, hashes and dollar amounts only.
+ */
+import type { BrainEngine } from '../engine.ts';
+import { chat, isThinkingModel, THINKING_MODEL_MAX_OUTPUT_TOKENS, type ChatResult } from '../ai/gateway.ts';
+import { thinkingOffControl, thinkingOffMaxOutputTokens } from '../ai/thinking-off.ts';
+import { mergedProviderEnv } from '../ai/provider-env.ts';
+import { loadConfig, type GBrainConfig } from '../config.ts';
+import { providerKeyReady, resolveModel, TIER_DEFAULTS } from '../model-config.ts';
+import { chatCallUsd, dailyLedger, estimateChatCallUsd, FENCE_REPAIR_LEDGER, type DailyLedger } from '../budget/daily-ledger.ts';
+import type { PricingOverrides } from '../budget/reservation-cost.ts';
+import type { NoPricingGuidance } from '../budget/no-pricing.ts';
+import type { CapSource } from '../consent.ts';
+import { attemptStore, type AttemptClaim, type AttemptStore } from '../fence-repair/attempts.ts';
+import { FENCE_REPAIR_MEASURED_MODELS } from '../fence-repair/measured.ts';
+import { FENCE_REPAIR_MODEL_KEY } from '../fence-repair/model.ts';
+import { TIER3_REASONING_TOKENS } from '../fence-repair/llm.ts';
+import { sha256, stableJson } from '../persistence/digest.ts';
+import { buildJudgmentPrompt, JUDGMENT_PROMPT_VERSION, parseJudgmentAnswer, type JudgmentFailureReason, type JudgmentInput, type JudgmentVerdict } from './judgment.ts';
+import { CONTENT_REPAIR_MEASURED_MODELS } from './measured.ts';
+
+export const CONTENT_REPAIR_MODEL_KEY = 'models.content_repair';
+/** Output tokens the JSON answer needs; a reasoning model adds TIER3_REASONING_TOKENS. */
+const ANSWER_TOKENS = 256;
+
+export type ContentRepairModelSource = 'config' | 'fence_config' | 'measured';
+
+/** The judgment model and where it came from; `env` replaces the environment and config-file keys (tests). */
+export async function resolveContentRepairModelWithSource(engine: Pick<BrainEngine, 'getConfig'>, env?: Record<string, string | undefined>): Promise<{ model: string | null; source: ContentRepairModelSource }> {
+ const read = (key: string) => engine.getConfig(key).catch(() => null);
+ if ((await read(CONTENT_REPAIR_MODEL_KEY))?.trim()) return { model: await resolveModel(engine, { configKey: CONTENT_REPAIR_MODEL_KEY, tier: 'deep', fallback: TIER_DEFAULTS.deep }), source: 'config' };
+ if ((await read(FENCE_REPAIR_MODEL_KEY))?.trim()) return { model: await resolveModel(engine, { configKey: FENCE_REPAIR_MODEL_KEY, tier: 'deep', fallback: TIER_DEFAULTS.deep }), source: 'fence_config' };
+ const keys = env ? Object.fromEntries(Object.entries(env).filter((e): e is [string, string] => !!e[1])) : mergedProviderEnv(fileConfig(), process.env);
+ const measured = [...CONTENT_REPAIR_MEASURED_MODELS, ...FENCE_REPAIR_MEASURED_MODELS].find(model => providerKeyReady(model, keys)) ?? null;
+ return { model: measured, source: 'measured' };
+}
+
+export async function resolveContentRepairModel(engine: Pick<BrainEngine, 'getConfig'>, env?: Record<string, string | undefined>): Promise<string | null> {
+ return (await resolveContentRepairModelWithSource(engine, env)).model;
+}
+
+function fileConfig(): GBrainConfig | null {
+ try { return loadConfig(); } catch { return null; }
+}
+
+/** The model may reason whatever the call asks: a thinking-by-default model, or a route whose thinking-off option does not turn reasoning fully off. */
+function mayReason(model: string): boolean {
+ return isThinkingModel(model) || !thinkingOffControl(model)?.disables;
+}
+
+/** Token bounds for one call: the prompt's size and the output ceiling the gateway will send. */
+export function judgmentTokenBudget(input: JudgmentInput, model: string): { inputTokens: number; maxOutputTokens: number } {
+ const chars = buildJudgmentPrompt(input).reduce((sum, message) => sum + (typeof message.content === 'string' ? message.content.length : 0), 0);
+ const requested = ANSWER_TOKENS + (mayReason(model) ? TIER3_REASONING_TOKENS : 0);
+ return { inputTokens: Math.ceil(chars / 3) + 64, maxOutputTokens: thinkingOffMaxOutputTokens(model, requested, isThinkingModel(model), THINKING_MODEL_MAX_OUTPUT_TOKENS) };
+}
+
+/** The worst-case estimate of one judgment call (what the preview lists and the ledger reserves). */
+export function judgmentEstimate(input: JudgmentInput, pricing: { model: string; overrides?: PricingOverrides; capSource: CapSource }):
+ { ok: true; usd: number; estimated: boolean } | { ok: false; reason: 'no_pricing'; guidance: NoPricingGuidance } {
+ const budget = judgmentTokenBudget(input, pricing.model);
+ const quote = estimateChatCallUsd({ model: pricing.model, inputTokens: budget.inputTokens, maxOutputTokens: budget.maxOutputTokens, overrides: pricing.overrides, capSource: pricing.capSource });
+ return quote.ok ? { ok: true, usd: quote.quote.usd, estimated: quote.quote.estimated } : quote;
+}
+
+/** The memo parts of one candidate: everything whose change earns a new call. */
+export interface JudgmentMemoParts { heldSha256: string; namedSha256: string | null; heldPageId: number | null; namedPageId: number | null; model: string }
+
+export function judgmentMemoKey(parts: JudgmentMemoParts): string {
+ return sha256(stableJson({ held: parts.heldSha256, named: parts.namedSha256 ?? 'none', held_id: parts.heldPageId, named_id: parts.namedPageId, model: parts.model, prompt: String(JUDGMENT_PROMPT_VERSION) }));
+}
+
+/** The attempt-store candidate of a held file (its own key space beside the fence repair's `path:` keys). */
+export function judgmentCandidate(sourceId: string, incarnation: string, path: string) {
+ return { sourceId, incarnation, key: `slug-conflict:${path}` };
+}
+
+/** The memo reason a verdict is stored under (the hold carries the same code). */
+export function judgmentMemoReason(verdict: JudgmentVerdict): 'remove_slug' | 'merge_recommended' | 'content_repair_needs_human' {
+ return verdict.action === 'remove_slug' ? 'remove_slug' : verdict.action === 'merge_into' ? 'merge_recommended' : 'content_repair_needs_human';
+}
+
+export type JudgmentAnswer =
+ | { ok: true; verdict: JudgmentVerdict; text: string; result: ChatResult }
+ | { ok: false; reason: JudgmentFailureReason; text?: string; result?: ChatResult; error?: string };
+
+/** One gateway call (no tools, no fallback model, thinking off where the route allows), classified. */
+export async function askJudgment(input: JudgmentInput, opts: { model: string; timeoutMs?: number; signal?: AbortSignal }): Promise<JudgmentAnswer> {
+ const [system, ...messages] = buildJudgmentPrompt(input);
+ const budget = judgmentTokenBudget(input, opts.model);
+ let result: ChatResult;
+ try {
+ result = await chat({ model: opts.model, system: typeof system!.content === 'string' ? system!.content : '', messages, maxTokens: budget.maxOutputTokens, allowFallback: false,
+ thinking: 'off', purpose: 'content_repair', ...(opts.timeoutMs ? { timeoutMs: opts.timeoutMs } : {}), ...(opts.signal ? { abortSignal: opts.signal } : {}) });
+ } catch (error) {
+ return { ok: false, reason: 'llm_unavailable', error: error instanceof Error ? error.name : 'Error' };
+ }
+ const parsed = parseJudgmentAnswer(result, { held: input.held.slug, named: input.named?.slug ?? null });
+ if (!parsed.ok) return { ok: false, reason: parsed.reason, text: result.text, result };
+ return { ok: true, verdict: parsed, text: result.text, result };
+}
+
+export interface JudgmentCallOptions {
+ /** The candidate (memo identity and attempt claim). */
+ sourceId: string; incarnation: string; path: string;
+ memo: Omit<JudgmentMemoParts, 'model'>;
+ overrides?: PricingOverrides;
+ capSource: CapSource;
+ perPageUsd: number;
+ perDayUsd: number;
+ /** What is left of the run's own paid-model allowance (`--max-usd`); undefined = none. */
+ allowanceUsd?: number;
+ timeoutMs: number;
+ now?: () => Date;
+ /** Injectable for tests; default the fence repair's ledger identity and attempt store on `engine`. */
+ ledger?: DailyLedger;
+ store?: AttemptStore;
+}
+
+export type JudgmentOutcome =
+ /** The model answered; the claim is `settled` and the caller publishes it (after a write) or rejects it (a verdict that writes nothing). */
+ | { ok: true; verdict: JudgmentVerdict; spentUsd: number; claim: AttemptClaim }
+ | { ok: false; reason: JudgmentFailureReason | 'budget_exhausted' | 'ledger_unavailable' | 'no_pricing' | 'claimed_elsewhere' | string; spentUsd: number; message: string;
+ /** The whole run should stop (the daily ledger or the run allowance refused the call). */
+ stop?: boolean; resetsAt?: string;
+ /** The stored verdict of an earlier call on these exact inputs ($0). */
+ memoHit?: boolean; guidance?: NoPricingGuidance };
+
+/**
+ * One metered judgment: claim the attempt (a stored verdict for these exact
+ * inputs returns at $0), check the per-page cap and the run allowance,
+ * reserve on the daily ledger, call, settle the actual cost. On a verdict
+ * the claim is left `settled` for the caller; on an unusable answer it is
+ * rejected (the memo is consumed); on a provider failure it is transient.
+ */
+export async function callJudgment(engine: BrainEngine, model: string, input: JudgmentInput, opts: JudgmentCallOptions): Promise<JudgmentOutcome> {
+ const now = opts.now ?? (() => new Date());
+ const ledger = opts.ledger ?? dailyLedger(engine, FENCE_REPAIR_LEDGER, { now });
+ const store = opts.store ?? attemptStore(engine, { now });
+ const claimed = await store.claim(judgmentCandidate(opts.sourceId, opts.incarnation, opts.path), judgmentMemoKey({ ...opts.memo, model }));
+ if (!claimed.ok) {
+ if (claimed.reason === 'claimed_elsewhere') return { ok: false, reason: 'claimed_elsewhere', spentUsd: 0, message: 'Another repair run holds this candidate; it is left to that run.' };
+ if (claimed.reason === 'store_unavailable') return { ok: false, reason: 'ledger_unavailable', spentUsd: 0, message: 'The repair attempt store could not be read, so no model call was made.' };
+ const reason = claimed.record.reason ?? 'llm_malformed';
+ return { ok: false, reason, spentUsd: 0, memoHit: true, message: `The model already judged these exact bytes (${reason}); no new call is made until the file, the named page, the model or the prompt changes.` };
+ }
+ let claim = claimed.claim;
+ const transient = async (reason: string, message: string, extra: Partial<Extract<JudgmentOutcome, { ok: false }>> = {}): Promise<JudgmentOutcome> => {
+ await store.transient(claim, reason);
+ return { ok: false, reason, spentUsd: 0, message, ...extra };
+ };
+ const budget = judgmentTokenBudget(input, model);
+ const quote = estimateChatCallUsd({ model, inputTokens: budget.inputTokens, maxOutputTokens: budget.maxOutputTokens, overrides: opts.overrides, capSource: opts.capSource });
+ if (!quote.ok) return transient('no_pricing', `A spend cap is set but gbrain has no price for ${model}; no call was made.`, { guidance: quote.guidance });
+ const estimate = quote.quote.usd;
+ if (estimate > opts.perPageUsd + 1e-9) return transient('budget_exhausted', `The estimated model cost ($${estimate.toFixed(4)}) exceeds fences.repair.max_usd_per_page ($${opts.perPageUsd.toFixed(2)}).`);
+ if (opts.allowanceUsd !== undefined && estimate > opts.allowanceUsd + 1e-9) {
+ return transient('budget_exhausted', `This run's paid-model allowance ($${opts.allowanceUsd.toFixed(4)} left) cannot cover the estimate ($${estimate.toFixed(4)}).`, { stop: true });
+ }
+ const reserved = await ledger.reserve(estimate, { capUsd: opts.perDayUsd });
+ if (!reserved.ok) {
+ if (reserved.reason === 'ledger_unavailable') return transient('ledger_unavailable', 'The spend ledger could not be read, so no model call was made; the next run retries.');
+ return transient('budget_exhausted', `The daily content-repair budget is spent ($${(reserved.committedUsd + reserved.reservedUsd).toFixed(4)} of $${reserved.capUsd.toFixed(2)} committed or reserved today; `
+ + `this call needs $${reserved.estimateUsd.toFixed(4)}). It resets at ${reserved.resetsAt}.`, { stop: true, resetsAt: reserved.resetsAt });
+ }
+ const moved = await store.dispatched(claim, reserved.reservation.id);
+ if (!moved.ok) {
+ await ledger.release(reserved.reservation.id);
+ if (moved.reason === 'lost_claim') return { ok: false, reason: 'claimed_elsewhere', spentUsd: 0, message: 'Another repair run took over this candidate.' };
+ await store.reject(claim, { reason: 'llm_malformed' });
+ return { ok: false, reason: 'llm_malformed', spentUsd: 0, message: 'The attempt reached its call limit.' };
+ }
+ claim = moved.claim;
+ if (!await ledger.dispatch(reserved.reservation.id)) {
+ await ledger.release(reserved.reservation.id);
+ await store.settled(claim).then(r => { if (r.ok) claim = r.claim; });
+ return transient('ledger_unavailable', 'The spend ledger refused to dispatch the reservation, so no model call was made.');
+ }
+ const answer = await askJudgment(input, { model, timeoutMs: opts.timeoutMs });
+ const actual = answer.result ? chatCallUsd(model, { inputTokens: answer.result.usage.input_tokens, outputTokens: answer.result.usage.output_tokens }, opts.overrides).usd : estimate;
+ const settle = await ledger.settle(reserved.reservation.id, actual);
+ const spent = settle.settled ? settle.actualUsd : actual;
+ const done = await store.settled(claim);
+ if (done.ok) claim = done.claim;
+ if (!answer.ok && answer.reason === 'llm_unavailable') {
+ await store.transient(claim, 'llm_unavailable');
+ return { ok: false, reason: 'llm_unavailable', spentUsd: spent, message: `The judgment model was unavailable (${answer.error ?? 'provider error'}); the next run retries.` };
+ }
+ if (!answer.ok) {
+ await store.reject(claim, { reason: answer.reason });
+ return { ok: false, reason: answer.reason, spentUsd: spent, message: answer.reason === 'llm_declined' ? 'The judgment model declined; a person decides.' : `The judgment model's answer was unusable (${answer.reason}).` };
+ }
+ return { ok: true, verdict: answer.verdict, spentUsd: spent, claim };
+}
diff --git a/src/core/content-repair/measured.ts b/src/core/content-repair/measured.ts
new file mode 100644
index 0000000000..6fef6ad2cb
--- /dev/null
+++ b/src/core/content-repair/measured.ts
@@ -0,0 +1,18 @@
+/**
+ * What the content-repair judgment eval measured (#6377 section 4,
+ * evals/content-repair-judgment/; verdicts in gbrain-evals).
+ *
+ * `CONTENT_REPAIR_MEASURED_MODELS`: the models that met the preregistered
+ * rule (zero hard failures: no `remove_slug` on a true duplicate, no
+ * `merge_into` on an unrelated pair or with the wrong canonical; at least 80%
+ * `merge_into` with the right canonical on true duplicates), best first,
+ * ties to the cheaper model. Until that eval has run it equals the fence
+ * repair's measured list (both frontier models); the content-repair eval
+ * fills it in its own PR. With `models.content_repair` and
+ * `models.fence_repair` unset, the judgment uses the first one the brain has
+ * a provider key for; with none, the model tier stays off
+ * (`no_measured_model`).
+ */
+import { FENCE_REPAIR_MEASURED_MODELS } from '../fence-repair/measured.ts';
+
+export const CONTENT_REPAIR_MEASURED_MODELS: readonly string[] = FENCE_REPAIR_MEASURED_MODELS;
diff --git a/src/core/content-repair/receipt.ts b/src/core/content-repair/receipt.ts
new file mode 100644
index 0000000000..329be1d2e3
--- /dev/null
+++ b/src/core/content-repair/receipt.ts
@@ -0,0 +1,56 @@
+/**
+ * #6377: what a slug-conflict repair records about one write, and the Git
+ * subject and trailer of a repaired file.
+ *
+ * The receipt rides the write's durable outcome (`content_repair`): the
+ * actor `content-repair`, the action written (`remove_slug` is the only one
+ * that writes; a recommended merge or an undecidable pair writes nothing
+ * and lives on the hold instead), the tier that decided it (`deterministic`
+ * or `llm`) with its confidence (`high` for the deterministic rules, `medium`
+ * for a model verdict), the model (llm only), the model spend and the sha256
+ * of the bytes before and after. Hashes and codes only, so it is safe in
+ * receipts, results and commit messages; `parseContentRepairReceipt` rejects
+ * anything else before it reaches a write.
+ */
+export const CONTENT_REPAIR_ACTOR = 'content-repair';
+export const CONTENT_REPAIR_HOLD_CODE = 'frontmatter_slug_conflict';
+
+export interface ContentRepairReceipt {
+ actor: typeof CONTENT_REPAIR_ACTOR;
+ hold_code: typeof CONTENT_REPAIR_HOLD_CODE;
+ action: 'remove_slug';
+ tier: 'deterministic' | 'llm';
+ confidence: 'high' | 'medium';
+ /** The model that judged (llm tier); null for the deterministic tier. */
+ model: string | null;
+ /** Model spend for this file (USD); 0 for the deterministic tier, null for an unpriced model. */
+ cost_usd: number | null;
+ before_sha256: string;
+ after_sha256: string;
+}
+
+const SHA = /^[0-9a-f]{64}$/;
+
+/** A receipt as stored: well-formed or null, so a forged or damaged value never reaches a receipt or a commit message. */
+export function parseContentRepairReceipt(value: unknown): ContentRepairReceipt | null {
+ if (!value || typeof value !== 'object') return null;
+ const r = value as Record<string, unknown>;
+ if (r.actor !== CONTENT_REPAIR_ACTOR || r.hold_code !== CONTENT_REPAIR_HOLD_CODE || r.action !== 'remove_slug') return null;
+ if (r.tier !== 'deterministic' && r.tier !== 'llm') return null;
+ if (r.confidence !== 'high' && r.confidence !== 'medium') return null;
+ if (r.model !== null && (typeof r.model !== 'string' || r.model.length > 200 || /[\r\n]/.test(r.model))) return null;
+ if (r.cost_usd !== null && (typeof r.cost_usd !== 'number' || !Number.isFinite(r.cost_usd) || r.cost_usd < 0)) return null;
+ if (typeof r.before_sha256 !== 'string' || !SHA.test(r.before_sha256) || typeof r.after_sha256 !== 'string' || !SHA.test(r.after_sha256)) return null;
+ return { actor: CONTENT_REPAIR_ACTOR, hold_code: CONTENT_REPAIR_HOLD_CODE, action: 'remove_slug', tier: r.tier, confidence: r.confidence,
+ model: r.model as string | null, cost_usd: r.cost_usd as number | null, before_sha256: r.before_sha256, after_sha256: r.after_sha256 };
+}
+
+/** `gbrain: repair frontmatter slug in <path>`, the subject of a repaired file's commit. */
+export function contentRepairCommitSubject(path: string): string {
+ return `gbrain: repair frontmatter slug in ${path.replace(/[\u0000-\u001f\u007f]/g, '?')}`;
+}
+
+/** `gbrain-repair: frontmatter_slug_conflict <tier> <confidence>`, the trailer every content-repair commit carries. */
+export function contentRepairTrailer(receipt: Pick<ContentRepairReceipt, 'tier' | 'confidence'>): string {
+ return `gbrain-repair: ${CONTENT_REPAIR_HOLD_CODE} ${receipt.tier} ${receipt.confidence}`;
+}
diff --git a/src/core/error-registry.ts b/src/core/error-registry.ts
index 23f91fd3bc..e9ce3ebe1f 100644
--- a/src/core/error-registry.ts
+++ b/src/core/error-registry.ts
@@ -116,6 +116,14 @@ export const CODES = {
connector_intent_outdated: { class: 'caller', summary: "The connector request no longer matches the stored connector intent." },
consent_timeout: { class: 'consent', summary: "Google connect credential error: consent timeout.", docs: 'docs/guides/google-connect.md#troubleshooting' },
consumers_without_heartbeat: { class: 'host_only', summary: "Running write claims on this host are stamped by a process that writes no `persistence_consumers` heartbeat row, so its liveness and mode cannot be read.", why: "Every full consumer on this release renews a heartbeat row every 10 s; a claim owner with no row is a gbrain process from before the heartbeat table (an older `serve`, jobs worker or sync CLI), which also never defers to the resident consumer, so the host may run two full consumers until it is upgraded.", docs: 'docs/guides/troubleshooting.md#consumers-without-heartbeat', suggestion: 'Upgrade and restart the process whose pid the check names (its kind and gbrain version come from the claim stamp); until then the host runs its consumer beside the resident one.', fix: { argv: ['gbrain', 'sources', 'writer', 'status', '--json'], consent: [], actor: 'agent', why: 'Read-only: lists the consumers alive on this host with their heartbeat rows beside the running claims and the owner each claim stamps.', requires_exclusive: false, verify: { argv: ['gbrain', 'doctor', '--only', 'consumers_without_heartbeat', '--json'] } } },
+ content_repair_needs_human: { class: 'caller', retryable: false, actor: 'user',
+ summary: "The content-repair model could not decide whether a held file and the page its frontmatter `slug:` names are the same page, so nothing was written and a person decides which keeps the slug.",
+ why: "A `frontmatter_slug_conflict` hold that the deterministic rules cannot clear (the named page exists and shares a type or a title word with the file) goes to the judgment model; `needs_human` is its answer when the shown frontmatter, headings, opening lines and cross-mentions do not decide identity. Removing the `slug:` line on a guess would mint a second page for the same thing, and merging on a guess would fold two different things together, so gbrain records the verdict on the hold as codes and slugs, retries nothing until the file changes, and the rest of the source keeps syncing.",
+ docs: 'docs/guides/write-refusals.md#content_repair_needs_human',
+ suggestion: 'Show the user the paragraph gbrain sources status <id> --json renders for the hold (the path and the two slugs). If the two differ, remove the slug: line of the file; if they are one page, merge the unique sections into the page that keeps the slug and delete the other file; then commit and run gbrain sync --source <id> --no-pull.',
+ fix: { argv: ['gbrain', 'sources', 'status', '{source_id}', '--json'], consent: [], actor: 'user', requires_exclusive: false,
+ why: 'Read-only: lists the held file with the two slugs and the rendered paragraph; the user decides which page keeps the slug before anything is edited.',
+ verify: { argv: ['gbrain', 'sources', 'status', '{source_id}', '--json'] } } },
content_rejected: { class: 'caller', summary: "The content-sanity gate rejected the content because the operator set `content_sanity.junk_disposition` to `reject`.", why: "A junk-pattern or operator-literal hit is refused instead of quarantined under that setting, so the page was not written. The same content refuses on every retry.", suggestion: 'Remove the matched junk from the file, or switch `content_sanity.junk_disposition` back to `quarantine` (a user decision), then import it again.' },
core_budget_exceeded: { class: 'caller', summary: "The write would push always-loaded core memory over its brain-wide character budget or page limit.", why: "Core pages enter every session's prompt in every harness, so their total size is capped on the write path.", docs: 'docs/guides/core-memory.md#budget', fix: { argv: ['gbrain', 'core', 'status', '--json'], consent: [], actor: 'agent', why: "Shows core usage against the budget and the largest core pages, read-only.", requires_exclusive: false } },
core_delete_owner_only: { class: 'consent', summary: "A remote caller tried to delete an always-loaded core page; only the owner can remove pages from core.", docs: 'docs/guides/core-memory.md#owner-only', actor: 'user' },
@@ -239,6 +247,14 @@ export const CODES = {
lock_busy: { class: 'retryable', summary: "Another process holds the lock this command needs." },
maintenance_backpressure: { class: 'retryable', summary: "Managed maintenance stopped admitting requests because this writer's outstanding requests, reserved receipt bytes or permanent request ids would pass 80% of their limit; nothing more was submitted.", why: "Each page of a maintenance run publishes as its own request under the local CLI writer the user's own CLI writes share. Stopping at 80% leaves room for those writes: reserved receipt bytes free only when receipts compact, request ids never.", docs: 'docs/guides/write-refusals.md#maintenance_backpressure', fix: { argv: ['gbrain', 'sources', 'writer', 'status', '--source', '{source_id}', '--json'], consent: [], actor: 'agent', why: "Shows the pending requests holding this writer's capacity, read-only.", requires_exclusive: false }, exit: 12 },
maintenance_lock_busy: { class: 'retryable', summary: "A source-scoped dream cycle skipped its brain-wide phases because another cycle (usually autopilot maintenance) holds the shared gbrain-cycle lease; its source phases still ran.", why: 'Brain-wide phases (synthesize, patterns, embed, purge and the other mixed or global phases) must not run twice at once, so a cycle that cannot take gbrain-cycle runs only the phases its own source lease covers.', docs: 'docs/guides/cron-schedule.md#dream-beside-autopilot', suggestion: 'Nothing is lost: the holder runs those phases itself. To run one now, wait until the lease is released, then re-run `gbrain dream --phase <phase>` (LLM-backed phases spend; ask the user first).', fix: { argv: ['gbrain', 'status', '--section', 'locks', '--json'], consent: [], actor: 'agent', why: 'Shows who holds gbrain-cycle and when its lease expires, read-only.', requires_exclusive: false } },
+ merge_recommended: { class: 'caller', retryable: false, actor: 'user',
+ summary: "The content-repair model judged a held file and the page its frontmatter `slug:` names to be the same page, so gbrain recommends merging them instead of removing the slug line; nothing was written.",
+ why: "A `frontmatter_slug_conflict` hold whose two sides describe the same person, company or topic is a duplicate, and the deterministic repair (delete the `slug:` line) would mint a second page for it. gbrain does not merge pages by itself yet (a lossless merge needs a coordinated two-page write with both revisions, withdrawal and metadata preservation; it ships separately), so the lane records the recommendation on the hold as codes and slugs (`meta.content_repair`: the canonical slug that keeps the page), `gbrain sync status` renders a paragraph for a person, and nothing retries it until the file changes.",
+ docs: 'docs/guides/write-refusals.md#merge_recommended',
+ suggestion: 'Show the user the paragraph gbrain sources status <id> --json renders for the hold (the path, the canonical slug and the recommendation). After they agree, merge the unique sections of the duplicate into the canonical page, delete the duplicate file, commit, and run gbrain sync --source <id> --no-pull; the hold clears on that sync.',
+ fix: { argv: ['gbrain', 'sources', 'status', '{source_id}', '--json'], consent: [], actor: 'user', requires_exclusive: false,
+ why: 'Read-only: lists the held file with the canonical slug gbrain recommends and the rendered paragraph; merging two pages is the user\'s decision.',
+ verify: { argv: ['gbrain', 'sources', 'status', '{source_id}', '--json'] } } },
managed_sync_not_moving: { class: 'server', retryable: false, actor: 'host_admin',
summary: "A managed source has unfinished sync work and a live consumer on its owner host, but no committed `managed_sync_*` receipt and no head step advance for longer than `persistence.preparation_ceiling_ms`.",
why: "Process liveness is not data movement: `/health` ok, a live pid and `sync_running: true` all held while one deployment moved nothing for weeks. `sources status --json` carries `data_moving`, `not_moving_since` and `movement_state` per source (`parked` when no drain or full consumer is live, informational), doctor warns with this code and counts it against the score, `serve` prints one notice when a source flips, and `gbrain sources writer movement` judges a window after a restart and exits 1 with this code (`reason: movement_check`) when pending work does not move.",
diff --git a/src/core/fence-repair/repair-io.ts b/src/core/fence-repair/repair-io.ts
index 1393ddf0d7..c9ca9669a1 100644
--- a/src/core/fence-repair/repair-io.ts
+++ b/src/core/fence-repair/repair-io.ts
@@ -73,10 +73,11 @@ function inGit(root: string): boolean {
}
/**
- * This host's view of one source for fence repair; null when the source is gone or archived. `remote` (default
- * true, the fail-closed reading of an unknown caller) keeps local paths out of the owner refusal's text.
+ * This host's view of one source for fence repair (and, with `work`, the content repair that shares this loader);
+ * null when the source is gone or archived. `remote` (default true, the fail-closed reading of an unknown caller)
+ * keeps local paths out of the owner refusal's text.
*/
-export async function loadFenceSource(engine: BrainEngine, sourceId: string, opts: { remote?: boolean } = {}): Promise<FenceSource | null> {
+export async function loadFenceSource(engine: BrainEngine, sourceId: string, opts: { remote?: boolean; work?: string } = {}): Promise<FenceSource | null> {
const [row] = await engine.executeRaw<{ id: string; incarnation: string; local_path: string | null }>(
'SELECT id, incarnation::text AS incarnation, local_path FROM sources WHERE id=$1 AND archived IS NOT TRUE', [sourceId]);
if (!row) return null;
@@ -90,7 +91,7 @@ export async function loadFenceSource(engine: BrainEngine, sourceId: string, opt
if (binding) {
const hostId = localHostId();
const checked = checkOwner(binding, row.incarnation, hostId);
- if (checked.reason) owner = ownerRefusal({ sourceId, reason: checked.reason, binding, incarnation: row.incarnation, hostId, remote: opts.remote !== false, work: 'fence repair' });
+ if (checked.reason) owner = ownerRefusal({ sourceId, reason: checked.reason, binding, incarnation: row.incarnation, hostId, remote: opts.remote !== false, work: opts.work ?? 'fence repair' });
else root = join(checked.binding.local_path, checked.binding.relative_path);
}
} else {
@@ -274,7 +275,7 @@ export async function writeFenceRepair(ctx: OperationContext, src: FenceSource,
}
if (target.hold) await clearGitHold(engine, { sourceId: src.id, incarnation: src.incarnation, path: target.path!, observedAt: new Date().toISOString() });
await clearCensus();
- const commitStep = inGit(root) ? legacyCommitStep(root, target.path!, receipt.classes) : null;
+ const commitStep = inGit(root) ? legacyCommitStep(root, target.path!, receipt.classes, receipt.tier) : null;
if (commitStep) await recordUncommittedFenceRepair(engine, { source_id: src.id, incarnation: src.incarnation, path: target.path!, root, repaired_at: new Date().toISOString(),
backup, commit_step: commitStep, receipt });
return { ok: true, after_sha256: receipt.after_sha256, detail: { mode: 'legacy', path: target.path, backup, imported: imported.status, fence_repair: receipt,
diff --git a/src/core/fence-repair/uncommitted.ts b/src/core/fence-repair/uncommitted.ts
index 252d800954..a3111686a8 100644
--- a/src/core/fence-repair/uncommitted.ts
+++ b/src/core/fence-repair/uncommitted.ts
@@ -37,9 +37,9 @@ export interface UncommittedFenceRepair {
const fingerprint = (sourceId: string, incarnation: string, path: string) => `${sourceId}:${incarnation}:${path}`;
-/** The commit step printed for a legacy repair: stage only this path and commit it with the fence-repair subject. */
-export function legacyCommitStep(root: string, path: string, classes: readonly string[]): string {
- return `git -C ${shellQuote([root])} add -- ${shellQuote([path])} && git -C ${shellQuote([root])} commit -m ${shellQuote([fenceRepairCommitSubject(path, classes)])} -- ${shellQuote([path])}`;
+/** The commit step printed for a legacy repair: stage only this path and commit it with the fence-repair subject and the `gbrain-repair:` trailer the Git effect would write. */
+export function legacyCommitStep(root: string, path: string, classes: readonly string[], tier: FenceRepairReceipt['tier'] = 'deterministic'): string {
+ return `git -C ${shellQuote([root])} add -- ${shellQuote([path])} && git -C ${shellQuote([root])} commit -m ${shellQuote([fenceRepairCommitSubject(path, classes)])} -m ${shellQuote([`gbrain-repair: invalid_fence ${tier} high`])} -- ${shellQuote([path])}`;
}
export async function recordUncommittedFenceRepair(engine: Exec, notice: UncommittedFenceRepair): Promise<void> {
diff --git a/src/core/persistence/effect-git.ts b/src/core/persistence/effect-git.ts
index b33aa9e1f2..ba75ead993 100644
--- a/src/core/persistence/effect-git.ts
+++ b/src/core/persistence/effect-git.ts
@@ -136,7 +136,9 @@ const commitText = (text: string) => text.replace(/[\u0000-\u001f\u007f]/g, '');
* `notes` (keyed by requested path) carry a preparer's commit metadata: a
* path that commits alone with a note uses its subject; a group keeps the
* generic subject and lists the noted paths' lines in the body, in path
- * order. Control characters are stripped from both.
+ * order. A note's `gbrain-repair:` trailer goes in the message's last
+ * paragraph (one line per noted path), where Git reads trailers. Control
+ * characters are stripped from all three.
*/
export async function commitGitTargets(root: string, relativePaths: string[], signal?: AbortSignal,
notes?: ReadonlyMap<string, GitCommitNote>): Promise<Map<string, GitOutcome | OperationError>> {
@@ -192,7 +194,8 @@ export async function commitGitTargets(root: string, relativePaths: string[], si
const subject = commitPaths.length > 1 ? `gbrain: persist ${commitPaths.length} canonical memory updates`
: commitText(noted.get(commitPaths[0]!)?.subject ?? '') || 'gbrain: persist canonical memory update';
const body = commitPaths.length > 1 ? [...new Set([...noted.keys()].sort().map(path => commitText(noted.get(path)!.line)).filter(Boolean))] : [];
- const result = await git(root, hooks, ['commit', '--only', '-m', subject, ...(body.length ? ['-m', body.join('\n')] : []), '--', ...commitPaths], signal);
+ const trailers = [...new Set([...noted.keys()].sort().map(path => commitText(noted.get(path)!.trailer ?? '')).filter(Boolean))];
+ const result = await git(root, hooks, ['commit', '--only', '-m', subject, ...(body.length ? ['-m', body.join('\n')] : []), ...(trailers.length ? ['-m', trailers.join('\n')] : []), '--', ...commitPaths], signal);
const outcome = result.code === 0 ? { git: 'committed' } : gitFailure('Cannot commit the canonical Git target.',
`git commit failed for ${commitPaths.length} file(s); a missing Git identity (user.name, user.email) in that checkout is one cause to check.`);
for (const c of changed) results.set(c.requested, outcome);
diff --git a/src/core/persistence/effect-journal.ts b/src/core/persistence/effect-journal.ts
index a5a3bcc312..cef591b6b1 100644
--- a/src/core/persistence/effect-journal.ts
+++ b/src/core/persistence/effect-journal.ts
@@ -43,7 +43,7 @@ export async function queuePublicationEffects(tx: BrainEngine, row: EffectReques
const commit = prepared.file.commit;
queue('git', { relative_path: relative(binding.local_path, prepared.file.path).split(sep).join('/'),
expected_hash: prepared.file.content === null ? null : sha256(prepared.file.content),
- ...(commit ? { commit_subject: commit.subject, commit_line: commit.line } : {}) });
+ ...(commit ? { commit_subject: commit.subject, commit_line: commit.line, ...(commit.trailer ? { commit_trailer: commit.trailer } : {}) } : {}) });
if (outcome.persistence && typeof outcome.persistence === 'object') Object.assign(outcome.persistence, { git_state: 'queued' });
}
if (snapshot && !snapshot.page.deleted_at) {
diff --git a/src/core/persistence/effect-model.ts b/src/core/persistence/effect-model.ts
index 29d454ca63..e771ce6fc8 100644
--- a/src/core/persistence/effect-model.ts
+++ b/src/core/persistence/effect-model.ts
@@ -1,6 +1,7 @@
import type { WriteRequest } from './model.ts';
import type { WithdrawalTarget } from '../facts/withdrawal-discovery.ts';
-import { fenceRepairCommitSubject } from '../fence-repair/receipt.ts';
+import { fenceRepairCommitSubject, type FenceRepairReceipt } from '../fence-repair/receipt.ts';
+import { contentRepairCommitSubject, contentRepairTrailer, type ContentRepairReceipt } from '../content-repair/receipt.ts';
export type EffectKind = 'git' | 'embedding' | 'withdrawal-mirror' | 'facts-backstop' | 'links';
/** Brain config key gating the remote mention-links effect; unset is on, false/0/no/off turns it off. */
@@ -11,13 +12,21 @@ export const REMOTE_MENTION_LINK_SOURCE = 'mcp-remote-mention';
export const REMOTE_MENTION_OPERATIONS: readonly string[] = ['put_page', 'capture', 'edit_page'];
/**
* Commit metadata a trusted local preparer attaches to a page file target
- * (a fence repair): the subject when the file commits alone, and its body
- * line when it commits with other files. Location only, never page text.
+ * (a fence or content repair): the subject when the file commits alone, its
+ * body line when it commits with other files, and the `gbrain-repair:` Git
+ * trailer (`<hold_code> <tier> <confidence>`) the Git effect prints after a
+ * blank line, so `git log --format=%(trailers)` finds every repair commit.
+ * Location only, never page text.
*/
-export interface GitCommitNote { subject: string; line: string }
-/** A fence-repaired file's note: `fenceRepairCommitSubject` alone, `<path> (<classes>)` as its line in a batched commit. */
-export function fenceRepairCommit(path: string, classes: readonly string[]): GitCommitNote {
- return { subject: fenceRepairCommitSubject(path, classes), line: `${path.replace(/[\u0000-\u001f\u007f]/g, '?')} (${classes.join(', ')})` };
+export interface GitCommitNote { subject: string; line: string; trailer?: string }
+const safe = (path: string) => path.replace(/[\u0000-\u001f\u007f]/g, '?');
+/** A fence-repaired file's note: `fenceRepairCommitSubject` alone, `<path> (<classes>)` as its line in a batched commit, trailer `gbrain-repair: invalid_fence <tier> high`. */
+export function fenceRepairCommit(path: string, classes: readonly string[], tier: FenceRepairReceipt['tier'] = 'deterministic'): GitCommitNote {
+ return { subject: fenceRepairCommitSubject(path, classes), line: `${safe(path)} (${classes.join(', ')})`, trailer: `gbrain-repair: invalid_fence ${tier} high` };
+}
+/** #6377 a slug-conflict repair's note: `gbrain: repair frontmatter slug in <path>`, `<path> (frontmatter_slug_conflict)` in a batch, trailer from the receipt's tier and confidence. */
+export function contentRepairCommit(path: string, receipt: Pick<ContentRepairReceipt, 'tier' | 'confidence'>): GitCommitNote {
+ return { subject: contentRepairCommitSubject(path), line: `${safe(path)} (frontmatter_slug_conflict)`, trailer: contentRepairTrailer(receipt) };
}
export interface ParkedTarget { slug?: string; error_code: string }
export interface SkippedTarget { slug: string; reason: 'metafile' | 'file_database_drift' }
@@ -51,6 +60,7 @@ export interface PersistenceEffect {
/** A single-file Git target's GitCommitNote, when its preparer gave one. */
commit_subject?: string;
commit_line?: string;
+ commit_trailer?: string;
/** Consecutive execution failures of the current Git or withdrawal target. */
target_failures?: number;
/** The target `target_failures` belongs to; a different target starts from zero. */
diff --git a/src/core/persistence/effects.ts b/src/core/persistence/effects.ts
index eafd886bbe..3bd3dd938f 100644
--- a/src/core/persistence/effects.ts
+++ b/src/core/persistence/effects.ts
@@ -210,8 +210,8 @@ async function singleFileGitTarget(engine: BrainEngine, effect: PersistenceEffec
/** The commit metadata a single-file Git effect's preparer recorded, if any. */
function gitCommitNote(effect: PersistenceEffect): GitCommitNote | undefined {
- const { commit_subject: subject, commit_line: line } = effect.data;
- return typeof subject === 'string' && typeof line === 'string' ? { subject, line } : undefined;
+ const { commit_subject: subject, commit_line: line, commit_trailer: trailer } = effect.data;
+ return typeof subject === 'string' && typeof line === 'string' ? { subject, line, ...(typeof trailer === 'string' ? { trailer } : {}) } : undefined;
}
async function gitPage(engine: BrainEngine, effect: PersistenceEffect, binding: WorktreeBinding | null, opts: EffectWorkerOptions,
diff --git a/src/core/persistence/file-repair.ts b/src/core/persistence/file-repair.ts
index 25591dbe1f..b306ce9359 100644
--- a/src/core/persistence/file-repair.ts
+++ b/src/core/persistence/file-repair.ts
@@ -23,8 +23,14 @@
* the intent (`fenceRepair`): the preparer refuses a malformed receipt or one
* whose before/after sha256 are not the previewed and the written bytes, the
* receipt rides the publication outcome as `fence_repair`, the file's Git
- * commit takes `fenceRepairCommitSubject`, and every refusal routes to
- * `gbrain repair fences` instead of `gbrain repair frontmatter`.
+ * commit takes `fenceRepairCommitSubject` with the `gbrain-repair:` trailer,
+ * and every refusal routes to `gbrain repair fences` instead of
+ * `gbrain repair frontmatter`. #6377: a slug-conflict repair (`gbrain repair
+ * content`, the `slug-conflicts` kind) rides the same way with its
+ * `ContentRepairReceipt` (`contentRepair`), outcome field `content_repair`,
+ * subject `gbrain: repair frontmatter slug in <path>` and trailer
+ * `gbrain-repair: frontmatter_slug_conflict <tier> <confidence>`; its
+ * refusals route to `gbrain repair content`.
*
* Trusted local CLI only: admission refuses remote and delegated callers, the
* `put_page` reserved-field gate refuses the kind from MCP, and the preparer
@@ -51,6 +57,7 @@ import { sealPageTextProjection } from '../page-state/projections.ts';
import { currentSubmissionAuthority } from '../minions/submission-authority.ts';
import { VERSION } from '../../version.ts';
import { parseFenceRepairReceipt, type FenceRepairReceipt } from '../fence-repair/receipt.ts';
+import { parseContentRepairReceipt, type ContentRepairReceipt } from '../content-repair/receipt.ts';
import { prepareCanonicalProjections } from './canonical-projections.ts';
import { digest, sha256 } from './digest.ts';
import { currentVerifiedLocalWriter, localHostId } from './identity.ts';
@@ -63,7 +70,7 @@ import { screenSyncImport } from './sync-prepare.ts';
import type { SyncRename } from './sync-discovery.ts';
import type { PreparedContentImport } from './prepared-import.ts';
import type { PreparedMutation } from './coordinator.ts';
-import { fenceRepairCommit } from './effect-model.ts';
+import { contentRepairCommit, fenceRepairCommit } from './effect-model.ts';
import type { WriteRequest } from './model.ts';
export interface ManagedFileRepairIntent extends Record<string, unknown> {
@@ -86,15 +93,18 @@ export interface ManagedFileRepairIntent extends Record<string, unknown> {
noEmbed: boolean;
/** A fence repair's receipt (location and hashes only). */
fenceRepair?: FenceRepairReceipt;
+ /** #6377 a slug-conflict repair's receipt (codes and hashes only). */
+ contentRepair?: ContentRepairReceipt;
}
-/** The repair command a refusal names (D6 router): a fence repair's, or the frontmatter repair's. */
-export type FileRepairKind = 'frontmatter' | 'fences';
+/** The repair command a refusal names (D6 router): a fence repair's, the content repair's, or the frontmatter repair's. */
+export type FileRepairKind = 'frontmatter' | 'fences' | 'content';
+const WORK: Record<FileRepairKind, string> = { frontmatter: 'frontmatter', fences: 'fence', content: 'slug-conflict' };
const ownerStatusFix = (sourceId: string): Action => readFix(`Shows source ${sourceId}'s canonical owner and its state, read-only.`,
{ argv: ['gbrain', 'sources', 'writer', 'status', '--source', sourceId, '--json'] });
const previewFix = (sourceId: string, kind: FileRepairKind): Action => ({ argv: ['gbrain', 'repair', kind, '--source', sourceId], consent: [], actor: 'agent',
- requires_exclusive: false, why: `Previews the ${kind === 'fences' ? 'fence' : 'frontmatter'} repair of source ${sourceId} again from the files as they are now; nothing is written.` });
+ requires_exclusive: false, why: `Previews the ${WORK[kind]} repair of source ${sourceId} again from the files as they are now; nothing is written.` });
function changedSincePreview(sourceId: string, path: string, why: string, kind: FileRepairKind) {
return opError('changed_since_preview', `${path} changed since its repair was previewed: ${why}.`,
@@ -120,6 +130,24 @@ function checkedFenceRepair(input: { fenceRepair?: unknown; beforeHash: string;
return receipt;
}
+/** #6377: the slug-conflict receipt of a repair request, checked the same way; undefined when the request carries none. */
+function checkedContentRepair(input: { contentRepair?: unknown; beforeHash: string; content: string; path: string }, sourceId: string): ContentRepairReceipt | undefined {
+ if (input.contentRepair === undefined) return undefined;
+ const refuse = (why: string): never => { throw opError('invalid_params', `The content repair receipt for ${input.path} ${why}, so nothing was written.`,
+ `gbrain repair content builds this receipt from the bytes it previewed and writes; this one does not describe them. Preview again with gbrain repair content --source ${sourceId} and apply its new plan; if the apply refuses the same way, tell the user and include gbrain doctor --json.`,
+ { fix: previewFix(sourceId, 'content') }); };
+ const receipt = parseContentRepairReceipt(input.contentRepair);
+ if (!receipt) return refuse('is malformed');
+ if (receipt.before_sha256 !== input.beforeHash) return refuse('does not name the previewed file bytes');
+ if (receipt.after_sha256 !== sha256(Buffer.from(input.content, 'utf8'))) return refuse('does not name the repaired file bytes');
+ return receipt;
+}
+
+/** Which repair command a request belongs to, from the receipt it carries. */
+function repairKindOf(input: { fenceRepair?: unknown; contentRepair?: unknown }): FileRepairKind {
+ return input.fenceRepair !== undefined ? 'fences' : input.contentRepair !== undefined ? 'content' : 'frontmatter';
+}
+
/**
* The absolute target of a source-relative repair path. Refuses an absolute
* or climbing path, a target outside the root, and any symlink on the way
@@ -223,7 +251,7 @@ export async function managedRepairRoot(engine: BrainEngine, sourceId: string, k
const binding = await getWorktreeBinding(engine, sourceId);
const hostId = localHostId();
const owner = checkOwner(binding, source?.incarnation ?? '', hostId);
- if (owner.reason) throw ownerUnavailableError({ sourceId, reason: owner.reason, binding, incarnation: source?.incarnation ?? '', hostId, remote: opts.remote !== false, work: `the ${kind} repair` });
+ if (owner.reason) throw ownerUnavailableError({ sourceId, reason: owner.reason, binding, incarnation: source?.incarnation ?? '', hostId, remote: opts.remote !== false, work: `the ${WORK[kind]} repair` });
return { root: join(owner.binding.local_path, owner.binding.relative_path), ownerEpoch: String(owner.binding.owner_epoch), incarnation: owner.binding.source_incarnation };
}
@@ -240,12 +268,15 @@ export interface ManagedFileRepairInput {
beforeHash: string; resultDigest: string; expected_revision?: string; renameFrom?: SyncRename; noEmbed: boolean;
/** Set by `gbrain repair fences`: the write's receipt, and its refusals route there. */
fenceRepair?: FenceRepairReceipt;
+ /** #6377 set by the `slug-conflicts` kind: the write's receipt, and its refusals route to `gbrain repair content`. */
+ contentRepair?: ContentRepairReceipt;
}
export async function submitManagedFileRepair(ctx: OperationContext, input: ManagedFileRepairInput): Promise<Record<string, unknown>> {
assertTrustedRepairCaller(ctx);
- const kind: FileRepairKind = input.fenceRepair !== undefined ? 'fences' : 'frontmatter';
+ const kind = repairKindOf(input);
checkedFenceRepair(input, input.sourceId);
+ checkedContentRepair(input, input.sourceId);
const { root, ownerEpoch, incarnation } = await managedRepairRoot(ctx.engine, input.sourceId, kind, { remote: false });
const target = confinedRepairTarget(root, input.path, input.sourceId, kind);
if (fileSha256(target) !== input.beforeHash) throw changedSincePreview(input.sourceId, input.path, 'the file bytes differ from the previewed hash', kind);
@@ -261,7 +292,7 @@ export async function submitManagedFileRepair(ctx: OperationContext, input: Mana
export async function prepareManagedFileRepairMutation(engine: BrainEngine, row: WriteRequest, _config: GBrainConfig): Promise<PreparedMutation> {
const p = row.intent as ManagedFileRepairIntent | null;
- const kind: FileRepairKind = p?.fenceRepair !== undefined ? 'fences' : 'frontmatter';
+ const kind = repairKindOf(p ?? {});
if (row.authority.remote || row.principal_kind !== 'local_cli') throw trustedCliRequired('A managed file repair requires a trusted local CLI writer.');
if (!p || p.kind !== 'managed_file_repair' || typeof p.content !== 'string' || typeof p.path !== 'string' || typeof p.sourcePath !== 'string'
|| typeof p.beforeHash !== 'string' || typeof p.resultDigest !== 'string') {
@@ -270,6 +301,7 @@ export async function prepareManagedFileRepairMutation(engine: BrainEngine, row:
{ fix: previewFix(row.source_id, kind) });
}
const fenceRepair = checkedFenceRepair(p, row.source_id);
+ const contentRepair = checkedContentRepair(p, row.source_id);
const binding = await getWorktreeBinding(engine, row.source_id);
if (!row.worktree_id || !binding?.local_path || String(binding.owner_epoch) !== p.ownerEpoch) throw opError('owner_unavailable', 'A managed file repair requires its accepted canonical owner.',
`Source ${row.source_id}'s canonical owner changed or went away after repair request ${row.request_id} was accepted, so it published nothing. Check the owner, then preview the repair again on the host that owns the source.`,
@@ -313,7 +345,8 @@ export async function prepareManagedFileRepairMutation(engine: BrainEngine, row:
const importOptions = { ...source, noEmbed: true, remote: false, preserveGateMarkers: true, activePack: screenConfig.activePack, filename: basename(p.sourcePath).replace(/\.mdx?$/i, ''), sourcePath: p.sourcePath, allowEmptyOverwrite: true };
return { observedRevision: snapshot?.revision ?? null, noop: ready.noop && !fileChanges && !moved, contentUnchanged: ready.noop && !fileChanges && !moved,
deferEmbedding: p.noEmbed, ...(moved ? { additionalPageKeys: [{ sourceId: row.source_id, slug: moved.slug }] } : {}),
- ...(fileChanges ? { file: { root, path: target, content: bytes, expectedBeforeHash: p.beforeHash, ...(fenceRepair ? { commit: fenceRepairCommit(p.path, fenceRepair.classes) } : {}) } } : {}),
+ ...(fileChanges ? { file: { root, path: target, content: bytes, expectedBeforeHash: p.beforeHash,
+ ...(fenceRepair ? { commit: fenceRepairCommit(p.path, fenceRepair.classes, fenceRepair.tier) } : contentRepair ? { commit: contentRepairCommit(p.path, contentRepair) } : {}) } } : {}),
validate: async tx => {
const current = await getWorktreeBinding(tx, row.source_id);
if (!current || current.worktree_id !== row.worktree_id || String(current.owner_epoch) !== p.ownerEpoch) throw opError('owner_unavailable', 'The repair owner changed.',
@@ -343,6 +376,6 @@ export async function prepareManagedFileRepairMutation(engine: BrainEngine, row:
raw_sha256: sha256(importContent), gbrain_version: VERSION });
return { status: moved ? 'renamed' : applied.noop ? 'skipped' : snapshot ? 'updated' : 'created', slug: row.slug, source_id: row.source_id,
chunks: applied.result.chunks, imported_file: true, file_repaired: fileChanges, hold_cleared: holdCleared, ...(moved ? { renamed_from: moved.slug } : {}),
- ...(fenceRepair ? { fence_repair: fenceRepair } : {}) };
+ ...(fenceRepair ? { fence_repair: fenceRepair } : {}), ...(contentRepair ? { content_repair: contentRepair } : {}) };
} };
}
diff --git a/src/core/persistence/page-prepare.ts b/src/core/persistence/page-prepare.ts
index e437cd8935..fffe006427 100644
--- a/src/core/persistence/page-prepare.ts
+++ b/src/core/persistence/page-prepare.ts
@@ -471,7 +471,7 @@ export async function preparePageMutation(unbounded: BrainEngine, row: WriteRequ
const shownFixes = (ready.result.fences_normalized ?? []).filter(fix => !row.authority.remote || fix.fence !== 'takes');
const fencesNormalized = shownFixes.length ? { fences_normalized: pageFencesNormalized({ sourceId: row.source_id, slug: row.slug, fixes: shownFixes,
writer: row.principal_kind, path: snapshot?.page.source_path ?? null, remote: row.authority.remote }) } : {};
- const file = target && fenceRepair ? { ...target, commit: fenceRepairCommit(relative(target.root, target.path).split(sep).join('/'), fenceRepair.classes) } : target;
+ const file = target && fenceRepair ? { ...target, commit: fenceRepairCommit(relative(target.root, target.path).split(sep).join('/'), fenceRepair.classes, fenceRepair.tier) } : target;
enterClaimStep(clock, 'publication_mode', undefined, 'db');
const [mintMode, databaseOnly] = await pipelined(together, [
async () => file && !snapshot?.page.source_path ? scannerSlugRootMode(engine, row.source_id, file.root) : undefined,
diff --git a/src/core/persistence/preview-approval.ts b/src/core/persistence/preview-approval.ts
index ac76124b95..409b130c48 100644
--- a/src/core/persistence/preview-approval.ts
+++ b/src/core/persistence/preview-approval.ts
@@ -40,7 +40,7 @@ export const PREVIEW_APPROVAL_OP = 'repair-approval';
/** The default `purgeStaleCheckpoints` TTL; an older approved set may already be gone. */
export const APPROVAL_MAX_AGE_DAYS = 7;
-export type PreviewApprovalCommand = 'authorize-legacy' | 'jobs-cancel' | 'stale-atoms' | 'extractor-facts' | 'conversation-labels' | 'captured-facts' | 'loop-facts' | 'ontology-facts' | 'failed-writes' | 'frontmatter' | 'fences';
+export type PreviewApprovalCommand = 'authorize-legacy' | 'jobs-cancel' | 'stale-atoms' | 'extractor-facts' | 'conversation-labels' | 'captured-facts' | 'loop-facts' | 'ontology-facts' | 'failed-writes' | 'frontmatter' | 'fences' | 'slug-conflicts';
export interface ApprovedSetKey {
command: PreviewApprovalCommand;
diff --git a/src/core/persistence/sync-fault-class.ts b/src/core/persistence/sync-fault-class.ts
index b8cf4ec55c..07d8b6493b 100644
--- a/src/core/persistence/sync-fault-class.ts
+++ b/src/core/persistence/sync-fault-class.ts
@@ -17,6 +17,13 @@
* `gbrain sync status --json`, `gbrain sync unblock` and the drain summary all
* read this table; `docs/guides/sync-unblock-runbook.md` renders it, and
* `test/sync-runbook-table.test.ts` pins the two together.
+ *
+ * #6377: a `frontmatter_slug_conflict` hold the content-repair lane judged
+ * (`meta.content_repair`) is classified from that verdict: a recommended
+ * merge (`merge_recommended`) or an undecidable pair
+ * (`content_repair_needs_human`) is `needs_human` with a paragraph rendered
+ * from the hold's codes and slugs (`contentRepairHumanReason`), never from
+ * model prose; the table row stays the lane's default for every other state.
*/
export type SyncFaultClass = 'page' | 'connection' | 'systemic';
export type SyncSafeAction = 'retry' | 'retry_when_clean' | 'repair' | 'reconcile' | 'upgrade' | 'none';
@@ -75,15 +82,52 @@ export const SYNC_FAULT_TABLE: ReadonlyArray<SyncFaultRule> = [
const BY_CODE = new Map(SYNC_FAULT_TABLE.map(rule => [rule.code, rule]));
+/** #6377: a slug-conflict hold's recorded verdict plus where it is (codes and slugs only). */
+export interface ContentRepairHoldInput {
+ action: 'remove_slug' | 'merge_into' | 'needs_human' | 'pending';
+ reason: string;
+ canonical?: string;
+ named?: string;
+ type?: string;
+ path: string;
+ slug: string | null;
+}
+
+/**
+ * The paragraph a person reads for a judged slug-conflict hold, or undefined when the verdict needs no person
+ * (`remove_slug` is applied by the lane; `pending` waits on the model tier). Names the path and the slugs; never
+ * the model's own words.
+ */
+export function contentRepairHumanReason(input: ContentRepairHoldInput): string | undefined {
+ const other = input.named ?? input.canonical;
+ const kind = input.type ? `the same ${input.type}` : 'the same thing';
+ if (input.action === 'merge_into' && input.canonical) {
+ if (input.slug && input.canonical === input.slug && other && other !== input.slug) {
+ return `This file and page \`${other}\` describe ${kind}; gbrain recommends keeping \`${input.path}\` (slug \`${input.canonical}\`), merging the unique sections of page \`${other}\` into it and deleting that page's file, then committing; `
+ + 'the hold clears on the next maintenance run after that file is gone. gbrain does not merge pages by itself yet.';
+ }
+ return `This file and page \`${input.canonical}\` describe ${kind}; gbrain recommends merging the unique sections of \`${input.path}\` into \`${input.canonical}\` and deleting \`${input.path}\`, then committing; `
+ + 'the hold clears on the next sync after the file is removed. gbrain does not merge pages by itself yet.';
+ }
+ if (input.action === 'needs_human') {
+ return `gbrain could not decide whether \`${input.path}\`${other ? ` and page \`${other}\`` : ' and the page its slug: line names'} are the same page; decide which keeps the slug: `
+ + `remove the slug: line of \`${input.path}\` if they differ, or merge them by hand and delete the duplicate, then commit; the hold clears on the next sync.`;
+ }
+ return undefined;
+}
+
export interface SyncFaultVerdict { class: SyncFaultClass; safe_actions: SyncSafeAction[]; needs_human: boolean; human_reason?: string }
/**
* The verdict for one fault. `attempts` is a hold's re-hold count: a page held `HOLD_ATTEMPTS_NEEDS_HUMAN` times with the
* same code keeps moving under the sync, so its own safe action is exhausted and a person is named. `detail` is a receipt's
* `reason` (for example `pinned_git_worktree_conflict` under `source_changed`) or a drain stop's `cause`; it refines the code
- * when the table knows it. An unknown code is systemic and human: an agent must not guess at it.
+ * when the table knows it. `content_repair` is a slug-conflict hold's recorded verdict: a recommended merge or an
+ * undecidable pair names a person. An unknown code is systemic and human: an agent must not guess at it.
*/
-export function classifySyncFault(input: { code: string; detail?: string | null; attempts?: number | null; message?: string | null }): SyncFaultVerdict {
+export function classifySyncFault(input: { code: string; detail?: string | null; attempts?: number | null; message?: string | null; content_repair?: ContentRepairHoldInput | null }): SyncFaultVerdict {
+ const judged = input.content_repair && input.code === 'frontmatter_slug_conflict' ? contentRepairHumanReason(input.content_repair) : undefined;
+ if (judged) return { class: 'page', safe_actions: ['none'], needs_human: true, human_reason: judged };
const rule = (input.detail ? BY_CODE.get(input.detail) : undefined) ?? BY_CODE.get(input.code)
?? (/ECONN|ETIMEDOUT|EPIPE|connection.*closed|CONNECTION_ENDED/i.test(input.message ?? '') ? BY_CODE.get('connection_lost') : undefined);
if (!rule) return { class: 'systemic', safe_actions: ['none'], needs_human: true, human_reason: `Unknown code ${input.code}; run gbrain doctor --json and read gbrain errors ${input.code}.` };
diff --git a/src/core/persistence/sync-holds.ts b/src/core/persistence/sync-holds.ts
index e0d2c2b7ea..058f6f6300 100644
--- a/src/core/persistence/sync-holds.ts
+++ b/src/core/persistence/sync-holds.ts
@@ -23,7 +23,13 @@
* 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).
+ * depends on 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';
@@ -33,6 +39,7 @@ import { FENCE_REASONS, type FenceMessageLocation } from '../fence-repair/reason
import type { FenceReason, FenceTier, GateLetter } from '../fence-repair/types.ts';
import { FENCE_VERSION } from '../fence-repair/refusal.ts';
import { fenceHoldFix, fenceHoldLocation, fencePreviewArgv, readFenceAutoRepair, type FenceAutoRepair, type FenceHoldLocation } from '../fence-repair/hold-fix.ts';
+import { contentHoldDocs, contentHoldFix } from '../content-repair/hold-fix.ts';
import { STRUCTURED_WRITE_ADVICE, type FencesNormalized } from '../fence-repair/report.ts';
import type { SyncRename } from './sync-discovery.ts';
import { VERSION } from '../../version.ts';
@@ -97,6 +104,8 @@ export interface GitHoldMeta {
attempts?: number;
/** #6188: the last fence repair attempt (repair kind or maintenance phase) that left this hold in place; location and reason only. */
fence_repair?: FenceHoldRepairState;
+ /** #6377 `frontmatter_slug_conflict`: the content-repair lane's last verdict or attempt on this hold; codes and slugs only. */
+ content_repair?: ContentHoldRepairState;
/** #6278 `preparation_stalled`: the failed receipt's step, wait cause and attempt count. */
stall?: PreparationStallMeta;
/** #6278: the held entry is a deletion (the file is gone); discovery re-screens it on request or a gbrain change, not on its absence. */
@@ -113,6 +122,27 @@ export interface FenceHoldRepairState {
rows?: number[];
}
+/**
+ * #6377: what the content-repair lane last decided about a `frontmatter_slug_conflict` hold. `action` is the verdict
+ * (`remove_slug` recorded only when the edit could not be written; `merge_into` and `needs_human` wait for a person;
+ * `pending` when no verdict was reached: the model tier was off, unavailable, unpriced or over budget). `reason` is the
+ * code behind it (`merge_recommended`, `content_repair_needs_human`, `llm_unavailable`, `budget_exhausted`, ...).
+ * `canonical` and `named` are slugs; `next_attempt_after` null means nothing retries it until the file changes.
+ */
+export interface ContentHoldRepairState {
+ action: 'remove_slug' | 'merge_into' | 'needs_human' | 'pending';
+ reason: string;
+ /** `merge_into`: the slug that keeps the page. */
+ canonical?: string;
+ /** The slug the held file's `slug:` line resolved to (when a page has it). */
+ named?: string;
+ /** The named page's type, for the rendered paragraph. */
+ type?: string;
+ model?: string;
+ at: string;
+ next_attempt_after: string | null;
+}
+
export interface GitHoldRecord {
version: 1;
source_id: string;
@@ -149,6 +179,8 @@ export interface GitHoldItem {
line?: number;
/** #6188 `invalid_fence` (D16): reason, fence, section, rows, columns, section line, classes, planned tier, auto_retry and next_attempt_after. */
fence?: FenceHoldLocation;
+ /** #6377 `frontmatter_slug_conflict`: the content-repair lane's last verdict or attempt (codes and slugs). */
+ content_repair?: ContentHoldRepairState;
message: string;
slug: string | null;
/** True when a page exists and keeps its last good revision; false when the file's page is missing. */
@@ -215,7 +247,11 @@ export async function writeGitHold(tx: Exec, input: Omit<GitHoldRecord, 'version
const now = new Date().toISOString();
// #6340: a path held again with the same code counts an attempt, so a page that keeps moving can be named.
const attempts = existing && existing.code === input.code ? (existing.meta.attempts ?? 1) + 1 : 1;
- const record: GitHoldRecord = { version: 1, ...input, meta: { ...input.meta, attempts },
+ // #6188/#6377: a re-screen of the same bytes under the same code keeps the last repair verdict; a changed file drops it.
+ const sameBytes = existing && existing.code === input.code && existing.upstream_version === input.upstream_version;
+ const kept = sameBytes ? { ...(existing.meta.fence_repair && !input.meta.fence_repair ? { fence_repair: existing.meta.fence_repair } : {}),
+ ...(existing.meta.content_repair && !input.meta.content_repair ? { content_repair: existing.meta.content_repair } : {}) } : {};
+ const record: GitHoldRecord = { version: 1, ...input, meta: { ...kept, ...input.meta, attempts },
held_at: existing && existing.upstream_version === input.upstream_version && existing.code === input.code ? existing.held_at : now, updated_at: now };
await tx.executeRaw(`INSERT INTO op_checkpoints(op,fingerprint,completed_keys) VALUES($1,$2,$3::text::jsonb)
ON CONFLICT(op,fingerprint) DO UPDATE SET completed_keys=EXCLUDED.completed_keys,updated_at=now()`,
@@ -265,6 +301,18 @@ export async function recordFenceHoldRepair(engine: Exec, input: { sourceId: str
return rows.length === 1;
}
+/**
+ * #6377: records on a `frontmatter_slug_conflict` hold what the content-repair lane last decided, conditional on the
+ * bytes it judged (`upstreamVersion`, the hold's `upstream_version`): a hold re-written for changed bytes is left alone.
+ * Observation time and counts are untouched. False when the hold is gone, holds other bytes or has another code.
+ */
+export async function recordContentHoldRepair(engine: Exec, input: { sourceId: string; incarnation: string; path: string; upstreamVersion: string | null; state: ContentHoldRepairState }): Promise<boolean> {
+ const rows = await engine.executeRaw(`UPDATE op_checkpoints SET completed_keys=jsonb_set(completed_keys,'{0,meta,content_repair}',$3::text::jsonb),updated_at=now()
+ WHERE op=$1 AND fingerprint=$2 AND completed_keys->0->>'code'='frontmatter_slug_conflict' AND completed_keys->0->>'upstream_version' IS NOT DISTINCT FROM $4 RETURNING 1`,
+ [GIT_HOLD_OP, gitHoldFingerprint(input.sourceId, input.incarnation, input.path), JSON.stringify(input.state), input.upstreamVersion]);
+ return rows.length === 1;
+}
+
export async function readGitHold(engine: Exec, sourceId: string, incarnation: string, path: string): Promise<GitHoldRecord | null> {
return readRow(engine, sourceId, incarnation, path);
}
@@ -473,7 +521,7 @@ export function gitHoldFix(record: Pick<GitHoldRecord, 'source_id' | 'path' | 'c
case 'rename_held':
return repair(true, `The page that ${record.path} renames changed after the rename was recorded, so it was not moved; the preview proposes re-binding the rename to the current page for approval.`);
case 'frontmatter_slug_conflict':
- return repair(true, `The frontmatter slug of ${record.path} names another page; the preview proposes removing that line for approval.`);
+ return contentHoldFix(record);
default:
return record.meta.reason === 'needs_interpretation'
? repair(true, `Reading ${record.path} needs an interpretation (folded lines, a duplicate key or an unclosed list); the preview shows the exact proposal for approval.`)
@@ -481,9 +529,11 @@ export function gitHoldFix(record: Pick<GitHoldRecord, 'source_id' | 'path' | 'c
}
}
-export function gitHoldDocs(code: GitHoldCode, reason?: GitHoldReason): string {
+export function gitHoldDocs(code: GitHoldCode, reason?: GitHoldReason, meta?: Pick<GitHoldMeta, 'content_repair'>): string {
// #6188: fence reasons carry their own anchors (`#fence-<reason>`).
if (code === 'invalid_fence') return reason && reason in FENCE_REASONS ? FENCE_REASONS[reason as FenceReason].docs : 'docs/guides/write-refusals.md#invalid_fence';
+ // #6377: a judged slug conflict points at its verdict's anchor.
+ if (code === 'frontmatter_slug_conflict') return contentHoldDocs(meta?.content_repair);
if (code === 'preparation_stalled') return 'docs/guides/write-refusals.md#preparation_stalled';
if (code === 'worktree_dirty') return 'docs/guides/write-refusals.md#worktree_dirty';
return `docs/guides/write-refusals.md#${reason ? `${code}-${reason}` : code}`;
@@ -495,8 +545,9 @@ export function gitHoldItem(record: GitHoldRecord, auto?: FenceAutoRepair): GitH
return { path: record.path, code: record.code, ...(record.meta.reason ? { reason: record.meta.reason } : {}),
...(record.meta.key ? { key: record.meta.key } : {}), ...(record.meta.line !== undefined ? { line: record.meta.line } : {}),
...(fence ? { fence } : {}),
+ ...(record.code === 'frontmatter_slug_conflict' && record.meta.content_repair ? { content_repair: record.meta.content_repair } : {}),
message: record.message, slug: record.slug, stale: record.page_id !== null, held_since: record.held_at,
- fix: gitHoldFix(record, auto), docs: gitHoldDocs(record.code, record.meta.reason) };
+ fix: gitHoldFix(record, auto), docs: gitHoldDocs(record.code, record.meta.reason, record.meta) };
}
/** What the maintenance run does about fence holds, read only when some of these holds are fence holds. */
diff --git a/src/core/persistence/sync-status.ts b/src/core/persistence/sync-status.ts
index 9d0efe814d..bc4c6baf13 100644
--- a/src/core/persistence/sync-status.ts
+++ b/src/core/persistence/sync-status.ts
@@ -78,7 +78,7 @@ async function cursorHeader(engine: BrainEngine, sourceId: string): Promise<Curs
function holdStatus(record: GitHoldRecord): SyncStatusHold {
const attempts = record.meta.attempts ?? 1;
- const verdict = classifySyncFault({ code: record.code, attempts });
+ const verdict = classifySyncFault({ code: record.code, attempts, ...(record.meta.content_repair ? { content_repair: { ...record.meta.content_repair, path: record.path, slug: record.slug } } : {}) });
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) };
}
diff --git a/src/core/repair/core.ts b/src/core/repair/core.ts
index 1f40620f94..2bb7d3b5dc 100644
--- a/src/core/repair/core.ts
+++ b/src/core/repair/core.ts
@@ -25,7 +25,7 @@ import { lookupEmbeddingPrice, estimateCostFromChars } from '../embedding-pricin
import { shellQuote, type Action } from '../agent-output.ts';
import type { RepairKindSpec } from './registry.ts';
-export const REPAIR_KINDS = ['timeline', 'visibility', 'safe-chunks', 'contextual-mode', 'connector-checkpoints', 'request-indexes', 'connector-fences', 'take-supersession', 'orphan-bindings', 'embedding-effects', 'attribution-backfill', 'planner-stats', 'google-file-modes', 'stale-atoms', 'extractor-facts', 'conversation-labels', 'captured-facts', 'loop-facts', 'ontology-facts', 'orphan-children', 'failed-writes', 'frontmatter', 'fences', 'timeline-comments'] as const;
+export const REPAIR_KINDS = ['timeline', 'visibility', 'safe-chunks', 'contextual-mode', 'connector-checkpoints', 'request-indexes', 'connector-fences', 'take-supersession', 'orphan-bindings', 'embedding-effects', 'attribution-backfill', 'planner-stats', 'google-file-modes', 'stale-atoms', 'extractor-facts', 'conversation-labels', 'captured-facts', 'loop-facts', 'ontology-facts', 'orphan-children', 'failed-writes', 'frontmatter', 'fences', 'slug-conflicts', 'timeline-comments'] as const;
export type RepairKind = typeof REPAIR_KINDS[number];
export interface RepairScope { brain_id: string; source_ids: string[] }
diff --git a/src/core/repair/registry.ts b/src/core/repair/registry.ts
index 5d6ee20ca4..a1fe0b1704 100644
--- a/src/core/repair/registry.ts
+++ b/src/core/repair/registry.ts
@@ -58,6 +58,7 @@ import { frontmatterRepair } from './frontmatter.ts';
import { attributionBackfillRepair } from './attribution-backfill.ts';
import { plannerStatsRepair } from './planner-stats.ts';
import { fencesRepair } from './fences.ts';
+import { slugConflictsRepair } from './slug-conflicts.ts';
import { ERROR_CATALOGUE, catalogueError } from '../error-catalogue.ts';
import type { OperationError } from '../ops/contract.ts';
@@ -234,6 +235,16 @@ const SPECS: Record<RepairKind, Omit<RepairKindSpec, 'kind'>> = {
+ 'the commit step, database-only pages take a revision-bound write. --only/--skip <path> and --slug <slug> select; --no-llm keeps to the free '
+ 'tiers; --max-usd <n> lowers the model cap for this run. Preview-bound: --apply --expect <hash> applies exactly the previewed set.',
},
+ 'slug-conflicts': {
+ handler: slugConflictsRepair, embeds: 'effect', checks: [], preview_bound: true, spends: 'llm',
+ summary: 'Clear frontmatter_slug_conflict sync holds (#6377): a file whose frontmatter slug: names another page. A stray slug (no such page and no such '
+ + 'file, or a page of another type with no title word in common) loses the slug: line deterministically; anything else is judged by the content-repair '
+ + 'model (models.content_repair, else models.fence_repair, else the measured list) under the fences.repair caps and the same daily ledger as fences: '
+ + 'remove_slug applies the one-line edit, merge_into and needs_human write nothing and record the recommendation on the hold for a person '
+ + '(gbrain sync status shows the paragraph). Managed sources commit through the Git effect with a gbrain-repair: trailer, legacy sources back up and '
+ + 'print the commit step. --only/--skip <path> select; --no-llm keeps to the deterministic tier; --max-usd <n> lowers the model cap for this run. '
+ + 'Preview-bound: --apply --expect <hash> applies exactly the previewed set. gbrain repair content runs fences, then this kind.',
+ },
'planner-stats': {
handler: plannerStatsRepair, embeds: 'none', checks: ['planner_stats_stale'],
summary: 'ANALYZE the hot tables (pages, links, facts, takes, content_chunks, timeline_entries) whose planner statistics are stale (F4b), '
diff --git a/src/core/repair/slug-conflicts.ts b/src/core/repair/slug-conflicts.ts
new file mode 100644
index 0000000000..d319805092
--- /dev/null
+++ b/src/core/repair/slug-conflicts.ts
@@ -0,0 +1,636 @@
+/**
+ * `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 };
+}
+
+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) {
+ 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 --git a/test/content-repair-judgment.test.ts b/test/content-repair-judgment.test.ts
new file mode 100644
index 0000000000..e47219f344
--- /dev/null
+++ b/test/content-repair-judgment.test.ts
@@ -0,0 +1,104 @@
+/**
+ * #6377 Lane B3: the slug-conflict judgment prompt and parser (pure).
+ *
+ * Protects: the prompt is built from the two participants only (both
+ * frontmatter blocks, headings, the first 60 body lines and the later lines
+ * that mention the other slug; never other page text), with a null named
+ * side when no page has the slug; each allowed answer parses with its
+ * optional why; a canonical that is neither slug, prose, an empty answer, a
+ * refusal, a truncated stop and the bare HOLD word land in their failure
+ * classes; the participant builder keeps frontmatter as text and bounds the
+ * mention lines.
+ * Fails when: the prompt leaks text past the participants, an answer shape
+ * parses wrong, or a failure class drifts from the fence tier's vocabulary.
+ * Why new: the module is new in #6377.
+ */
+import { describe, expect, test } from 'bun:test';
+import type { ChatResult } from '../src/core/ai/gateway.ts';
+import { buildJudgmentPrompt, JUDGMENT_HEAD_LINES, JUDGMENT_MAX_MENTIONS, JUDGMENT_PROMPT_VERSION, judgmentParticipant, parseJudgmentAnswer, parseJudgmentText,
+ type JudgmentInput } from '../src/core/content-repair/judgment.ts';
+
+const SECRET = 'Sentinelbodyqx9 lives elsewhere';
+const result = (text: string, stopReason: ChatResult['stopReason'] = 'end'): ChatResult => ({ text, blocks: [], stopReason, usage: { input_tokens: 10, output_tokens: 5, cache_read_tokens: 0, cache_creation_tokens: 0 },
+ model: 'anthropic:claude-opus-5-5', providerId: 'anthropic' });
+
+const heldFile = `---\ntitle: Alice Example\ntype: person\nslug: people/alice-example\ntags: [founder, synthetic]\n---\n# Alice Example\n\nA synthetic founder.\n\n## Notes\n\nPossible duplicate of people/alice-example.\n${Array.from({ length: 70 }, (_, i) => `Line ${i} of filler.`).join('\n')}\nSee also people/alice-example for the older record.\n`;
+const namedPage = `---\ntitle: Alice Example\ntype: person\n---\nA synthetic founder, first met in 2024.\n\nThe newer file people/alice-example-2 repeats this page.\n`;
+
+function input(): JudgmentInput {
+ return {
+ held: judgmentParticipant({ path: 'people/alice-example-2.md', slug: 'people/alice-example-2', content: heldFile, otherSlug: 'people/alice-example' }),
+ named: judgmentParticipant({ path: 'people/alice-example.md', slug: 'people/alice-example', content: namedPage, otherSlug: 'people/alice-example-2', type: 'person' }),
+ reason: 'frontmatter_slug_conflict',
+ };
+}
+
+describe('judgmentParticipant', () => {
+ test('frontmatter as text, headings, the first 60 body lines and the later lines that mention the other slug', () => {
+ const held = input().held;
+ expect(held.frontmatter).toEqual({ title: 'Alice Example', type: 'person', slug: 'people/alice-example', tags: '[founder, synthetic]' });
+ expect(held.headings).toEqual(['Alice Example', 'Notes']);
+ expect(held.head_lines).toHaveLength(JUDGMENT_HEAD_LINES);
+ expect(held.head_lines[0]).toBe('# Alice Example');
+ expect(held.mentions).toEqual(['See also people/alice-example for the older record.']);
+ expect(held.type).toBe('person');
+ });
+
+ test('mentions are bounded and a leaf-word mention counts', () => {
+ const body = `---\ntitle: T\n---\n${Array.from({ length: 60 }, () => 'filler').join('\n')}\n${Array.from({ length: 50 }, (_, i) => `mention ${i} of acme-example`).join('\n')}\n`;
+ const p = judgmentParticipant({ path: 'notes/t.md', slug: 'notes/t', content: body, otherSlug: 'companies/acme-example' });
+ expect(p.mentions).toHaveLength(JUDGMENT_MAX_MENTIONS);
+ expect(judgmentParticipant({ path: 'notes/t.md', slug: 'notes/t', content: body, otherSlug: null }).mentions).toEqual([]);
+ });
+});
+
+describe('buildJudgmentPrompt', () => {
+ test('one system and one user message built from both participants only', () => {
+ const messages = buildJudgmentPrompt(input());
+ expect(messages.map(m => m.role)).toEqual(['system', 'user']);
+ const system = messages[0]!.content as string;
+ const user = messages[1]!.content as string;
+ expect(system).toContain('exactly one JSON object');
+ expect(system).toContain('people/alice-example-2 or people/alice-example');
+ expect(system).toMatch(/^8\. .*needs_human/m);
+ expect(user).toContain('## Held file');
+ expect(user).toContain('## Named page');
+ expect(user).toContain('path: people/alice-example-2.md');
+ expect(user).toContain('slug: people/alice-example');
+ expect(user).toContain('Possible duplicate of people/alice-example.');
+ expect(user).toContain('later lines mentioning the other slug:');
+ expect(user).toContain('The newer file people/alice-example-2 repeats this page.');
+ expect(user).not.toContain('Line 65 of filler.');
+ expect(user).not.toContain(SECRET);
+ expect(JUDGMENT_PROMPT_VERSION).toBe(1);
+ });
+
+ test('no named page: the user message says so and the system message offers only the held slug as canonical', () => {
+ const messages = buildJudgmentPrompt({ ...input(), named: null });
+ expect(messages[1]!.content as string).toContain('(no page has that slug)');
+ expect(messages[0]!.content as string).toContain('where <slug> is exactly people/alice-example-2\n');
+ });
+});
+
+describe('parseJudgmentAnswer', () => {
+ const slugs = { held: 'people/alice-example-2', named: 'people/alice-example' };
+ test('each allowed answer, with and without why, in a code fence too', () => {
+ expect(parseJudgmentAnswer(result('{"action":"remove_slug"}'), slugs)).toEqual({ ok: true, action: 'remove_slug' });
+ expect(parseJudgmentAnswer(result('{"action":"merge_into","canonical":"people/alice-example","why":"Same founder, same company."}'), slugs))
+ .toEqual({ ok: true, action: 'merge_into', canonical: 'people/alice-example', why: 'Same founder, same company.' });
+ expect(parseJudgmentAnswer(result('```json\n{"action":"needs_human"}\n```'), slugs)).toEqual({ ok: true, action: 'needs_human' });
+ expect(parseJudgmentText('{"action":"merge_into","canonical":"anything/goes"}')).toMatchObject({ ok: true, action: 'merge_into', canonical: 'anything/goes' });
+ });
+
+ test('failure classes: malformed, a canonical that is neither slug, prose, refusal, empty, truncated, declined', () => {
+ expect(parseJudgmentAnswer(result('{"action":"merge_into","canonical":"people/someone-else"}'), slugs)).toMatchObject({ ok: false, reason: 'llm_malformed' });
+ expect(parseJudgmentAnswer(result('{"action":"delete_page"}'), slugs)).toMatchObject({ ok: false, reason: 'llm_malformed' });
+ expect(parseJudgmentAnswer(result('The two pages look like the same person, so merge them.'), slugs)).toMatchObject({ ok: false, reason: 'llm_malformed' });
+ expect(parseJudgmentAnswer(result('I cannot help with that request.'), slugs)).toMatchObject({ ok: false, reason: 'llm_refused' });
+ expect(parseJudgmentAnswer(result('{"action":"remove_slug"}', 'refusal'), slugs)).toMatchObject({ ok: false, reason: 'llm_refused' });
+ expect(parseJudgmentAnswer(result('', 'end'), slugs)).toMatchObject({ ok: false, reason: 'llm_empty' });
+ expect(parseJudgmentAnswer(result('', 'length'), slugs)).toMatchObject({ ok: false, reason: 'llm_empty' });
+ expect(parseJudgmentAnswer(result('{"action":"merge_in', 'length'), slugs)).toMatchObject({ ok: false, reason: 'llm_truncated' });
+ expect(parseJudgmentAnswer(result('HOLD'), slugs)).toMatchObject({ ok: false, reason: 'llm_declined' });
+ });
+});
diff --git a/test/fixtures/goldens/exports/types.json b/test/fixtures/goldens/exports/types.json
index ab3c0459d5..faeb28590b 100644
--- a/test/fixtures/goldens/exports/types.json
+++ b/test/fixtures/goldens/exports/types.json
@@ -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_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\" | \"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_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",
"canonicalCode: string",
"cause?: unknown",
"code: ErrorCode",
diff --git a/test/persistence-sync-holds.test.ts b/test/persistence-sync-holds.test.ts
index 0b0f879c92..e84349b210 100644
--- a/test/persistence-sync-holds.test.ts
+++ b/test/persistence-sync-holds.test.ts
@@ -16,7 +16,7 @@ import { claimWorktree } from '../src/core/persistence/ownership.ts';
import { disposePersistenceConsumer } from '../src/core/persistence/service.ts';
import { performManagedSync } from '../src/core/persistence/sync-run.ts';
import { sha256 } from '../src/core/persistence/digest.ts';
-import { GIT_HOLD_OP, SYNC_IMPORT_PROVENANCE_OP, readGitSourceHolds, requestGitHoldRetry } from '../src/core/persistence/sync-holds.ts';
+import { GIT_HOLD_OP, SYNC_IMPORT_PROVENANCE_OP, gitHoldItem, readGitSourceHolds, recordContentHoldRepair, requestGitHoldRetry } from '../src/core/persistence/sync-holds.ts';
import { printSyncResult, type SyncOpts, type SyncResult } from '../src/commands/sync.ts';
import { gitHoldStatusLines, readGitHoldStatuses } from '../src/core/persistence/connector-status.ts';
import { isolatedPersistencePostgres } from './helpers/persistence-postgres.ts';
@@ -383,3 +383,39 @@ test('a hold an older reader wrote is re-screened by the next sync even though G
expect(hold!.meta.recovery_version).toBeGreaterThan(0);
expect(hold!.run_id).not.toBe(first.runId);
}), 180_000);
+
+test('#6377: a slug-conflict hold carries the content-repair verdict only for the bytes it judged, keeps it across a re-screen of the same bytes, and drops it when the file changes', () => each(async engine => {
+ const s = await source(engine, { 'notes/slug.md': '---\ntitle: Slug\nslug: notes/elsewhere\n---\nBody.\n', 'notes/ok.md': note('Ok') });
+ await s.sync();
+ const [hold] = await s.holds();
+ expect(hold).toMatchObject({ code: 'frontmatter_slug_conflict' });
+ expect(gitHoldItem(hold!).fix.argv).toEqual(['gbrain', 'repair', 'content', '--source', s.id, '--only', 'notes/slug.md']);
+ expect(gitHoldItem(hold!).fix.why).toContain('gbrain repairs this itself on the next maintenance run');
+ const state = { action: 'merge_into' as const, reason: 'merge_recommended', canonical: 'notes/elsewhere', named: 'notes/elsewhere', model: 'anthropic:claude-opus-5-5', at: new Date().toISOString(), next_attempt_after: null };
+ // Conditional on the judged bytes and the code: other bytes or another path record nothing.
+ expect(await recordContentHoldRepair(engine, { sourceId: s.id, incarnation: hold!.incarnation, path: 'notes/slug.md', upstreamVersion: sha256('other bytes'), state })).toBe(false);
+ expect(await recordContentHoldRepair(engine, { sourceId: s.id, incarnation: hold!.incarnation, path: 'notes/ok.md', upstreamVersion: null, state })).toBe(false);
+ expect(await recordContentHoldRepair(engine, { sourceId: s.id, incarnation: hold!.incarnation, path: 'notes/slug.md', upstreamVersion: hold!.upstream_version, state })).toBe(true);
+ const judged = (await s.holds())[0]!;
+ expect(judged.meta.content_repair).toEqual(state);
+ expect(judged.observed_at).toBe(hold!.observed_at);
+ const item = gitHoldItem(judged);
+ expect(item).toMatchObject({ content_repair: state, docs: 'docs/guides/write-refusals.md#merge_recommended' });
+ expect(item.fix).toMatchObject({ actor: 'user', argv: ['gbrain', 'repair', 'content', '--source', s.id, '--only', 'notes/slug.md'] });
+ expect(item.fix.user_message).toContain('`notes/elsewhere`');
+ expect(item.fix.user_message).toContain('gbrain does not merge pages by itself yet');
+ // A re-screen of the same bytes (slug conflicts always re-screen) keeps the verdict, with or without a retry request.
+ s.write('notes/ok.md', note('Ok 2')); commit(s.root, 'touch ok');
+ await s.sync();
+ expect((await s.holds())[0]!.meta.content_repair).toEqual(state);
+ await requestGitHoldRetry(engine, s.id, hold!.incarnation, ['notes/slug.md']);
+ await s.sync();
+ expect((await s.holds())[0]!.meta).toMatchObject({ content_repair: state, attempts: 3 });
+ // Changed bytes under the same code drop it: the verdict was about other content.
+ s.write('notes/slug.md', '---\ntitle: Slug\nslug: notes/elsewhere\n---\nBody, edited.\n'); commit(s.root, 'edit slug file');
+ await s.sync();
+ const changed = (await s.holds())[0]!;
+ expect(changed.code).toBe('frontmatter_slug_conflict');
+ expect(changed.meta.content_repair).toBeUndefined();
+ expect(gitHoldItem(changed).docs).toBe('docs/guides/write-refusals.md#frontmatter_slug_conflict');
+}), 180_000);
diff --git a/test/repair-slug-conflicts.test.ts b/test/repair-slug-conflicts.test.ts
new file mode 100644
index 0000000000..36f445a18f
--- /dev/null
+++ b/test/repair-slug-conflicts.test.ts
@@ -0,0 +1,308 @@
+/**
+ * #6377 Lane B (T3): `gbrain repair slug-conflicts` end to end on a managed
+ * source, with the judgment model behind the gateway's chat transport seam.
+ *
+ * Protects: the deterministic tier removes a stray `slug:` line when the
+ * named slug has no page and no file, or names a page of another type with
+ * no title word in common, through the coordinated file repair (file
+ * rewritten, imported, hold cleared, Git commit `gbrain: repair frontmatter
+ * slug in <path>` with the `gbrain-repair:` trailer, a content_repair
+ * receipt); a slug that resolves through an alias to the file's own page is
+ * `already_exempt`; a duplicate pair goes to the model tier at apply time
+ * while the preview calls no model; a stubbed `merge_into` writes nothing,
+ * records the verdict on the hold as codes and slugs, and `sync status`
+ * renders `needs_human` with a paragraph naming the canonical; a stubbed
+ * `remove_slug` applies through the same coordinated path; the memo makes a
+ * second run on unchanged bytes spend nothing while a transient provider
+ * error does not consume it; `changed_since_preview` and `--no-llm` write
+ * nothing; the daily ledger is the fence repair's, so a prior fences spend
+ * stops the run with `budget_exhausted` before any call; the location-only
+ * rule on holds, receipts, results and commits.
+ * Fails when: any of those paths regresses (a slug line removed for a likely
+ * duplicate, a second paid call for the same bytes, model prose on a hold, a
+ * write without the receipt or the trailer).
+ * Why new: the kind is new in #6377.
+ * Seams: __setChatTransportForTests (no provider call).
+ */
+import { afterAll, afterEach, beforeAll, expect, test } from 'bun:test';
+import { execFileSync } from 'node:child_process';
+import { randomUUID } from 'node:crypto';
+import { chmodSync, 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 { __setChatTransportForTests, configureGateway, resetGateway, type ChatOpts, type ChatResult } from '../src/core/ai/gateway.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 { localHostId } from '../src/core/persistence/identity.ts';
+import { runPersistenceEffects } from '../src/core/persistence/effects.ts';
+import { gitHoldItem, readGitSourceHolds } from '../src/core/persistence/sync-holds.ts';
+import { readSyncStatus } from '../src/core/persistence/sync-status.ts';
+import { dailyLedger, FENCE_REPAIR_LEDGER } from '../src/core/budget/daily-ledger.ts';
+import { resolveRepairScope, type RepairResult } from '../src/core/repair/core.ts';
+import { repairRunner, repairSpec } from '../src/core/repair/registry.ts';
+import { parseRepairArgs } from '../src/commands/repair.ts';
+import type { SlugConflictsPreviewDetails } from '../src/core/repair/slug-conflicts.ts';
+import { withEnv } from './helpers/with-env.ts';
+
+const home = mkdtempSync(join(tmpdir(), 'gbrain-repair-slug-conflicts-'));
+let engine: PGLiteEngine;
+const env = { GBRAIN_HOME: home, GBRAIN_SYNC_FAILURES_DIR: home, OPENAI_API_KEY: undefined, VOYAGE_API_KEY: undefined, ANTHROPIC_API_KEY: 'sk-test-not-used' };
+const git = (root: string, ...args: string[]) => execFileSync('git', ['-C', root, ...args], { encoding: 'utf8', stdio: ['ignore', 'pipe', 'pipe'] }).trim();
+const commit = (root: string, message = 'content') => { git(root, 'add', '-A'); git(root, 'commit', '-qm', message); return git(root, 'rev-parse', 'HEAD'); };
+const quiet = { info() {}, warn() {}, error() {} };
+
+// Body text that must never leave a file through a hold, a receipt, a result field or a commit message.
+const SECRET = 'Sentinelbodyzr9 moved to Lisbon';
+const WHY = 'Both describe the same synthetic founder.';
+const page = (title: string, type: string, body: string, extra = '') => `---\ntitle: ${title}\ntype: ${type}\n${extra}---\n${body}\n`;
+const answer = (text: string, stop: ChatResult['stopReason'] = 'end'): ChatResult => ({ text, blocks: [], stopReason: stop,
+ usage: { input_tokens: 400, output_tokens: 30, cache_read_tokens: 0, cache_creation_tokens: 0 }, model: 'anthropic:claude-opus-5-5', providerId: 'anthropic' });
+
+let calls: ChatOpts[] = [];
+function transport(reply: (opts: ChatOpts, n: number) => ChatResult | Error) {
+ calls = [];
+ __setChatTransportForTests(async opts => { calls.push(opts); const out = reply(opts, calls.length); if (out instanceof Error) throw out; return out; });
+}
+
+beforeAll(async () => { engine = new PGLiteEngine(); await engine.connect({}); await engine.initSchema(); }, 120_000);
+afterEach(() => { __setChatTransportForTests(null); });
+afterAll(async () => {
+ await withEnv(env, async () => { await disposePersistenceConsumer(engine); await engine.disconnect(); });
+ resetGateway(); rmSync(home, { recursive: true, force: true });
+});
+
+async function managed(files: Record<string, string>) {
+ const id = `slug-${randomUUID().replace(/-/g, '').slice(0, 16)}`, root = join(home, id);
+ mkdirSync(root, { recursive: true }); git(root, 'init', '-q');
+ git(root, 'config', 'user.name', 'Example'); git(root, 'config', 'user.email', '[email protected]');
+ const write = (path: string, content: string) => { mkdirSync(join(root, path, '..'), { recursive: true }); writeFileSync(join(root, path), content); };
+ for (const [path, content] of Object.entries(files)) write(path, content);
+ commit(root, 'fixture');
+ writeFileSync(join(root, '.git', 'hooks', 'post-commit'), '#!/bin/sh\n# gbrain brain-durability post-commit hook (v0.42.44+)\n'); chmodSync(join(root, '.git', 'hooks', 'post-commit'), 0o755);
+ 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');
+ const sync = () => performManagedSync(engine, { sourceId: id, noPull: true, noEmbed: true, noExtract: true });
+ const holds = async () => (await readGitSourceHolds(engine, { sourceIds: [id] }))[0]?.holds ?? [];
+ const run = async (opts: { apply?: boolean; expect?: string; only?: string[]; noLlm?: boolean; maxLlmUsd?: number } = {}) => {
+ const runner = await repairRunner(engine, { apply: opts.apply === true, noEmbed: true, logger: quiet });
+ return runner.run('slug-conflicts', await resolveRepairScope(engine, id), { explicit: true, sourceFlag: id, expect: opts.expect, only: opts.only, noLlm: opts.noLlm, maxLlmUsd: opts.maxLlmUsd });
+ };
+ return { id, root, write, sync, holds, run, read: (path: string) => readFileSync(join(root, path), 'utf8') };
+}
+
+async function gitEffectsSettled(sourceId: string) {
+ for (let i = 0; i < 100; i++) {
+ await runPersistenceEffects(engine, { engine: engine.kind }, { hostId: localHostId(), limit: 10 });
+ const open = await engine.executeRaw("SELECT 1 FROM persistence_effects WHERE source_id=$1 AND kind='git' AND state<>'committed'", [sourceId]);
+ if (!open.length) return;
+ await Bun.sleep(100);
+ }
+ throw new Error('git effects did not settle');
+}
+
+const details = (result: RepairResult) => result.details as unknown as SlugConflictsPreviewDetails;
+const hashOf = (result: RepairResult) => result.apply_command.split('--expect ')[1]!.split(' ')[0]!;
+const receipts = (sourceId: string) => engine.executeRaw<{ outcome: Record<string, any> }>("SELECT outcome FROM persistence_requests WHERE source_id=$1 AND outcome ? 'content_repair' ORDER BY sequence", [sourceId]);
+const expectNoSecrets = (value: unknown) => { const text = typeof value === 'string' ? value : JSON.stringify(value); expect(text).not.toContain('Sentinelbodyzr9'); };
+/** Result fields that carry no diff: the preview's diffs show file lines to the operator by design. */
+const surfaceOf = (result: RepairResult) => ({ ...result, details: undefined });
+
+function each(run: () => Promise<void>) {
+ return withEnv(env, async () => {
+ configureGateway({ chat_model: 'anthropic:claude-sonnet-4-6' } as never);
+ try { await run(); } finally { await disposePersistenceConsumer(engine); }
+ });
+}
+
+test('registry: preview-bound, spends llm, clears no doctor check, not explicit-only; the CLI takes --only and --no-llm', () => {
+ const spec = repairSpec('slug-conflicts');
+ expect(spec).toMatchObject({ preview_bound: true, spends: 'llm', checks: [], embeds: 'effect' });
+ expect(spec.explicit_only).toBeUndefined();
+ expect(parseRepairArgs(['slug-conflicts', '--source', 's', '--only', 'notes/a.md', '--no-llm', '--apply', '--expect', 'abc'])).toMatchObject({ kind: 'slug-conflicts', only: ['notes/a.md'], noLlm: true, expect: 'abc' });
+});
+
+test('deterministic tier: a stray slug (no page, no file) and a slug naming a page of another type lose the line; an alias to the own page is exempt; the preview writes nothing', () => each(async () => {
+ const s = await managed({
+ 'companies/acme-example.md': page('Acme Widgets', 'company', 'A synthetic company.'),
+ 'people/carol-example.md': page('Carol Example', 'person', 'A synthetic person.'),
+ 'notes/stray.md': page('Stray Note', 'note', `A note from a template. ${SECRET}`, 'slug: notes/nowhere-at-all\n'),
+ 'people/bob-example.md': page('Bob Example', 'person', 'A synthetic person who works at the company.', 'slug: companies/acme-example\n'),
+ });
+ expect((await s.sync()).held_count).toBe(2);
+ // An alias to the file's own page: held by the screen, exempt for the lane.
+ await engine.transaction(async tx => {
+ await tx.executeRaw("SELECT set_config('gbrain.write_sources', $1, true)", [JSON.stringify([s.id])]);
+ await tx.executeRaw('INSERT INTO slug_aliases (source_id, alias_slug, canonical_slug) VALUES ($1, $2, $3)', [s.id, 'people/carol', 'people/carol-example']);
+ });
+ s.write('people/carol-example.md', page('Carol Example', 'person', 'A synthetic person.', 'slug: people/carol\n')); commit(s.root, 'alias slug');
+ expect((await s.sync()).held_count).toBe(3);
+ transport(() => answer('{"action":"remove_slug"}'));
+ const preview = await s.run();
+ expect(calls).toHaveLength(0);
+ expect(preview.listing!.map(entry => [entry.item, entry.class]).sort()).toEqual([
+ [`${s.id}:notes/stray.md`, 'deterministic'], [`${s.id}:people/bob-example.md`, 'deterministic'], [`${s.id}:people/carol-example.md`, 'already_exempt']]);
+ expect(details(preview).counts).toEqual({ deterministic: 2, llm: 0, held: 0, skipped: 1 });
+ expect(details(preview).diffs.map(d => d.rule).sort()).toEqual(['absent_page', 'different_type']);
+ expect(details(preview).diffs[0]!.diff).toContain('-slug: ');
+ expect(preview.cost.llm_usd).toBe(0);
+ expect(preview.apply_command).toBe(`gbrain repair slug-conflicts --source ${s.id} --apply --expect ${hashOf(preview)}`);
+ expect(s.read('notes/stray.md')).toContain('slug: notes/nowhere-at-all');
+ const applied = await s.run({ apply: true, expect: hashOf(preview) });
+ expect(applied).toMatchObject({ mode: 'apply', applied: 2, repaired: 2, outcomes: { repaired: 2 } });
+ expect(calls).toHaveLength(0);
+ expect(s.read('notes/stray.md')).toBe(page('Stray Note', 'note', `A note from a template. ${SECRET}`));
+ expect(s.read('people/bob-example.md')).not.toContain('slug:');
+ expect((await engine.getPage('people/bob-example', { sourceId: s.id }))?.compiled_truth).toContain('works at the company');
+ const holds = await s.holds();
+ expect(holds.map(h => h.path)).toEqual(['people/carol-example.md']);
+ // The receipt and the commit: actor, tier, confidence, hashes; the subject names the path and the trailer the hold code.
+ const rows = await receipts(s.id);
+ expect(rows.map(r => r.outcome.content_repair.tier)).toEqual(['deterministic', 'deterministic']);
+ expect(rows[0]!.outcome.content_repair).toMatchObject({ actor: 'content-repair', hold_code: 'frontmatter_slug_conflict', action: 'remove_slug', confidence: 'high', model: null, cost_usd: 0 });
+ await gitEffectsSettled(s.id);
+ const log = git(s.root, 'log', '--format=%B');
+ expect(log).toContain('gbrain: repair frontmatter slug in notes/stray.md');
+ expect(log).toContain('gbrain-repair: frontmatter_slug_conflict deterministic high');
+ expect(git(s.root, 'log', '-1', '--format=%(trailers:key=gbrain-repair,valueonly)')).toMatch(/^frontmatter_slug_conflict deterministic high/);
+ expect(git(s.root, 'status', '--porcelain')).toBe('');
+ expectNoSecrets([holds, rows, surfaceOf(applied), log]);
+ // The hold fix of the remaining (exempt) hold names the content repair preview.
+ expect(gitHoldItem(holds[0]!).fix.argv).toEqual(['gbrain', 'repair', 'content', '--source', s.id, '--only', 'people/carol-example.md']);
+}), 240_000);
+
+test('model tier: a duplicate pair is judged at apply time; merge_into writes nothing and names the canonical for a person; the memo spends nothing twice; remove_slug applies through the coordinated path', () => each(async () => {
+ const s = await managed({
+ 'people/alice-example.md': page('Alice Example', 'person', 'A synthetic founder, first met in 2024.'),
+ 'people/alice-example-2.md': page('Alice Example', 'person', `A synthetic founder. Possible duplicate of people/alice-example. ${SECRET}`, 'slug: people/alice-example\n'),
+ 'people/dan-example.md': page('Dan Example', 'person', 'A synthetic engineer.'),
+ 'people/dan-other.md': page('Dan Other Example', 'person', 'A different synthetic person.', 'slug: people/dan-example\n'),
+ });
+ expect((await s.sync()).held_count).toBe(2);
+ transport(() => answer('{"action":"merge_into","canonical":"people/alice-example","why":"' + WHY + '"}'));
+ const preview = await s.run();
+ expect(calls).toHaveLength(0);
+ expect(preview.listing!.map(entry => entry.class)).toEqual(['llm', 'llm']);
+ expect(details(preview).llm_items.map(i => i.named).sort()).toEqual(['people/alice-example', 'people/dan-example']);
+ expect(preview.cost.llm_usd).toBeGreaterThan(0);
+ expect(preview.cost.llm_cap_remaining_usd).toBe(1);
+ expect(details(preview).model).toBe('anthropic:claude-opus-5-5');
+ // --no-llm holds both without a call and records the state.
+ const free = await s.run({ apply: true, noLlm: true });
+ expect(free).toMatchObject({ applied: 0, remaining: { llm_disabled: 2 } });
+ expect(calls).toHaveLength(0);
+ expect((await s.holds())[0]!.meta.content_repair).toMatchObject({ action: 'pending', reason: 'llm_disabled', next_attempt_after: null });
+ // The model: merge_into for the duplicate, remove_slug for the other.
+ transport(opts => answer(JSON.stringify(opts.messages).includes('people/dan-other') ? '{"action":"remove_slug","why":"Different people."}' : `{"action":"merge_into","canonical":"people/alice-example","why":"${WHY}"}`));
+ const applied = await s.run({ apply: true });
+ expect(calls).toHaveLength(2);
+ expect(applied).toMatchObject({ applied: 1, repaired: 1, remaining: { merge_recommended: 1 }, outcomes: { repaired: 1, held: 1 } });
+ expect(applied.cost.llm_usd).toBeGreaterThan(0);
+ const prompt = `${calls[0]!.system}\n${JSON.stringify(calls[0]!.messages)}`;
+ expect(prompt).toContain('people/alice-example-2');
+ expect(prompt).toContain('exactly one JSON object');
+ // merge_into: nothing written, the hold carries codes and slugs (never the model's sentence), the run output carries why.
+ expect(s.read('people/alice-example-2.md')).toContain('slug: people/alice-example');
+ const held = applied.outcome_items!.find(o => o.outcome === 'held')!;
+ expect(held).toMatchObject({ reason: 'merge_recommended', detail: { action: 'merge_into', canonical: 'people/alice-example', why: WHY, tier: 'llm' } });
+ const holds = await s.holds();
+ expect(holds.map(h => h.path)).toEqual(['people/alice-example-2.md']);
+ expect(holds[0]!.meta.content_repair).toMatchObject({ action: 'merge_into', reason: 'merge_recommended', canonical: 'people/alice-example', named: 'people/alice-example', type: 'person', model: 'anthropic:claude-opus-5-5', next_attempt_after: null });
+ expect(JSON.stringify(holds[0]!.meta)).not.toContain(WHY);
+ const status = await readSyncStatus(engine, s.id);
+ expect(status.needs_human).toBe(true);
+ expect(status.human_reason).toContain('`people/alice-example`');
+ expect(status.human_reason).toContain('`people/alice-example-2.md`');
+ expect(status.human_reason).toContain('gbrain does not merge pages by itself yet');
+ expect(status.human_reason).not.toContain(WHY);
+ expect(status.next).toMatchObject({ actor: 'user', argv: ['gbrain', 'repair', 'content', '--source', s.id, '--only', 'people/alice-example-2.md'] });
+ const item = gitHoldItem(holds[0]!);
+ expect(item.docs).toBe('docs/guides/write-refusals.md#merge_recommended');
+ expect(item.fix.user_message).toContain('people/alice-example');
+ // remove_slug: written through the coordinated path with the llm receipt and trailer.
+ expect(s.read('people/dan-other.md')).not.toContain('slug:');
+ const rows = await receipts(s.id);
+ expect(rows).toHaveLength(1);
+ expect(rows[0]!.outcome.content_repair).toMatchObject({ tier: 'llm', confidence: 'medium', model: 'anthropic:claude-opus-5-5' });
+ expect(rows[0]!.outcome.content_repair.cost_usd).toBeGreaterThan(0);
+ await gitEffectsSettled(s.id);
+ const log = git(s.root, 'log', '--format=%B');
+ expect(log).toContain('gbrain: repair frontmatter slug in people/dan-other.md');
+ expect(log).toContain('gbrain-repair: frontmatter_slug_conflict llm medium');
+ // The memo: the same bytes, pages, model and prompt are never sent again; the hold keeps its verdict.
+ const again = await s.run({ apply: true });
+ expect(calls).toHaveLength(2);
+ expect(again).toMatchObject({ applied: 0, remaining: { merge_recommended: 1 } });
+ expect(again.cost.llm_usd).toBe(0);
+ expect(again.outcome_items![0]!.detail).toMatchObject({ memo: 'judged_before' });
+ expect((await s.holds())[0]!.meta.content_repair).toMatchObject({ action: 'merge_into', canonical: 'people/alice-example' });
+ // A re-screen of the same bytes keeps the verdict; a changed file drops it and earns a new judgment.
+ await s.sync();
+ expect((await s.holds())[0]!.meta.content_repair).toMatchObject({ action: 'merge_into' });
+ s.write('people/alice-example-2.md', page('Alice Example', 'person', 'A synthetic founder, edited.', 'slug: people/alice-example\n')); commit(s.root, 'edit');
+ await s.sync();
+ expect((await s.holds())[0]!.meta.content_repair).toBeUndefined();
+ transport(() => answer('{"action":"needs_human"}'));
+ const undecided = await s.run({ apply: true });
+ expect(calls).toHaveLength(1);
+ expect(undecided).toMatchObject({ applied: 0, remaining: { content_repair_needs_human: 1 } });
+ expect((await s.holds())[0]!.meta.content_repair).toMatchObject({ action: 'needs_human', reason: 'content_repair_needs_human', next_attempt_after: null });
+ const undecidedStatus = await readSyncStatus(engine, s.id);
+ expect(undecidedStatus.needs_human).toBe(true);
+ expect(undecidedStatus.human_reason).toContain('could not decide');
+ expect(gitHoldItem((await s.holds())[0]!).docs).toBe('docs/guides/write-refusals.md#content_repair_needs_human');
+ expectNoSecrets([await s.holds(), rows, surfaceOf(applied), surfaceOf(again), log, status]);
+}), 240_000);
+
+test('a transient provider error keeps the memo and schedules a retry; changed_since_preview writes nothing; the fence ledger counts, so a prior fences spend stops the run before any call', () => each(async () => {
+ const s = await managed({
+ 'people/erin-example.md': page('Erin Example', 'person', 'A synthetic founder.'),
+ 'people/erin-example-2.md': page('Erin Example', 'person', 'Another record of the same synthetic founder.', 'slug: people/erin-example\n'),
+ });
+ expect((await s.sync()).held_count).toBe(1);
+ transport(() => Object.assign(new Error('rate limited'), { status: 429 }));
+ const down = await s.run({ apply: true });
+ expect(calls).toHaveLength(1);
+ expect(down).toMatchObject({ applied: 0, remaining: { llm_unavailable: 1 } });
+ const state = (await s.holds())[0]!.meta.content_repair!;
+ expect(state).toMatchObject({ action: 'pending', reason: 'llm_unavailable' });
+ expect(Date.parse(state.next_attempt_after!)).toBeGreaterThan(Date.now() + 23 * 3_600_000);
+ expect(gitHoldItem((await s.holds())[0]!).fix.why).toContain('tries again');
+ // The memo was not consumed: the next run asks again.
+ transport(() => answer('{"action":"needs_human"}'));
+ const preview = await s.run();
+ expect(calls).toHaveLength(0);
+ // changed_since_preview: the file moved after the preview, so the approved set skips it without a call.
+ const edited = page('Erin Example', 'person', 'Another record of the same synthetic founder, edited.', 'slug: people/erin-example\n');
+ s.write('people/erin-example-2.md', edited);
+ const stale = await s.run({ apply: true, expect: hashOf(preview) });
+ expect(stale).toMatchObject({ applied: 0, outcomes: { skipped: 1 }, remaining: { changed_since_preview: 1 } });
+ expect(calls).toHaveLength(0);
+ expect(s.read('people/erin-example-2.md')).toBe(edited);
+ s.write('people/erin-example-2.md', page('Erin Example', 'person', 'Another record of the same synthetic founder.', 'slug: people/erin-example\n'));
+ // One shared daily cap: a fences spend committed today leaves nothing for the judgment.
+ const ledger = dailyLedger(engine, FENCE_REPAIR_LEDGER);
+ const day = await ledger.readDay();
+ const cap = Math.round((day.committedUsd + day.reservedUsd + 0.01) * 10_000) / 10_000;
+ await engine.setConfig('fences.repair.max_usd_per_day', String(cap));
+ const reserved = await ledger.reserve(0.009, { capUsd: cap });
+ expect(reserved.ok).toBe(true);
+ if (reserved.ok) { await ledger.dispatch(reserved.reservation.id); await ledger.settle(reserved.reservation.id, 0.0095); }
+ const capped = await s.run({ apply: true });
+ expect(calls).toHaveLength(0);
+ expect(capped).toMatchObject({ applied: 0 });
+ expect(capped.stopped).toMatchObject({ reason: 'budget_exhausted', fix: { argv: ['gbrain', 'config', 'set', 'fences.repair.max_usd_per_day', '<usd>'], consent: ['paid'] } });
+ expect(capped.stopped!.message).toMatch(/resets at \d{4}-\d{2}-\d{2}T00:00:00\.000Z/);
+ expect((await s.holds())[0]!.meta.content_repair).toMatchObject({ action: 'pending', reason: 'budget_exhausted' });
+ expect((await s.holds())[0]!.meta.content_repair!.next_attempt_after).toMatch(/T00:00:00\.000Z$/);
+ expect(gitHoldItem((await s.holds())[0]!).fix).toMatchObject({ consent: ['paid'], argv: ['gbrain', 'config', 'set', 'fences.repair.max_usd_per_day', '<usd>'] });
+ await engine.executeRaw("DELETE FROM config WHERE key='fences.repair.max_usd_per_day'");
+ // With the cap back, the judgment runs once.
+ expect(await s.run({ apply: true })).toMatchObject({ remaining: { content_repair_needs_human: 1 } });
+ expect(calls).toHaveLength(1);
+ expectNoSecrets([await s.holds(), surfaceOf(down), surfaceOf(capped)]);
+}), 240_000);