Garry's Opinionated OpenClaw/Hermes Agent Brain
TypeScript
wip(#6865): review fixes: YAML-read declared slug, publication recheck of the declared slug, bounded blob slices, restart a moved scan, never schedule collisions or deleted pages, heal only unjudged holds
garrytancee094e8dfb4
diff --git a/src/commands/doctor/checks/unindexed-files.ts b/src/commands/doctor/checks/unindexed-files.tsindex abd420627e..ab59b4a2ee 100644--- a/src/commands/doctor/checks/unindexed-files.ts+++ b/src/commands/doctor/checks/unindexed-files.ts@@ -47,6 +47,16 @@ function sourceLine(state: UnindexedState): string {+ `${hours(state.age_ms)} h ago${samples ? `; e.g. ${samples}` : ''})`;}+/** The read-only note on files a re-screen cannot import (slug collisions, deleted pages), or '' when there are none. */+function blockedNote(states: UnindexedState[]): string {+ const found = states.filter(state => state.state !== 'missing' && state.blocked);+ if (!found.length) return '';+ const samples = found.flatMap(state => state.record!.samples.filter(sample => sample.slug_taken || sample.deleted_page).slice(0, 3)+ .map(sample => `${state.source_id}:${sample.path} (${sample.slug_taken ? 'its slug belongs to another page' : 'its page was deleted'})`)).slice(0, 5).join(', ');+ return `${found.reduce((n, state) => n + state.blocked, 0)} committed file(s) cannot be imported as they are${samples ? ` (e.g. ${samples})` : ''}: `+ + 'rename one of two files that share a slug, or delete the file of a deleted page (or restore the page with gbrain restore), commit, then sync.';+}+/** The read-only note on scaffolding-named files sync skips on purpose, or '' when there are none. */function metafileNote(states: UnindexedState[]): string {const found = states.filter(state => state.state !== 'missing' && state.record?.metafile_skipped);@@ -76,9 +86,9 @@ async function runUnindexedFiles(ctx: DoctorContext): Promise<Check[]> {const states = await judgeUnindexedFiles(engine, sources);const details = { docs: DOCS, sources: states.map(({ source_id, state, record, ...rest }) => !record || state === 'missing' ? { source_id, state }: { source_id, state, unscheduled: rest.unscheduled, waiting: rest.waiting, still_unindexed: rest.still_unindexed, age_hours: hours(rest.age_ms), complete: record.complete,- scanned: record.scanned, unindexed: record.unindexed, slug_taken: record.slug_taken, by_code: record.by_code, samples: record.samples, target: record.target, computed_at: record.computed_at,+ scanned: record.scanned, unindexed: record.unindexed, slug_taken: record.slug_taken, deleted_page: record.deleted_page ?? 0, by_code: record.by_code, samples: record.samples, target: record.target, computed_at: record.computed_at,metafile_skipped: record.metafile_skipped ?? 0, metafile_samples: record.metafile_samples ?? [] }) };- const scaffolding = metafileNote(states);+ const scaffolding = [blockedNote(states), metafileNote(states)].filter(Boolean).join(' ');const unindexed = states.filter(state => state.state === 'unindexed');const waiting = states.filter(state => state.state === 'scheduled');if (unindexed.length || waiting.length) {@@ -90,7 +100,7 @@ async function runUnindexedFiles(ctx: DoctorContext): Promise<Check[]> {checks.push({ name: 'unindexed_files', status: 'warn', details, fix,message: `Committed files in managed Git sources have no page and no hold, so they are missing from search: ${[...unindexed, ...waiting].map(sourceLine).join('; ')}. `+ 'Usually an older gbrain refused them before refusals became holds. Schedule them with gbrain sources retry-held <id> --unindexed, then run the sync it prints: '- + 'each file then imports or is held with its reason (a file sharing a slug with another page stays out until one of them is renamed).'+ + 'each file then imports or is held with its reason.'+ (scaffolding ? ` ${scaffolding}` : '') });return checks;}@@ -106,12 +116,14 @@ async function runUnindexedFiles(ctx: DoctorContext): Promise<Check[]> {return checks;}if (scaffolding) {- const first = states.find(state => state.record?.metafile_skipped)!;+ const first = states.find(state => state.record?.metafile_skipped || state.blocked)!;+ const metafile = first.record!.metafile_skipped ? first.record!.metafile_samples[0] : undefined;checks.push(infoCheck('unindexed_files', `Every other committed file of ${states.length} managed Git source(s) is indexed, held or excluded. ${scaffolding}`, 'degraded', {argv: await gitFollowUpSync(engine, first.source_id, []), consent: [], actor: 'user', requires_exclusive: false, verify: doctorVerify('unindexed_files'), docs: DOCS,- why: 'Sync skips index.md and the other scaffolding names on purpose; a file renamed to an ordinary name is imported by the next sync.',- user_message: `Sync skips files named index.md (and README.md, schema.md, log.md, RESOLVER.md) on purpose, as folder scaffolding, so ${first.record!.metafile_samples[0]} is not in search. `- + 'To index such a file, rename it, for example investors/fund-a/index.md -> investors/fund-a.md, commit, then run this sync.' }, details));+ why: metafile ? 'Sync skips index.md and the other scaffolding names on purpose; a file renamed to an ordinary name is imported by the next sync.'+ : 'A re-screen cannot import these files as they are; after the rename, delete or restore is committed, the next sync settles them.',+ user_message: metafile ? `Sync skips files named index.md (and README.md, schema.md, log.md, RESOLVER.md) on purpose, as folder scaffolding, so ${metafile} is not in search. `+ + 'To index such a file, rename it, for example investors/fund-a/index.md -> investors/fund-a.md, commit, then run this sync.' : blockedNote([first]) }, details));return checks;}checks.push({ name: 'unindexed_files', status: 'ok', details,diff --git a/src/core/persistence/file-repair.ts b/src/core/persistence/file-repair.tsindex 13d1a2ac88..8dd63b7785 100644--- a/src/core/persistence/file-repair.ts+++ b/src/core/persistence/file-repair.ts@@ -41,7 +41,7 @@* the source root and walked component by component with `lstat`, so a* symlinked directory or file is never written through.*/-import { lstatSync, readFileSync } from 'node:fs';+import { existsSync, lstatSync, readFileSync } from 'node:fs';import { basename, isAbsolute, join, resolve, sep } from 'node:path';import type { BrainEngine } from '../engine.ts';import type { GBrainConfig } from '../config.ts';@@ -113,6 +113,20 @@ const ownerStatusFix = (sourceId: string): Action => readFix(`Shows source ${souconst previewFix = (sourceId: string, kind: FileRepairKind): Action => ({ argv: ['gbrain', 'repair', kind, '--source', sourceId], consent: [], actor: 'agent',requires_exclusive: false, why: `Previews the ${WORK[kind]} repair of source ${sourceId} again from the files as they are now; nothing is written.` });+/**+ * #6865: a stray slug-line removal whose receipt records the declared alias (the sync-time `absent_page` heal) publishes+ * only while that slug still names no page, no alias of another page and no file at its path: one written since the heal+ * read the source refuses the write, and the next run judges the file again.+ */+async function assertDeclaredSlugAbsent(tx: BrainEngine, sourceId: string, root: string, p: { path: string; sourcePath: string }, alias: string, slug: string, kind: FileRepairKind) {+ const named = await tx.readPageSnapshot(alias, { sourceId, resolveAlias: true });+ if (named && named.page.slug !== slug) throw changedSincePreview(sourceId, p.path, `its slug: line now names page ${named.page.slug}`, kind);+ const prefix = p.sourcePath.endsWith(p.path) ? p.sourcePath.slice(0, p.sourcePath.length - p.path.length) : '';+ const rel = prefix && alias.startsWith(prefix) ? alias.slice(prefix.length) : alias;+ const file = ['.md', '.mdx'].map(ext => rel + ext).find(candidate => candidate !== p.path && existsSync(join(root, candidate)));+ if (file) throw changedSincePreview(sourceId, p.path, `its slug: line now names the file ${file}`, kind);+}+function changedSincePreview(sourceId: string, path: string, why: string, kind: FileRepairKind) {return opError('changed_since_preview', `${path} changed since its repair was previewed: ${why}.`,`Nothing was written for ${path}. Preview again with gbrain repair ${kind} --source ${sourceId}, review the new proposal, and approve its new hash.`,@@ -364,6 +378,7 @@ export async function prepareManagedFileRepairMutation(engine: BrainEngine, row:`Source ${row.source_id}'s canonical owner changed while repair request ${row.request_id} was prepared, so it published nothing. Check the owner, then preview the repair again.`,{ fix: ownerStatusFix(row.source_id) });checkFile();+ if (contentRepair?.declared_alias) await assertDeclaredSlugAbsent(tx, row.source_id, root, p, contentRepair.declared_alias, row.slug, kind);await assertRenameSource(tx);await ready.validate(tx);},diff --git a/src/core/persistence/unindexed-files.ts b/src/core/persistence/unindexed-files.tsindex 6cd69316ce..0655a4c0ca 100644--- a/src/core/persistence/unindexed-files.ts+++ b/src/core/persistence/unindexed-files.ts@@ -11,7 +11,11 @@* source-path space: a file counts as indexed when a live page records its* origin, held when it has a sync hold, and `scheduled` when a re-screen is* already requested for it. A file whose path slug belongs to a live page with- * another or no origin is not indexed either; it is counted as `slug_taken`.+ * another or no origin is not indexed either; it is counted as `slug_taken`,+ * and one whose page was deleted while the file stayed committed as+ * `deleted_page`. Neither is ever scheduled: a re-screen cannot import them+ * (a collision, or a page sync keeps deleted), so a person renames, deletes or+ * restores, and doctor names them read-only.* Lookups run in batches on the existing indexes, never over every page at* once. A file sync skips on purpose as folder scaffolding (`index.md`,* `README.md` and the other `isSyncMetafile` names) that would otherwise be eligible@@ -29,7 +33,10 @@* write) and stores the result per source in `op_checkpoints` (op* `unindexed-files`), where doctor `unindexed_files` reads it through* `judgeUnindexedFiles`. An incomplete stored result is continued and- * accumulated by the next pass.+ * accumulated by the next pass while its target commit and eligibility+ * fingerprint are unchanged; otherwise the pass starts over. Blobs are read+ * and screened in slices bounded by bytes, with the deadline checked between+ * slices (a file left unread counts as `unscreened`).*/import type { BrainEngine } from '../engine.ts';import type { SyncOpts } from '../../commands/sync.ts';@@ -43,6 +50,7 @@ import { loadSyncEligibility, resolveManagedSyncContext, syncExcludePatterns, tyimport { heldGitPaths, readGitHoldRetryPaths, requestGitHoldRetry } from './sync-holds.ts';import { readBlobContents, type TreeBlob } from './sync-blobs.ts';import { isWindowsColonTarget } from './native-file-target.ts';+import { createHash } from 'node:crypto';export const UNINDEXED_FILES_OP = 'unindexed-files';/** Paths one pass schedules for a re-screen, and the most scheduled paths a stored result names. */@@ -55,15 +63,19 @@ export const UNINDEXED_SCAN_BUDGET_MS = 60_000;/** A stored result older than this is stale. */export const UNINDEXED_STALE_MS = 7 * 24 * 3_600_000;const BATCH = 1_000;+/** Blob bytes one screening slice holds in memory at most (a single larger blob is read alone); each slice is released before the next. */+const SCREEN_SLICE_BYTES = 32 * 1024 ** 2;-export interface UnindexedFile { path: string; source_path: string; code: string; slug_taken: boolean }-export interface UnindexedSample { path: string; code: string; slug_taken?: true }+export interface UnindexedFile { path: string; source_path: string; code: string; slug_taken: boolean; deleted_page: boolean }+export interface UnindexedSample { path: string; code: string; slug_taken?: true; deleted_page?: true }export interface UnindexedScan {source_id: string;incarnation: string;/** The commit whose tree was scanned (the source's last synced commit); null when the source never synced. */target: string | null;+ /** Fingerprint of what decides eligibility (scope, slug mode, sync excludes); a continuation needs the same one. */+ eligibility: string;complete: boolean;/** The last Git path examined when the budget stopped the scan; null when complete. */cursor: string | null;@@ -71,8 +83,10 @@ export interface UnindexedScan {scanned: number;/** Files with no page, no hold and no scheduled re-screen. */unindexed: number;- /** Of `unindexed`: the path slug belongs to a live page with another or no recorded origin. */+ /** Of `unindexed`: the path slug belongs to a live page with another or no recorded origin; never scheduled (a re-screen cannot import it). */slug_taken: number;+ /** Of `unindexed`: the file's page was deleted while the file stayed committed; never scheduled (sync keeps the page deleted). */+ deleted_page: number;/** Files with no page and no hold whose re-screen is already scheduled. */scheduled: number;by_code: Record<string, number>;@@ -118,6 +132,16 @@ export interface UnindexedRecord extends Omit<UnindexedScan, 'files' | 'scheduleinterface TreeEntry { path: string; oid: string; size: number }+/** Reads `entries` in slices of at most `SCREEN_SLICE_BYTES` and visits each with its text (undefined when too large to read); stops before a slice once `stop()` is true. */+function visitBlobSlices<T extends TreeBlob>(gitRoot: string, entries: T[], visit: (entry: T, content: string | undefined) => void, stop: () => boolean): void {+ for (let i = 0; i < entries.length && !stop();) {+ const slice: T[] = [];+ for (let bytes = 0; i < entries.length && (!slice.length || bytes + entries[i]!.size <= SCREEN_SLICE_BYTES); i++) { bytes += entries[i]!.size; slice.push(entries[i]!); }+ const contents = readBlobContents(gitRoot, slice);+ for (const entry of slice) visit(entry, contents.get(entry.oid));+ }+}+/** The blobs of `target` under `scope` in tree order, after `after`, in batches; the child stops when the consumer does. */async function* treeBatches(gitRoot: string, target: string, scope: string, after: string | null, size: number): AsyncGenerator<TreeEntry[]> {const child = spawn('git', ['-c', 'core.quotepath=false', '--literal-pathspecs', '-C', gitRoot, 'ls-tree', '-r', '-l', '-z', target, ...(scope ? ['--', scope] : [])],@@ -149,6 +173,8 @@ async function* treeBatches(gitRoot: string, target: string, scope: string, afte}}+const eligibilityKey = (scope: string, slugMode: string, exclude: string[]) => createHash('sha256').update(JSON.stringify([scope, slugMode, exclude])).digest('hex').slice(0, 16);+/** Files of one managed Git source with no live page, no hold and no scheduled re-screen; bounded by `opts`. */export async function findUnindexedFiles(engine: BrainEngine, sourceId: string, opts: UnindexedScanOpts = {}): Promise<UnindexedScan> {const context = opts.context ?? await resolveManagedSyncContext(engine, { sourceId, noPull: true } as SyncOpts);@@ -156,14 +182,15 @@ export async function findUnindexedFiles(engine: BrainEngine, sourceId: string,const now = opts.now ?? Date.now;const keep = opts.keep ?? UNINDEXED_SCHEDULE_CAP;const screenLimit = opts.screenLimit ?? UNINDEXED_SCREEN_LIMIT;- const scan: UnindexedScan = { source_id: sourceId, incarnation, target: context.source.last_commit, complete: true, cursor: null, scanned: 0, unindexed: 0,- slug_taken: 0, scheduled: 0, by_code: {}, samples: [], metafile_skipped: 0, metafile_samples: [], files: [], scheduled_paths: [] };- if (!scan.target) return scan;const { scope, slugMode, eligible, sourcePath } = await loadSyncEligibility(engine, context);const exclude = await syncExcludePatterns(engine);+ const scan: UnindexedScan = { source_id: sourceId, incarnation, target: context.source.last_commit, eligibility: eligibilityKey(scope, slugMode, exclude), complete: true, cursor: null, scanned: 0, unindexed: 0,+ slug_taken: 0, deleted_page: 0, scheduled: 0, by_code: {}, samples: [], metafile_skipped: 0, metafile_samples: [], files: [], scheduled_paths: [] };+ if (!scan.target) return scan;const scaffolding = (path: string) => isSyncMetafile(path) && !matchesAnyGlob(scope ? path.slice(scope.length + 1) : path, exclude)&& !isReservedSkillBundlePath(sourcePath(path)) && eligible(`${path.slice(0, path.lastIndexOf('/') + 1)}gbrain-metafile-probe${path.slice(path.lastIndexOf('.'))}`);const retry = new Set(await readGitHoldRetryPaths(engine, sourceId, incarnation));+ const pastDeadline = () => opts.deadlineAt !== undefined && now() >= opts.deadlineAt;let screened = 0;for await (const batch of treeBatches(gitRoot, scan.target, scope, opts.cursor ?? null, opts.batch ?? BATCH)) {const rows = batch.filter(entry => eligible(entry.path) && !isWindowsColonTarget(entry.path)).map(entry => {@@ -177,13 +204,12 @@ export async function findUnindexedFiles(engine: BrainEngine, sourceId: string,[sourceId, metafiles.map(entry => sourcePath(entry.path))])).map(page => page.source_path));const unread = metafiles.filter(entry => !indexed.has(sourcePath(entry.path))).slice(0, Math.max(0, screenLimit - screened));screened += unread.length;- const contents = readBlobContents(gitRoot, unread.map((entry): TreeBlob => ({ oid: entry.oid, size: entry.size })));- for (const entry of unread) {- const frontmatter = parseMarkdownHead(contents.get(entry.oid) ?? '').frontmatter;- if (frontmatter.type == null && frontmatter.title == null) continue;+ visitBlobSlices(gitRoot, unread, (entry, content) => {+ const frontmatter = parseMarkdownHead(content ?? '').frontmatter;+ if (frontmatter.type == null && frontmatter.title == null) return;scan.metafile_skipped++;if (scan.metafile_samples.length < UNINDEXED_SAMPLE_LIMIT) scan.metafile_samples.push(scope ? entry.path.slice(scope.length + 1) : entry.path);- }+ }, () => false);}if (rows.length) {const origins = rows.flatMap(row => row.legacy ? [row.origin, row.legacy] : [row.origin]);@@ -201,25 +227,27 @@ export async function findUnindexedFiles(engine: BrainEngine, sourceId: string,const slugs = fresh.map(row => resolveSlugForPath(row.origin)).filter(Boolean);const taken = new Set(slugs.length ? (await engine.executeRaw<{ slug: string }>('SELECT slug FROM pages WHERE source_id=$1 AND deleted_at IS NULL AND slug = ANY($2::text[])', [sourceId, slugs])).map(page => page.slug) : []);+ const deleted = new Set(fresh.length ? (await engine.executeRaw<{ source_path: string }>(+ 'SELECT source_path FROM pages WHERE source_id=$1 AND deleted_at IS NOT NULL AND source_path = ANY($2::text[])', [sourceId, fresh.map(row => row.origin)])).map(page => page.source_path) : []);const toScreen = fresh.slice(0, Math.max(0, screenLimit - screened));screened += toScreen.length;- const contents = readBlobContents(gitRoot, toScreen.map((row): TreeBlob => ({ oid: row.oid, size: row.size })));- const codes = new Map(toScreen.map(row => {- const content = contents.get(row.oid);- if (content === undefined) return [row.root, 'file_too_large'];+ const codes = new Map<string, string>();+ visitBlobSlices(gitRoot, toScreen, (row, content) => {+ if (content === undefined) { codes.set(row.root, 'file_too_large'); return; }const result = screenImportContent({ content, path: row.origin, byteLength: row.size, expectedSlug: resolveSlugForPath(row.origin) || null });- return [row.root, result.status === 'refused' ? result.refusal.code : 'clean'];- }));+ codes.set(row.root, result.status === 'refused' ? result.refusal.code : 'clean');+ }, pastDeadline);for (const row of fresh) {- const code = codes.get(row.root) ?? 'unscreened', slugTaken = taken.has(resolveSlugForPath(row.origin));+ const code = codes.get(row.root) ?? 'unscreened', slugTaken = taken.has(resolveSlugForPath(row.origin)), deletedPage = deleted.has(row.origin);scan.unindexed++;if (slugTaken) scan.slug_taken++;+ if (deletedPage) scan.deleted_page++;scan.by_code[code] = (scan.by_code[code] ?? 0) + 1;- if (scan.samples.length < UNINDEXED_SAMPLE_LIMIT) scan.samples.push({ path: row.root, code, ...(slugTaken ? { slug_taken: true as const } : {}) });- if (scan.files.length < keep) scan.files.push({ path: row.root, source_path: row.origin, code, slug_taken: slugTaken });+ if (scan.samples.length < UNINDEXED_SAMPLE_LIMIT) scan.samples.push({ path: row.root, code, ...(slugTaken ? { slug_taken: true as const } : {}), ...(deletedPage ? { deleted_page: true as const } : {}) });+ if (scan.files.length < keep) scan.files.push({ path: row.root, source_path: row.origin, code, slug_taken: slugTaken, deleted_page: deletedPage });}}- if ((opts.deadlineAt !== undefined && now() >= opts.deadlineAt) || (opts.maxScanned !== undefined && scan.scanned >= opts.maxScanned)) {+ if (pastDeadline() || (opts.maxScanned !== undefined && scan.scanned >= opts.maxScanned)) {scan.complete = false;scan.cursor = batch[batch.length - 1]!.path;break;@@ -252,17 +280,21 @@ export async function refreshUnindexedFiles(engine: BrainEngine, sourceId: strinconst context = opts.context ?? await resolveManagedSyncContext(engine, { sourceId, noPull: true } as SyncOpts);const now = opts.now ?? Date.now;const stored = (await readUnindexedFiles(engine, [sourceId])).get(sourceId);- const previous = stored && !stored.complete && stored.incarnation === context.incarnation && stored.cursor ? stored : null;+ const eligibility = await loadSyncEligibility(engine, context);+ const key = eligibilityKey(eligibility.scope, eligibility.slugMode, await syncExcludePatterns(engine));+ const previous = stored && !stored.complete && stored.incarnation === context.incarnation && stored.cursor+ && stored.target === context.source.last_commit && stored.eligibility === key ? stored : null;const scan = await findUnindexedFiles(engine, sourceId, { ...opts, context, cursor: previous?.cursor ?? null });- const scheduled = opts.schedule === false ? [] : scan.files.map(file => file.path);+ const scheduled = opts.schedule === false ? [] : scan.files.filter(file => !file.slug_taken && !file.deleted_page).map(file => file.path);if (scheduled.length) await requestGitHoldRetry(engine, sourceId, context.incarnation, scheduled);const pending = [...new Set([...(previous?.pending ?? []), ...scan.scheduled_paths, ...scheduled])];- const { scope, slugMode } = await loadSyncEligibility(engine, context);+ const { scope, slugMode } = eligibility;const at = new Date(now()).toISOString();const record: UnindexedRecord = {- version: 1, source_id: sourceId, incarnation: context.incarnation, target: scan.target, complete: scan.complete, cursor: scan.cursor,+ version: 1, source_id: sourceId, incarnation: context.incarnation, target: scan.target, eligibility: scan.eligibility, complete: scan.complete, cursor: scan.cursor,started_at: previous?.started_at ?? at, computed_at: at,scanned: (previous?.scanned ?? 0) + scan.scanned, unindexed: (previous?.unindexed ?? 0) + scan.unindexed, slug_taken: (previous?.slug_taken ?? 0) + scan.slug_taken,+ deleted_page: (previous?.deleted_page ?? 0) + scan.deleted_page,scheduled: (previous?.scheduled ?? 0) + scan.scheduled, by_code: addCounts(previous?.by_code ?? {}, scan.by_code),samples: [...(previous?.samples ?? []), ...scan.samples].slice(0, UNINDEXED_SAMPLE_LIMIT),metafile_skipped: (previous?.metafile_skipped ?? 0) + scan.metafile_skipped,@@ -283,8 +315,10 @@ export interface UnindexedState {record: UnindexedRecord | null;/** `missing`: no result for the current incarnation; `partial`: nothing found so far but the scan is incomplete. */state: 'ok' | 'unindexed' | 'scheduled' | 'partial' | 'stale' | 'missing';- /** Found files no pass scheduled. */+ /** Found files no pass scheduled that a re-screen could import (not `slug_taken`, not `deleted_page`). */unscheduled: number;+ /** Found files a re-screen cannot import (`slug_taken` + `deleted_page`): a person renames, deletes or restores; never scheduled. */+ blocked: number;/** Scheduled paths the next sync has not re-screened yet. */waiting: number;/** Scheduled paths a sync re-screened that still have no page and no hold. */@@ -301,10 +335,11 @@ export async function judgeUnindexedFiles(engine: Pick<BrainEngine, 'executeRaw'const out: UnindexedState[] = [];for (const source of sources) {const record = records.get(source.id) ?? null;- const base = { source_id: source.id, record, unscheduled: 0, waiting: 0, still_unindexed: 0, age_ms: record ? Math.max(0, now - Date.parse(record.computed_at)) : null };+ const base = { source_id: source.id, record, unscheduled: 0, blocked: 0, waiting: 0, still_unindexed: 0, age_ms: record ? Math.max(0, now - Date.parse(record.computed_at)) : null };if (!record || record.incarnation !== source.incarnation) { out.push({ ...base, state: 'missing' }); continue; }if (base.age_ms! > UNINDEXED_STALE_MS) { out.push({ ...base, state: 'stale' }); continue; }- const unscheduled = Math.max(0, record.unindexed - record.scheduled_now);+ const blocked = (record.slug_taken ?? 0) + (record.deleted_page ?? 0);+ const unscheduled = Math.max(0, record.unindexed - blocked - record.scheduled_now);const retry = new Set(await readGitHoldRetryPaths(engine, source.id, source.incarnation));const waiting = record.pending.filter(path => retry.has(path)).length;const consumed = record.pending.filter(path => !retry.has(path));@@ -317,7 +352,7 @@ export async function judgeUnindexedFiles(engine: Pick<BrainEngine, 'executeRaw'stillUnindexed = consumed.filter(path => !indexed.has(`${record.source_prefix}${path}`) && !held.has(path)).length;}const state = unscheduled || stillUnindexed ? 'unindexed' : waiting ? 'scheduled' : record.complete && !record.pending_truncated ? 'ok' : 'partial';- out.push({ ...base, state, unscheduled, waiting, still_unindexed: stillUnindexed });+ out.push({ ...base, state, unscheduled, blocked, waiting, still_unindexed: stillUnindexed });}return out;}diff --git a/src/core/repair/slug-autoheal.ts b/src/core/repair/slug-autoheal.tsindex 6c21489bc8..4f5059d7f1 100644--- a/src/core/repair/slug-autoheal.ts+++ b/src/core/repair/slug-autoheal.ts@@ -14,8 +14,11 @@* - 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;+ * - the declared slug is checked again inside the publication: a page, an alias or a file at its path written since+ * the heal read the source refuses the write;+ * - bounded: only holds the lane has not judged for these bytes (a current-lane verdict is the lane's), at most+ * `SLUG_HEAL_MAX_FILES` attempts 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.@@ -26,13 +29,14 @@ 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 { contentRepairLaneCurrent } from '../persistence/sync-fault-class.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. */+/** The most held files one sync examines (each heal 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;@@ -90,9 +94,11 @@ export async function healAfterManagedSync(engine: BrainEngine, outer: SyncOpts,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 all = ((await readGitSourceHolds(engine, { sourceIds: [sourceId] }))[0]?.holds ?? []).filter(hold => hold.code === 'frontmatter_slug_conflict');+ if (!all.length) return result;+ const holds = all.filter(hold => !contentRepairLaneCurrent(hold.meta.content_repair));+ const judged = all.length - holds.length;+ const base = { removed: 0, pending: holds.length, failed: 0, left_by_reason: (judged ? { lane_verdict: judged } : {}) 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'@@ -105,8 +111,9 @@ export async function healAfterManagedSync(engine: BrainEngine, outer: SyncOpts,remote: false, dryRun: false, sourceId } as unknown as OperationContext;const deadline = Math.min(now() + SLUG_HEAL_BUDGET_MS, outer.deadlineAtMs ?? Infinity);const healed: string[] = [];+ let attempts = 0;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;+ if (attempts++ >= SLUG_HEAL_MAX_FILES || now() >= deadline || outer.signal?.aborted) break;base.pending--;try {const outcome = await healAbsentSlugLine(ctx, run, hold.path);diff --git a/src/core/repair/slug-conflicts.ts b/src/core/repair/slug-conflicts.tsindex 4406f89798..3f9e462605 100644--- a/src/core/repair/slug-conflicts.ts+++ b/src/core/repair/slug-conflicts.ts@@ -55,7 +55,7 @@ import { OperationError, type OperationContext } from '../ops/contract.ts';import { trustedCliRequired } from '../ops/op-fix.ts';import { shellQuote, type Action } from '../agent-output.ts';import { autoFixFrontmatter, createFrontmatterBackup, makeFrontmatterBackupRunId } from '../brain-writer.ts';-import { classifyImportHold, parseMarkdown, serializePageToMarkdown } from '../markdown.ts';+import { classifyImportHold, coerceFrontmatterString, parseMarkdown, parseMarkdownHead, serializePageToMarkdown } from '../markdown.ts';import { MAX_FILE_SIZE, type ImportScreenResult } from '../import-screen.ts';import { importFromFile } from '../import-file.ts';import { resolveSlugForPath, slugifyPath } from '../sync.ts';@@ -172,11 +172,12 @@ function checkoutSlugs(root: string): Set<string> {return out;}-/** The declared `slug:` value of a file as written, or null when the frontmatter has none. */+/**+ * The declared `slug:` value of a file as the import reads it (the YAML scalar: a trailing comment, quoting and+ * escapes resolved, as `parseMarkdown` coerces it), or null when the frontmatter has none.+ */function declaredSlug(content: string): string | null {- const block = /^\uFEFF?---[ \t]*\r?\n([\s\S]*?)\r?\n---[ \t]*(?:\r?\n|$)/.exec(content)?.[1];- const line = block?.split(/\r?\n/).find(l => /^slug:\s*\S/.test(l));- return line ? line.replace(/^slug:\s*/, '').trim().replace(/^["']|["']$/g, '') : null;+ return coerceFrontmatterString(parseMarkdownHead(content).frontmatter.slug).trim() || null;}/** The slug a declared value is looked up by: as written, then as the screen normalizes it. */@@ -644,7 +645,7 @@ async function write(ctx: OperationContext, src: FenceSource, cand: Candidate, areturn { applied: false, outcome: 'skipped', reason: 'changed_since_read', detail: { ...detail, message: `${cand.path} changed while it was being repaired; the next run reads it again.` }, ...spend };}if (error instanceof OperationError && error.code === 'sync_in_progress') {- await recordState(engine, { src, path: cand.path, hold: cand.hold }, { action: 'pending', reason: 'sync_in_progress', next_attempt_after: nextAttempt('sync_in_progress') });+ if (extra.trigger !== 'sync') await recordState(engine, { src, path: cand.path, hold: cand.hold }, { action: 'pending', reason: 'sync_in_progress', next_attempt_after: nextAttempt('sync_in_progress') });return { applied: false, outcome: 'skipped', reason: 'sync_in_progress', detail: { ...detail, message: error.message }, ...spend };}throw error;@@ -780,10 +781,7 @@ export async function healAbsentSlugLine(ctx: OperationContext, run: AbsentSlugHreturn 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 } };- };+ const held: HeldFn = async (reason, message, _state, extra = {}) => ({ 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' });}diff --git a/test/unindexed-files.test.ts b/test/unindexed-files.test.tsindex bbadc7d9e3..80bd128dcb 100644--- a/test/unindexed-files.test.ts+++ b/test/unindexed-files.test.ts@@ -222,7 +222,7 @@ for (const mode of ['git-root', 'source-root'] as const) {await s.legacy({ 'brain/notes/c.md': note('C'), 'other/y.md': note('Y') });const scan = await findUnindexedFiles(engine, s.id);expect(scan).toMatchObject({ complete: true, scanned: 3, unindexed: 1 });- expect(scan.files).toEqual([{ path: 'notes/c.md', source_path: mode === 'git-root' ? 'brain/notes/c.md' : 'notes/c.md', code: 'clean', slug_taken: false }]);+ expect(scan.files).toEqual([{ path: 'notes/c.md', source_path: mode === 'git-root' ? 'brain/notes/c.md' : 'notes/c.md', code: 'clean', slug_taken: false, deleted_page: false }]);}), 240_000);}