Garry's Opinionated OpenClaw/Hermes Agent Brain
TypeScript
fix(repair): slug-conflicts clears a hold whose only other auto-fix is a style-only NESTED_QUOTES (#6749)
garrytan4fe29aecea70
diff --git a/docs/architecture/key-files/core-utilities-2.md b/docs/architecture/key-files/core-utilities-2.mdindex b2544ffa4b..5a638b27dc 100644--- a/docs/architecture/key-files/core-utilities-2.md+++ b/docs/architecture/key-files/core-utilities-2.md@@ -17,7 +17,7 @@ Current behavior and load-bearing invariants; history belongs in Git and CHANGEL- `src/core/repair/orphan-children.ts` — `gbrain repair orphan-children` (#5216, #4738), explicit-only, brain-wide, projection publication. `PAGE_CHILD_FK_TARGETS` + `orphanPredicate` (a correlated, table-qualified `NOT EXISTS`, so Postgres plans an anti-join instead of a per-row subplan once page ids outgrow work_mem; `test/e2e/repair-orphan-children-plan-postgres.test.ts`) are the single target list (doctor `child_table_orphans` in `doctor/checks/core-health.ts` imports them and names this repair instead of printing SQL). One item per (table, column); apply deletes orphans or clears the two ON DELETE SET NULL references in one rechecking statement. `probeTornPages` reads every page body in 500-row batches, row by row inside a failing batch, and the plan reports torn rows as the `torn_pages` residual plus a warning naming id/source/slug; they are never changed. The `storage_corrupt` reason in `pg-access-classify.ts` points XX000 storage errors here (`repair-orphan-children-5216.test.ts`, `pg-access-storage-corrupt-5216.test.ts`).- `src/core/repair/fences.ts` — `gbrain repair fences` (#6188), preview-bound, `spends: 'llm'`, not explicit-only (no destructive consent). Candidates: the fence census (`listFenceCandidates` after a bounded `runFenceCensus`, `GBRAIN_FENCE_REPAIR_SCAN_MS`, default 10 s) filtered by `--only`/`--skip <path>` and `--slug <slug>`, plus files or pages the selection names that the census has not judged. Per candidate (`fence-repair/repair-io.ts` reads the current bytes): a host that may not write the source is skipped with the owner condition as its reason (`host_mismatch`, `transfer_in_progress`, `clone_in_progress`, `incarnation_changed`, `local_path_missing`, `coordination_path_missing`; `owner_unavailable` is the fallback; the skip's detail carries `why`, the read-only fix and `retryable`), a candidate a write in flight or an unfinished sync's frozen manifest still names is `sync_in_progress` (#6278: checked at plan, at apply and again at the write's admission in `file-repair.ts`; the rest of the source repairs while the sync runs, and a held path is not busy); `analyzeFences` (`repair-tiers.ts`) decides `proposal` (Tier 1 or Tier 2, validated, a fixed point, the exact diff), `llm` (only Tier 3 residuals: `fences.repair.llm`/`--no-llm` → `llm_disabled`, a page whose tags its file lacks → `canonical_overlay` before any spend, no measured model with a key and `models.fence_repair` unset → `no_measured_model`, an unpriced model under a user cap → `no_pricing`, under the default caps a warn-and-run notice naming `gbrain pricing set`, 0 caps or an estimate over `fences.repair.max_usd_per_page` → `budget_exhausted`, an attempt memo already rejected for these bytes → its stored verdict at $0) or `manual` with the exact location-only edit. The model is `resolveFenceRepairModel` (`fence-repair/model.ts`: `models.fence_repair`, else the first measured model with a key, else none). The preview saves the approved set (`previewHash` over sources, selection and each item's location, bytes hash, revision, tier and after-hash) and prints `apply_command` with `--expect`; `--apply --expect` replays it (`changed_since_preview` for moved bytes or revision), a bare `--apply` applies the current plan starting after the last candidate the previous bare run touched (`fence-repair-rotation`). Apply refuses a remote caller (`trusted_cli_required`) and runs Tier 3 through `runTier3` (ledger reservation, attempt claim, a corrective re-ask only after gate (a) or (e)); a daily-ledger refusal stops the run (`budget_exhausted`, D15: spent and cap, reset time, pages waiting, `gbrain config set fences.repair.max_usd_per_day <usd>` with consent `paid`). Outcomes `repaired` / `held` (FenceReason, also written to the hold with `recordFenceHoldRepair`) / `skipped`; `report` adds `repaired`, `remaining` by reason (an `--expect` apply re-checks the selection for what stays held) and `verification` (`FenceRepairVerification`: repaired per tier, held per reason, oldest hold, USD per Tier 3 repair). Tests: `test/repair-fences.test.ts` (PGLite and Postgres), `test/fence-repair-llm.test.ts`.- `src/core/repair/content-lane.ts` — the content-repair lane (#6377). `CONTENT_REPAIR_KINDS` is the ordered list of repair kinds that clear managed-sync content holds (today `fences`; the GBRA-72 integration appends `slug-conflicts`), read by `gbrain repair content` (`src/commands/repair-content.ts`), the `content_repair` cycle phase and `gbrain sync unblock --apply`, so a new kind plugs in with one entry. `CONTENT_REPAIR_HOLD_KINDS` maps a hold code to the kind that clears it (`invalid_fence` → `fences`; `frontmatter_slug_conflict` → `null` until Lane B's kind lands, which keeps the surfaces' refusal text). `runContentLane(engine, scope, { apply, kinds?, only, skip, expect?, noLlm, maxLlmUsd, deadline, registry? })` has no rule logic: it runs each kind through `repairRunner` in order, passing the run's paid allowance minus what earlier kinds spent (read from each result's `cost.llm_usd`; the daily ledger is `FENCE_REPAIR_LEDGER` for every kind) and one absolute deadline (a `time_budget` stop ends the pass; any other stop lets the next kind run), and returns per-kind results, each kind's own `preview_hash` (no combined hash: `--expect` is one hash per kind in lane order, `parseContentLaneExpect` refuses a wrong count with `invalid_params` before any kind runs), the lane's spend and remaining allowance, and `apply_command` (`contentLaneArgv`). A preview plans every kind before any mutation; `--apply --expect` binds each kind to its approved set; a bare apply runs each kind's own plan-and-apply (`changed_since_read` binding, held reasons recorded on the holds). `contentHoldDisposition(record, auto)` reads a hold's stored repair state (`fenceHoldStatus` for a fence hold; `meta.content_repair.action` for a slug-conflict hold, read loosely) and says whether an unattended surface may run the kind (`repair`), must list it (`listed`: `needs_human` for a manual reason or a recommended merge, `paid`, `owner`) or has no kind for it (`unsupported`). Output is counts, codes, hashes and paths only. Tests: `test/cycle-content-repair.test.ts` (stub kinds), `test/repair-content.test.ts` (the real `fences` kind through the CLI).-- `src/core/repair/slug-conflicts.ts` — `gbrain repair slug-conflicts` (#6377, Lane B), the lane kind that clears `frontmatter_slug_conflict` holds: preview-bound, `spends: 'llm'`, `checks: []` (doctor keeps `git_held_files` on `frontmatter`), not explicit-only. Candidates are the source's slug-conflict holds (plus `--only <path>`); identity is resolved, not textual: the frontmatter slug is normalized the way the screen does and resolved through `slug_aliases` to a page id in the same source (a slug resolving to the held file's own page is exempt; a held file with no page yet is a normal candidate). Deterministic tier (`remove_slug`, confidence high): the named slug resolves to no page and names no other file, or to a page of a different type sharing no title token; the one-line edit publishes through the frontmatter repair's coordinated path (`prepareRepairPublication` / `submitManagedFileRepair`: bytes bound to the sha256 the preview read, import, hold clear and Git effect in one write). Every verdict uses managed sync's own screen (`sync-screen.ts` `loadSyncScreenRun` + `frozenImportScreenInput` + `screenFrozenContent`, on the file's bytes and on the edited bytes): a held file the screen now admits as it is (its line is clean, or names the file's own page as written) is planned as `import` and published unchanged through `submitManagedFileRepair` with an `import` receipt and `holdObservedAt` (the hold observation the plan read; a newer hold is kept and the hold records a `changed_since_read` retry); a file sync would hold whatever the lane writes (the page it is filed as carries another slug than its path, or the line reaches the own page only through an alias) is held `slug_page_mismatch` with both slugs (`named` on the hold). Everything else goes to the model tier (`src/core/content-repair/judgment.ts`): `remove_slug` applies the same way, `merge_into <canonical>` and `needs_human` are recorded on the hold as codes and slugs only (`recordContentHoldRepair`, `meta.content_repair`) and rendered by `sync status` as `needs_human` paragraphs; nothing merges pages. Caps and ledger are the fence repair's (`FENCE_REPAIR_LEDGER`, `fences.repair.max_usd_per_page` / `_per_day`, `fences.repair.llm`, `--no-llm`, `--max-usd`); the receipt is a `content_repair` receipt (action, tier, confidence, model, cost, before/after sha256) carried by the write and the commit trailer `gbrain-repair: <hold_code> <tier> <confidence>`. Tests: `test/repair-slug-conflicts.test.ts`, `test/repair-slug-conflicts-sync-screen.test.ts`.+- `src/core/repair/slug-conflicts.ts` — `gbrain repair slug-conflicts` (#6377, Lane B), the lane kind that clears `frontmatter_slug_conflict` holds: preview-bound, `spends: 'llm'`, `checks: []` (doctor keeps `git_held_files` on `frontmatter`), not explicit-only. Candidates are the source's slug-conflict holds (plus `--only <path>`); identity is resolved, not textual: the frontmatter slug is normalized the way the screen does and resolved through `slug_aliases` to a page id in the same source (a slug resolving to the held file's own page is exempt; a held file with no page yet is a normal candidate). Deterministic tier (`remove_slug`, confidence high): the named slug resolves to no page and names no other file, or to a page of a different type sharing no title token; besides SLUG_MISMATCH `autoFixFrontmatter` may propose only style-only `NESTED_QUOTES` (left as written, listed as `style_only`), any other code holds it `still_invalid` naming it; the one-line edit publishes through the frontmatter repair's coordinated path (`prepareRepairPublication` / `submitManagedFileRepair`: bytes bound to the sha256 the preview read, import, hold clear and Git effect in one write). Every verdict uses managed sync's own screen (`sync-screen.ts` `loadSyncScreenRun` + `frozenImportScreenInput` + `screenFrozenContent`, on the file's bytes and on the edited bytes): a held file the screen now admits as it is (its line is clean, or names the file's own page as written) is planned as `import` and published unchanged through `submitManagedFileRepair` with an `import` receipt and `holdObservedAt` (the hold observation the plan read; a newer hold is kept and the hold records a `changed_since_read` retry); a file sync would hold whatever the lane writes (the page it is filed as carries another slug than its path, or the line reaches the own page only through an alias) is held `slug_page_mismatch` with both slugs (`named` on the hold). Everything else goes to the model tier (`src/core/content-repair/judgment.ts`): `remove_slug` applies the same way, `merge_into <canonical>` and `needs_human` are recorded on the hold as codes and slugs only (`recordContentHoldRepair`, `meta.content_repair`) and rendered by `sync status` as `needs_human` paragraphs; nothing merges pages. Caps and ledger are the fence repair's (`FENCE_REPAIR_LEDGER`, `fences.repair.max_usd_per_page` / `_per_day`, `fences.repair.llm`, `--no-llm`, `--max-usd`); the receipt is a `content_repair` receipt (action, tier, confidence, model, cost, before/after sha256, style_only) carried by the write and the commit trailer `gbrain-repair: <hold_code> <tier> <confidence>`. Tests: `test/repair-slug-conflicts.test.ts`, `test/repair-slug-conflicts-sync-screen.test.ts`.- `src/core/repair/frontmatter.ts` — `gbrain repair frontmatter` (#5988), explicit-only, preview-bound, destructive consent (`--yes` with the hash, registry `consent`). #5966 (W14 P1.7): the slug rule itself is `slugStampedFrontmatter(slug, fm)` in `src/core/markdown.ts` (stamps `slug:` when the path cannot derive it, such as a doubled hyphen, and replaces a foreign `fm.slug`; used by `serializePageToMarkdown` and `commands/export.ts`, digest-neutral since `parseMarkdown` drops `fm.slug`); `slugStampCandidate` proposes a SAFE `slug:` stamp for a well-formed file at a page's recorded `source_path` whose path derives another slug and that declares none (a legacy render of a slug the path cannot derive), inserted as `serializeMarkdown` writes it; never normalizes or guesses. Scope: Git-visible `.md`/`.mdx` per source (managed owner root or legacy `local_path`) plus every Git hold row; database side, pages whose body begins with an embedded frontmatter block or whose title is the humanized slug while the file names one. `frontmatterCandidates` builds a safe rewrite (NUL strip, nested-quote swap, `repairRecoverableFrontmatter` quoting; parsed values must be unchanged) and an interpretive one (`autoFixFrontmatter` missing close / slug line, fold, dup, unclosed, `#` rescue); both must strict-parse with no hold. `prepareRepairPublication` binds each proposal to the page fields its import would store; a refusal or canonical overlay is `needs_review`. The hash covers sources, `include_ambiguous`, `--only`/`--skip`, and per file before/after sha256, page id/revision, result digest and `rename_from`; the approved set stores no frontmatter text. An `invalid_fence` hold is listed with a resolution that defers to `gbrain repair fences --source <id> --only <path>` (frontmatter repair never changes fences). Apply refuses while an unfinished managed sync cursor names a selected path, re-derives each change, then publishes through `managed_file_repair` (managed) or backup, write, `importFromFile`, hold clear and a printed commit step (legacy). Tests: `test/repair-frontmatter.test.ts`.- `src/core/persistence/mirror-read-only.ts` and `src/commands/sources-mirror.ts` — #5409 read-only mirror sources. `sourceMirrorReadOnly(engine, sourceId)` reads `sources.config.mirror_read_only` (default false). When true, `prepareFileTarget` (`page-prepare.ts`) returns no file for any coordinated page write into the source (receipt `write_through.skipped: 'mirror_read_only'`, `storage: 'database_only'`, set in `coordinator.ts`), and managed sync (`sync-prepare.ts`) imports an overlay (canonical form differs from the file bytes) database-only: no `file`, no newer-working-tree refusal, and `contentUnchanged` ignores the overlay. A page created that way with no recorded file is stamped `pages.database_only_reason='mirror_read_only'` (`classifyMirrorPage`, in the publication) and stays database-only after the flag is cleared; the coordinator refuses (`source_changed`) a file target prepared before the flag was set (rechecked under the publication with the source row `FOR SHARE`); `gitPage` (`effects.ts`) completes a mirror source's Git effects as skipped. `gbrain sources mirror-readonly|mirror-writable <id>` set and clear the key like `federate`/`unfederate`; `sources list --json` reports `mirror_read_only`.diff --git a/src/core/content-repair/receipt.ts b/src/core/content-repair/receipt.tsindex ed0e3ad338..6c76ccb432 100644--- a/src/core/content-repair/receipt.ts+++ b/src/core/content-repair/receipt.ts@@ -9,7 +9,8 @@* 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+ * of the bytes before and after; a `remove_slug` also lists the style-only+ * frontmatter fix codes it left as written (`style_only`, e.g. `NESTED_QUOTES`). Hashes and codes only, so it is safe in* receipts, results and commit messages; `parseContentRepairReceipt` rejects* anything else before it reaches a write.*/@@ -28,9 +29,12 @@ export interface ContentRepairReceipt {cost_usd: number | null;before_sha256: string;after_sha256: string;+ /** remove_slug: style-only frontmatter fix codes (`NESTED_QUOTES`) the edit left as written; omitted when there are none. */+ style_only?: string[];}const SHA = /^[0-9a-f]{64}$/;+const FIX_CODE = /^[A-Z][A-Z_]{0,39}$/;/** 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 {@@ -43,8 +47,11 @@ export function parseContentRepairReceipt(value: unknown): ContentRepairReceiptif (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;if (r.action === 'import' && r.before_sha256 !== r.after_sha256) return null;+ if (r.style_only !== undefined && (r.action !== 'remove_slug' || !Array.isArray(r.style_only) || r.style_only.length === 0 || r.style_only.length > 8+ || !r.style_only.every(code => typeof code === 'string' && FIX_CODE.test(code)))) return null;return { actor: CONTENT_REPAIR_ACTOR, hold_code: CONTENT_REPAIR_HOLD_CODE, action: r.action, 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 };+ model: r.model as string | null, cost_usd: r.cost_usd as number | null, before_sha256: r.before_sha256, after_sha256: r.after_sha256,+ ...(r.style_only !== undefined ? { style_only: [...r.style_only as string[]] } : {}) };}/** `gbrain: repair frontmatter slug in <path>`, the subject of a repaired file's commit. */diff --git a/src/core/repair/slug-conflicts.ts b/src/core/repair/slug-conflicts.tsindex 99546b2b5b..c24dde40fb 100644--- a/src/core/repair/slug-conflicts.ts+++ b/src/core/repair/slug-conflicts.ts@@ -22,7 +22,9 @@* 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+ * strict-parse with no hold. A style-only `NESTED_QUOTES` it also proposes+ * is left as written and listed as `style_only` in the preview, the result+ * and the receipt; any other fix code holds the file `still_invalid`, named. 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.*@@ -99,6 +101,8 @@ interface ApprovedConflict {tier: Tier;/** Deterministic: the rule (or the import reason) and the sha256 of the bytes written; null for the model tier (decided at apply time). */rule: DeterministicRule | ImportReason | null; after: string | null;+ /** Deterministic remove_slug: style-only fix codes the edit leaves as written (omitted when none). */+ style_only?: string[];estimate_usd: number;/** Model items from this one to the end of the plan (the pages a budget stop leaves waiting). */llm_waiting: number;@@ -111,7 +115,7 @@ 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 }>;+ diffs: Array<{ item: string; rule: DeterministicRule; diff: string; style_only?: string[] }>;/** #6696 C8: held files the sync screen now admits as they are (imported unchanged, the hold cleared). */imports: Array<{ item: string; reason: ImportReason }>;llm_items: Array<{ item: string; named: string | null; estimate_usd: number }>;@@ -178,25 +182,45 @@ function lookupSlugs(declared: string): string[] {return [...new Set([declared, slugifyPath(declared)])].filter(Boolean);}+/** Fix codes `autoFixFrontmatter` may report beside SLUG_MISMATCH that the slug-line edit leaves as written: style-only rewrites (the strict parse of the edit proves the file needs none). */+const STYLE_ONLY_CODES: ReadonlySet<string> = new Set(['NESTED_QUOTES']);++/** The slug-line edit: the edited bytes (null when it is not enough), the style-only codes left as written, and the other fix codes that block it. */+export interface SlugLineRemoval { after: string | null; style_only: string[]; blocking: string[] }+/*** 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.+ * file path must propose SLUG_MISMATCH, as `repair frontmatter` does, and nothing else but style-only codes;+ * `after` is null when it proposes other fixes (`blocking`), or the result still fails to strict-parse or earns a hold.*/-export function removeSlugLine(content: string, sourcePath: string, activePack?: FenceSource['activePack']): string | null {+export function removeSlugLine(content: string, sourcePath: string, activePack?: FenceSource['activePack']): SlugLineRemoval {const fixed = autoFixFrontmatter(content, { filePath: sourcePath });- if (fixed.fixes.length !== 1 || fixed.fixes[0]!.code !== 'SLUG_MISMATCH' || fixed.content === content) return null;+ const codes = [...new Set(fixed.fixes.map(fix => fix.code))];+ const style_only = codes.filter(code => STYLE_ONLY_CODES.has(code));+ const blocking = codes.filter(code => code !== 'SLUG_MISMATCH' && !STYLE_ONLY_CODES.has(code));+ const refused: SlugLineRemoval = { after: null, style_only, blocking };+ if (!codes.includes('SLUG_MISMATCH') || blocking.length || fixed.content === content) return refused;const block = /^(\uFEFF?---[ \t]*(\r?\n))([\s\S]*?)(\r?\n---[ \t]*(?:\r?\n|$))/.exec(content);- if (!block) return null;+ if (!block) return refused;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;+ if (at < 0) return refused;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, sourcePath, { 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;+ if (parsed.errors?.some(error => error.code === 'YAML_PARSE')) return refused;+ if (classifyImportHold(parsed, { expectedSlug: resolveSlugForPath(sourcePath), byteLength: Buffer.byteLength(after), maxBytes: MAX_FILE_SIZE })) return refused;+ return { after, style_only, blocking: [] };+}++/** What else the frontmatter needs when the slug-line edit is not enough: the blocking fix codes when there are any. */+function otherChanges(removal: SlugLineRemoval): string {+ return removal.blocking.length ? `the frontmatter also needs ${removal.blocking.join(', ')}` : 'the frontmatter needs other changes too';+}++/** The style-only codes the edit left as written, as a receipt or result field (omitted when there are none). */+function styleOnly(removal: Pick<SlugLineRemoval, 'style_only'>): { style_only?: string[] } {+ return removal.style_only.length ? { style_only: removal.style_only } : {};}/** A stored page as the judgment shows it: serialized with its frontmatter, so both sides read alike. */@@ -232,7 +256,7 @@ interface Candidate {type Analysis =| { status: 'skip'; reason: 'already_exempt' | 'already_clean' | 'gone' | 'unsafe_path' | 'not_utf8'; message: string }| { status: 'import'; reason: ImportReason }- | { status: 'deterministic'; rule: DeterministicRule; after: string }+ | { status: 'deterministic'; rule: DeterministicRule; after: string; style_only: string[] }| { status: 'llm'; input: JudgmentInput }| { status: 'held'; reason: string; message: string; named?: string };@@ -303,10 +327,11 @@ async function analyze(cand: Candidate, slugsInCheckout: () => Set<string>, screreturn { status: 'held', reason: now.refusal.code, message: `Sync now holds ${cand.path} for ${now.refusal.code}, not for its slug: line; the next gbrain sync --source ${cand.src.id} --no-pull records that hold.` };}const edit = async (rule: DeterministicRule): Promise<Analysis> => {- const after = removeSlugLine(cand.content, cand.sourcePath, cand.src.activePack);- if (after === null) return { 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.` };+ const removal = removeSlugLine(cand.content, cand.sourcePath, cand.src.activePack);+ const after = removal.after;+ if (after === null) return { status: 'held', reason: 'still_invalid', message: `Removing the slug: line of ${cand.path} alone does not make it importable (${otherChanges(removal)}); preview gbrain repair frontmatter --source ${cand.src.id} --only ${cand.path} --include-ambiguous.` };const screened = screen ? await screen(cand, after) : null;- if (screened?.status !== 'refused') return { status: 'deterministic', rule, after };+ if (screened?.status !== 'refused') return { status: 'deterministic', rule, after, style_only: removal.style_only };if (screened.refusal.code === 'frontmatter_slug_conflict') return slugPageMismatch(cand, expected, `but its path derives ${expected}`);return { status: 'held', reason: 'still_invalid', message: `Removing the slug: line of ${cand.path} would leave it held for ${screened.refusal.code}; preview gbrain repair frontmatter --source ${cand.src.id} --only ${cand.path} --include-ambiguous.` };};@@ -317,7 +342,8 @@ async function analyze(cand: Candidate, slugsInCheckout: () => Set<string>, screconst shared = [...titleTokens(parsed.title)].some(token => titleTokens(cand.named!.page.title ?? '').has(token));if (parsed.type !== cand.named.page.type && !shared) return edit('different_type');}- if (removeSlugLine(cand.content, cand.sourcePath, cand.src.activePack) === 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 removal = removeSlugLine(cand.content, cand.sourcePath, cand.src.activePack);+ if (removal.after === null) return { status: 'held', reason: 'still_invalid', message: `Removing the slug: line of ${cand.path} alone would not make it importable (${otherChanges(removal)}), 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' } };@@ -430,8 +456,8 @@ export const slugConflictsRepair: RepairHandler = {continue;}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) });+ approved.push({ ...base, tier: 'deterministic', rule: analysis.rule, after: sha256(Buffer.from(analysis.after, 'utf8')), ...styleOnly(analysis), estimate_usd: 0, llm_waiting: 0 });+ diffs.push({ item: name, rule: analysis.rule, diff: lineDiff(path, cand.content, analysis.after), ...styleOnly(analysis) });continue;}const pending = (reason: string, resolution: string, next: string | null = null) => keep({ reason, tier: 'llm', resolution }, { action: 'pending', reason, ...(cand.namedSlug ? { named: cand.namedSlug } : {}),@@ -468,7 +494,7 @@ export const slugConflictsRepair: RepairHandler = {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: isImport(entry) ? 'import' : entry.tier, detail: isImport(entry) ? `import (${entry.rule}): sync would import the file as it is, so it is imported unchanged and its hold clears`- : entry.tier === 'deterministic' ? `remove_slug (${entry.rule}): the slug: line is removed; the path decides the slug`+ : entry.tier === 'deterministic' ? `remove_slug (${entry.rule}): the slug: line is removed; the path decides the slug${entry.style_only ? `; style-only ${entry.style_only.join(', ')} left as written` : ''}`: `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 })),@@ -501,7 +527,7 @@ export const slugConflictsRepair: RepairHandler = {+ `${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}`));+ for (const diff of shown) lines.push(` deterministic: ${diff.item} (remove_slug, ${diff.rule}${diff.style_only ? `; style-only ${diff.style_only.join(', ')} left as written` : ''})`, ...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 entry of d.imports ?? []) lines.push(` import: ${entry.item} (${entry.reason}): sync would import it as it is; it is imported unchanged and its hold clears`);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)}`);@@ -559,7 +585,7 @@ async function applyConflict(ctx: OperationContext, entry: ApprovedConflict, opt}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, { action: 'remove_slug', tier: 'deterministic', confidence: 'high', model: null, cost_usd: 0 }, opts, held, { rule: analysis.rule });+ return write(ctx, src, cand, analysis.after, { action: 'remove_slug', tier: 'deterministic', confidence: 'high', model: null, cost_usd: 0, ...styleOnly(analysis) }, opts, held, { rule: analysis.rule });}return judge(ctx, src, cand, analysis.input, entry, opts, held);}@@ -571,12 +597,12 @@ type HeldFn = (reason: string, message: string, state: Omit<ContentHoldRepairSta* #6696 C8: `import` writes no file: the held bytes are imported as they are, and the hold clears only while it is still the observation* `observedAt` the repair read (a hold a sync wrote since is kept, with a retry recorded on it).*/-async function write(ctx: OperationContext, src: FenceSource, cand: Candidate, after: string, parts: Pick<ContentRepairReceipt, 'action' | 'tier' | 'confidence' | 'model' | 'cost_usd'>, opts: ApplyOptions, held: HeldFn,+async function write(ctx: OperationContext, src: FenceSource, cand: Candidate, after: string, parts: Pick<ContentRepairReceipt, 'action' | 'tier' | 'confidence' | 'model' | 'cost_usd' | 'style_only'>, opts: ApplyOptions, held: HeldFn,extra: Record<string, unknown>, observedAt?: string): 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, ...parts, before_sha256: cand.before, after_sha256: sha256(Buffer.from(after, 'utf8')) };- const detail = { path: cand.path, slug: cand.slug, action: parts.action, tier: parts.tier, confidence: parts.confidence, ...(cand.namedSlug ? { named: cand.namedSlug } : {}), ...extra };+ const detail = { path: cand.path, slug: cand.slug, action: parts.action, tier: parts.tier, confidence: parts.confidence, ...(parts.style_only ? { style_only: parts.style_only } : {}), ...(cand.namedSlug ? { named: cand.namedSlug } : {}), ...extra };const spend = parts.cost_usd ? { llm_usd: parts.cost_usd } : {};const what = parts.action === 'import' ? `${cand.path} as it is` : `the repaired ${cand.path}`;const refused = (code: string, how: string, reason = code) => code === 'frontmatter_slug_conflict'@@ -652,7 +678,10 @@ async function judge(ctx: OperationContext, src: FenceSource, cand: Candidate, iif (!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, src.activePack)!, { action: 'remove_slug', tier: 'llm', confidence: 'medium', model, cost_usd: 0 }, opts, held, { memo: 'judged_before' });+ if (result.memoHit && result.reason === 'remove_slug') {+ const removal = removeSlugLine(cand.content, cand.sourcePath, src.activePack);+ return write(ctx, src, cand, removal.after!, { action: 'remove_slug', tier: 'llm', confidence: 'medium', model, cost_usd: 0, ...styleOnly(removal) }, 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',@@ -678,9 +707,10 @@ async function judge(ctx: OperationContext, src: FenceSource, cand: Candidate, iconst 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, 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, { action: 'remove_slug', tier: 'llm', confidence: 'medium', model, cost_usd: result.spentUsd }, opts, held, why);+ const removal = removeSlugLine(cand.content, cand.sourcePath, src.activePack);+ const after = removal.after;+ 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 (${otherChanges(removal)}).`, { action: 'remove_slug', reason: 'still_invalid', model, next_attempt_after: null }, { ...why, ...spend }); }+ const written = await write(ctx, src, cand, after, { action: 'remove_slug', tier: 'llm', confidence: 'medium', model, cost_usd: result.spentUsd, ...styleOnly(removal) }, 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' });diff --git a/test/repair-slug-conflicts.test.ts b/test/repair-slug-conflicts.test.tsindex 2ed89dbba4..9b77272008 100644--- a/test/repair-slug-conflicts.test.ts+++ b/test/repair-slug-conflicts.test.ts@@ -44,7 +44,7 @@ import { dailyLedger, FENCE_REPAIR_LEDGER } from '../src/core/budget/daily-ledgeimport { 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 { slugConflictsRepair, 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-'));@@ -306,3 +306,41 @@ test('a transient provider error keeps the memo and schedules a retry; changed_sexpect(calls).toHaveLength(1);expectNoSecrets([await s.holds(), surfaceOf(down), surfaceOf(capped)]);}), 240_000);++// #6749: the issue's fixture. autoFixFrontmatter reports [NESTED_QUOTES, SLUG_MISMATCH] (a style-only re-quote of a valid JSON-style+// alias array beside the slug), so the lane used to hold it still_invalid. Now the slug: line alone is removed, the aliases line stays+// byte-for-byte, and the preview, the result and the receipt list the untouched NESTED_QUOTES alongside remove_slug.+const ACME = '---\ntitle: "Acme Capital"\ntype: company\nslug: acme-capital\naliases: ["Acme", "Acme Capital Management"]\n---\nbody\n';++test('#6749: a mismatched slug beside a style-only NESTED_QUOTES alias array is a deterministic remove_slug; the aliases line is untouched', () => each(async () => {+ const s = await managed({ 'companies/acme-capital.md': ACME });+ expect((await s.sync()).held_count).toBe(1);+ const preview = await s.run({ noLlm: true });+ expect(preview.listing!.map(entry => [entry.item, entry.class])).toEqual([[`${s.id}:companies/acme-capital.md`, 'deterministic']]);+ expect(preview.listing![0]!.detail).toContain('remove_slug (absent_page)');+ expect(preview.listing![0]!.detail).toContain('NESTED_QUOTES');+ expect(details(preview).diffs).toEqual([expect.objectContaining({ rule: 'absent_page', style_only: ['NESTED_QUOTES'] })]);+ expect(details(preview).diffs[0]!.diff).toContain('-slug: acme-capital');+ expect(details(preview).diffs[0]!.diff).not.toContain('aliases');+ const rendered = slugConflictsRepair.render!(preview.details!, { diff: true } as never).join('\n');+ expect(rendered).toContain('remove_slug, absent_page; style-only NESTED_QUOTES left as written');+ const applied = await s.run({ apply: true, expect: hashOf(preview), noLlm: true });+ expect(applied).toMatchObject({ applied: 1, repaired: 1 });+ expect(s.read('companies/acme-capital.md')).toBe(ACME.replace('slug: acme-capital\n', ''));+ expect(await s.holds()).toEqual([]);+ const [row] = await receipts(s.id);+ expect(row!.outcome.content_repair).toMatchObject({ action: 'remove_slug', tier: 'deterministic', style_only: ['NESTED_QUOTES'] });+ expect(JSON.stringify(applied)).toContain('NESTED_QUOTES');+}), 240_000);++test('#6749: a slug conflict that also needs NULL_BYTES stays still_invalid and the hold message names the code', () => each(async () => {+ const content = '---\ntitle: "Acme Capital"\ntype: company\nslug: acme-capital\n---\nbo\u0000dy\n';+ const s = await managed({ 'companies/acme-capital.md': content });+ expect((await s.sync()).held_count).toBe(1);+ const preview = await s.run({ noLlm: true });+ expect(preview.listing!.map(entry => entry.class)).toEqual(['still_invalid']);+ expect(preview.listing![0]!.detail).toContain('NULL_BYTES');+ expect(details(preview).diffs).toEqual([]);+ expect(await s.run({ apply: true, noLlm: true })).toMatchObject({ applied: 0 });+ expect(s.read('companies/acme-capital.md')).toBe(content);+}), 240_000);