Garry's Opinionated OpenClaw/Hermes Agent Brain
TypeScript
feat(doctor): git_held_files, frontmatter_repairable and frontmatter_hook findings; post-upgrade unblock note (#5988)
garrytan3c969bab7a0e
diff --git a/docs/architecture/key-files/commands-2.md b/docs/architecture/key-files/commands-2.mdindex 97f1098def..825b544fee 100644--- a/docs/architecture/key-files/commands-2.md+++ b/docs/architecture/key-files/commands-2.md@@ -16,9 +16,10 @@ Doctor's embedding-dimension warning treats existing chunks as existing data eve- `src/commands/doctor/checks/auto-chronicle.ts` — `auto_chronicle` (#5876), registered after `unlinked_facts`: warns (code `auto_chronicle_no_effect`, fix `gbrain chronicle-backfill --dry-run`) while `auto_chronicle=true`, because nothing reads that setting; ok otherwise.- `src/commands/doctor/checks/vector-coverage.ts` — `fact_take_vectors` (#5188, #5885), registered after `auto_chronicle`: per unarchived source (honoring `--source`), active facts (`eligibleFactEmbedding` + `staleFactEmbedding`) and takes (`countStaleTakes` with the DB-plane model and width) with no vector for their current text, split into missing versus other-model; warns with code `stale_vectors` and `details.fix` (`gbrain embed --stale`, or `gbrain takes embed` when `takes.auto_embed` is off; per-source `gbrain embed --facts --stale --source <id> --dry-run --json`). Keyless brains report `applicable: false`; a brain with no recorded model or width warns `vectors_not_verified`.+- `src/commands/doctor/checks/git-holds.ts` + `checks/frontmatter-repairable.ts` + `checks/frontmatter-hook.ts` — the #5988 hold and frontmatter checks. `git_held_files` (wave, host-only, `resolution: 'repair'`): Git-source holds per source from `readHeldCoverage` (missing vs stale counts) and the first five paths from `readGitHoldListing` with each one's code and `gitHoldFix` step, the put_page read-only note, `gbrain sources status <id>` and `gbrain repair frontmatter --source <id>`; `fail` once a source holds more than `sync.hold_escalate_count`; connector holds stay on `connector_held_items`. `frontmatter_repairable` (registered inline: emitted by the `frontmatter_integrity` entry from the same `scanBrainSources` walk, whose `PerSourceReport.repairable` counts files by repairable cause: recoverable `YAML_PARSE`, `needs_interpretation`, `FRONTMATTER_COMMENT_VALUE` on title/name/description/summary, `NESTED_QUOTES`, `NULL_BYTES`, `MISSING_CLOSE`, `SLUG_MISMATCH`); a deadline-partial scan sets `details.partial`. Both list `details.source_ids` and belong to the explicit-only `frontmatter` kind, so remediation classifies them `explicit_kind_required` with `--source <id>` when one source is named. `frontmatter_hook` (wave, operator): installed gbrain pre-commit hooks older than `FRONTMATTER_HOOK_VERSION`, fix `gbrain frontmatter install-hook --source <id> --force`. `frontmatterHoldsBannerNote` (a `POST_UPGRADE_NOTES` entry) names sources whose unfinished managed cursor stopped on a failed content refusal: the next sync recovers them, `gbrain sync --source <id> --no-pull` does it now, plus the repair preview and the hook refresh. Test: `test/doctor-frontmatter-holds.test.ts`.- `src/commands/doctor/wave-checks.ts` — `WAVE_CHECKS`, the table of managed-persistence wave checks (stable id, `resolution` `repair`/`operator`/`unsupported`, count-free remote `impact`, operator `instruction`, `count` for banners, `registration` inline-in-doctor.ts or from this table). `runWaveChecks` turns a throwing check into an `unknown` finding; `checkHealthUnknown` reads `details.health === 'unknown'`. `remoteWaveHandoff` returns one line per remotely offered check with `details.host_action` {`check_id`, `state` ok/action_required/unknown, `preview_command`} and no paths, rows, SQL, emails or installation ids. Consumers: doctor.ts, `report-remote.ts`, `remediate.ts`, `upgrade-banner.ts`. Tests: `test/recovery-layer.test.ts`, `test/e2e/recovery-layer.test.ts`.-- `src/commands/doctor/remediate.ts` — the `--remediation-plan` / `--remediate` CLI shell (re-exported from doctor.ts): per-step `command` (`gbrain jobs submit …` for job steps, `gbrain repair <kind> --apply` for repair steps), `combinedRemediateCommand` (with repair steps it ends `--expect <plan_hash>`, the same hash `--remediation-plan --json` reports as `plan_hash`), `REMEDIATE_HELP`, `--include-repairs`/`--no-embed`/`--resume` handling, the resume command after budget exhaustion (repeats the recorded cap and consent), `classifyWaveFindings` (cleared / pending / consent_required / operator_required / unsupported, from wave checks run before and after) and `remediationExitStatus` (0 when no repairable finding remains and no step failed; 1 otherwise or on budget exhaustion; 2 when the target is unreachable with no repair step, or a resume is refused), set through `setCliExitVerdict`; 3 when consent is required), set through `setCliExitVerdict`. Consent (agent operator wave C1) lives in `doctor/remediate-consent.ts`: the CLI connects probe-only (no migrations) and computes the plan; when anything would run it calls `requireConsent` (effects `paid`, plus `destructive` with `--include-repairs`, bound to a `plan_hash` over the brain id, job step ids, repair kinds and pending counts, and the parameters, and persisted with the approval). Non-TTY without authorization changes nothing and exits 3 with the consent payload; `--json` never implies consent; `--yes` without `--max-usd` runs under the derived cap (estimate ×1.5, floor $0.25; the default cap when unpriced), and derived-cap exhaustion prints the `--max-usd` resume command. Startup (migrations) completes only after consent. A `--resume` is bound by its checkpoint manifest, not a new plan hash. Pinned by `test/doctor-remediate-consent.test.ts`.+- `src/commands/doctor/remediate.ts` — the `--remediation-plan` / `--remediate` CLI shell (re-exported from doctor.ts): per-step `command` (`gbrain jobs submit …` for job steps, `gbrain repair <kind> --apply` for repair steps), `combinedRemediateCommand` (with repair steps it ends `--expect <plan_hash>`, the same hash `--remediation-plan --json` reports as `plan_hash`), `REMEDIATE_HELP`, `--include-repairs`/`--no-embed`/`--resume` handling, the resume command after budget exhaustion (repeats the recorded cap and consent), `classifyWaveFindings` (cleared / pending / consent_required / operator_required / explicit_kind_required / unsupported, from wave checks run before and after; `details.partial` is pending; an explicit-only kind's preview gets `--source <id>` via `findingSource` when the finding names one source; `--remediation-plan` runs the wave checks too and reports the same classification as `findings`) and `remediationExitStatus` (0 when no repairable finding remains and no step failed; 1 otherwise or on budget exhaustion; 2 when the target is unreachable with no repair step, or a resume is refused), set through `setCliExitVerdict`; 3 when consent is required), set through `setCliExitVerdict`. Consent (agent operator wave C1) lives in `doctor/remediate-consent.ts`: the CLI connects probe-only (no migrations) and computes the plan; when anything would run it calls `requireConsent` (effects `paid`, plus `destructive` with `--include-repairs`, bound to a `plan_hash` over the brain id, job step ids, repair kinds and pending counts, and the parameters, and persisted with the approval). Non-TTY without authorization changes nothing and exits 3 with the consent payload; `--json` never implies consent; `--yes` without `--max-usd` runs under the derived cap (estimate ×1.5, floor $0.25; the default cap when unpriced), and derived-cap exhaustion prints the `--max-usd` resume command. Startup (migrations) completes only after consent. A `--resume` is bound by its checkpoint manifest, not a new plan hash. Pinned by `test/doctor-remediate-consent.test.ts`.- `src/commands/doctor/checks/global-maintenance-timeouts.ts` — `global_maintenance_timeouts` (#4578): warns when the last three finished `autopilot-global-maintenance` jobs died at their deadline, or one phase was running in three consecutive job deaths (read from config `autopilot.global_maintenance.progress`). Details carry `code`, `cause`, `fix` (`gbrain dream --phase <name>`, else the deadline config key) and the `docs/guides/troubleshooting.md#global-maintenance-timeouts` anchor. Pinned by `test/autopilot-global-maintenance-resume-4578.test.ts`.- `src/commands/doctor/checks/legacy-job-authority.ts` — `legacy_job_authority` (#5157): the claim gate's population (`UNREVIEWED_LIVE_JOBS_WHERE`), split into authorizable SQL NULL and unsupported rows; terminal keyed SQL NULL rows are reported as `ok`. Live rows `fail` with the filled recovery. `legacyJobAuthorityBannerNote` feeds the banner. Test: `test/doctor-legacy-job-authority.test.ts`.diff --git a/src/commands/doctor/checks/content-quality.ts b/src/commands/doctor/checks/content-quality.tsindex 0878206d01..a5bddb4d68 100644--- a/src/commands/doctor/checks/content-quality.ts+++ b/src/commands/doctor/checks/content-quality.ts@@ -12,7 +12,7 @@ import { startHeartbeat } from '../../../core/progress.ts';import { checkUnverifiedExtractions } from './extraction-sync.ts';import type { Check } from '../../doctor.ts';import { connectedEngine, type DoctorContext, type DoctorEntry } from '../context.ts';-import { checkError } from '../check-fix.ts';+import { agentFix, checkError } from '../check-fix.ts';async function runContentSanity(ctx: DoctorContext): Promise<Check[]> {const { args, progress } = ctx;@@ -318,11 +318,8 @@ async function runFrontmatter(ctx: DoctorContext): Promise<Check[]> {// - Configurable via GBRAIN_DOCTOR_FM_TIMEOUT_MS (default 30000ms).progress.heartbeat('frontmatter_integrity');const fmHb = startHeartbeat(progress, 'scanning frontmatter…');- const fmTimeoutMs = (() => {- const raw = process.env.GBRAIN_DOCTOR_FM_TIMEOUT_MS;- const n = raw ? parseInt(raw, 10) : NaN;- return Number.isFinite(n) && n > 0 ? n : 30000;- })();+ const { frontmatterScanTimeoutMs, frontmatterRepairableFromReport } = await import('./frontmatter-repairable.ts');+ const fmTimeoutMs = frontmatterScanTimeoutMs();try {const { scanBrainSources } = await import('../../../core/brain-writer.ts');const fmDeadline = Date.now() + fmTimeoutMs;@@ -392,9 +389,12 @@ async function runFrontmatter(ctx: DoctorContext): Promise<Check[]> {.join(', ');sourceMessages.push(`${src.source_id}: ${src.total} (${codes})`);}+ const repairHint = 'Fix: gbrain repair frontmatter --source <id> previews the line fix for every file it can repair (and names the manual fix for the rest, '+ + 'such as a missing opening ---); on an unmanaged checkout gbrain frontmatter validate <source-path> --fix applies the same safe fixes';+ const sourcesWithIssues = report.per_source.filter(src => src.total > 0).map(src => src.source_id);const fixHint = report.partial- ? `Raise GBRAIN_DOCTOR_FM_TIMEOUT_MS or run \`gbrain frontmatter validate <source>\` directly. Fix issues: \`gbrain frontmatter validate <source> --fix\``- : `Fix: gbrain frontmatter validate <source-path> --fix`;+ ? `Raise GBRAIN_DOCTOR_FM_TIMEOUT_MS or run \`gbrain frontmatter validate <source-path>\` directly. ${repairHint}`+ : repairHint;checks.push({name: 'frontmatter_integrity',status: 'warn',@@ -402,8 +402,12 @@ async function runFrontmatter(ctx: DoctorContext): Promise<Check[]> {`${report.total} frontmatter issue(s)` +(report.partial ? ` (PARTIAL SCAN — timeout after ${fmTimeoutMs / 1000}s)` : '') +`. ${sourceMessages.join('; ')}. ${fixHint}`,+ ...(sourcesWithIssues.length === 1 ? { fix: agentFix(['gbrain', 'repair', 'frontmatter', '--source', sourcesWithIssues[0]!],+ 'Previews the line fix for each file the repair can fix and names the manual fix for the rest; it writes nothing.', 'frontmatter_integrity',+ { docs: 'docs/guides/repair.md#frontmatter' }) } : {}),});}+ checks.push(frontmatterRepairableFromReport(report, fmTimeoutMs));} catch (e) {// Codex outside-voice D4: the abort path returns cleanly via partial// state — this catch is purely for unexpected errors (FS permission,@@ -419,6 +423,6 @@ async function runFrontmatter(ctx: DoctorContext): Promise<Check[]> {export const frontmatterEntry: DoctorEntry = {name: 'frontmatter_integrity',- emits: ['frontmatter_integrity'],+ emits: ['frontmatter_integrity', 'frontmatter_repairable'],run: runFrontmatter,};diff --git a/src/commands/doctor/checks/frontmatter-hook.ts b/src/commands/doctor/checks/frontmatter-hook.tsnew file mode 100644index 0000000000..e78124b9fe--- /dev/null+++ b/src/commands/doctor/checks/frontmatter-hook.ts@@ -0,0 +1,44 @@+import type { BrainEngine } from '../../../core/engine.ts';+import type { Check } from '../../doctor.ts';+import { agentFix } from '../check-fix.ts';++export interface OutdatedFrontmatterHook { source_id: string; hook_path: string; version: number; fix: string[] }++/** Installed gbrain pre-commit hooks older than this gbrain's script, one per hook file. */+export async function outdatedFrontmatterHooks(engine: BrainEngine, sourceIds?: string[]): Promise<OutdatedFrontmatterHook[]> {+ const { inspectFrontmatterHook } = await import('../../frontmatter-install-hook.ts');+ const rows = await engine.executeRaw<{ id: string; local_path: string }>(+ 'SELECT id, local_path FROM sources WHERE local_path IS NOT NULL AND ($1::text[] IS NULL OR id = ANY($1::text[])) ORDER BY id', [sourceIds ?? null]);+ const seen = new Set<string>();+ const out: OutdatedFrontmatterHook[] = [];+ for (const row of rows) {+ const hook = inspectFrontmatterHook(row.local_path, row.id);+ if (!hook || hook.current || seen.has(hook.hookPath)) continue;+ seen.add(hook.hookPath);+ out.push({ source_id: row.id, hook_path: hook.hookPath, version: hook.version, fix: hook.fix! });+ }+ return out;+}++/**+ * #5988 (E24): an installed frontmatter pre-commit hook written by an older+ * gbrain validates working-tree bytes instead of the staged blobs, so a broken+ * staged file can still be committed. Refreshing an installed hook is the+ * operator's earlier decision carried forward: `gbrain frontmatter+ * install-hook --force` rewrites the gbrain script only.+ */+export async function frontmatterHookCheck(engine: BrainEngine, sourceIds?: string[]): Promise<Check> {+ try {+ const hooks = await outdatedFrontmatterHooks(engine, sourceIds);+ const details = { count: hooks.length, hooks, docs: 'docs/guides/repair.md#held-files' };+ if (!hooks.length) return { name: 'frontmatter_hook', status: 'ok', message: 'No outdated gbrain frontmatter pre-commit hook is installed.', details };+ return { name: 'frontmatter_hook', status: 'warn', details,+ message: `${hooks.length} gbrain frontmatter pre-commit hook(s) predate this release and check working-tree files instead of what is staged: `+ + `${hooks.map(hook => `${hook.source_id} (${hook.hook_path}, v${hook.version})`).join('; ')}. Refresh with ${hooks.map(hook => hook.fix.join(' ')).join('; ')}.`,+ fix: agentFix(hooks[0]!.fix, 'Rewrites the installed gbrain pre-commit hook with the current script (validates staged blobs in one process); hooks that are not gbrain\'s are never touched.',+ 'frontmatter_hook') };+ } catch (error) {+ return { name: 'frontmatter_hook', status: 'warn', fix_unavailable_reason: 'check_errored', details: { count: 'unknown' },+ message: `Frontmatter pre-commit hooks could not be inspected: ${error instanceof Error ? error.message : String(error)}. Health is unknown.` };+ }+}diff --git a/src/commands/doctor/checks/frontmatter-repairable.ts b/src/commands/doctor/checks/frontmatter-repairable.tsnew file mode 100644index 0000000000..f66d24c5a0--- /dev/null+++ b/src/commands/doctor/checks/frontmatter-repairable.ts@@ -0,0 +1,56 @@+import type { BrainEngine } from '../../../core/engine.ts';+import type { Check } from '../../doctor.ts';+import type { AuditReport } from '../../../core/brain-writer.ts';+import { agentFix } from '../check-fix.ts';++/** `GBRAIN_DOCTOR_FM_TIMEOUT_MS` (default 30 s): the wall-clock bound of one frontmatter scan. */+export function frontmatterScanTimeoutMs(): number {+ const n = parseInt(process.env.GBRAIN_DOCTOR_FM_TIMEOUT_MS ?? '', 10);+ return Number.isFinite(n) && n > 0 ? n : 30000;+}++/**+ * #5988 `frontmatter_repairable`: files `gbrain repair frontmatter` can fix+ * (recoverable YAML, `needs_interpretation` holds, a `#`-leading title read as+ * a comment, nested quotes, NUL bytes, a missing closing fence, a conflicting+ * slug line). Codes no repair fixes (MISSING_OPEN, EMPTY_FRONTMATTER,+ * NON_STRING_FIELD) stay on `frontmatter_integrity`. Built from the same scan+ * `frontmatter_integrity` reads, so doctor walks each source once. A scan+ * that hit its deadline is `partial` (remediation reports it pending), never ok.+ */+export function frontmatterRepairableFromReport(report: AuditReport, timeoutMs: number): Check {+ const sources = report.per_source.filter(src => (src.repairable?.files ?? 0) > 0).map(src => ({+ source_id: src.source_id, files: src.repairable!.files, by_code: src.repairable!.by_code, sample_paths: src.repairable!.sample.slice(0, 5),+ status: src.status, preview: `gbrain repair frontmatter --source ${src.source_id}`,+ }));+ const files = sources.reduce((sum, src) => sum + src.files, 0);+ const unscanned = report.per_source.filter(src => src.status !== 'scanned').map(src => src.source_id);+ const details = { repairable: files, source_ids: sources.map(src => src.source_id), sources, partial: report.partial, unscanned,+ docs: 'docs/guides/repair.md#frontmatter' };+ const single = sources.length === 1 ? sources[0]!.source_id : undefined;+ const fix = agentFix(['gbrain', 'repair', 'frontmatter', ...(single ? ['--source', single] : [])],+ 'Previews the minimal line fix per file (safe quoting first; interpretations only with --include-ambiguous) and prints the hash-bound apply command; it writes nothing.',+ 'frontmatter_repairable', { docs: 'docs/guides/repair.md#frontmatter' });+ const partial = report.partial+ ? ` PARTIAL SCAN: the walk stopped after ${timeoutMs / 1000}s, so ${unscanned.join(', ')} ${unscanned.length === 1 ? 'was' : 'were'} not fully checked; raise GBRAIN_DOCTOR_FM_TIMEOUT_MS and run gbrain doctor --only frontmatter_repairable again.`+ : '';+ if (!files && !report.partial) {+ return { name: 'frontmatter_repairable', status: 'ok', details,+ message: report.per_source.length ? 'No file has frontmatter gbrain repair frontmatter would fix.' : 'No registered sources to scan.' };+ }+ if (!files) return { name: 'frontmatter_repairable', status: 'warn', details, fix_unavailable_reason: 'check_errored', message: `No repairable frontmatter found so far.${partial}` };+ return {+ name: 'frontmatter_repairable', status: 'warn', details, fix,+ message: `${files} file(s) have frontmatter gbrain repair frontmatter can fix: `+ + `${sources.map(src => `${src.source_id}: ${src.files} (${Object.entries(src.by_code).map(([code, n]) => `${code}=${n}`).join(', ')})`).join('; ')}. `+ + `Preview with ${sources.map(src => src.preview).join('; ')} (writes nothing; add --include-ambiguous for interpretations after the safe pass).${partial}`,+ };+}++/** The wave-check entry point: one bounded scan of the scoped sources. */+export async function frontmatterRepairableCheck(engine: BrainEngine, sourceId?: string): Promise<Check> {+ const { scanBrainSources } = await import('../../../core/brain-writer.ts');+ const timeoutMs = frontmatterScanTimeoutMs();+ const report = await scanBrainSources(engine, { sourceId, deadline: Date.now() + timeoutMs, signal: AbortSignal.timeout(timeoutMs) });+ return frontmatterRepairableFromReport(report, timeoutMs);+}diff --git a/src/commands/doctor/checks/git-holds.ts b/src/commands/doctor/checks/git-holds.tsnew file mode 100644index 0000000000..b68f375229--- /dev/null+++ b/src/commands/doctor/checks/git-holds.ts@@ -0,0 +1,80 @@+import type { BrainEngine } from '../../../core/engine.ts';+import type { Check } from '../../doctor.ts';+import { gitHoldFix, readGitHoldListing, readSyncHoldPolicy } from '../../../core/persistence/sync-holds.ts';+import { readHeldCoverage } from '../../../core/persistence/held-reads.ts';+import { agentFix } from '../check-fix.ts';+import { isContentRefusal } from '../../../core/import-screen.ts';++const SAMPLE_PATHS = 5;++/**+ * #5988: files a Git source holds instead of importing (unreadable or+ * ambiguous frontmatter, a conflicting slug, over-size, an operator content+ * reject). Connector holds stay on `connector_held_items`. Warns per source+ * with the missing and stale counts, the first paths with their code and next+ * step (the check is host-only, so paths never reach a remote caller), and the+ * inspect and repair commands; fails once a source carries more holds than+ * `sync.hold_escalate_count`, the same count rule that escalates a sync result.+ */+export async function gitHeldFilesCheck(engine: BrainEngine, sourceIds?: string[]): Promise<Check> {+ try {+ const [coverage, policy] = await Promise.all([readHeldCoverage(engine, sourceIds ? { sourceIds } : {}), readSyncHoldPolicy(engine)]);+ const listing = new Map((await readGitHoldListing(engine, coverage.map(source => source.source_id), SAMPLE_PATHS)).map(entry => [entry.sourceId, entry.holds]));+ const sources = coverage.map(source => ({ source_id: source.source_id, held: source.missing + source.stale, stale: source.stale, missing: source.missing,+ first: (listing.get(source.source_id) ?? []).map(hold => ({ path: hold.path, code: hold.code, ...(hold.meta.reason ? { reason: hold.meta.reason } : {}), why: gitHoldFix(hold).why })),+ escalated: source.missing + source.stale > policy.escalateCount,+ status: `gbrain sources status ${source.source_id}`, repair: `gbrain repair frontmatter --source ${source.source_id}` }));+ const held = sources.reduce((sum, source) => sum + source.held, 0);+ const details = { held, source_ids: sources.map(source => source.source_id), sources, escalate_count: policy.escalateCount,+ docs: 'docs/guides/repair.md#held-files' };+ if (!held) return { name: 'git_held_files', status: 'ok', message: 'No Git source files are held.', details };+ const escalated = sources.filter(source => source.escalated);+ const single = sources.length === 1 ? sources[0]!.source_id : undefined;+ const lines = sources.map(source => `${source.source_id}: ${source.held} held (${source.stale} page(s) keep an older revision, ${source.missing} file(s) have no page), `+ + `first: ${source.first.map(hold => `${hold.path} [${hold.code}${hold.reason ? `/${hold.reason}` : ''}]`).join(', ')}`);+ return {+ name: 'git_held_files', status: escalated.length ? 'fail' : 'warn', details,+ message: `${held} file(s) in Git sources are held and not imported; the rest of each sync continues. ${lines.join('; ')}. `+ + (escalated.length ? `Escalated: ${escalated.map(source => source.source_id).join(', ')} hold more than ${policy.escalateCount} files (sync.hold_escalate_count), so a generator or an upgrade is likely writing or reading them wrong; fix the cause first. ` : '')+ + 'A page whose newer file is held is read-only for put_page until the file is repaired, so do not retry a refused write. '+ + `Inspect with ${sources.map(source => source.status).join('; ')}; preview the fix with ${sources.map(source => source.repair).join('; ')}.`,+ fix: agentFix(['gbrain', 'repair', 'frontmatter', ...(single ? ['--source', single] : [])],+ 'Previews the minimal line fix for each held file (or names the line to fix by hand) and prints the hash-bound apply command; it writes nothing.', 'git_held_files',+ { docs: 'docs/guides/repair.md#held-files' }),+ };+ } catch (error) {+ return { name: 'git_held_files', status: 'warn', fix_unavailable_reason: 'check_errored',+ message: `Git source holds could not be inspected: ${error instanceof Error ? error.message : String(error)}. Health is unknown.`,+ details: { held: 0, health: 'unknown' } };+ }+}++/** Sources whose unfinished managed sync cursor is stopped on a failed content refusal (fixed by the next sync, which converts it in place). */+export async function contentBlockedSources(engine: BrainEngine): Promise<string[]> {+ const rows = await engine.executeRaw<{ source_id: string; error_code: string | null; error_message: string | null }>(`SELECT c.completed_keys->0->>'sourceId' AS source_id,+ r.error_code, r.error_message FROM op_checkpoints c JOIN persistence_requests r ON r.request_id::text = c.completed_keys->0->'pending'->>'requestId'+ AND r.source_id = c.completed_keys->0->>'sourceId'+ WHERE c.op = 'managed-sync' AND COALESCE(c.completed_keys->0->>'done','false') <> 'true' AND r.state IN ('failed','conflict','cancelled')+ ORDER BY 1`).catch(() => []);+ return [...new Set(rows.filter(row => isContentRefusal(row.error_code, row.error_message)).map(row => row.source_id))];+}++/**+ * #5988 `gbrain post-upgrade` line: a source blocked by one file recovers on+ * its next sync (scheduled or manual) without ledger surgery. The line names+ * the command that does it now and the repair preview for the backlog, plus+ * the hook refresh when an older hook is installed (held files already appear+ * as the `git_held_files` finding). Null when neither applies.+ */+export async function frontmatterHoldsBannerNote(engine: BrainEngine): Promise<string | null> {+ const { outdatedFrontmatterHooks } = await import('./frontmatter-hook.ts');+ const [blocked, hooks] = await Promise.all([contentBlockedSources(engine), outdatedFrontmatterHooks(engine).catch(() => [])]);+ const parts: string[] = [];+ if (blocked.length) {+ parts.push(`${blocked.length} source(s) are blocked by a file gbrain could not import (${blocked.join(', ')}). The next scheduled or manual sync recovers a blocked source `+ + `automatically; to do it now run ${blocked.map(id => `gbrain sync --source ${id} --no-pull`).join('; ')}. The file is then held and the rest of the source imports; `+ + `inspect it with ${blocked.map(id => `gbrain sources status ${id}`).join('; ')} and preview the backlog fix with ${blocked.map(id => `gbrain repair frontmatter --source ${id}`).join('; ')} (writes nothing; ask the user before applying)`);+ }+ if (hooks.length) parts.push(`an older frontmatter pre-commit hook is installed; refresh it with ${hooks.map(hook => hook.fix.join(' ')).join('; ')}`);+ return parts.length ? `frontmatter_holds: ${parts.join('. ')}. Recipe: docs/guides/repair.md#held-files` : null;+}diff --git a/src/commands/doctor/checks/graph-health.ts b/src/commands/doctor/checks/graph-health.tsindex c00b35b40f..f2c8318326 100644--- a/src/commands/doctor/checks/graph-health.ts+++ b/src/commands/doctor/checks/graph-health.ts@@ -276,6 +276,8 @@ export const timelineHistoryEntry: DoctorEntry = {'persistence_request_indexes','persistence_request_growth','connector_held_items',+ 'git_held_files',+ 'frontmatter_hook','orphan_persistence_bindings','unbound_source','writer_version',diff --git a/src/commands/doctor/remediate.ts b/src/commands/doctor/remediate.tsindex 04a603497c..3004282b25 100644--- a/src/commands/doctor/remediate.ts+++ b/src/commands/doctor/remediate.ts@@ -28,7 +28,7 @@ import { clearHealthMemo } from '../../core/health-memo.ts';import type { RemediationPlan, RemediationResult } from '../../core/remediation/types.ts';import type { RepairPlanStep } from '../../core/remediation/repairs.ts';import { repairPreviewCommand, repairSpec, type ExplicitRepairNotice } from '../../core/repair/registry.ts';-import { runWaveChecks, waveRepairKind, type WaveFinding } from './wave-checks.ts';+import { findingSource, runWaveChecks, waveRepairKind, type WaveFinding } from './wave-checks.ts';import { derivedCapExhaustedError, type CapSource } from '../../core/consent.ts';import { previewRemediationPlan, remediateConsent, remediateFlags, remediationPlanHash, type RemediateFlags } from './remediate-consent.ts';import { cliRenderContext, renderAction, renderNotice, type Action, type Notice } from '../../core/agent-output.ts';@@ -167,7 +167,9 @@ export async function pendingMigrationsNotice(engine: BrainEngine): Promise<Noti/*** CLI wrapper around computeRemediationPlan. Read-only — never enqueues,* never mutates, never migrates (the engine is probe-only). JSON adds a- * `command` per job step, the repair steps, the combined command and a+ * `command` per job step, the repair steps, the combined command, the wave+ * check `findings` classified as a run would leave them (an explicit-only+ * kind's finding is `explicit_kind_required` with its preview command) and a* `notices` array (pending migrations) to the library's stable envelope.*/export async function runRemediationPlan(engine: BrainEngine, args: string[]): Promise<void> {@@ -178,12 +180,14 @@ export async function runRemediationPlan(engine: BrainEngine, args: string[]): Pconst migrations = await pendingMigrationsNotice(engine);const plan = await computeRemediationPlan(engine, { targetScore, repairs: { noEmbed } });const planHash = plan.repair_steps?.length ? await remediationPlanHash(engine, args, plan) : undefined;+ const waves = await runWaveChecks(engine);+ const findings = classifyWaveFindings(waves, waves, { repairs: [], repairs_skipped: plan.repair_steps ?? [] });if (args.includes('--json')) {const ctx = cliRenderContext();const steps = await Promise.all(plan.plan.map(async step => ({ ...step, command: jobStepCommand(step), fix: renderAction(await jobStepFix(step), ctx) })));const repairSteps = plan.repair_steps?.map(step => ({ ...step, fix: renderAction(repairStepFix(step), ctx) }));await writeJsonDocument(JSON.stringify({ ...plan, plan: steps, ...(repairSteps ? { repair_steps: repairSteps } : {}),- combined_command: combinedRemediateCommand(plan, plan.target_unreachable ? plan.max_reachable_score : targetScore, { noEmbed, planHash }), ...(planHash ? { plan_hash: planHash } : {}),+ combined_command: combinedRemediateCommand(plan, plan.target_unreachable ? plan.max_reachable_score : targetScore, { noEmbed, planHash }), ...(planHash ? { plan_hash: planHash } : {}), findings,...(migrations ? { notices: [renderNotice(migrations, cliRenderContext())] } : {}) }, null, 2));return;}@@ -194,6 +198,11 @@ export async function runRemediationPlan(engine: BrainEngine, args: string[]): P}const paidJobs = new Set((await Promise.all(plan.plan.map(async step => (await jobStepFix(step)).consent.length ? step.step : null))).filter((n): n is number => n !== null));for (const line of renderRemediationPlanLines(plan, targetScore, { noEmbed, planHash, paidSteps: paidJobs })) console.log(line);+ const named = findings.filter(f => f.class === 'explicit_kind_required');+ if (named.length) {+ console.log('\nFindings an explicit-only repair clears (preview each on this host, then ask the user before applying):');+ for (const finding of named) console.log(` ${finding.check_id}: ${finding.command}`);+ }}interface RemediationPlanShape {@@ -281,8 +290,10 @@ export interface RemediationFinding {* Classify every wave check that reported a finding before or after the run.* A repairable finding the run did not clear is `pending` (the step stopped,* was refused by the budget, or items remain) or `consent_required` (the step- * was skipped for lack of --include-repairs). A check that could not run is- * `pending`: its state is unknown, never assumed clean.+ * was skipped for lack of --include-repairs). A check that could not run, or+ * whose scan stopped at its deadline (`details.partial`), is `pending`: its+ * state is unknown or incomplete, never assumed clean. An explicit-only kind's+ * preview names `--source <id>` when the finding names one source.*/export function classifyWaveFindings(before: WaveFinding[], after: WaveFinding[], result: Pick<RemediationResult, 'repairs' | 'repairs_skipped'>): RemediationFinding[] {const findings: RemediationFinding[] = [];@@ -295,13 +306,18 @@ export function classifyWaveFindings(before: WaveFinding[], after: WaveFinding[]}const base = { check_id: now.spec.id, message: now.check.message };if (now.state === 'unknown') { findings.push({ ...base, class: 'pending', instruction: 'The check could not run; rerun gbrain doctor on the brain host.' }); continue; }+ if (now.check.details?.partial === true) {+ findings.push({ ...base, class: 'pending', ...(kind ? { repair_kind: kind } : {}),+ instruction: `The scan stopped at its deadline, so the finding is incomplete; raise GBRAIN_DOCTOR_FM_TIMEOUT_MS and rerun gbrain doctor --only ${now.spec.id} on the brain host.` });+ continue;+ }if (now.spec.resolution === 'operator') { findings.push({ ...base, class: 'operator_required', instruction: now.spec.instruction }); continue; }if (now.spec.resolution === 'unsupported') { findings.push({ ...base, class: 'unsupported', instruction: now.spec.instruction }); continue; }// A repairable finding the repair can only report blocked needs the operator first.const blocked = now.check.details?.operator_instruction;if (typeof blocked === 'string') { findings.push({ ...base, class: 'operator_required', instruction: blocked, ...(kind ? { repair_kind: kind } : {}) }); continue; }if (kind && repairSpec(kind).explicit_only) {- findings.push({ ...base, class: 'explicit_kind_required', repair_kind: kind, command: repairPreviewCommand(kind) });+ findings.push({ ...base, class: 'explicit_kind_required', repair_kind: kind, command: repairPreviewCommand(kind, { source: findingSource(now) }) });continue;}const skipped = result.repairs_skipped?.find(step => step.kind === kind);diff --git a/src/commands/doctor/upgrade-banner.ts b/src/commands/doctor/upgrade-banner.tsindex c2e0d2eca6..6b4f623b1f 100644--- a/src/commands/doctor/upgrade-banner.ts+++ b/src/commands/doctor/upgrade-banner.ts@@ -10,10 +10,11 @@* never runs it. A clean brain prints nothing.*/import type { BrainEngine } from '../../core/engine.ts';-import { runWaveChecks, waveRepairKind, type WaveFinding } from './wave-checks.ts';+import { findingSource, runWaveChecks, waveRepairKind, type WaveFinding } from './wave-checks.ts';import { repairPreviewCommand, repairSpec } from '../../core/repair/registry.ts';import { readConnectorSourceStatuses } from '../../core/persistence/connector-status.ts';import { legacyJobAuthorityBannerNote } from './checks/legacy-job-authority.ts';+import { frontmatterHoldsBannerNote } from './checks/git-holds.ts';/** #5686: connector sources that re-walk their window once, or resumed from a pre-upgrade checkpoint. */async function connectorRewalkNote(engine: BrainEngine): Promise<string | null> {@@ -30,13 +31,13 @@ async function connectorRewalkNote(engine: BrainEngine): Promise<string | null>* of connector sources that will re-walk once after a checkpoint migration).* Each returns null when it has nothing to say.*/-export const POST_UPGRADE_NOTES: Array<(engine: BrainEngine) => Promise<string | null>> = [connectorRewalkNote, legacyJobAuthorityBannerNote];+export const POST_UPGRADE_NOTES: Array<(engine: BrainEngine) => Promise<string | null>> = [connectorRewalkNote, legacyJobAuthorityBannerNote, frontmatterHoldsBannerNote];/** One banner line for a non-ok wave finding. */export function bannerFindingLine({ spec, check, state }: WaveFinding): string {if (state === 'unknown') return `[AGENT] ${spec.id}: could not be checked (health unknown)`;const kind = waveRepairKind(spec);- const how = kind && repairSpec(kind).explicit_only ? `explicit_kind_required; preview with: ${repairPreviewCommand(kind)}`+ const how = kind && repairSpec(kind).explicit_only ? `explicit_kind_required; preview with: ${repairPreviewCommand(kind, { source: findingSource({ check }) })}`: spec.resolution === 'repair' ? 'repairable after the user agrees' : spec.resolution === 'operator' ? 'needs an operator action' : 'reported only; no command clears it yet';return `[AGENT] ${spec.id}: ${spec.count(check.details ?? {})} (${how})`;}diff --git a/src/commands/doctor/wave-checks.ts b/src/commands/doctor/wave-checks.tsindex 1dfcd265dc..15e0c6d401 100644--- a/src/commands/doctor/wave-checks.ts+++ b/src/commands/doctor/wave-checks.ts@@ -100,6 +100,28 @@ export const WAVE_CHECKS: readonly WaveCheckSpec[] = [instruction: 'Inspect them with `gbrain sources status <source>`, fix the cause, then run `gbrain sources retry-held <source>` and `gbrain sync --source <source>` (docs/guides/repair.md#connector-held-items).',run: async (engine, scope) => (await import('./checks/connector-holds.ts')).connectorHeldItemsCheck(engine, scope.sourceIds),},+ {+ id: 'git_held_files', resolution: 'repair', registration: 'wave',+ hostOnly: 'Held file paths are host-local; remote callers see held counts on sync results, get_page and search.',+ count: d => Number(d.held ?? 0),+ impact: 'Some Git source files are held instead of imported, so their pages are missing or keep an older revision',+ run: async (engine, scope) => (await import('./checks/git-holds.ts')).gitHeldFilesCheck(engine, scope.sourceIds),+ },+ {+ id: 'frontmatter_repairable', resolution: 'repair', registration: 'doctor.ts',+ hostOnly: 'The scan reads source checkouts on the brain host, and the frontmatter repair rewrites files there (explicit-only).',+ count: d => Number(d.repairable ?? 0),+ impact: 'Some source files have frontmatter gbrain reads only by quoting or interpreting it',+ run: async (engine, scope) => { const { frontmatterRepairableCheck } = await import('./checks/frontmatter-repairable.ts'); return perSource(scope, id => frontmatterRepairableCheck(engine, id)); },+ },+ {+ id: 'frontmatter_hook', resolution: 'operator', registration: 'wave',+ hostOnly: 'Pre-commit hooks live in the source checkouts on the brain host.',+ count: d => Number(d.count ?? 0),+ impact: 'An installed frontmatter pre-commit hook predates this release and checks working-tree files instead of staged content',+ instruction: 'Refresh it on the brain host with `gbrain frontmatter install-hook --force` (add `--source <id>` for one source); only the gbrain hook script is rewritten.',+ run: async (engine, scope) => (await import('./checks/frontmatter-hook.ts')).frontmatterHookCheck(engine, scope.sourceIds),+ },{id: 'orphan_persistence_bindings', resolution: 'repair', registration: 'wave',hostOnly: 'Bindings of removed sources are brain-wide persistence bookkeeping outside any source scope.',@@ -223,6 +245,12 @@ export async function runWaveChecks(engine: BrainEngine, opts: WaveScope & { onlreturn findings;}+/** The one source a finding names (`details.source_ids` of length 1), so its repair command can say `--source <id>`. */+export function findingSource(finding: Pick<WaveFinding, 'check'>): string | undefined {+ const ids = finding.check.details?.source_ids;+ return Array.isArray(ids) && ids.length === 1 && typeof ids[0] === 'string' ? ids[0] : undefined;+}+/** The repair kind that clears a wave finding, when its resolution is `repair`. */export function waveRepairKind(spec: WaveCheckSpec) {return spec.resolution === 'repair' ? repairForCheck(spec.id)?.kind : undefined;diff --git a/src/core/brain-writer.ts b/src/core/brain-writer.tsindex a8f96d9d50..3c6085d1a9 100644--- a/src/core/brain-writer.ts+++ b/src/core/brain-writer.ts@@ -53,12 +53,32 @@ export interface AuditFix {*/export type RecoverabilityByCode = Partial<Record<ParseValidationCode, { recoverable: number; unrecoverable: number }>>;+/**+ * #5988: files `gbrain repair frontmatter` can fix, by the cause it fixes:+ * recoverable `YAML_PARSE`, `needs_interpretation` (the held reading needs a+ * fold or a duplicate-key choice), a `#`-leading value YAML read as a comment+ * (`FRONTMATTER_COMMENT_VALUE` on title/name/description/summary),+ * `NESTED_QUOTES`, `NULL_BYTES`, `MISSING_CLOSE`, `SLUG_MISMATCH`. A file+ * counts once in `files` and once per cause in `by_code`.+ */+export interface RepairableReport {+ files: number;+ by_code: Partial<Record<RepairableCause, number>>;+ sample: string[];+}++export type RepairableCause = 'YAML_PARSE' | 'needs_interpretation' | 'FRONTMATTER_COMMENT_VALUE' | 'NESTED_QUOTES' | 'NULL_BYTES' | 'MISSING_CLOSE' | 'SLUG_MISMATCH';++const REPAIRABLE_ERRORS: ReadonlySet<string> = new Set(['NESTED_QUOTES', 'NULL_BYTES', 'MISSING_CLOSE', 'SLUG_MISMATCH']);+const RESCUE_KEYS: ReadonlySet<string> = new Set(['title', 'name', 'description', 'summary']);+export interface PerSourceReport {source_id: string;source_path: string;total: number;errors_by_code: Partial<Record<ParseValidationCode, number>>;recoverability_by_code?: RecoverabilityByCode;+ repairable?: RepairableReport;sample: { path: string; codes: ParseValidationCode[] }[];ignoredMissingOpen: number;/** Did this source finish the walk, get interrupted, or never start?@@ -734,6 +754,7 @@ function scanOneSource(const errorsByCode: Partial<Record<ParseValidationCode, number>> = {};const recoverability: RecoverabilityByCode = {};const sample: PerSourceReport['sample'] = [];+ const repairable: RepairableReport = { files: 0, by_code: {}, sample: [] };const rootResolved = resolve(sourcePath);let scanned = 0;let total = 0;@@ -774,10 +795,22 @@ function scanOneSource(ignoredMissingOpen++;return false;});+ const hold = classifyImportHold(parsed, { expectedSlug });+ const causes = new Set<RepairableCause>();+ for (const e of parsed.errors ?? []) {+ if (e.code === 'YAML_PARSE' && e.recoverable) causes.add('YAML_PARSE');+ else if (REPAIRABLE_ERRORS.has(e.code)) causes.add(e.code as RepairableCause);+ }+ if (hold?.reason === 'needs_interpretation') causes.add('needs_interpretation');+ if ((parsed.warnings ?? []).some(w => w.code === 'FRONTMATTER_COMMENT_VALUE' && RESCUE_KEYS.has(w.key))) causes.add('FRONTMATTER_COMMENT_VALUE');+ if (causes.size > 0) {+ repairable.files++;+ for (const cause of causes) repairable.by_code[cause] = (repairable.by_code[cause] ?? 0) + 1;+ if (repairable.sample.length < SAMPLE_PER_SOURCE) repairable.sample.push(relPath);+ }if (errs.length > 0) {total += errs.length;const codes: ParseValidationCode[] = [];- const hold = classifyImportHold(parsed, { expectedSlug });for (const e of errs) {errorsByCode[e.code] = (errorsByCode[e.code] ?? 0) + 1;codes.push(e.code);@@ -818,6 +851,7 @@ function scanOneSource(total,errors_by_code: errorsByCode,recoverability_by_code: recoverability,+ repairable,sample,ignoredMissingOpen,status: interrupted ? 'partial' : 'scanned',diff --git a/src/core/doctor-categories.ts b/src/core/doctor-categories.tsindex 0d8682ec38..b2c93ae194 100644--- a/src/core/doctor-categories.ts+++ b/src/core/doctor-categories.ts@@ -60,6 +60,7 @@ export const BRAIN_CHECK_NAMES: ReadonlySet<string> = new Set(['captured_facts_active','connector_checkpoints','connector_held_items',+ 'git_held_files','credential_projection_pending','derived_visibility','extractor_facts_expired',@@ -107,6 +108,7 @@ export const BRAIN_CHECK_NAMES: ReadonlySet<string> = new Set(['facts_extraction_health','facts_health','frontmatter_integrity',+ 'frontmatter_repairable','malformed_path_pages','memory_writeback','grade_confidence_drift',@@ -186,6 +188,7 @@ export const SKILL_CHECK_NAMES: ReadonlySet<string> = new Set([export const OPS_CHECK_NAMES: ReadonlySet<string> = new Set([// Agent operator wave: is an agent harness wired to this brain (registration read; --only adds the smoke test).'harness_wiring',+ 'frontmatter_hook',// F4b: PGLite row-delta planner statistics / Postgres autovacuum ANALYZE lag on the hot tables.'planner_stats_stale','alternative_providers',diff --git a/test/doctor-frontmatter-holds.test.ts b/test/doctor-frontmatter-holds.test.tsnew file mode 100644index 0000000000..d07148a22b--- /dev/null+++ b/test/doctor-frontmatter-holds.test.ts@@ -0,0 +1,210 @@+/**+ * #5988 doctor surfaces for held and repairable frontmatter. `git_held_files`+ * (Git-source holds) and `frontmatter_repairable` (files the repair can fix)+ * are wave findings the explicit-only `frontmatter` repair kind clears:+ * `doctor --remediation-plan --json` classifies them `explicit_kind_required`+ * with `gbrain repair frontmatter --source <id>`, and `--remediate+ * --include-repairs` never runs the kind. A deadline-partial scan is pending,+ * an outdated pre-commit hook is an operator finding, and the post-upgrade+ * banner tells the agent the next sync unblocks a source a file blocked.+ */+import { afterAll, beforeAll, expect, test } from 'bun:test';+import { execFileSync } from 'node:child_process';+import { randomUUID } from 'node:crypto';+import { mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from 'node:fs';+import { tmpdir } from 'node:os';+import { join } from 'node:path';+import type { BrainEngine } from '../src/core/engine.ts';+import { PGLiteEngine } from '../src/core/pglite-engine.ts';+import { claimWorktree } from '../src/core/persistence/ownership.ts';+import { disposePersistenceConsumer } from '../src/core/persistence/service.ts';+import { performManagedSync } from '../src/core/persistence/sync-run.ts';+import { readGitSourceHolds } from '../src/core/persistence/sync-holds.ts';+import type { SyncOpts } from '../src/commands/sync.ts';+import { gitHeldFilesCheck } from '../src/commands/doctor/checks/git-holds.ts';+import { frontmatterRepairableCheck, frontmatterRepairableFromReport } from '../src/commands/doctor/checks/frontmatter-repairable.ts';+import { frontmatterHookCheck } from '../src/commands/doctor/checks/frontmatter-hook.ts';+import { WAVE_CHECKS, runWaveChecks, type WaveFinding } from '../src/commands/doctor/wave-checks.ts';+import { classifyWaveFindings, runRemediate, runRemediationPlan } from '../src/commands/doctor/remediate.ts';+import { postUpgradeRecoveryBanner } from '../src/commands/doctor/upgrade-banner.ts';+import { repairForCheck } from '../src/core/repair/registry.ts';+import type { AuditReport } from '../src/core/brain-writer.ts';+import { capture } from './helpers/wave-scenarios.ts';+import { approvedRemediateArgs } from './helpers/remediate-approval.ts';+import { isolatedPersistencePostgres } from './helpers/persistence-postgres.ts';+import { testBackends } from './helpers/test-backends.ts';+import { withEnv } from './helpers/with-env.ts';++const backends = testBackends();+const home = mkdtempSync(join(tmpdir(), 'gbrain-doctor-holds-'));+const engines: BrainEngine[] = [];+let closePostgres: (() => Promise<void>) | undefined;+const env = { GBRAIN_HOME: home, GBRAIN_SYNC_FAILURES_DIR: home };+const git = (root: string, ...args: string[]) => execFileSync('git', ['-C', root, ...args], { encoding: 'utf8', stdio: ['ignore', 'pipe', 'pipe'] }).trim();+const commit = (root: string) => { git(root, 'add', '-A'); git(root, '-c', 'user.name=Example', '-c', '[email protected]', 'commit', '-qm', 'content'); };+const note = (title: string) => `---\ntitle: ${title}\n---\nA synthetic observation.\n`;+const FOLDED = '---\ntitle: alice-example first line\nalice-example second line\n---\nA synthetic post.\n';+const AUTHOR = '---\ntitle: Payments roundup\nauthor: acme-example (citing fund-a / fund-b) (original: https://example.com/a/1)\n---\nA synthetic roundup.\n';+const OLD_HOOK = '#!/bin/sh\n# gbrain frontmatter pre-commit hook (v0.22.4+)\ngbrain frontmatter validate "$f"\n';++beforeAll(async () => {+ if (backends.includes('pglite')) { const engine = new PGLiteEngine(); await engine.connect({}); await engine.initSchema(); engines.push(engine); }+ if (backends.includes('postgres')) { const pg = await isolatedPersistencePostgres(process.env.DATABASE_URL!); engines.push(pg.engine); closePostgres = pg.close; }+}, 120_000);++afterAll(async () => {+ for (const engine of engines) { await disposePersistenceConsumer(engine); await engine.disconnect(); }+ await closePostgres?.(); rmSync(home, { recursive: true, force: true });+});++async function source(engine: BrainEngine, files: Record<string, string>) {+ const id = `fmh-${randomUUID().replace(/-/g, '').slice(0, 20)}`, root = join(home, id);+ mkdirSync(root, { recursive: true }); git(root, 'init', '-q');+ for (const [path, content] of Object.entries(files)) { mkdirSync(join(root, path, '..'), { recursive: true }); writeFileSync(join(root, path), content); }+ commit(root);+ await engine.executeRaw('UPDATE persistence_brain SET enabled=false WHERE singleton=1');+ await engine.executeRaw("INSERT INTO sources(id,name,local_path,config) VALUES($1,$1,$2,'{}')", [id, root]);+ await claimWorktree(engine, id, root);+ await engine.executeRaw('UPDATE persistence_brain SET enabled=true WHERE singleton=1');+ const sync = (extra: Partial<SyncOpts> = {}) => performManagedSync(engine, { sourceId: id, noPull: true, noEmbed: true, noExtract: true, ...extra });+ return { id, root, sync };+}++/** Each test sees only its own sources: the wave checks are brain-wide. */+async function each(run: (engine: BrainEngine) => Promise<void>) {+ await withEnv(env, async () => {+ for (const engine of engines) {+ try { await run(engine); }+ finally {+ await disposePersistenceConsumer(engine);+ for (const key of ['sync.holds', 'sync.hold_escalate_count']) await engine.unsetConfig(key);+ await engine.executeRaw('UPDATE persistence_brain SET enabled=false WHERE singleton=1');+ await engine.executeRaw("UPDATE sources SET local_path=NULL WHERE id LIKE 'fmh-%'");+ await engine.executeRaw("DELETE FROM op_checkpoints WHERE op LIKE 'sync-hold%' OR op LIKE 'managed-sync%'");+ }+ }+ });+}++const finding = (findings: Array<{ check_id: string }>, id: string) => findings.find(f => f.check_id === id);++test('the frontmatter kind owns both findings and both are host-only repair findings', () => {+ for (const id of ['git_held_files', 'frontmatter_repairable']) {+ const spec = WAVE_CHECKS.find(s => s.id === id)!;+ expect(spec).toMatchObject({ resolution: 'repair' });+ expect(typeof spec.hostOnly).toBe('string');+ expect(repairForCheck(id)).toMatchObject({ kind: 'frontmatter', explicit_only: true });+ }+ expect(WAVE_CHECKS.find(s => s.id === 'frontmatter_hook')).toMatchObject({ resolution: 'operator' });+});++test('a clean brain has no held, repairable or hook finding', () => each(async engine => {+ const s = await source(engine, { 'notes/a.md': note('A'), 'notes/b.md': note('B') });+ expect((await s.sync()).status).toBe('first_sync');+ expect(await gitHeldFilesCheck(engine)).toMatchObject({ status: 'ok', details: { held: 0 } });+ expect(await frontmatterRepairableCheck(engine, s.id)).toMatchObject({ status: 'ok', details: { repairable: 0, partial: false } });+ expect(await frontmatterHookCheck(engine)).toMatchObject({ status: 'ok' });+ const plan = JSON.parse((await capture(() => runRemediationPlan(engine, ['--remediation-plan', '--no-embed', '--json']))).out) as { findings: Array<{ check_id: string }> };+ for (const id of ['git_held_files', 'frontmatter_repairable', 'frontmatter_hook']) expect(finding(plan.findings, id)).toBeUndefined();+ expect((await postUpgradeRecoveryBanner(engine, 'host')).join('\n')).not.toMatch(/git_held_files|frontmatter_/);+}), 180_000);++test('holds and repairable files: the plan says explicit_kind_required with the source preview, and remediate never runs the kind', () => each(async engine => {+ const s = await source(engine, { 'notes/a.md': note('A'), 'notes/held-one.md': FOLDED, 'notes/held-two.md': FOLDED, 'notes/roundup.md': AUTHOR });+ const synced = await s.sync();+ expect(synced).toMatchObject({ status: 'first_sync', held_count: 2 });+ const preview = `gbrain repair frontmatter --source ${s.id}`;++ const held = await gitHeldFilesCheck(engine);+ expect(held).toMatchObject({ status: 'warn', details: { held: 2, source_ids: [s.id] },+ fix: { argv: ['gbrain', 'repair', 'frontmatter', '--source', s.id] } });+ expect(held.message).toContain(`${s.id}: 2 held (0 page(s) keep an older revision, 2 file(s) have no page)`);+ expect(held.message).toContain('notes/held-one.md [invalid_frontmatter/needs_interpretation]');+ expect(held.message).toContain('read-only for put_page until the file is repaired');+ expect(held.message).toContain(`gbrain sources status ${s.id}`);+ expect(held.message).toContain(preview);+ expect((held.details as { sources: Array<{ first: Array<{ why: string }> }> }).sources[0]!.first[0]!.why).toContain('needs an interpretation');++ const repairable = await frontmatterRepairableCheck(engine, s.id);+ expect(repairable).toMatchObject({ status: 'warn', details: { repairable: 3, source_ids: [s.id] } });+ expect((repairable.details as { sources: Array<{ by_code: Record<string, number> }> }).sources[0]!.by_code).toEqual({ needs_interpretation: 2, YAML_PARSE: 1 });+ expect(repairable.message).toContain(preview);++ const before = readFileSync(join(s.root, 'notes/held-one.md'), 'utf8');+ const plan = JSON.parse((await capture(() => runRemediationPlan(engine, ['--remediation-plan', '--no-embed', '--json']))).out) as {+ findings: Array<{ check_id: string; class: string; repair_kind?: string; command?: string }>; repair_steps?: Array<{ kind: string }> };+ for (const id of ['git_held_files', 'frontmatter_repairable']) {+ expect(finding(plan.findings, id)).toMatchObject({ class: 'explicit_kind_required', repair_kind: 'frontmatter', command: preview });+ }+ expect((plan.repair_steps ?? []).map(step => step.kind)).not.toContain('frontmatter');+ const text = (await capture(() => runRemediationPlan(engine, ['--remediation-plan', '--no-embed']))).out;+ expect(text).toContain(` git_held_files: ${preview}`);++ const run = JSON.parse((await capture(async () => runRemediate(engine, await approvedRemediateArgs(engine,+ ['--remediate', '--yes', '--include-repairs', '--no-embed', '--max-usd', '0', '--json'])))).out) as {+ repairs?: Array<{ kind: string }>; findings: Array<{ check_id: string; class: string; command?: string }> };+ expect((run.repairs ?? []).map(r => r.kind)).not.toContain('frontmatter');+ expect(finding(run.findings, 'git_held_files')).toMatchObject({ class: 'explicit_kind_required', command: preview });+ expect(readFileSync(join(s.root, 'notes/held-one.md'), 'utf8')).toBe(before);+ expect((await readGitSourceHolds(engine, { sourceIds: [s.id] }))[0]?.count).toBe(2);++ const banner = (await postUpgradeRecoveryBanner(engine, 'host')).join('\n');+ expect(banner).toContain(`[AGENT] git_held_files: 2 (explicit_kind_required; preview with: ${preview})`);+ expect(banner).not.toMatch(/--apply|--yes/);++ await engine.setConfig('sync.hold_escalate_count', '1');+ const escalated = await gitHeldFilesCheck(engine);+ expect(escalated.status).toBe('fail');+ expect(escalated.message).toContain(`Escalated: ${s.id} hold more than 1 files`);+}), 240_000);++test('a deadline-partial frontmatter scan reports pending, never clean or explicit', () => {+ const report: AuditReport = { ok: false, total: 0, errors_by_code: {}, partial: true, aborted_at_source: 'wiki', scanned_at: new Date().toISOString(),+ per_source: [{ source_id: 'wiki', source_path: '/tmp/wiki', total: 0, errors_by_code: {}, sample: [], ignoredMissingOpen: 0, status: 'partial', files_scanned: 3,+ repairable: { files: 1, by_code: { YAML_PARSE: 1 }, sample: ['notes/a.md'] } }] };+ const check = frontmatterRepairableFromReport(report, 1000);+ expect(check).toMatchObject({ status: 'warn', details: { partial: true, unscanned: ['wiki'] } });+ expect(check.message).toContain('PARTIAL SCAN');+ const spec = WAVE_CHECKS.find(s => s.id === 'frontmatter_repairable')!;+ const now: WaveFinding = { spec, check, state: 'finding' };+ expect(classifyWaveFindings([now], [now], { repairs: [], repairs_skipped: [] })).toEqual([expect.objectContaining({+ check_id: 'frontmatter_repairable', class: 'pending', repair_kind: 'frontmatter', instruction: expect.stringContaining('GBRAIN_DOCTOR_FM_TIMEOUT_MS') })]);++ const clean = frontmatterRepairableFromReport({ ...report, per_source: [{ ...report.per_source[0]!, repairable: { files: 0, by_code: {}, sample: [] } }] }, 1000);+ expect(clean.status).toBe('warn');+ expect(classifyWaveFindings([], [{ spec, check: clean, state: 'finding' }], { repairs: [], repairs_skipped: [] })[0]!.class).toBe('pending');+});++test('an older installed pre-commit hook is an operator finding naming install-hook --force', () => each(async engine => {+ const s = await source(engine, { 'notes/a.md': note('A') });+ mkdirSync(join(s.root, '.githooks'), { recursive: true });+ writeFileSync(join(s.root, '.githooks', 'pre-commit'), OLD_HOOK);+ const check = await frontmatterHookCheck(engine);+ expect(check).toMatchObject({ status: 'warn', details: { count: 1 }, fix: { argv: ['gbrain', 'frontmatter', 'install-hook', '--source', s.id, '--force'] } });+ expect(check.message).toContain(`gbrain frontmatter install-hook --source ${s.id} --force`);+ const waves = (await runWaveChecks(engine)).filter(f => f.spec.id === 'frontmatter_hook');+ expect(classifyWaveFindings(waves, waves, { repairs: [], repairs_skipped: [] })).toEqual([expect.objectContaining({+ check_id: 'frontmatter_hook', class: 'operator_required', instruction: expect.stringContaining('gbrain frontmatter install-hook --force') })]);+ const banner = (await postUpgradeRecoveryBanner(engine, 'host')).join('\n');+ expect(banner).toContain(`refresh it with gbrain frontmatter install-hook --source ${s.id} --force`);+}), 120_000);++test('post-upgrade: a source a file blocked is told the next sync recovers it, with the unblock and repair commands', () => each(async engine => {+ await engine.setConfig('sync.holds', 'fail');+ const s = await source(engine, { 'notes/broken.md': FOLDED, 'notes/ok.md': note('Ok') });+ expect((await s.sync()).status).toBe('blocked_by_failures');+ await engine.unsetConfig('sync.holds');+ const [failed] = await engine.executeRaw<{ request_id: string }>("SELECT request_id::text AS request_id FROM persistence_requests WHERE source_id=$1 AND state='failed'", [s.id]);+ // The exact text an older release stored for this refusal.+ await engine.executeRaw("UPDATE persistence_requests SET error_code='invalid_params',error_message=$2 WHERE request_id=$1::uuid",+ [failed!.request_id, 'Invalid YAML frontmatter: bad indentation of a mapping entry (3:1)']);++ const banner = (await postUpgradeRecoveryBanner(engine, 'host')).join('\n');+ expect(banner).toContain(`[AGENT] frontmatter_holds: 1 source(s) are blocked by a file gbrain could not import (${s.id}).`);+ expect(banner).toContain('The next scheduled or manual sync recovers a blocked source automatically; '+ + `to do it now run gbrain sync --source ${s.id} --no-pull.`);+ expect(banner).toContain(`gbrain repair frontmatter --source ${s.id}`);++ expect(await s.sync()).toMatchObject({ status: 'first_sync', held_count: 1, converted_from_failed: [failed!.request_id] });+ expect((await postUpgradeRecoveryBanner(engine, 'host')).join('\n')).not.toContain('frontmatter_holds:');+}), 180_000);diff --git a/test/fixtures/goldens/doctor/json-pglite-degraded.json b/test/fixtures/goldens/doctor/json-pglite-degraded.jsonindex 7faa0e10c7..dfe24bce7b 100644--- a/test/fixtures/goldens/doctor/json-pglite-degraded.json+++ b/test/fixtures/goldens/doctor/json-pglite-degraded.json@@ -507,7 +507,7 @@},{"category": "meta",- "message": "Version 198 (latest: 198)",+ "message": "Version 199 (latest: 199)","name": "schema_version","status": "ok"},@@ -730,6 +730,30 @@"name": "connector_held_items","status": "ok"},+ {+ "category": "brain",+ "details": {+ "docs": "docs/guides/repair.md#held-files",+ "escalate_count": 50,+ "held": 0,+ "source_ids": [],+ "sources": []+ },+ "message": "No Git source files are held.",+ "name": "git_held_files",+ "status": "ok"+ },+ {+ "category": "ops",+ "details": {+ "count": 0,+ "docs": "docs/guides/repair.md#held-files",+ "hooks": []+ },+ "message": "No outdated gbrain frontmatter pre-commit hook is installed.",+ "name": "frontmatter_hook",+ "status": "ok"+ },{"category": "brain","details": {@@ -979,6 +1003,20 @@"name": "frontmatter_integrity","status": "ok"},+ {+ "category": "brain",+ "details": {+ "docs": "docs/guides/repair.md#frontmatter",+ "partial": false,+ "repairable": 0,+ "source_ids": [],+ "sources": [],+ "unscanned": []+ },+ "message": "No file has frontmatter gbrain repair frontmatter would fix.",+ "name": "frontmatter_repairable",+ "status": "ok"+ },{"category": "meta","message": "No capture failures in the last 24h",diff --git a/test/fixtures/goldens/doctor/json-pglite-fresh.json b/test/fixtures/goldens/doctor/json-pglite-fresh.jsonindex f8ce9a12d3..bda53a8f2f 100644--- a/test/fixtures/goldens/doctor/json-pglite-fresh.json+++ b/test/fixtures/goldens/doctor/json-pglite-fresh.json@@ -510,7 +510,7 @@},{"category": "meta",- "message": "Version 198 (latest: 198)",+ "message": "Version 199 (latest: 199)","name": "schema_version","status": "ok"},@@ -818,6 +818,30 @@"name": "connector_held_items","status": "ok"},+ {+ "category": "brain",+ "details": {+ "docs": "docs/guides/repair.md#held-files",+ "escalate_count": 50,+ "held": 0,+ "source_ids": [],+ "sources": []+ },+ "message": "No Git source files are held.",+ "name": "git_held_files",+ "status": "ok"+ },+ {+ "category": "ops",+ "details": {+ "count": 0,+ "docs": "docs/guides/repair.md#held-files",+ "hooks": []+ },+ "message": "No outdated gbrain frontmatter pre-commit hook is installed.",+ "name": "frontmatter_hook",+ "status": "ok"+ },{"category": "brain","details": {@@ -1067,6 +1091,20 @@"name": "frontmatter_integrity","status": "ok"},+ {+ "category": "brain",+ "details": {+ "docs": "docs/guides/repair.md#frontmatter",+ "partial": false,+ "repairable": 0,+ "source_ids": [],+ "sources": [],+ "unscanned": []+ },+ "message": "No file has frontmatter gbrain repair frontmatter would fix.",+ "name": "frontmatter_repairable",+ "status": "ok"+ },{"category": "meta","message": "No capture failures in the last 24h",diff --git a/test/fixtures/goldens/doctor/json-postgres-fresh.json b/test/fixtures/goldens/doctor/json-postgres-fresh.jsonindex 0c9ef0501c..fc61d8855a 100644--- a/test/fixtures/goldens/doctor/json-postgres-fresh.json+++ b/test/fixtures/goldens/doctor/json-postgres-fresh.json@@ -503,7 +503,7 @@},{"category": "meta",- "message": "Version 198 (latest: 198)",+ "message": "Version 199 (latest: 199)","name": "schema_version","status": "ok"},@@ -807,6 +807,30 @@"name": "connector_held_items","status": "ok"},+ {+ "category": "brain",+ "details": {+ "docs": "docs/guides/repair.md#held-files",+ "escalate_count": 50,+ "held": 0,+ "source_ids": [],+ "sources": []+ },+ "message": "No Git source files are held.",+ "name": "git_held_files",+ "status": "ok"+ },+ {+ "category": "ops",+ "details": {+ "count": 0,+ "docs": "docs/guides/repair.md#held-files",+ "hooks": []+ },+ "message": "No outdated gbrain frontmatter pre-commit hook is installed.",+ "name": "frontmatter_hook",+ "status": "ok"+ },{"category": "brain","details": {@@ -1060,6 +1084,20 @@"name": "frontmatter_integrity","status": "ok"},+ {+ "category": "brain",+ "details": {+ "docs": "docs/guides/repair.md#frontmatter",+ "partial": false,+ "repairable": 0,+ "source_ids": [],+ "sources": [],+ "unscanned": []+ },+ "message": "No file has frontmatter gbrain repair frontmatter would fix.",+ "name": "frontmatter_repairable",+ "status": "ok"+ },{"category": "meta","message": "No capture failures in the last 24h",diff --git a/test/fixtures/goldens/doctor/registry-build-checks.json b/test/fixtures/goldens/doctor/registry-build-checks.jsonindex ecd3fe34e5..84ece91565 100644--- a/test/fixtures/goldens/doctor/registry-build-checks.json+++ b/test/fixtures/goldens/doctor/registry-build-checks.json@@ -377,6 +377,14 @@"category": "brain","name": "connector_held_items"},+ {+ "category": "brain",+ "name": "git_held_files"+ },+ {+ "category": "ops",+ "name": "frontmatter_hook"+ },{"category": "brain","name": "orphan_persistence_bindings"@@ -485,6 +493,10 @@"category": "brain","name": "frontmatter_integrity"},+ {+ "category": "brain",+ "name": "frontmatter_repairable"+ },{"category": "meta","name": "eval_capture"