Skip to content

Garry's Opinionated OpenClaw/Hermes Agent Brain

TypeScript

wip(#6865): sync-time absent_page heal, truthful slug-conflict verdicts, lane recheck

garrytan29ce45c6fdfb
diff --git a/docs/guides/sync-unblock-runbook.md b/docs/guides/sync-unblock-runbook.md
index eac49525e1..720804d9a0 100644
--- a/docs/guides/sync-unblock-runbook.md
+++ b/docs/guides/sync-unblock-runbook.md
@@ -111,7 +111,7 @@ Every hold and error has three fields, from one table
| `preparation_stalled` | page | retry, upgrade | no | 3 failed attempts over 24 h, or writer status names a step that never finishes |
| `invalid_fence` | page | repair | no | the fence repair preview offers no plan (a manual reason) |
| `invalid_frontmatter` | page | repair | no | the repair preview needs an interpretation (--include-ambiguous) |
-| `frontmatter_slug_conflict` | page | repair | no | the repair preview needs an interpretation |
+| `frontmatter_slug_conflict` | page | repair | no | the content-repair lane recorded what it could not do (an existing named page, other frontmatter fixes, a hand edit) |
| `rename_held` | page | repair | no | the repair preview needs an interpretation |
| `file_too_large` | page | none | yes | always |
| `content_rejected` | page | none | yes | always |
@@ -215,7 +215,10 @@ it and kept going; the receipt lists the hold (`held`, `held_count`) and
`gbrain sources writer status --source <id> --json` names the step.
`unblock --apply` schedules the re-screen.
- `invalid_fence` and `frontmatter_slug_conflict`: the content-repair lane
- clears them. `unblock --apply` runs it on the held paths now; the maintenance
+ clears them. A `slug:` line that names no page and no file is removed by the
+ managed sync itself right after it releases its drain lease
+ (`sync.slug_conflicts.auto_remove`, default on; the result's
+ `slug_lines_removed` counts them, #6865). `unblock --apply` runs it on the held paths now; the maintenance
run's `fence_repair` and `content_repair` phases run it by themselves;
`gbrain repair content --source <id>` previews it. A hold the lane will not
decide is `needs_human` with the paragraph in `human_reason`
diff --git a/scripts/module-size-limits.tsv b/scripts/module-size-limits.tsv
index 94726c59a5..3d4e31b874 100644
--- a/scripts/module-size-limits.tsv
+++ b/scripts/module-size-limits.tsv
@@ -45,5 +45,5 @@ src/core/search/mode.ts 1669 ratchet +53 W3 confidence-gated reranking: reranker
src/commands/eval-longmemeval.ts 1544 ratchet new row: crossed the 1500 unlisted cap in fw3-search (#5092 benchmark-brain recycling: configureBrain split + recycler wiring + test seams; the recycler itself lives in src/eval/longmemeval/harness.ts); +1 P6: tokenmax synopsis-tier wiring (logic in eval/longmemeval/synopsis-tier.ts); +13 GBRA-81 lane A: --via-operation query|search (flags, per-call expansion pin, the run's expectExpansion, the op branch in runOneQuestion, row field, via_operation_summary and its FAIL line; logic in eval/longmemeval/via-operation.ts); +12 --call-plan FILE / --call-plan-gate CMD: two LME_FLAGS entries (CLI help lines), two ParsedArgs fields, the parseArgs pairing check and the header invariant (planner lives in eval/longmemeval/call-plan.ts; runEvalLongMemEval is one line shorter)
src/commands/doctor/checks/extraction-sync.ts 1543 ratchet +1 undeclared_db_only_pages computes the source Git scope once per source (logic in core/markdown.ts sourceGitScope); new row: crossed the 1500 unlisted cap at the fix wave 9 merge: +7 lane W #5028 (extract_atoms freshness judged by the phase itself) and +3 lane F #5863 (extract_health dates a high halt rate by its last halt), each under the cap alone; +7 #5019: content_hash_duplicates fix pins the pairs' source (GBRAIN_SOURCE) and names a delete that runs; +1 fix wave 10 lane L1 #5556: links_extraction_lag denominator excludes quarantined pages (quarantineFilterFragment import); +11 fix wave 15 P2.8 (#5495): extract_health reads the 7-day halt reasons per kind (halt_reasons, top_halt_reason in details and the top reason in the warn line); the read, the unknown bucket and the ranking live in core/extract/rollup-writer.ts; +20 wave 18b lane 1: links_extraction_lag names the columns its pre-migration degrade reads (#6599 strict predicate), sync_freshness separates sync outcome from freshness for a source with no successful sync (#4960; verdict text, fixes and the attempt read live in doctor/sync-outcome.ts and core/sync-attempt.ts) and exempts read-only skill-pack catalogs (#6076; core/shared-skills/adopted-packs.ts)
src/core/search/evidence-delivery.ts 1673 ratchet +5 W5: EvidencePlan.rankCut resolved with the plan (logic in search/page-rank-cut.ts); +20 W5 whole_pages: wholeCost prices a block as delivery would emit it whole (needs the private Block/enrichBlock internals) and the cut is wired before allocate (cutWholePages lives in search/page-rank-cut.ts); new row: crossed the 1500 unlisted cap at the #6367 merge (master 1479, its explicit-budget cap) by the C1 date header threaded through every block path, cap included; pagePlanHits (search/page-plan-hits.ts) and the header loader (evidence-date.ts blockDateHeaders) were peeled first; peel candidate: allocateCapped; +8 at the #6396 merge: page evidence text cut through the fence-chunk trust overlay and the caller minTrust floor (re-summed: our 1504 + master +8); +119 Cat 40 next wave F2: the search.long_page_unit policy (withLongPagePolicy, selectLongPages size preflight with page/byte/deadline limits) and the long-page fetch and fallback in deliverEvidence, kept in the shared seam the plan names (gbrain-evals docs/plans/2026-10-11-cat40-next-wave, F2); +17 F2 rework to the frozen-comparison policy: search.long_page_min_chars (rendered-body characters, default 20,000) read in withLongPagePolicy, a character count in the preflight, the rendered-body confirmation in deliverEvidence, and the long-page row exemption in capDeliveredSnippets (re-summed at the 0.60.225.0 merge: master 1537 + F2 136)
-src/commands/config.ts 1510 ratchet new row: crossed the 1500 unlisted cap in wave 15 P7.4 #5461: set-time validation of think.pages_budget_chars / think.excerpt_ceiling_chars (range + parser live in core/think/pages-budget.ts), mirroring the cycle.consolidate.cluster_threshold hook; +1 wave 16 G5.1 (#6495): set-time refusal hook for search.keyword_statement_timeout_ms (check lives in commands/config/keyword-timeout-value.ts); +1 wave 18b lane 5 (#5012 item 6): search.contextual_retrieval prints the existing-pages hint after the write (text lives in commands/config/contextual-mode-hint.ts); +1 #6712 PR 2: retired/rollback sync key dispatch line (logic in core/sync-config-keys.ts handleSyncKeyConfig)
+src/commands/config.ts 1511 ratchet new row: crossed the 1500 unlisted cap in wave 15 P7.4 #5461: set-time validation of think.pages_budget_chars / think.excerpt_ceiling_chars (range + parser live in core/think/pages-budget.ts), mirroring the cycle.consolidate.cluster_threshold hook; +1 wave 16 G5.1 (#6495): set-time refusal hook for search.keyword_statement_timeout_ms (check lives in commands/config/keyword-timeout-value.ts); +1 wave 18b lane 5 (#5012 item 6): search.contextual_retrieval prints the existing-pages hint after the write (text lives in commands/config/contextual-mode-hint.ts); +1 #6712 PR 2: retired/rollback sync key dispatch line (logic in core/sync-config-keys.ts handleSyncKeyConfig); +1 #6865: sync.slug_conflicts.auto_remove boolean validation at set time (refusal text in repair/slug-autoheal.ts)
src/commands/mcp-expose.ts 1512 ratchet hosted_option: Session carries the gbrain.io coaching notice on the first-receipt run and Tailscale/service friction exits (copy, refs and gating live in core/onboard/hosted-option.ts)
diff --git a/src/commands/config.ts b/src/commands/config.ts
index 26da2f2166..c2596d4db3 100644
--- a/src/commands/config.ts
+++ b/src/commands/config.ts
@@ -397,6 +397,7 @@ async function setConfigWithDecideHooks(engine: BrainEngine, key: string, value:
if (err) { console.error(`[config] ${err}`); process.exit(1); }
}
if (key.startsWith('loops.')) (await import('./config/loops-values.ts')).refuseInvalidLoopsConfigValue(key, value);
+ if (key === 'sync.slug_conflicts.auto_remove') { const err = (await import('../core/repair/slug-autoheal.ts')).slugAutoRemoveValueRefusal(value); if (err) { console.error(`[config] ${err}`); process.exit(1); } }
if (key.startsWith('search.')) (await import('./config/keyword-timeout-value.ts')).refuseInvalidKeywordTimeoutValue(key, value);
if (key === 'persistence.max_claim_ms') {
const { validateMaxClaimConfigValue } = await import('../core/persistence/claim-phase.ts');
diff --git a/src/commands/sync.ts b/src/commands/sync.ts
index c017b0b778..977a347943 100644
--- a/src/commands/sync.ts
+++ b/src/commands/sync.ts
@@ -36,7 +36,7 @@ export interface SyncResult {
/** #6693: caller remembers refused while their page's file awaited import (or was held), replayed after this sync imported it. */
replayedRemembers?: import('../core/repair/failed-writes.ts').ImportReplayReport;
/** #6712 PR 2 (L4): live pages whose canonical file is gone (ghost pages), counted after a managed sync with the read-only repair preview; sync never deletes them. */
- ghostPages?: import('../core/persistence/sync-ghosts.ts').SyncGhostPages;
+ ghostPages?: import('../core/persistence/sync-ghosts.ts').SyncGhostPages; /** #6865: stray slug: lines naming no page this sync removed (repair/slug-autoheal.ts). */ slug_lines_removed?: import('../core/repair/slug-autoheal.ts').SlugHealReport;
/** #6722: pages this run left large or embed_skip (chunked, keyword-searchable) and their embedding state. */ size_states?: import('../core/page-embedding-budget.ts').SyncSizeStates;
status: 'up_to_date' | 'synced' | 'first_sync' | 'dry_run' | 'blocked_by_failures' | 'partial';
fromCommit: string | null;
diff --git a/src/commands/sync/perform.ts b/src/commands/sync/perform.ts
index 24a8ae0456..1d85afbb5f 100644
--- a/src/commands/sync/perform.ts
+++ b/src/commands/sync/perform.ts
@@ -151,7 +151,7 @@ async function performManagedBranch(engine: BrainEngine, outer: SyncOpts): Promi
if (outer.dryRun) return work(undefined);
const { withSyncTail } = await import('../../core/persistence/sync-tail.ts');
try {
- return await withSyncTail(engine, sourceId, await withDrainLease(engine, sourceId, {
+ return await (await import('../../core/repair/slug-autoheal.ts')).healAfterManagedSync(engine, outer, await withSyncTail(engine, sourceId, await withDrainLease(engine, sourceId, {
holder: outer.drainHolder ?? { kind: 'cli', id: null }, remote: currentSubmissionAuthority()?.kind === 'remote_generic',
...(outer.followDrainLease ? { follow: { signal: outer.signal, deadlineAtMs: outer.deadlineAtMs } } : {}),
tty: process.stderr.isTTY === true,
@@ -162,7 +162,7 @@ async function performManagedBranch(engine: BrainEngine, outer: SyncOpts): Promi
? `[sync] source ${sourceId} is being drained by ${who}; following it until it finishes or this run's budget ends (one drainer per source; it resumes the same cursor). Ctrl-C stops following and leaves it running.`
: `[sync] following ${who}: ${done}.`);
},
- }, work), { signal: outer.signal, deadlineAtMs: outer.deadlineAtMs });
+ }, work), { signal: outer.signal, deadlineAtMs: outer.deadlineAtMs }));
} catch (err) {
if (err instanceof LockUnavailableError && err.lockId === lockKey) throw new SyncLockBusyError(await formatLockBusyMessage(engine, lockKey), lockKey);
throw err;
diff --git a/src/core/behavior-change-notice.ts b/src/core/behavior-change-notice.ts
index 7eda5fe2a0..2c051ffd87 100644
--- a/src/core/behavior-change-notice.ts
+++ b/src/core/behavior-change-notice.ts
@@ -729,6 +729,7 @@ export const BEHAVIOR_CHANGES: ReadonlyArray<{ since: string; text: ChangeText }
{ since: '0.60.269.0', text: 'A managed sync no longer forks a second page for a file whose page an older gbrain imported under a slug the current slug fold spells differently (#6727: punctuation, spaces, accents, emoji, full-width characters): a file with no recorded origin and no page at its slug imports into the one live page without a recorded file that folds to it, keeping that page\'s id, links and history. When several such pages match, the file is held `legacy_slug_conflict` (needs a person: keep one, remove the others, then sync); with `sync.holds=fail` the run stops `page_identity_changed`. Pages already forked by older syncs are not merged.' },
{ since: '0.60.269.0', text: 'A managed sync\'s final checkpoint validation reads at most one committed receipt per unfinished receipt, so a catch-up of tens of thousands of entries no longer times out at its last step (#6735). A checkpoint that still hits `checkpoint_validation_timeout` is re-validated by the next sync of the source (once per run, after the stop is recorded) instead of rediscovering the whole manifest.' },
{ since: '0.60.269.0', text: 'Doctor no longer warns that a managed sync cursor has been idle "over an hour" right after the cursor was discovered (#6763): idle time counts from the cursor\'s last advance, or from its discovery when it has not advanced yet.' },
+ { since: '0.60.270.0', text: 'A managed `gbrain sync` now removes a stray frontmatter `slug:` line by itself when the slug it names has no page and no file (#6865, the content-repair lane\'s deterministic `absent_page` rule): right after the sync releases its drain lease, each such held file is rewritten without that one line, imported under the slug its path gives, its `frontmatter_slug_conflict` hold cleared and the edit committed as `gbrain: repair frontmatter slug in <path>` with the `gbrain-repair:` trailer, through the same coordinated repair write the maintenance run already used; the declared slug becomes an alias of the page so links written against it keep resolving. At most 200 files and 60 s per sync; the result\'s `slug_lines_removed` counts them and the rest. A line naming an existing page (with a file or database-only), a file edited since sync held it, a source with an unfinished sync, and a sync submitted by a remote job or agent are left held. Preview what the lane would do with `gbrain repair content --source <id> --no-llm`; opt out with `gbrain config set sync.slug_conflicts.auto_remove false` (or pause the whole lane with `fences.repair.enabled false`); undo one edit with `git revert` of its commit and a sync, which holds the file again. Nothing runs at upgrade. Slug-conflict hold status now follows what the lane found: "decide which page keeps the slug" appears only when the line names a live page, a hold with no verdict yet never escalates to a person, and a verdict an older gbrain recorded is rechecked once by the next sync or maintenance run instead of being listed for a person.' },
];
/** The newest disclosed change's release: the notice id moves only when a release adds rows. */
diff --git a/src/core/config.ts b/src/core/config.ts
index 50bfceb191..6d3c5e778c 100644
--- a/src/core/config.ts
+++ b/src/core/config.ts
@@ -1741,7 +1741,7 @@ export const KNOWN_CONFIG_KEYS: readonly string[] = [
// #5988: Git sync holds (read by readSyncHoldPolicy). `sync.holds=fail`
// restores fail-closed blocking. Detail, escalation and the parser-regression
// stop are tuned by GBRAIN_SYNC_* env since #6712 PR 2 (RETIRED_SYNC_KEYS).
- 'sync.holds',
+ 'sync.holds', 'sync.slug_conflicts.auto_remove', // #6865: sync-time removal of a stray slug: line naming no page (repair/slug-autoheal.ts); default on
'fences.normalize', // #6188: inline Tier 1 fence normalization (fence-repair/config.ts); default on
'fences.repair.enabled', 'fences.repair.llm', // #6188: the fence_repair cycle phase and its Tier 3 model step (fence-repair/config.ts); default on
'fences.repair.max_usd_per_page', 'fences.repair.max_usd_per_day', // #6188: Tier 3 fence repair caps; 0 = no model spend
diff --git a/src/core/content-repair/hold-fix.ts b/src/core/content-repair/hold-fix.ts
index c5bf083126..506c1ee3bb 100644
--- a/src/core/content-repair/hold-fix.ts
+++ b/src/core/content-repair/hold-fix.ts
@@ -31,10 +31,16 @@
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';
+import { contentRepairHumanReason, contentRepairLaneCurrent } from '../persistence/sync-fault-class.ts';
const PAID: ReadonlySet<string> = new Set(['llm_disabled', 'budget_exhausted', 'no_measured_model', 'no_pricing']);
+
+/** The page a held file's slug: line names, as a person reads it: `page <slug>`, marked when it has no file. */
+export function namedPageLabel(state: Pick<ContentHoldRepairState, 'named' | 'named_db_only'>): string | null {
+ return state.named ? `page ${state.named}${state.named_db_only ? ' (a database-only page with no file)' : ''}` : null;
+}
+
/** 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] : [])];
@@ -69,10 +75,16 @@ export function contentHoldFix(record: { source_id: string; path: string; slug?:
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. The content-repair lane clears this itself on the next maintenance run or with gbrain sync unblock --source ${source} --apply: `
+ why: `The frontmatter slug: line of ${record.path} names a slug other than its path; a line naming no page is removed by the next managed sync itself (sync.slug_conflicts.auto_remove). `
+ + `The content-repair lane clears 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.' };
}
+ if (!contentRepairLaneCurrent(state) && state.action !== 'pending') {
+ return { ...base, actor: 'agent',
+ why: `An older gbrain recorded ${state.action} (${state.reason}) for ${record.path}; this release's content-repair lane rechecks it once on the next sync or maintenance run, reading the file and retrying through the normal repair write. `
+ + `To recheck now: gbrain sync unblock --source ${source} --apply. The preview is read-only and calls no model.` };
+ }
const paragraph = contentRepairHumanReason({ ...state, path: record.path, slug: record.slug ?? null });
if (paragraph) {
return { ...base, actor: 'user', user_message: paragraph,
@@ -82,14 +94,16 @@ export function contentHoldFix(record: { source_id: string; path: string; slug?:
: `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.' };
}
+ const named = namedPageLabel(state);
if (state.action === 'pending' && PAID.has(state.reason)) {
+ const pair = named ? `${record.path} (page ${record.slug ?? '?'}) declares the slug of ${named}` : `${record.path} has a frontmatter slug conflict`;
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'
+ + `Preview: ${preview.join(' ')}. By hand instead: if ${record.path} and ${named ?? 'the page its slug: line names'} are different pages, delete the slug: line of ${record.path} and commit; if they are the same, merge them and delete the duplicate.`,
+ user_message: `${pair}; only a model call can judge whether they are the same page, 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') {
@@ -103,6 +117,11 @@ export function contentHoldFix(record: { source_id: string; path: string; slug?:
+ `so removing the line would not clear the hold (slug_page_mismatch). By hand: make the slug: line name ${record.slug ?? 'the page'} exactly or move the file to the path that derives it, `
+ `commit, and run gbrain sync --source ${source} --no-pull; the preview shows the current state.` };
}
+ if (state.reason === 'still_invalid' && state.other_codes?.length) {
+ return { ...base, argv: ['gbrain', 'repair', 'frontmatter', '--source', source, '--only', record.path, '--include-ambiguous'], actor: 'agent',
+ why: `Removing the slug: line of ${record.path} alone leaves it unimportable: the frontmatter also needs ${state.other_codes.join(', ')}. `
+ + 'The frontmatter repair preview shows that edit and writes nothing; applying it is an interpretation, so ask the user before running the apply command it prints.' };
+ }
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/receipt.ts b/src/core/content-repair/receipt.ts
index 6c76ccb432..b27a508f76 100644
--- a/src/core/content-repair/receipt.ts
+++ b/src/core/content-repair/receipt.ts
@@ -31,10 +31,13 @@ export interface ContentRepairReceipt {
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[];
+ /** #6865 remove_slug (absent_page): the removed line's slug, recorded as an alias of the page in the same write so links written against it keep resolving. */
+ declared_alias?: string;
}
const SHA = /^[0-9a-f]{64}$/;
const FIX_CODE = /^[A-Z][A-Z_]{0,39}$/;
+const ALIAS = /^[^\s/\u0000-\u001f\u007f][^\s\u0000-\u001f\u007f]{0,254}$/u;
/** 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 {
@@ -49,9 +52,10 @@ export function parseContentRepairReceipt(value: unknown): ContentRepairReceipt
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;
+ if (r.declared_alias !== undefined && (r.action !== 'remove_slug' || typeof r.declared_alias !== 'string' || !ALIAS.test(r.declared_alias))) 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,
- ...(r.style_only !== undefined ? { style_only: [...r.style_only as string[]] } : {}) };
+ ...(r.style_only !== undefined ? { style_only: [...r.style_only as string[]] } : {}), ...(r.declared_alias !== undefined ? { declared_alias: r.declared_alias as string } : {}) };
}
/** `gbrain: repair frontmatter slug in <path>`, the subject of a repaired file's commit. */
diff --git a/src/core/page-state/rename-alias.ts b/src/core/page-state/rename-alias.ts
index 8de4998cc5..5be7b68820 100644
--- a/src/core/page-state/rename-alias.ts
+++ b/src/core/page-state/rename-alias.ts
@@ -32,6 +32,24 @@ export async function recordRenameAlias(
}
}
+/**
+ * #6865: records the slug a removed stray frontmatter `slug:` line declared as an alias of the page its path decides,
+ * inside the caller's write (the content-repair publication). Only while no live page has that slug, and never over an
+ * alias someone already set. A brain whose schema predates slug_aliases skips it inside a savepoint.
+ */
+export async function recordSlugLineAlias(tx: Pick<BrainEngine, 'transaction'>, sourceId: string, alias: string, canonical: string): Promise<void> {
+ if (!alias || alias === canonical) return;
+ try {
+ await tx.transaction(async savepoint => {
+ await savepoint.executeRaw(`INSERT INTO slug_aliases (source_id, alias_slug, canonical_slug, notes)
+ SELECT $1::text, $2::text, $3::text, 'frontmatter_slug_line' WHERE NOT EXISTS (SELECT 1 FROM pages WHERE source_id=$1::text AND slug=$2::text AND deleted_at IS NULL)
+ ON CONFLICT (source_id, alias_slug) DO NOTHING`, [sourceId, alias, canonical]);
+ });
+ } catch (error) {
+ if (!isMissingSchemaObject(error, 'table', 'slug_aliases')) throw error;
+ }
+}
+
/**
* Move the slug-keyed rows that belong to a renamed page (#5431): facts about
* it (`entity_slug`), facts read from its `## Facts` fence
diff --git a/src/core/persistence/file-repair.ts b/src/core/persistence/file-repair.ts
index bba8598a41..13d1a2ac88 100644
--- a/src/core/persistence/file-repair.ts
+++ b/src/core/persistence/file-repair.ts
@@ -75,6 +75,7 @@ import type { SyncRename } from './sync-discovery.ts';
import type { PreparedContentImport } from './prepared-import.ts';
import type { PreparedMutation } from './coordinator.ts';
import { contentRepairCommit, fenceRepairCommit } from './effect-model.ts';
+import { recordSlugLineAlias } from '../page-state/rename-alias.ts';
import type { WriteRequest } from './model.ts';
export interface ManagedFileRepairIntent extends Record<string, unknown> {
@@ -381,6 +382,7 @@ export async function prepareManagedFileRepairMutation(engine: BrainEngine, row:
await tx.executeRaw('UPDATE pages SET source_path=$3 WHERE source_id=$1 AND slug=$2 AND source_path IS DISTINCT FROM $3', [row.source_id, row.slug, p.sourcePath]);
if (!applied.noop) { await project(tx); await sealPageTextProjection(tx, row.slug, row.source_id); }
const holdCleared = await clearGitHold(tx, { sourceId: row.source_id, incarnation: row.source_incarnation, path: p.path, observedAt: p.holdObservedAt ?? new Date().toISOString() });
+ if (contentRepair?.declared_alias) await recordSlugLineAlias(tx, row.source_id, contentRepair.declared_alias, row.slug);
// #6712 PR 1: the record names what is on disk now (the approved bytes), the page revision they produced and the parser, so the next discovery prescreens the file.
const page = await tx.readPageSnapshot(row.slug, { ...source, includeDeleted: true });
if (page && page.page.deleted_at == null) await recordSyncImportProvenance(tx, { source_id: row.source_id, incarnation: row.source_incarnation, page_id: Number(page.page.id), origin: p.sourcePath,
diff --git a/src/core/persistence/sync-fault-class.ts b/src/core/persistence/sync-fault-class.ts
index 10ab3fa521..600561e7b6 100644
--- a/src/core/persistence/sync-fault-class.ts
+++ b/src/core/persistence/sync-fault-class.ts
@@ -60,7 +60,7 @@ export const SYNC_FAULT_TABLE: ReadonlyArray<SyncFaultRule> = [
escalate: `${ESCALATE_AFTER}, or writer status names a step that never finishes`, human_reason: 'The write owner cannot finish preparing this file; writer status names the step, fix or report it.' },
{ code: 'invalid_fence', class: 'page', safe_actions: ['repair'], needs_human: false, escalate: 'the fence repair preview offers no plan (a manual reason)', human_reason: 'Edit the facts or takes table the hold names and commit.' },
{ code: 'invalid_frontmatter', class: 'page', safe_actions: ['repair'], needs_human: false, escalate: 'the repair preview needs an interpretation (--include-ambiguous)', human_reason: 'Approve the proposed frontmatter fix or edit the file.' },
- { code: 'frontmatter_slug_conflict', class: 'page', safe_actions: ['repair'], needs_human: false, escalate: 'the repair preview needs an interpretation', human_reason: 'Decide which page keeps the slug.' },
+ { code: 'frontmatter_slug_conflict', class: 'page', safe_actions: ['repair'], needs_human: false, escalate: 'the content-repair lane recorded what it could not do (an existing named page, other frontmatter fixes, a hand edit)', human_reason: 'The content-repair lane could not clear the hold; its recorded verdict names the page, edit or setting.' },
{ code: 'rename_held', class: 'page', safe_actions: ['repair'], needs_human: false, escalate: 'the repair preview needs an interpretation', human_reason: 'Approve re-binding the rename to the current page.' },
{ code: 'file_too_large', class: 'page', safe_actions: ['none'], needs_human: true, escalate: 'always', human_reason: 'The file is over the page size limit; exclude it with sync.exclude, or split it into files under the limit.' },
{ code: 'content_rejected', class: 'page', safe_actions: ['none'], needs_human: true, escalate: 'always', human_reason: 'The content-sanity gate rejected the file; remove the junk or change junk_disposition.' },
@@ -147,6 +147,45 @@ export interface ContentRepairHoldInput {
type?: string;
path: string;
slug: string | null;
+ /** #6865: the lane version that recorded the verdict, the other frontmatter fix codes (`still_invalid`), a named page with no file. */
+ lane_version?: number;
+ other_codes?: string[];
+ named_db_only?: true;
+}
+
+/** #6865: the content-repair lane's verdict version; a verdict an older lane recorded (or one with none) is rechecked once, never shown as a person's decision. */
+export const CONTENT_REPAIR_LANE_VERSION = 2;
+
+/** Whether this release's lane recorded the verdict. */
+export function contentRepairLaneCurrent(state: { lane_version?: number } | null | undefined): boolean {
+ return (state?.lane_version ?? 1) >= CONTENT_REPAIR_LANE_VERSION;
+}
+
+const SLUG_PAID: ReadonlySet<string> = new Set(['llm_disabled', 'budget_exhausted', 'no_measured_model', 'no_pricing']);
+const SLUG_TRANSIENT: ReadonlySet<string> = new Set(['llm_unavailable', 'ledger_unavailable', 'sync_in_progress', 'claimed_elsewhere', 'changed_since_read', 'changed_since_preview']);
+
+/**
+ * #6865: what a person does about a slug-conflict hold, from what the lane actually found; undefined while an agent or the
+ * lane itself can still clear it (no verdict yet, an older lane's verdict awaiting its recheck, a transient retry), so the
+ * attempts escalation never names a person then. "Decide which page keeps the slug" only when the line names a live page.
+ */
+export function slugConflictEscalation(input: ContentRepairHoldInput | null | undefined): string | undefined {
+ if (!input || !contentRepairLaneCurrent(input) || SLUG_TRANSIENT.has(input.reason)) return undefined;
+ const named = input.named ? `page \`${input.named}\`${input.named_db_only ? ' (a database-only page with no file)' : ''}` : null;
+ if (input.action === 'pending') {
+ if (!SLUG_PAID.has(input.reason)) return undefined;
+ return `\`${input.path}\` declares the slug of ${named ?? 'the page its slug: line names'}; whether they are the same page needs the content-repair model, which waits on a setting only the user changes (${input.reason}). `
+ + `Allow it, or decide which page keeps the slug: delete the slug: line of \`${input.path}\` if they differ, or merge them and delete the duplicate, then commit.`;
+ }
+ if (input.action !== 'remove_slug') return undefined;
+ if (input.reason === 'still_invalid') {
+ return `Removing the slug: line of \`${input.path}\` alone leaves it unimportable${input.other_codes?.length ? ` (the frontmatter also needs ${input.other_codes.join(', ')})` : ''}; `
+ + `the user approves the frontmatter fix (gbrain repair frontmatter --only ${input.path} --include-ambiguous previews it and writes nothing) or edits the file.`;
+ }
+ if (input.reason === 'slug_page_mismatch') {
+ return `Sync files \`${input.path}\` as page \`${input.slug ?? '?'}\`, which its slug: line does not name exactly; make the line name that slug or move the file, then commit.`;
+ }
+ return `gbrain decided to remove the slug: line of \`${input.path}\` but could not write it (${input.reason}); delete the line by hand and commit.`;
}
/**
@@ -166,7 +205,7 @@ export function contentRepairHumanReason(input: ContentRepairHoldInput): string
+ '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: `
+ return `gbrain could not decide whether \`${input.path}\`${other ? ` and page \`${other}\`${input.named_db_only ? ' (a database-only page with no file)' : ''}` : ' 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;
@@ -187,14 +226,16 @@ export function classifySyncFault(input: { code: string; detail?: string | null;
held_for_ms?: number | null;
/** #6712 PR 2: a `worktree_dirty` hold whose uncommitted bytes changed within `HOLD_ESCALATE_MS`: someone is still editing. */
live_editor?: boolean }): SyncFaultVerdict {
- const judged = input.content_repair && input.code === 'frontmatter_slug_conflict' ? contentRepairHumanReason(input.content_repair) : undefined;
+ const slugRepair = input.code === 'frontmatter_slug_conflict' ? input.content_repair : undefined;
+ const judged = slugRepair && contentRepairLaneCurrent(slugRepair) ? contentRepairHumanReason(slugRepair) : undefined;
if (judged) return { class: 'page', safe_actions: ['none'], needs_human: true, human_reason: judged };
+ const slugHuman = input.code === 'frontmatter_slug_conflict' ? slugConflictEscalation(slugRepair) : undefined;
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}.` };
const exhausted = !rule.needs_human && (input.attempts ?? 0) >= HOLD_ATTEMPTS_NEEDS_HUMAN && (input.held_for_ms ?? 0) >= HOLD_ESCALATE_MS && !input.live_editor
- && rule.safe_actions[0] !== 'none' && rule.class === 'page';
+ && rule.safe_actions[0] !== 'none' && rule.class === 'page' && (input.code !== 'frontmatter_slug_conflict' || slugHuman !== undefined);
if (!exhausted) return { class: rule.class, safe_actions: rule.safe_actions, needs_human: rule.needs_human, ...(rule.needs_human && rule.human_reason ? { human_reason: rule.human_reason } : {}) };
return { class: rule.class, safe_actions: ['none'], needs_human: true,
- human_reason: `${(rule.human_reason ?? 'The page keeps moving under the sync.').replace(/\.$/, '')} (held ${input.attempts} times over ${Math.floor(input.held_for_ms! / 3_600_000)} h with code ${rule.code}).` };
+ human_reason: `${(slugHuman ?? rule.human_reason ?? 'The page keeps moving under the sync.').replace(/\.$/, '')} (held ${input.attempts} times over ${Math.floor(input.held_for_ms! / 3_600_000)} h with code ${rule.code}).` };
}
diff --git a/src/core/persistence/sync-holds.ts b/src/core/persistence/sync-holds.ts
index fe8e42b115..ff94580f28 100644
--- a/src/core/persistence/sync-holds.ts
+++ b/src/core/persistence/sync-holds.ts
@@ -166,6 +166,12 @@ export interface ContentHoldRepairState {
model?: string;
at: string;
next_attempt_after: string | null;
+ /** #6865: the content-repair lane version that recorded this verdict (absent: before versioning); an older one is rechecked once. */
+ lane_version?: number;
+ /** #6865 `still_invalid`: the other frontmatter fix codes removing the slug: line alone leaves. */
+ other_codes?: string[];
+ /** #6865: the named page has no file (a database-only page). */
+ named_db_only?: true;
}
export interface GitHoldRecord {
@@ -1031,6 +1037,6 @@ export async function buildHoldReport(engine: Exec, input: { sourceId: string; i
export function syncHoldJsonFields(result: object): Record<string, unknown> {
const fields = result as Record<string, unknown>;
return Object.fromEntries(['held', 'held_count', 'holds_outstanding', 'holds_escalated', 'holds_truncated', 'holds_pending_screen', 'holds_fix',
- 'converted_from_failed', 'recovered_frontmatter', 'fences_normalized', 'fence_issues', 'dry_run', 'would_hold', 'would_hold_count', 'would_normalize', 'would_normalize_count', 'screen_skipped', 'breaker']
+ 'converted_from_failed', 'recovered_frontmatter', 'fences_normalized', 'fence_issues', 'dry_run', 'would_hold', 'would_hold_count', 'would_normalize', 'would_normalize_count', 'screen_skipped', 'breaker', 'slug_lines_removed']
.filter(key => fields[key] !== undefined).map(key => [key, fields[key]]));
}
diff --git a/src/core/repair/content-lane.ts b/src/core/repair/content-lane.ts
index 723ef84f15..0b7bc34e1f 100644
--- a/src/core/repair/content-lane.ts
+++ b/src/core/repair/content-lane.ts
@@ -39,6 +39,7 @@ import { readFix } from '../ops/op-fix.ts';
import { shellQuote } from '../agent-output.ts';
import { fenceHoldStatus, type FenceAutoRepair } from '../fence-repair/hold-fix.ts';
import type { GitHoldRecord } from '../persistence/sync-holds.ts';
+import { contentRepairLaneCurrent } from '../persistence/sync-fault-class.ts';
import type { RepairFailedItem, RepairKind, RepairResult, RepairScope } from './core.ts';
import { repairRunner, type RepairKindSpec } from './registry.ts';
@@ -81,6 +82,8 @@ export function contentHoldDisposition(record: Pick<GitHoldRecord, 'code' | 'met
return { action: 'repair', kind };
}
const stored = storedContentAction(record.meta);
+ // #6865: a verdict an older lane recorded is rechecked once; the recheck records this lane's version, so it is listed again after that.
+ if (!contentRepairLaneCurrent(record.meta.content_repair)) return { action: 'repair', kind };
if (stored === 'merge_into') return { action: 'listed', kind, state: 'needs_human', reason: 'merge_recommended' };
if (stored === 'needs_human') return { action: 'listed', kind, state: 'needs_human', reason: 'content_repair_needs_human' };
return { action: 'repair', kind };
diff --git a/src/core/repair/slug-autoheal.ts b/src/core/repair/slug-autoheal.ts
new file mode 100644
index 0000000000..6c21489bc8
--- /dev/null
+++ b/src/core/repair/slug-autoheal.ts
@@ -0,0 +1,142 @@
+/**
+ * #6865: the sync-time heal of stray frontmatter `slug:` lines. A file whose `slug:` line names a slug other than
+ * its path is held by sync (`frontmatter_slug_conflict`, the anti-spoof screen, unchanged). When the declared slug
+ * names no page and no file (the content-repair lane's deterministic `absent_page` rule), nothing is ambiguous: the
+ * path is the only identity. So right after a managed sync of a source finishes and releases its drain lease, this
+ * removes that one line from each such held file through the lane's managed repair publication (hash-bound bytes,
+ * import under the path slug, hold clear and a `gbrain: repair frontmatter slug in <path>` commit in one coordinated
+ * write) and records the declared slug as an alias of the page, so links written against it keep resolving.
+ *
+ * Scope and guards:
+ * - only `absent_page`; a line naming an existing page (file-backed or database-only), another type, or anything the
+ * model would judge is left exactly as held, with nothing recorded, for the maintenance run and a person;
+ * - only the bytes sync held: a file edited since (a newer draft) waits for the next sync to re-screen it;
+ * - never while the source has an unfinished managed sync cursor (another drainer, or this run's own resumable
+ * stop), and every write re-reads the busy set at admission, so no file whose publication is in flight is edited;
+ * - only under local authority: a sync a remote job or agent submitted defers to the maintenance run;
+ * - bounded: at most `SLUG_HEAL_MAX_FILES` files and `SLUG_HEAL_BUDGET_MS` (or the caller's deadline) per sync, one
+ * checkout scan per source; the rest are counted as pending for the next sync or the maintenance run;
+ * - `sync.slug_conflicts.auto_remove false` turns it off (held until the maintenance run or an operator repairs
+ * them), and so does `fences.repair.enabled false` (the whole lane); a skipped heal says which setting skipped it.
+ * Nothing here runs at upgrade. A failure is counted and never fails the sync whose checkpoint already committed.
+ */
+import type { BrainEngine } from '../engine.ts';
+import type { OperationContext } from '../ops/contract.ts';
+import type { SyncOpts, SyncResult } from '../../commands/sync.ts';
+import { serr } from '../console-prefix.ts';
+import { currentSubmissionAuthority } from '../minions/submission-authority.ts';
+import { readGitSourceHolds } from '../persistence/sync-holds.ts';
+import { FENCE_REPAIR_ENABLED_KEY, fenceRepairEnabled } from '../fence-repair/config.ts';
+import { absentSlugHealRun, healAbsentSlugLine } from './slug-conflicts.ts';
+
+export const SLUG_AUTO_REMOVE_KEY = 'sync.slug_conflicts.auto_remove';
+/** The longest one sync spends healing; a caller deadline that comes sooner wins. */
+export const SLUG_HEAL_BUDGET_MS = 60_000;
+/** The most files one sync heals (each is one coordinated write and one commit); the rest wait for the next pass. */
+export const SLUG_HEAL_MAX_FILES = 200;
+
+const FALSE = /^(false|0|off|no)$/i;
+const TRUE = /^(true|1|on|yes)$/i;
+
+/** `gbrain config set` refusal text for a value that is not a boolean; null when it is one. */
+export function slugAutoRemoveValueRefusal(value: string): string | null {
+ return TRUE.test(value.trim()) || FALSE.test(value.trim()) ? null : `${SLUG_AUTO_REMOVE_KEY} must be true or false (got "${value}"). Nothing was written.`;
+}
+
+export interface SlugHealReport {
+ /** Files whose stray slug: line was removed and which are now indexed under their path slug. */
+ removed: number;
+ /** Held files this pass did not reach (budget, deadline, cancellation); the next sync or the maintenance run takes them. */
+ pending: number;
+ failed: number;
+ /** Held files left as they are, by why (an existing named page, a newer draft, a busy path, ...). */
+ left_by_reason: Record<string, number>;
+ /** Up to 20 of the files healed. */
+ removed_paths: string[];
+ /** Set when the pass did not run, naming why. */
+ skipped?: 'disabled' | 'lane_paused' | 'remote_authority' | 'sync_unfinished' | 'not_writable';
+ notice: string;
+ /** The read-only preview of what the content-repair lane would do with the rest, and the opt-out. */
+ preview_argv: string[];
+ opt_out_argv: string[];
+}
+
+const OK_STATUSES: ReadonlyArray<SyncResult['status']> = ['synced', 'first_sync', 'up_to_date'];
+
+/** One line the sync caller sees, and the same text on the result for `--json`. */
+function noticeOf(sourceId: string, r: Omit<SlugHealReport, 'notice' | 'preview_argv' | 'opt_out_argv'>): string {
+ const left = Object.values(r.left_by_reason).reduce((a, b) => a + b, 0);
+ if (r.skipped) {
+ const why = r.skipped === 'disabled' ? `${SLUG_AUTO_REMOVE_KEY} is false` : r.skipped === 'lane_paused' ? `content repair is paused (${FENCE_REPAIR_ENABLED_KEY} false)`
+ : r.skipped === 'remote_authority' ? 'this sync runs under a remote job or agent, which may import but not rewrite files'
+ : r.skipped === 'sync_unfinished' ? 'the source still has an unfinished sync cursor' : 'this host may not write the source checkout';
+ return `[sync] ${r.pending} held file(s) of source ${sourceId} have a stray frontmatter slug: line; sync left them held because ${why}. `
+ + `Preview the repair with gbrain repair content --source ${sourceId} --no-llm (read-only); the maintenance run applies it when the lane is on.`;
+ }
+ return `[sync] removed the stray frontmatter slug: line of ${r.removed} file(s) in source ${sourceId} that named no page; each is indexed under its path and committed by gbrain`
+ + `${r.pending ? `; ${r.pending} more wait for the next sync` : ''}${r.failed ? `; ${r.failed} failed (gbrain repair content --source ${sourceId} shows why)` : ''}`
+ + `${left ? `; ${left} held file(s) need more than that and stay for the content-repair lane` : ''}. Opt out: gbrain config set ${SLUG_AUTO_REMOVE_KEY} false.`;
+}
+
+/** Whether the source has a managed sync cursor that has not finished (a drain in progress, or a resumable stop). */
+async function unfinishedCursor(engine: BrainEngine, sourceId: string): Promise<boolean> {
+ const rows = await engine.executeRaw(`SELECT 1 FROM op_checkpoints WHERE op='managed-sync' AND COALESCE(completed_keys->0->>'done','false')<>'true'
+ AND completed_keys->0->>'sourceId'=$1 LIMIT 1`, [sourceId]);
+ return rows.length > 0;
+}
+
+/** The post-sync heal of one managed source; returns the result with the report and the held fields it cleared. Never throws. */
+export async function healAfterManagedSync(engine: BrainEngine, outer: SyncOpts, result: SyncResult, now: () => number = Date.now): Promise<SyncResult> {
+ if (outer.dryRun || !OK_STATUSES.includes(result.status)) return result;
+ const sourceId = outer.sourceId ?? 'default';
+ try {
+ const holds = ((await readGitSourceHolds(engine, { sourceIds: [sourceId] }))[0]?.holds ?? []).filter(hold => hold.code === 'frontmatter_slug_conflict');
+ if (!holds.length) return result;
+ const base = { removed: 0, pending: holds.length, failed: 0, left_by_reason: {} as Record<string, number>, removed_paths: [] as string[] };
+ const authority = currentSubmissionAuthority();
+ const skipped: SlugHealReport['skipped'] = FALSE.test(String(await engine.getConfig(SLUG_AUTO_REMOVE_KEY) ?? '').trim()) ? 'disabled'
+ : !(await fenceRepairEnabled(engine)) ? 'lane_paused'
+ : authority && authority.kind !== 'application' ? 'remote_authority'
+ : await unfinishedCursor(engine, sourceId) ? 'sync_unfinished' : undefined;
+ const run = skipped ? null : await absentSlugHealRun(engine, sourceId, { embed: !outer.noEmbed && !outer.embedDeferred && !result.inherited_options?.includes('noEmbed') });
+ if (skipped || !run) return withReport(result, sourceId, { ...base, skipped: skipped ?? 'not_writable' }, []);
+ const { loadConfig } = await import('../config.ts');
+ const ctx = { engine, config: loadConfig() ?? { engine: engine.kind }, logger: { info: () => {}, warn: (m: string) => serr(m), error: (m: string) => serr(m) },
+ remote: false, dryRun: false, sourceId } as unknown as OperationContext;
+ const deadline = Math.min(now() + SLUG_HEAL_BUDGET_MS, outer.deadlineAtMs ?? Infinity);
+ const healed: string[] = [];
+ for (const hold of [...holds].sort((a, b) => a.path.localeCompare(b.path))) {
+ if (healed.length + base.failed >= SLUG_HEAL_MAX_FILES || now() >= deadline || outer.signal?.aborted) break;
+ base.pending--;
+ try {
+ const outcome = await healAbsentSlugLine(ctx, run, hold.path);
+ if (outcome.applied) { healed.push(hold.path); base.removed++; continue; }
+ const reason = outcome.reason ?? outcome.outcome;
+ base.left_by_reason[reason] = (base.left_by_reason[reason] ?? 0) + 1;
+ } catch (error) {
+ base.failed++;
+ serr(`[sync] could not remove the slug: line of ${hold.path}: ${error instanceof Error ? error.message : String(error)}`);
+ }
+ }
+ return withReport(result, sourceId, { ...base, removed_paths: healed.slice(0, 20) }, healed);
+ } catch (error) {
+ serr(`[sync] the stray slug: line heal of source ${sourceId} did not run (${error instanceof Error ? error.message : String(error)}); the maintenance run repairs those files.`);
+ return result;
+ }
+}
+
+/** The result with the heal report, and the held files it cleared taken out of this run's hold fields. */
+function withReport(result: SyncResult, sourceId: string, report: Omit<SlugHealReport, 'notice' | 'preview_argv' | 'opt_out_argv'>, healed: string[]): SyncResult {
+ const notice = noticeOf(sourceId, report);
+ if (report.removed || report.failed || report.skipped === 'lane_paused' || report.skipped === 'remote_authority') serr(notice);
+ const full: SlugHealReport = { ...report, notice, preview_argv: ['gbrain', 'repair', 'content', '--source', sourceId, '--no-llm'], opt_out_argv: ['gbrain', 'config', 'set', SLUG_AUTO_REMOVE_KEY, 'false'] };
+ const gone = new Set(healed);
+ const held = result.held?.filter(item => !gone.has(item.path));
+ const runHealed = (result.held?.length ?? 0) - (held?.length ?? 0);
+ const heldCount = result.held_count !== undefined ? Math.max(0, result.held_count - runHealed) : undefined;
+ const outstanding = result.holds_outstanding !== undefined ? Math.max(0, result.holds_outstanding - healed.length) : undefined;
+ const cleared = !heldCount && !outstanding;
+ return { ...result, slug_lines_removed: full,
+ ...(held ? { held } : {}), ...(heldCount !== undefined ? { held_count: heldCount } : {}), ...(outstanding !== undefined ? { holds_outstanding: outstanding } : {}),
+ ...(cleared && result.holds_fix ? { holds_fix: undefined, holds_escalated: undefined } : {}) };
+}
diff --git a/src/core/repair/slug-conflicts.ts b/src/core/repair/slug-conflicts.ts
index c24dde40fb..4406f89798 100644
--- a/src/core/repair/slug-conflicts.ts
+++ b/src/core/repair/slug-conflicts.ts
@@ -80,9 +80,11 @@ import { callJudgment, CONTENT_REPAIR_MODEL_KEY, judgmentEstimate, judgmentMemoR
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 { CONTENT_REPAIR_LANE_VERSION, contentRepairLaneCurrent } from '../persistence/sync-fault-class.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';
import { gitChildEnv } from '../git-env.ts';
+import { recordSlugLineAlias } from '../page-state/rename-alias.ts';
type Tier = 'deterministic' | 'llm';
type DeterministicRule = 'absent_page' | 'different_type';
@@ -218,6 +220,11 @@ function otherChanges(removal: SlugLineRemoval): string {
return removal.blocking.length ? `the frontmatter also needs ${removal.blocking.join(', ')}` : 'the frontmatter needs other changes too';
}
+/** #6865: the blocking codes as the hold records them (omitted when there are none). */
+function otherCodes(removal: SlugLineRemoval): { other_codes?: string[] } {
+ return removal.blocking.length ? { other_codes: removal.blocking } : {};
+}
+
/** 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 } : {};
@@ -258,7 +265,7 @@ type Analysis =
| { status: 'import'; reason: ImportReason }
| { status: 'deterministic'; rule: DeterministicRule; after: string; style_only: string[] }
| { status: 'llm'; input: JudgmentInput }
- | { status: 'held'; reason: string; message: string; named?: string };
+ | { status: 'held'; reason: string; message: string; named?: string; other_codes?: string[] };
/** #6696 C8: the managed sync screen of a candidate's bytes, exactly as the next sync freezes them; null when `sync.holds=fail` (sync screens nothing). */
type SyncScreen = ((cand: Candidate, content: string) => Promise<ImportScreenResult>) | null;
@@ -329,7 +336,7 @@ async function analyze(cand: Candidate, slugsInCheckout: () => Set<string>, scre
const edit = async (rule: DeterministicRule): Promise<Analysis> => {
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.` };
+ if (after === null) return { status: 'held', reason: 'still_invalid', ...otherCodes(removal), 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, style_only: removal.style_only };
if (screened.refusal.code === 'frontmatter_slug_conflict') return slugPageMismatch(cand, expected, `but its path derives ${expected}`);
@@ -343,7 +350,7 @@ async function analyze(cand: Candidate, slugsInCheckout: () => Set<string>, scre
if (parsed.type !== cand.named.page.type && !shared) return edit('different_type');
}
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.` };
+ if (removal.after === null) return { status: 'held', reason: 'still_invalid', ...otherCodes(removal), 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' } };
@@ -351,10 +358,13 @@ async function analyze(cand: Candidate, slugsInCheckout: () => Set<string>, scre
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;
+/** Records the lane's verdict on the hold, stamped with this lane's version (#6865) and whether the named page has no file. */
async function recordState(engine: BrainEngine, cand: Pick<Candidate, 'src' | 'path' | 'hold'>, state: Omit<ContentHoldRepairState, 'at'>): Promise<void> {
if (!cand.hold) return;
+ const [named] = state.named ? await engine.executeRaw<{ source_path: string | null }>('SELECT source_path FROM pages WHERE source_id=$1 AND slug=$2 AND deleted_at IS NULL LIMIT 1',
+ [cand.src.id, state.named]).catch(() => []) : [];
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);
+ state: { ...state, ...(named && named.source_path == null ? { named_db_only: true as const } : {}), lane_version: CONTENT_REPAIR_LANE_VERSION, at: new Date().toISOString() } }).catch(() => false);
}
function item(entry: ApprovedConflict, index: number, hash: string | null, last: boolean): ConflictItem {
@@ -444,7 +454,7 @@ export const slugConflictsRepair: RepairHandler = {
const analysis = await analyze(cand, slugsInCheckout, screen);
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, ...(analysis.named ? { named: analysis.named } : {}), next_attempt_after: null });
+ await keep({ reason: analysis.reason, tier: 'manual', resolution: analysis.message }, { action: 'remove_slug', reason: analysis.reason, ...(analysis.named ? { named: analysis.named } : {}), ...(analysis.other_codes ? { other_codes: analysis.other_codes } : {}), 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',
@@ -574,7 +584,7 @@ async function applyConflict(ctx: OperationContext, entry: ApprovedConflict, opt
let slugs: Set<string> | null = null;
const analysis = await analyze(cand, () => (slugs ??= src.root ? checkoutSlugs(src.root) : new Set<string>()), await syncScreen(engine, src));
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, ...(analysis.named ? { named: analysis.named } : {}), next_attempt_after: null });
+ if (analysis.status === 'held') return held(analysis.reason, analysis.message, { action: 'remove_slug', reason: analysis.reason, ...(analysis.named ? { named: analysis.named } : {}), ...(analysis.other_codes ? { other_codes: analysis.other_codes } : {}), next_attempt_after: null });
if (analysis.status === 'import') {
// #6696 C8: the clear is bound to the hold observation the plan read; a hold a sync wrote since is kept and retried.
if (opts.expect && cand.hold?.observed_at !== entry.observed_at) {
@@ -585,7 +595,8 @@ 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, ...styleOnly(analysis) }, 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),
+ ...(analysis.rule === 'absent_page' ? declaredAlias(cand) : {}) }, opts, held, { rule: analysis.rule });
}
return judge(ctx, src, cand, analysis.input, entry, opts, held);
}
@@ -597,7 +608,7 @@ 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' | 'style_only'>, 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' | 'declared_alias'>, 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;
@@ -655,6 +666,7 @@ async function write(ctx: OperationContext, src: FenceSource, cand: Candidate, a
return refused(imported.refusal?.code ?? 'error', edits ? 'so the file was restored from its backup' : 'so the hold stays', 'still_invalid');
}
const holdCleared = cand.hold ? await kept(await clearGitHold(engine, { sourceId: src.id, incarnation: src.incarnation, path: cand.path, observedAt: observedAt ?? new Date().toISOString() })) : false;
+ if (parts.declared_alias) await recordSlugLineAlias(engine, src.id, parts.declared_alias, cand.slug);
if (!edits) return { applied: true, outcome: 'repaired', detail: { ...detail, mode: 'legacy', imported: imported.status, hold_cleared: holdCleared, content_repair: receipt }, ...spend };
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 };
@@ -684,7 +696,7 @@ async function judge(ctx: OperationContext, src: FenceSource, cand: Candidate, i
}
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',
+ const out = await held(result.reason, result.message, state && state.reason === result.reason && contentRepairLaneCurrent(state) ? 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 };
}
@@ -709,7 +721,7 @@ async function judge(ctx: OperationContext, src: FenceSource, cand: Candidate, i
if (verdict.action === 'remove_slug') {
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 }); }
+ 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', ...otherCodes(removal), 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);
@@ -726,6 +738,56 @@ async function judge(ctx: OperationContext, src: FenceSource, cand: Candidate, i
return { ...await held(reason, message, state, { action: verdict.action, ...(verdict.action === 'merge_into' ? { canonical: verdict.canonical } : {}), ...why, tier: 'llm' }), ...spend };
}
+/**
+ * #6865: the alias an absent_page removal records in its write (receipt 'declared_alias'): the removed line's slug, so links
+ * written against it keep resolving to the page the path decides; it named no page and no file, and an exact page lookup
+ * still wins. Omitted when it normalizes to nothing or to the page's own slug.
+ */
+function declaredAlias(cand: Pick<Candidate, 'declared' | 'slug'>): { declared_alias?: string } {
+ const alias = slugifyPath(cand.declared);
+ return alias && alias !== cand.slug ? { declared_alias: alias } : {};
+}
+
+/** #6865: what one sync-time heal pass shares across its files: the source, one checkout slug census and the sync screen. */
+export interface AbsentSlugHealRun { src: FenceSource; slugs: () => Set<string>; screen: SyncScreen; embed: boolean }
+
+/** The heal pass over one source, or null when this host may not write it (no managed checkout, another owner, a mirror). */
+export async function absentSlugHealRun(engine: BrainEngine, sourceId: string, opts: { embed: boolean }): Promise<AbsentSlugHealRun | null> {
+ const src = await loadFenceSource(engine, sourceId, { remote: false, work: 'content repair' });
+ if (!src?.managed || !src.root || src.owner || src.mirror) return null;
+ let slugs: Set<string> | null = null;
+ return { src, slugs: () => (slugs ??= checkoutSlugs(src.root!)), screen: await syncScreen(engine, src), embed: opts.embed };
+}
+
+/**
+ * #6865: the sync-time heal of one held file. Only the deterministic `absent_page` removal is written (the declared
+ * slug names no page and no file), bound to the exact bytes sync held: a file edited since (a newer draft in the
+ * working tree) is left for the next sync to re-screen. Every other analysis is left exactly as held, with nothing
+ * recorded, so a model verdict or the maintenance run's own pass is untouched. The write is the lane's managed
+ * repair publication (hash-bound bytes, import, hold clear and commit in one coordinated write, busy re-read at admission).
+ */
+export async function healAbsentSlugLine(ctx: OperationContext, run: AbsentSlugHealRun, path: string): Promise<RepairItemOutcome> {
+ const { src } = run;
+ const left = (reason: string, message: string): RepairItemOutcome => ({ applied: false, outcome: 'skipped', reason, detail: { path, message } });
+ if (repairBusy(src.busy, { path })) return left('sync_in_progress', repairBusyMessage(src.busy, src.id, path));
+ const read = await readCandidate(ctx.engine, src, path);
+ if (!read.ok) return left(read.reason, `${path} is ${read.reason}.`);
+ const cand = read.cand;
+ if (cand.hold?.code !== 'frontmatter_slug_conflict') return left('not_held', `${path} is no longer held for its slug: line.`);
+ if (cand.before !== cand.hold.upstream_version) return left('changed_since_hold', `${path} changed since sync held it; the next sync re-screens the new bytes.`);
+ const analysis = await analyze(cand, run.slugs, run.screen);
+ if (analysis.status !== 'deterministic' || analysis.rule !== 'absent_page') {
+ return left(analysis.status === 'held' || analysis.status === 'skip' ? analysis.reason : analysis.status === 'deterministic' ? analysis.rule : analysis.status,
+ `${path} is not a stray slug: line naming no page; the content-repair lane decides it on the maintenance run.`);
+ }
+ const held: HeldFn = async (reason, message, state, extra = {}) => {
+ if (state) await recordState(ctx.engine, cand, state);
+ return { applied: false, outcome: 'held', reason, detail: { path, message, ...extra } };
+ };
+ return write(ctx, src, cand, analysis.after, { action: 'remove_slug', tier: 'deterministic', confidence: 'high', model: null, cost_usd: 0, ...styleOnly(analysis), ...declaredAlias(cand) },
+ { embed: run.embed, expect: null, noLlm: true }, held, { rule: 'absent_page', trigger: 'sync' });
+}
+
async function reportConflicts(ctx: OperationContext, scope: RepairScope, result: RepairResult) {
const repairedByTier: Record<Tier, number> = { deterministic: 0, llm: 0 };
const remaining: Record<string, number> = {};
diff --git a/test/e2e/slug-autoheal-6865-postgres.test.ts b/test/e2e/slug-autoheal-6865-postgres.test.ts
new file mode 100644
index 0000000000..e6b6efe5ec
--- /dev/null
+++ b/test/e2e/slug-autoheal-6865-postgres.test.ts
@@ -0,0 +1,12 @@
+/** Postgres arm of test/slug-autoheal-6865.test.ts (#6865). */
+import { describe, test } from 'bun:test';
+import { existingPageStopsAndAsks, healNeverEditsInFlight, killSwitchKeepsHold, olderVerdictRecheckedAfterUpgrade, strayLineHealedBySync } from '../helpers/slug-autoheal-scenarios.ts';
+
+const url = process.env.DATABASE_URL;
+describe.skipIf(!url)('Postgres stray frontmatter slug: lines (#6865)', () => {
+ test('the next sync removes a line naming no page and indexes the file under its path', () => strayLineHealedBySync(url), 180_000);
+ test('sync.slug_conflicts.auto_remove false keeps the file held and says so', () => killSwitchKeepsHold(url), 180_000);
+ test('a line naming an existing page (file-backed or database-only) stays held and the verdict names both pages', () => existingPageStopsAndAsks(url), 180_000);
+ test('no edit while the source syncs, the path is busy, the file changed since the hold, or under remote authority', () => healNeverEditsInFlight(url), 180_000);
+ test('a verdict an older gbrain recorded is rechecked, and the next sync heals the file', () => olderVerdictRecheckedAfterUpgrade(url), 180_000);
+});
diff --git a/test/helpers/slug-autoheal-scenarios.ts b/test/helpers/slug-autoheal-scenarios.ts
new file mode 100644
index 0000000000..23a07090eb
--- /dev/null
+++ b/test/helpers/slug-autoheal-scenarios.ts
@@ -0,0 +1,199 @@
+/**
+ * #6865: stray frontmatter `slug:` lines on a managed source. PGLite runs these from test/slug-autoheal-6865.test.ts;
+ * the Postgres arm is test/e2e/slug-autoheal-6865-postgres.test.ts.
+ *
+ * Protects: a held file whose `slug:` line names no page and no file is healed by the next plain sync (line removed,
+ * aliases line left as written, indexed under its path slug, hold cleared, gbrain commit, declared slug kept as an
+ * alias); a line naming an existing page (a file-backed one, and a database-only one) is left held with nothing
+ * recorded, and the lane's later verdict names both pages; the heal never edits a file while its source has an
+ * unfinished sync, its path is busy, it changed since sync held it, or the sync runs under remote authority; a verdict an
+ * older lane recorded is rechecked by the next sync; the kill switch leaves the file held and says so.
+ */
+import { expect } from 'bun:test';
+import { execFileSync } from 'node:child_process';
+import { chmodSync, mkdirSync, readFileSync, writeFileSync } from 'node:fs';
+import { join } from 'node:path';
+import type { BrainEngine } from '../../src/core/engine.ts';
+import type { SyncResult } from '../../src/commands/sync.ts';
+import { performSync } from '../../src/commands/sync/perform.ts';
+import { resolveSlugForPath } from '../../src/core/sync.ts';
+import { localHostId } from '../../src/core/persistence/identity.ts';
+import { runPersistenceEffects } from '../../src/core/persistence/effects.ts';
+import { gitHoldItem, readGitSourceHolds, recordContentHoldRepair, syncHoldJsonFields } from '../../src/core/persistence/sync-holds.ts';
+import { holdVerdict } from '../../src/core/persistence/sync-status.ts';
+import { contentHoldDisposition } from '../../src/core/repair/content-lane.ts';
+import { resolveRepairScope } from '../../src/core/repair/core.ts';
+import { repairRunner } from '../../src/core/repair/registry.ts';
+import { absentSlugHealRun, healAbsentSlugLine } from '../../src/core/repair/slug-conflicts.ts';
+import { healAfterManagedSync, SLUG_AUTO_REMOVE_KEY } from '../../src/core/repair/slug-autoheal.ts';
+import { withSubmissionAuthority } from '../../src/core/minions/submission-authority.ts';
+import { CONTENT_REPAIR_LANE_VERSION } from '../../src/core/persistence/sync-fault-class.ts';
+import { managedBrain, type ManagedBrain } from './managed-brain.ts';
+
+const git = (root: string, ...args: string[]) => execFileSync('git', ['-C', root, ...args], { encoding: 'utf8', stdio: ['ignore', 'pipe', 'pipe'] }).trim();
+const quiet = { info() {}, warn() {}, error() {} };
+
+export const STRAY = 'investors/fund-a.md';
+const ALIASES = 'aliases: ["Fund A", "Fund A Capital"]';
+const STRAY_BYTES = `---\ntitle: "Fund A"\ntype: company\nslug: fund-a\n${ALIASES}\n---\nFund A invests in example companies.\n`;
+const DB_ONLY_HELD = 'companies/fund-b-partners.md';
+const FILE_HELD = 'people/alice-example.md';
+
+/** A git checkout with the fixture committed, before the managed brain claims it; `dbOnly` adds a database-only page `fund-b`. */
+function plant(files: Record<string, string>, dbOnly = false) {
+ return async ({ engine, root }: { engine: BrainEngine; root: string }) => {
+ git(root, 'init', '-q'); git(root, 'config', 'user.name', 'Example'); git(root, 'config', 'user.email', '[email protected]');
+ for (const [path, content] of Object.entries(files)) { mkdirSync(join(root, path, '..'), { recursive: true }); writeFileSync(join(root, path), content); }
+ git(root, 'add', '-A'); git(root, 'commit', '-qm', '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);
+ if (dbOnly) await engine.putPage('fund-b', { type: 'company', title: 'Fund B', compiled_truth: 'Fund B, kept only in the database.', timeline: '' });
+ };
+}
+
+const sync = (engine: BrainEngine) => performSync(engine, { sourceId: 'default', noPull: true, noEmbed: true, noExtract: true } as never);
+const holds = async (engine: BrainEngine) => (await readGitSourceHolds(engine, { sourceIds: ['default'] }))[0]?.holds ?? [];
+const read = (root: string, path: string) => readFileSync(join(root, path), 'utf8');
+
+async function gitEffectsSettled(engine: BrainEngine) {
+ 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='default' AND kind='git' AND state<>'committed'");
+ if (!open.length) return;
+ await Bun.sleep(100);
+ }
+ throw new Error('git effects did not settle');
+}
+
+/** Holds the stray file with the heal off, so a test controls when the heal runs. */
+async function heldWithHealOff(brain: ManagedBrain) {
+ await brain.engine.setConfig(SLUG_AUTO_REMOVE_KEY, 'false');
+ const first = await sync(brain.engine);
+ expect(first.slug_lines_removed).toMatchObject({ skipped: 'disabled', removed: 0, pending: 1 });
+ expect((await holds(brain.engine)).map(hold => [hold.path, hold.code])).toEqual([[STRAY, 'frontmatter_slug_conflict']]);
+ expect(read(brain.root, STRAY)).toBe(STRAY_BYTES);
+ await brain.engine.setConfig(SLUG_AUTO_REMOVE_KEY, 'true');
+}
+
+/** The next plain sync removes a stray slug: line naming no page and indexes the file under its path slug. */
+export async function strayLineHealedBySync(databaseUrl?: string) {
+ await managedBrain(async ({ engine, root }) => {
+ const slug = resolveSlugForPath(STRAY);
+ const result = await sync(engine);
+ expect(result.slug_lines_removed).toMatchObject({ removed: 1, pending: 0, failed: 0, removed_paths: [STRAY] });
+ expect(syncHoldJsonFields(result).slug_lines_removed).toBeDefined();
+ expect(result.held?.some(item => item.path === STRAY) ?? false).toBe(false);
+ expect(await holds(engine)).toEqual([]);
+ const after = read(root, STRAY);
+ expect(after).not.toContain('slug: fund-a');
+ expect(after).toContain(ALIASES);
+ expect(after).toBe(STRAY_BYTES.replace('slug: fund-a\n', ''));
+ expect((await engine.readPageSnapshot(slug, { sourceId: 'default' }))?.page.source_path).toBe(STRAY);
+ expect(await engine.readPageSnapshot('fund-a', { sourceId: 'default' })).toBeNull();
+ const [alias] = await engine.executeRaw<{ canonical_slug: string }>("SELECT canonical_slug FROM slug_aliases WHERE source_id='default' AND alias_slug='fund-a'");
+ expect(alias?.canonical_slug).toBe(slug);
+ await gitEffectsSettled(engine);
+ expect(git(root, 'log', '-1', '--format=%s')).toBe(`gbrain: repair frontmatter slug in ${STRAY}`);
+ expect(git(root, 'status', '--porcelain')).toBe('');
+ const again = await sync(engine);
+ expect(again.slug_lines_removed).toBeUndefined();
+ expect(await holds(engine)).toEqual([]);
+ }, { databaseUrl, setup: plant({ [STRAY]: STRAY_BYTES, 'notes/clean.md': '---\ntitle: Clean\ntype: note\n---\nSee [[fund-a]].\n' }) });
+}
+
+/** The kill switch keeps today's behavior: held, untouched, and the result says which setting skipped the heal. */
+export async function killSwitchKeepsHold(databaseUrl?: string) {
+ await managedBrain(async brain => {
+ await heldWithHealOff(brain);
+ await brain.engine.setConfig(SLUG_AUTO_REMOVE_KEY, 'off');
+ const result = await sync(brain.engine);
+ expect(result.slug_lines_removed?.notice).toContain(`${SLUG_AUTO_REMOVE_KEY} is false`);
+ expect(read(brain.root, STRAY)).toBe(STRAY_BYTES);
+ }, { databaseUrl, setup: plant({ [STRAY]: STRAY_BYTES }) });
+}
+
+/** A slug: line naming an existing page stays held with nothing recorded; the lane's verdict then names both pages. */
+export async function existingPageStopsAndAsks(databaseUrl?: string) {
+ const files = {
+ [DB_ONLY_HELD]: '---\ntitle: Fund B Partners\ntype: company\nslug: fund-b\n---\nFund B Partners notes.\n',
+ 'concepts/fund-c.md': '---\ntitle: Fund C\ntype: concept\n---\nThe Fund C idea.\n',
+ [FILE_HELD]: '---\ntitle: Fund C notes\ntype: concept\nslug: concepts/fund-c\n---\nMore on Fund C.\n',
+ };
+ await managedBrain(async ({ engine, root }) => {
+ const result = await sync(engine);
+ expect(result.slug_lines_removed).toMatchObject({ removed: 0, failed: 0 });
+ expect(Object.values(result.slug_lines_removed!.left_by_reason).reduce((a, b) => a + b, 0)).toBe(2);
+ for (const [path, content] of Object.entries(files)) expect(read(root, path)).toBe(content);
+ const held = await holds(engine);
+ expect(held.map(hold => hold.path).sort()).toEqual([DB_ONLY_HELD, FILE_HELD]);
+ for (const hold of held) expect(hold.meta.content_repair).toBeUndefined();
+ const runner = await repairRunner(engine, { apply: true, noEmbed: true, logger: quiet });
+ await runner.run('slug-conflicts', await resolveRepairScope(engine, 'default'), { explicit: true, sourceFlag: 'default', noLlm: true });
+ const judged = new Map((await holds(engine)).map(hold => [hold.path, hold]));
+ expect(judged.get(DB_ONLY_HELD)!.meta.content_repair).toMatchObject({ action: 'pending', reason: 'llm_disabled', named: 'fund-b', named_db_only: true, lane_version: CONTENT_REPAIR_LANE_VERSION });
+ expect(judged.get(FILE_HELD)!.meta.content_repair).toMatchObject({ action: 'pending', reason: 'llm_disabled', named: 'concepts/fund-c', lane_version: CONTENT_REPAIR_LANE_VERSION });
+ expect(judged.get(FILE_HELD)!.meta.content_repair!.named_db_only).toBeUndefined();
+ const dbOnlyFix = gitHoldItem(judged.get(DB_ONLY_HELD)!).fix;
+ expect(dbOnlyFix.user_message).toContain(DB_ONLY_HELD);
+ expect(dbOnlyFix.user_message).toContain('page fund-b (a database-only page with no file)');
+ expect(dbOnlyFix.argv).toEqual(['gbrain', 'config', 'set', 'fences.repair.llm', 'true']);
+ expect(dbOnlyFix.consent).toEqual(['paid']);
+ const stale = { ...judged.get(FILE_HELD)!, held_at: new Date(Date.now() - 48 * 3_600_000).toISOString(), meta: { ...judged.get(FILE_HELD)!.meta, attempts: 5, first_held_at: new Date(Date.now() - 48 * 3_600_000).toISOString() } };
+ const verdict = holdVerdict(stale, undefined);
+ expect(verdict.needs_human).toBe(true);
+ expect(verdict.human_reason).toContain(FILE_HELD);
+ expect(verdict.human_reason).toContain('page `concepts/fund-c`');
+ expect(verdict.human_reason).toContain('decide which page keeps the slug');
+ for (const [path, content] of Object.entries(files)) expect(read(root, path)).toBe(content);
+ }, { databaseUrl, setup: plant(files, true) });
+}
+
+/** No edit while the source has an unfinished sync, the path is busy, the file changed since the hold, or under remote authority. */
+export async function healNeverEditsInFlight(databaseUrl?: string) {
+ await managedBrain(async brain => {
+ const { engine, root } = brain;
+ await heldWithHealOff(brain);
+ const synced = { status: 'synced', fromCommit: null, toCommit: '', added: 0, modified: 0, deleted: 0, renamed: 0, chunksCreated: 0, embedded: 0, pagesAffected: [] } as SyncResult;
+ const [{ incarnation }] = await engine.executeRaw<{ incarnation: string }>("SELECT incarnation::text AS incarnation FROM sources WHERE id='default'");
+ await engine.executeRaw("INSERT INTO op_checkpoints (op, fingerprint, completed_keys, updated_at) VALUES ('managed-sync', 'test-6865-unfinished', $1::text::jsonb, now())",
+ [JSON.stringify([{ sourceId: 'default', incarnation, done: false, runId: 'test-6865', index: 0 }])]);
+ expect((await healAfterManagedSync(engine, { sourceId: 'default' } as never, synced)).slug_lines_removed).toMatchObject({ skipped: 'sync_unfinished', removed: 0 });
+ await engine.executeRaw("DELETE FROM op_checkpoints WHERE op='managed-sync' AND fingerprint='test-6865-unfinished'");
+ expect(read(root, STRAY)).toBe(STRAY_BYTES);
+ const remote = { version: 1, kind: 'remote_generic' } as never;
+ expect((await withSubmissionAuthority(remote, () => healAfterManagedSync(engine, { sourceId: 'default' } as never, synced))).slug_lines_removed)
+ .toMatchObject({ skipped: 'remote_authority', removed: 0 });
+ expect(read(root, STRAY)).toBe(STRAY_BYTES);
+ const ctx = { engine, config: { engine: engine.kind }, logger: quiet, remote: false, dryRun: false, sourceId: 'default' } as never;
+ const busy = (await absentSlugHealRun(engine, 'default', { embed: false }))!;
+ busy.src.busy.paths.add(STRAY);
+ expect(await healAbsentSlugLine(ctx, busy, STRAY)).toMatchObject({ applied: false, reason: 'sync_in_progress' });
+ expect(read(root, STRAY)).toBe(STRAY_BYTES);
+ const draft = STRAY_BYTES.replace('Fund A invests', 'Fund A (draft) invests');
+ writeFileSync(join(root, STRAY), draft);
+ expect(await healAbsentSlugLine(ctx, (await absentSlugHealRun(engine, 'default', { embed: false }))!, STRAY)).toMatchObject({ applied: false, reason: 'changed_since_hold' });
+ expect(read(root, STRAY)).toBe(draft);
+ expect((await holds(engine)).map(hold => hold.path)).toEqual([STRAY]);
+ }, { databaseUrl, setup: plant({ [STRAY]: STRAY_BYTES }) });
+}
+
+/** A verdict an older gbrain recorded is rechecked: listed or escalated no longer, and the next sync heals the file. */
+export async function olderVerdictRecheckedAfterUpgrade(databaseUrl?: string) {
+ await managedBrain(async brain => {
+ const { engine, root } = brain;
+ await heldWithHealOff(brain);
+ const [hold] = await holds(engine);
+ const at = new Date(Date.now() - 72 * 3_600_000).toISOString();
+ for (const state of [{ action: 'needs_human' as const, reason: 'content_repair_needs_human' }, { action: 'remove_slug' as const, reason: 'still_invalid' }]) {
+ expect(await recordContentHoldRepair(engine, { sourceId: 'default', incarnation: hold!.incarnation, path: STRAY, upstreamVersion: hold!.upstream_version,
+ state: { ...state, at, next_attempt_after: null } })).toBe(true);
+ const [old] = await holds(engine);
+ expect(contentHoldDisposition(old!)).toEqual({ action: 'repair', kind: 'slug-conflicts' });
+ expect(holdVerdict({ ...old!, held_at: at, meta: { ...old!.meta, attempts: 37, first_held_at: at } }, undefined).needs_human).toBe(false);
+ expect(gitHoldItem(old!).fix.why).toContain('rechecks it once on the next sync or maintenance run');
+ }
+ const result = await sync(engine);
+ expect(result.slug_lines_removed).toMatchObject({ removed: 1, removed_paths: [STRAY] });
+ expect(await holds(engine)).toEqual([]);
+ expect(read(root, STRAY)).not.toContain('slug: fund-a');
+ }, { databaseUrl, setup: plant({ [STRAY]: STRAY_BYTES }) });
+}
diff --git a/test/slug-autoheal-6865.test.ts b/test/slug-autoheal-6865.test.ts
new file mode 100644
index 0000000000..0118209c58
--- /dev/null
+++ b/test/slug-autoheal-6865.test.ts
@@ -0,0 +1,11 @@
+/** PGLite arm of the #6865 stray slug: line scenarios (test/helpers/slug-autoheal-scenarios.ts); Postgres: test/e2e/slug-autoheal-6865-postgres.test.ts. */
+import { describe, test } from 'bun:test';
+import { existingPageStopsAndAsks, healNeverEditsInFlight, killSwitchKeepsHold, olderVerdictRecheckedAfterUpgrade, strayLineHealedBySync } from './helpers/slug-autoheal-scenarios.ts';
+
+describe('PGLite stray frontmatter slug: lines (#6865)', () => {
+ test('the next sync removes a line naming no page and indexes the file under its path', () => strayLineHealedBySync(), 180_000);
+ test('sync.slug_conflicts.auto_remove false keeps the file held and says so', () => killSwitchKeepsHold(), 180_000);
+ test('a line naming an existing page (file-backed or database-only) stays held and the verdict names both pages', () => existingPageStopsAndAsks(), 180_000);
+ test('no edit while the source syncs, the path is busy, the file changed since the hold, or under remote authority', () => healNeverEditsInFlight(), 180_000);
+ test('a verdict an older gbrain recorded is rechecked, and the next sync heals the file', () => olderVerdictRecheckedAfterUpgrade(), 180_000);
+});
diff --git a/test/slug-conflict-verdict-6865.test.ts b/test/slug-conflict-verdict-6865.test.ts
new file mode 100644
index 0000000000..977bef0dc5
--- /dev/null
+++ b/test/slug-conflict-verdict-6865.test.ts
@@ -0,0 +1,63 @@
+/**
+ * #6865: slug-conflict hold status says what the content-repair lane found.
+ * Protects: no verdict (or an older lane's verdict) never escalates to a person after repeated attempts; "decide which page
+ * keeps the slug" appears only when the line names a live page; `still_invalid` names the other fix codes and routes to the
+ * frontmatter preview; a database-only named page is labelled; an older lane's model verdict is rechecked, not listed.
+ * Fails when: status pages a person for a hold whose own fix is an agent-runnable step, or names a second page that does not exist.
+ */
+import { describe, expect, test } from 'bun:test';
+import { classifySyncFault, CONTENT_REPAIR_LANE_VERSION, slugConflictEscalation } from '../src/core/persistence/sync-fault-class.ts';
+import { contentHoldFix } from '../src/core/content-repair/hold-fix.ts';
+import { contentHoldDisposition } from '../src/core/repair/content-lane.ts';
+import type { ContentHoldRepairState, GitHoldRecord } from '../src/core/persistence/sync-holds.ts';
+
+const PATH = 'companies/acme-example.md';
+const stale = { attempts: 37, held_for_ms: 55 * 3_600_000 };
+const state = (s: Partial<ContentHoldRepairState>): ContentHoldRepairState => ({ action: 'remove_slug', reason: 'still_invalid', at: '2026-10-16T00:00:00.000Z', next_attempt_after: null, lane_version: CONTENT_REPAIR_LANE_VERSION, ...s });
+const input = (s: ContentHoldRepairState) => ({ ...s, path: PATH, slug: 'companies/acme-example' });
+const record = (s?: ContentHoldRepairState) => ({ code: 'frontmatter_slug_conflict', meta: s ? { content_repair: s } : {} }) as unknown as Pick<GitHoldRecord, 'code' | 'meta'>;
+
+describe('#6865 slug-conflict verdicts', () => {
+ test('a hold the lane has not judged never escalates to a person, and the fix is the agent preview', () => {
+ const verdict = classifySyncFault({ code: 'frontmatter_slug_conflict', ...stale });
+ expect(verdict.needs_human).toBe(false);
+ expect(verdict.human_reason).toBeUndefined();
+ const fix = contentHoldFix({ source_id: 'default', path: PATH, meta: {} });
+ expect(fix.actor).toBe('agent');
+ expect(fix.why).toContain('removed by the next managed sync itself');
+ });
+
+ test('still_invalid names the other fix codes, routes to the frontmatter preview, and escalates without naming a second page', () => {
+ const s = state({ other_codes: ['INVALID_DATE'] });
+ const verdict = classifySyncFault({ code: 'frontmatter_slug_conflict', ...stale, content_repair: input(s) });
+ expect(verdict.needs_human).toBe(true);
+ expect(verdict.human_reason).toContain('INVALID_DATE');
+ expect(verdict.human_reason).not.toContain('Decide which page keeps the slug');
+ expect(verdict.human_reason).not.toContain('decide which page keeps the slug');
+ const fix = contentHoldFix({ source_id: 'default', path: PATH, meta: { content_repair: s } });
+ expect(fix.argv).toEqual(['gbrain', 'repair', 'frontmatter', '--source', 'default', '--only', PATH, '--include-ambiguous']);
+ expect(fix.why).toContain('INVALID_DATE');
+ });
+
+ test('only a named live page earns "decide which page keeps the slug", with a database-only page labelled', () => {
+ const named = state({ action: 'pending', reason: 'llm_disabled', named: 'fund-a', named_db_only: true });
+ expect(slugConflictEscalation(input(named))).toContain('page `fund-a` (a database-only page with no file)');
+ expect(slugConflictEscalation(input(named))).toContain('decide which page keeps the slug');
+ expect(slugConflictEscalation(input(state({ action: 'pending', reason: 'llm_disabled' })))).not.toContain('page `');
+ for (const reason of ['sync_in_progress', 'changed_since_read', 'llm_unavailable']) {
+ expect(classifySyncFault({ code: 'frontmatter_slug_conflict', ...stale, content_repair: input(state({ action: 'pending', reason })) }).needs_human).toBe(false);
+ }
+ });
+
+ test('an older lane verdict is rechecked once instead of listed for a person', () => {
+ const old = state({ action: 'needs_human', reason: 'content_repair_needs_human', named: 'fund-a', lane_version: undefined });
+ expect(contentHoldDisposition(record(old))).toEqual({ action: 'repair', kind: 'slug-conflicts' });
+ expect(classifySyncFault({ code: 'frontmatter_slug_conflict', ...stale, content_repair: input(old) }).needs_human).toBe(false);
+ const fix = contentHoldFix({ source_id: 'default', path: PATH, meta: { content_repair: old } });
+ expect(fix.actor).toBe('agent');
+ expect(fix.user_message).toBeUndefined();
+ const current = { ...old, lane_version: CONTENT_REPAIR_LANE_VERSION };
+ expect(contentHoldDisposition(record(current))).toMatchObject({ action: 'listed', state: 'needs_human' });
+ expect(classifySyncFault({ code: 'frontmatter_slug_conflict', content_repair: input(current) }).needs_human).toBe(true);
+ });
+});