Garry's Opinionated OpenClaw/Hermes Agent Brain
TypeScript
feat(frontmatter): validate --stdin/--staged/--importable and safe --fix repair (#5988)
garrytana40ee975bbc6
diff --git a/docs/architecture/KEY_FILES.md b/docs/architecture/KEY_FILES.mdindex 6e56bac86c..2efc5ebe76 100644--- a/docs/architecture/KEY_FILES.md+++ b/docs/architecture/KEY_FILES.md@@ -32,7 +32,7 @@ boundary and add its link here rather than raising the cap.| [Commands (2/6)](key-files/commands-2.md) | `src/commands/doctor.ts` and `src/commands/doctor/` || [Commands (2/6, continued)](key-files/commands-2-continued.md) | `src/commands/dream-retriage.ts` through `src/commands/embed.ts` || [Commands (3/6)](key-files/commands-3.md) | `src/commands/engine-status.ts` through `src/commands/frontmatter-install-hook.ts` |-| [Commands (4/6)](key-files/commands-4.md) | `src/commands/graph-query.ts` through `src/commands/pglite-repair.ts` |+| [Commands (4/6)](key-files/commands-4.md) | `src/commands/frontmatter.ts` through `src/commands/pglite-repair.ts` || [Commands (4/6, continued)](key-files/commands-4-continued.md) | `src/commands/protocol.ts` through `src/commands/reindex-search-vector.ts`, `init-mode-picker.ts`, `src/core/embedding-migration-cli.ts` || [Commands (5/6)](key-files/commands-5.md) | `src/commands/reindex.ts` through `src/commands/storage.ts` || [Commands (6/6)](key-files/commands-6.md) | `src/commands/sync.ts` through `src/commands/whoknows.ts` |diff --git a/docs/architecture/key-files/commands-4.md b/docs/architecture/key-files/commands-4.mdindex 71fe2301a8..6860ca5651 100644--- a/docs/architecture/key-files/commands-4.md+++ b/docs/architecture/key-files/commands-4.md@@ -3,6 +3,8 @@[Subsystem index](../KEY_FILES.md). Read only the entries relevant to your change.Current behavior and load-bearing invariants; history belongs in Git and CHANGELOG.+- `src/commands/frontmatter.ts` — `gbrain frontmatter validate|generate|audit|install-hook`. `validate` keeps the producer rule: exit 1 on any `parseMarkdown` validation error, including `YAML_PARSE` that ingestion recovers by quoting (those print "importable but not canonical" with the `--fix` command). `--importable` switches to the ingestion view through `screenImportContent` (exit 1 only for a hold). Inputs: a file or directory, `--stdin`/`-` (with optional `--path <source-relative path>` for the slug check, otherwise reported skipped), or `--staged [paths]` (git index blobs via one `ls-files --stage` and one `cat-file --batch`; a failing blob whose working copy passes says to `git add` it). `--fix` runs `autoFixFrontmatter` then `repairRecoverableFrontmatter` (`brain-writer.ts`: safe `quote` recoveries line by line, CRLF/BOM kept, gated on the strict parse equalling what ingestion read; `--include-ambiguous` adds fold/dup/unclosed proposals and `#`-title quoting), re-validates and exits 1 if errors remain, prints the restage step inside git, and refuses on a managed root with `writer_coordinator_required` whose fix is `gbrain repair frontmatter [--source <id>]`. `audit --json` adds `recoverability_by_code` (imported anyway vs held on import). `runFrontmatter(args, io)` takes stdin-stream and git-cwd test seams. Pinned by `test/frontmatter-cli.test.ts` and `test/frontmatter-validate-producer.test.ts`.+- `src/commands/graph-query.ts` — `gbrain graph-query <slug> [--type T] [--depth N] [--direction in|out|both] [--source <id>] [--include-foreign]`: typed-edge relationship traversal (renders indented tree). The local walk is scoped to the resolved source (`--source` / `GBRAIN_SOURCE` / `.gbrain-source` / path match / brain default via `resolveSourceId`, the same scalar scope the `traverse_graph` op gets from `sourceScopeOpts`); an explicit `--source` that fails to resolve throws. `--include-foreign` (or `--source __all__`) drops the scope so the walk spans every source. The foreign-edge footer (`N edges to foreign-source pages hidden; pass --include-foreign`) prints only when the walk was actually scoped, so cross-source edges never disappear silently and the footer never describes a filter that did not apply. The local path uses `engine.traversePathsDetailed` and prints a stderr note when the walk hit `TRAVERSE_PATH_ROW_CAP` (shallowest edges kept; lower `--depth` or narrow with `--type`/`--direction`); the thin-client path goes through the `traverse_graph` op, which has no `source_id` param (the server scopes the walk to the caller's grant): an explicit `--source` there is rejected with exit 1 (same policy + wording as `applyThinClientSourceScope`, never silently dropped) and `--include-foreign` prints a stderr note that it is not forwarded. Pinned by `test/graph-query.test.ts` (local) + `test/graph-query-thin-client-source-flag.serial.test.ts` (thin client; mocks `isThinClient` + `callRemoteTool`).- `src/commands/import.ts` — `gbrain import <path> [--source-id <id> | --source <id>]`: page import with ordinary-import progress checkpoints and content-hash revalidation; company-brain ingestion resumes an approved committed manifest. `runImport` contains NO `process.exit`: all five preflight/argv failure sites (deferred-setup embedding sentinel, missing embedding credentials, invalid `--workers`, missing dir arg, unreadable target) throw the exported typed `ImportAbortError` (carries `exitCode`; the user-facing message is printed at the throw site), so in-process callers — the `sync_brain` MCP op, autopilot, the Minions `import` handler — survive a failed preflight as a normal tool/job error instead of the whole serving process dying mid-call. The CLI's `import` case catches it and exits `e.exitCode`. Pinned by `test/import-abort-error.test.ts`. Human-only output (the `info()` lines and the end-of-run `Import complete` summary) goes through `slog()` from `console-prefix.ts` — identical to `console.log` outside a wrap, but an in-process caller in its own `--json` mode (`sync --json` → `performFullSync` → `runImport`, wrapped in `withHumanLogsToStderr`) keeps stdout pure JSON; `import --json` itself sends them to stderr directly. Pinned by `test/sync-json-stdout-clean.test.ts` (first-sync case) + `test/import-json-stdout.serial.test.ts`. The `--json` payload also carries `source_id`, the effective destination the pages were written to (`sourceId ?? 'default'`, identical to the ingest_log row and to the import-file write) — NOT the resolver's tier answer, since `runImport` adopts only flag/env/sole_non_default resolutions and lets dotfile/local_path/brain_default fall through to `default`; pinned by the `--json payload names …` cases in `test/import-source-id.test.ts`. `--source-id <id>` (alias `--source <id>`; passing both with different values aborts) routes pages to the named source (resolved via `resolveSourceWithTier()` at the boundary; consistent across `import`, `extract`, `graph-query`, `sources current`; `graph-query` takes `--source <id>`). Pinned by `test/import-source-id.test.ts`. An unscoped import that resolves to tier `seed_default` runs the default-write assessment through `assessDefaultWriteGuardOnce(engine)` (memoized per engine — in-process callers such as the `sync_brain` op, autopilot, and minion sync invoke `runImport` repeatedly on one engine) and WARNS via `formatDefaultWriteWarning(a, '--source-id')` when the brain's pages overwhelmingly live outside `default` — never aborts, since aborting would take an in-process host down mid-call; `GBRAIN_ALLOW_DEFAULT_WRITE=1` skips it. Pinned by `test/import-default-write-guard-once.test.ts`. `gbrain import` CLI + `runImport` library entrypoint. Ordinary imports use a path-set progress checkpoint via `src/core/import-checkpoint.ts`; their `runImport` path walks all current files, including previously completed paths, through the existing `importFile` content-hash comparison. Persisted path membership and an mtime before checkpoint flush do not prove the imported revision is still current. Unchanged files avoid re-import, while edits, new files, and failed files are reconsidered. Ordinary resume pays the full walk/read/hash cost rather than blindly skipping paths. Company-brain ingestion instead skips completed paths within its immutable approved committed manifest, using protected `op_checkpoints` entries keyed by the admission receipt; it does not resume from the ordinary JSON checkpoint. See [company-brain ingestion](company-brain.md). The walk still applies `sortNewestFirst()` for embed-cost ordering. A file enters `completed: Set<relativePath>` only when its `processFile` returns success (including content-hash short-circuit no-ops); failed files never enter the set so the next run retries them automatically with no manual `~/.gbrain/import-checkpoint.json` delete. Progress remains completion-based and sort-order-independent; old positional checkpoints are discarded with a stderr diagnostic. Checkpoint persists every 100 successful adds, not every 100 processed files. The `managedBookmark` opt (set by `performFullSync` when `runImport` is the full-sync engine) suppresses `runImport`'s own `sync.last_commit` advance so the shared `applySyncFailureGate` (`src/core/sync-failure-ledger.ts`) owns the bookmark + failure-ledger gating on that path — one gate decides advance/block/auto-skip across both sync paths. Pinned by `test/import-checkpoint.test.ts` + `test/import-resume.test.ts` (incl. the SLUG_MISMATCH retry case). `collectSyncableFiles`' shared emit filter `isCollectibleForWalker` applies the SAME segment-level `pruneDir` gate as incremental sync's `classifySync` — load-bearing for the `git ls-files` fast path, which enumerates tracked files under dot-dirs/vendored trees that the FS walk never descends into; without it `sync --full` would import (and resurrect soft-deleted) pages incremental sync excludes. Pinned by `test/import-git-fastpath-prune.test.ts`. `runImport` opts also carry `exclude` (glob filter over dir-relative paths, threaded by `performFullSync` for `sync --exclude`; warns when every file is excluded — NAV-4) and `slugRoot` (slug/`source_path` base for monorepo subdir syncs; the progress checkpoint stays dir-relative; ordinary imports do not use `resumeFilter` to skip paths). The `--json` payload carries, beside the counts, `unchanged` (content-hash no-ops), `malformed_skipped`, and `failures: [{path, error}]` — rethurned per-file failures `importFile` RETURNS (invalid frontmatter, oversize, symlink, slug mismatch) count under both `skipped`, anotd `errors`, are excluded from `unchanged`, and produce `status: "partial"` with a nonzero CLI exit. Failed imports retain their completed-path checkpoint; queued imports report failure instead of successful completion. The failure ledger is written only for gGit- repo dsitories, so the JSON faislure list remains a non-gGit caller's only per-file channel. Pinned by `test/import-json-stdout.serial.test.ts`. A directory the enclosing git repository ignores (for example a scratch folder under `.context/`) returns no `git ls-files` rows, so `gitListSyncableFiles` falls back to the filesystem walk when `git check-ignore` reports the directory itself ignored; an explicit import of it no longer succeeds with zero files (`test/import-ignored-root.test.ts`).diff --git a/scripts/structural-suites.tsv b/scripts/structural-suites.tsvindex d2d318e7e6..bfc5bd9918 100644--- a/scripts/structural-suites.tsv+++ b/scripts/structural-suites.tsv@@ -175,7 +175,7 @@ test/fix-wave-structural.test.ts v0.41.8.0 #1340 — PGLite WASM init classifiertest/fix-wave-structural.test.ts v0.42.20.0 — background-work registry drains every sink before disconnect 9 readFileSync,source-surface-helpertest/fix-wave-structural.test.ts v0.42.20.0 — search-cache drained via the background-work registry 1 source-surface-helpertest/fix-wave-structural.test.ts v0.42.43.0 #2095 — volunteer-events sink + cycle purge wiring (structural pins) 2 readFileSync,source-surface-helper-test/frontmatter-install-hook.test.ts frontmatter install-hook (B13) 22 readFileSync+test/frontmatter-install-hook.test.ts frontmatter install-hook (B13) 25 readFileSynctest/gbrain-owned-page-types.test.ts #5881 gbrain-owned page types are declared by gbrain-base-v2 3 readFileSynctest/get-page-federated-scope.test.ts #2555 get_chunks federated scope 5 source-surface-helpertest/get-page-federated-scope.test.ts #4275 alias hop scope: archived sources, include_deleted, fuzzy precedence, grant precedence 5 source-surface-helperdiff --git a/src/commands/frontmatter.ts b/src/commands/frontmatter.tsindex 350d468652..251e4ba970 100644--- a/src/commands/frontmatter.ts+++ b/src/commands/frontmatter.ts@@ -1,12 +1,16 @@-import { assertManagedFilesystemWrite } from '../core/persistence/filesystem-guard.ts';+import { assertManagedFilesystemWrite, managedFilesystemRootFor } from '../core/persistence/filesystem-guard.ts';/*** gbrain frontmatter — Frontmatter validation, audit, and auto-repair.** Subcommands:- * gbrain frontmatter validate <path> [--json] [--fix] [--dry-run]- * Validate one file or recursively a directory. --fix writes centralized- * backups under ~/.gbrain/backups/frontmatter/... then rewrites in place.- * --dry-run previews without writing.+ * gbrain frontmatter validate <path> [--json] [--importable] [--fix [--include-ambiguous]] [--dry-run]+ * gbrain frontmatter validate --stdin|- [--path <source-relative path>] [--importable] [--json]+ * gbrain frontmatter validate --staged [<path>...] [--importable] [--json]+ * Validate one file, a directory, piped content, or staged git blobs.+ * Strict producer rule by default (any error fails); --importable is the+ * ingestion hold view. --fix writes centralized backups under+ * ~/.gbrain/backups/frontmatter/... then rewrites in place and+ * re-validates. --dry-run previews without writing.** gbrain frontmatter audit [--source <id>] [--json]* Read-only scan across all registered sources (or one with --source).@@ -17,14 +21,20 @@ import { assertManagedFilesystemWrite } from '../core/persistence/filesystem-gua*/import { readFileSync, writeFileSync, existsSync, lstatSync, readdirSync } from 'fs';+import { execFileSync } from 'child_process';import { setCliExitVerdict } from '../core/cli-force-exit.ts';-import { join, relative, resolve, basename, dirname } from 'path';+import { join, relative, resolve, basename, dirname, isAbsolute, posix } from 'path';import type { BrainEngine } from '../core/engine.ts';import { loadConfig, toEngineConfig } from '../core/config.ts';import { createEngine } from '../core/engine-factory.ts';-import { parseMarkdown, type ParseValidationCode } from '../core/markdown.ts';+import { parseMarkdown, type ParseValidationCode, type ParseWarningCode } from '../core/markdown.ts';+import { MAX_FILE_SIZE, screenImportContent, type ContentRefusal } from '../core/import-screen.ts';+import { readStdinBounded } from '../core/interaction.ts';+import { OperationError, opError } from '../core/ops/contract.ts';+import { shellQuote } from '../core/shell-quote.ts';import {autoFixFrontmatter,+ repairRecoverableFrontmatter,createFrontmatterBackup,isFrontmatterScannablePath,makeFrontmatterBackupRunId,@@ -35,7 +45,13 @@ import {import { collectGitVisibleFiles } from '../core/git-visible-files.ts';import { isMarkdownFilePath, pruneDir, slugifyPath } from '../core/sync.ts';-export async function runFrontmatter(args: string[]): Promise<void> {+/** Test seams: the stream `validate --stdin` reads, and the directory `--staged` runs git in. */+export interface FrontmatterIo {+ stdin?: NodeJS.ReadableStream;+ cwd?: string;+}++export async function runFrontmatter(args: string[], io: FrontmatterIo = {}): Promise<void> {const sub = args[0];if (!sub || sub === '--help' || sub === '-h') {printHelp();@@ -44,7 +60,7 @@ export async function runFrontmatter(args: string[]): Promise<void> {const rest = args.slice(1);if (sub === 'validate') {- await runValidate(rest);+ await runValidate(rest, io);return;}if (sub === 'audit') {@@ -85,7 +101,9 @@ function printHelp() {console.log(`gbrain frontmatter — frontmatter validation, audit, auto-repair, and generationUsage:- gbrain frontmatter validate <path> [--json] [--fix] [--dry-run]+ gbrain frontmatter validate <path> [--json] [--importable] [--fix [--include-ambiguous]] [--dry-run]+ gbrain frontmatter validate --stdin [--path <source-relative path>] [--importable] [--json]+ gbrain frontmatter validate --staged [<path>...] [--importable] [--json]gbrain frontmatter generate <path> [--fix] [--dry-run] [--json] [--include-catch-all]gbrain frontmatter audit [--source <id>] [--json]gbrain frontmatter install-hook [--source <id>] [--force] [--uninstall]@@ -95,14 +113,34 @@ validateparseMarkdown(..., {validate:true}); errors are reported by code:MISSING_OPEN, MISSING_CLOSE, YAML_PARSE, SLUG_MISMATCH,NULL_BYTES, NESTED_QUOTES, EMPTY_FRONTMATTER-- --fix Auto-repair the fixable subset (NULL_BYTES, MISSING_CLOSE,- NESTED_QUOTES, SLUG_MISMATCH). Writes a backup under- ~/.gbrain/backups/frontmatter/... before any in-place rewrite.- Backups work for both git and non-git brain repos without- littering the source tree.- --dry-run Preview --fix without writing.- --json Emit a JSON envelope on stdout.+ Producer rule (default): exits 1 on any error, including YAML_PARSE that+ gbrain could still import by quoting a value. Use it before committing+ generated files.++ --importable Ingestion view instead: exit 1 only for what import/sync+ would hold (invalid_frontmatter, frontmatter_slug_conflict,+ file_too_large). Recovered and #-comment values are reported.+ --stdin, - Validate content piped on stdin (nothing is written).+ --path <p> With --stdin: the source-relative path the content would+ live at, so the declared slug is checked. Without it the+ slug check is skipped (and says so).+ --staged Validate the staged (git index) version of each staged+ .md/.mdx file, or of the named paths, in one process. This+ is what the pre-commit hook runs.+ --fix Auto-repair: NULL_BYTES, MISSING_CLOSE, NESTED_QUOTES,+ SLUG_MISMATCH, and YAML gbrain reads by quoting (only the+ recovered lines change; line endings and BOM kept). Writes a+ backup under ~/.gbrain/backups/frontmatter/... first, then+ re-validates: exit 1 when errors remain. In a git repo,+ restage the fixed files afterwards (git add). On a managed+ brain use gbrain repair frontmatter --source <id> instead.+ --include-ambiguous+ With --fix: also apply interpretations (fold unquoted+ continuation lines into the value, keep the later of a+ duplicated key, quote an unclosed [ or {, quote a #-leading+ title). Preview them with --dry-run first.+ --dry-run Preview --fix without writing.+ --json Emit a JSON envelope on stdout.generateSynthesize frontmatter for files that have none (MISSING_OPEN). Uses@@ -148,13 +186,70 @@ interface ValidateFlags {json: boolean;fix: boolean;dryRun: boolean;+ importable: boolean;+ includeAmbiguous: boolean;+ stdin: boolean;+ staged: boolean;+ /** --stdin only: the source-relative path the content would live at (enables the slug check). */+ path?: string;+}++interface ValidationIssue {+ code: ParseValidationCode;+ message: string;+ line?: number;+ /** YAML_PARSE only: ingestion reads it by quoting; producer checks still fail on it. */+ recoverable?: boolean;}interface FileValidation {path: string;- errors: { code: ParseValidationCode; message: string; line?: number }[];+ errors: ValidationIssue[];+ /** Local only: FRONTMATTER_RECOVERED carries the original line and its quoted replacement. */+ warnings?: Array<{ code: ParseWarningCode; message: string; key: string; line: number; original?: string; replacement?: string }>;+ /** --importable: the hold ingestion would record; null when the file imports. */+ hold?: ContentRefusal | null;+ /** The strict check fails only on YAML gbrain reads by quoting. */+ importable_but_not_canonical?: boolean;fixesApplied?: AuditFix[];backupPath?: string;+ /** --fix: what still fails once the fixes are applied (re-validated). */+ remaining_errors?: ValidationIssue[];+ remaining_hold?: ContentRefusal | null;+ /** --staged: whether the working-tree copy passes the same check (false when absent or failing). */+ working_copy_ok?: boolean;+ /** Why the file could not be checked at all. */+ note?: string;+ failed: boolean;+}++interface ContentCheck {+ errors: ValidationIssue[];+ warnings: NonNullable<FileValidation['warnings']>;+ hold: ContentRefusal | null;+ failed: boolean;+ canonicalOnly: boolean;+}++/**+ * Producer rule by default: any error fails, including YAML_PARSE ingestion+ * could recover. `importable` switches to the ingestion view: only what+ * `screenImportContent` refuses (the hold codes) fails. `slugPath` is the+ * path the slug derives from; without it the slug check is skipped.+ */+function checkContent(content: string, slugPath: string | undefined, importable: boolean): ContentCheck {+ const expectedSlug = slugPath ? slugifyPath(slugPath) : undefined;+ const parsed = parseMarkdown(content, slugPath, { validate: true, ...(expectedSlug ? { expectedSlug } : {}) });+ const errors = (parsed.errors ?? []).map(e => ({ code: e.code, message: e.message, line: e.line, ...(e.recoverable ? { recoverable: true } : {}) }));+ const warnings = (parsed.warnings ?? []).map(w => ({ code: w.code, message: w.message, key: w.key, line: w.line,+ ...(w.original !== undefined ? { original: w.original } : {}), ...(w.replacement !== undefined ? { replacement: w.replacement } : {}) }));+ const screen = importable ? screenImportContent({ content, path: slugPath ?? 'stdin.md', expectedSlug }) : null;+ const hold = screen?.status === 'refused' ? screen.refusal : null;+ return {+ errors, warnings, hold,+ failed: importable ? hold !== null : errors.length > 0,+ canonicalOnly: !importable && errors.length > 0 && errors.every(e => e.code === 'YAML_PARSE' && e.recoverable),+ };}/**@@ -178,110 +273,309 @@ function findBrainRoot(start: string): string {return startDir;}-async function runValidate(rest: string[]): Promise<void> {- const flags: ValidateFlags = { json: false, fix: false, dryRun: false };- let target: string | null = null;- for (const a of rest) {+/**+ * The staged blob of each path (`git show :<path>` for all of them in one+ * `ls-files` and one `cat-file --batch`), root-relative. No paths: every+ * added, copied or modified staged Markdown file. A path with no index entry+ * comes back with `content: null`.+ */+function readStagedBlobs(paths: string[], cwd = process.cwd()): { root: string; files: Array<{ rel: string; content: string | null }> } {+ const git = (args: string[], input?: string): Buffer =>+ execFileSync('git', ['--literal-pathspecs', ...args], { cwd, input, maxBuffer: 1 << 30, env: process.env, stdio: ['pipe', 'pipe', 'pipe'] });+ const root = git(['rev-parse', '--show-toplevel']).toString('utf8').trim();+ const listed = paths.length > 0+ ? git(['ls-files', '--stage', '--full-name', '-z', '--', ...paths])+ : (() => {+ const names = git(['-C', root, 'diff', '--cached', '--name-only', '-z', '--diff-filter=ACM']).toString('utf8').split('\0').filter(isMarkdownFilePath);+ return names.length > 0 ? git(['-C', root, 'ls-files', '--stage', '-z', '--', ...names]) : Buffer.alloc(0);+ })();+ const entries = listed.toString('utf8').split('\0').filter(Boolean)+ .map(record => /^\d+ ([0-9a-f]+) (\d)\t(.*)$/s.exec(record))+ .filter((m): m is RegExpExecArray => m !== null && m[2] === '0' && isMarkdownFilePath(m[3]!))+ .map(m => ({ oid: m[1]!, rel: m[3]! }));+ const files: Array<{ rel: string; content: string | null }> = [];+ if (entries.length > 0) {+ const out = git(['-C', root, 'cat-file', '--batch'], entries.map(e => e.oid).join('\n') + '\n');+ let pos = 0;+ for (const entry of entries) {+ const eol = out.indexOf(10, pos);+ const header = out.subarray(pos, eol).toString('utf8').split(' ');+ if (header[1] !== 'blob') { files.push({ rel: entry.rel, content: null }); pos = eol + 1; continue; }+ const size = Number(header[2]);+ files.push({ rel: entry.rel, content: out.subarray(eol + 1, eol + 1 + size).toString('utf8') });+ pos = eol + 1 + size + 1;+ }+ }+ if (paths.length > 0) {+ const prefix = git(['rev-parse', '--show-prefix']).toString('utf8').trim();+ for (const p of paths) {+ const full = isAbsolute(p) ? relative(root, p) : posix.normalize(prefix + p);+ if (!files.some(f => f.rel === full || f.rel.startsWith(full.replace(/\/$/, '') + '/'))) files.push({ rel: full, content: null });+ }+ }+ return { root, files };+}++/** `validate --fix` on a managed brain: name the coordinated repair instead of a bare coordinator error. */+function managedFixRefusal(file: string, error: OperationError): OperationError {+ const sourceId = managedFilesystemRootFor(file)?.sourceId;+ return opError('writer_coordinator_required',+ `${file} is in a managed brain${sourceId ? ` (source ${sourceId})` : ''}, so frontmatter validate --fix cannot rewrite it in place.`,+ `Preview the repair with gbrain repair frontmatter${sourceId ? ` --source ${sourceId}` : ''}; it writes through the persistence coordinator, and only after the preview hash is approved.`,+ {+ why: 'Files in a managed canonical worktree change only through the persistence coordinator, so the page and its file stay in step.',+ ...(error.detail !== undefined ? { detail: error.detail } : {}),+ fix: {+ argv: ['gbrain', 'repair', 'frontmatter', ...(sourceId ? ['--source', sourceId] : [])],+ consent: [], actor: 'agent', requires_exclusive: false,+ why: 'Previews every frontmatter repair with its diff and a hash; nothing is written until that hash is applied.',+ },+ });+}++function usage(message: string): void {+ console.error(`error: ${message}`);+ setCliExitVerdict(1);+}++async function runValidate(rest: string[], io: FrontmatterIo): Promise<void> {+ const flags: ValidateFlags = { json: false, fix: false, dryRun: false, importable: false, includeAmbiguous: false, stdin: false, staged: false };+ const targets: string[] = [];+ for (let i = 0; i < rest.length; i++) {+ const a = rest[i]!;+ if (a === '--') { targets.push(...rest.slice(i + 1)); break; }if (a === '--json') flags.json = true;else if (a === '--fix') flags.fix = true;else if (a === '--dry-run') flags.dryRun = true;- else if (!a.startsWith('--')) target = a;- }- if (!target) {- console.error('error: gbrain frontmatter validate requires a <path> argument');- setCliExitVerdict(1);+ else if (a === '--importable') flags.importable = true;+ else if (a === '--include-ambiguous') flags.includeAmbiguous = true;+ else if (a === '--stdin' || a === '-') flags.stdin = true;+ else if (a === '--staged') flags.staged = true;+ else if (a === '--path') flags.path = rest[++i];+ else if (a.startsWith('--path=')) flags.path = a.slice('--path='.length);+ else if (!a.startsWith('--')) targets.push(a);+ }+ if (flags.path !== undefined && (!flags.stdin || !flags.path)) {+ usage('--path names where --stdin content would live (source-relative, e.g. --path people/alice-example.md); it needs --stdin and a value.');return;}-- const resolved = resolve(target);- if (!existsSync(resolved)) {- console.error(`error: path not found: ${target}`);- setCliExitVerdict(1);+ if (flags.fix && (flags.stdin || flags.staged)) {+ usage(`--fix rewrites working-tree files, not ${flags.stdin ? 'stdin' : 'staged blobs'}. Run: gbrain frontmatter validate <file> --fix${flags.staged ? ', then git add <file>' : ''}`);return;}- if (lstatSync(resolved).isFile() && !isMarkdownFilePath(resolved)) {- console.error(`error: frontmatter validation supports only .md and .mdx files: ${target}`);- setCliExitVerdict(1);+ if (flags.stdin && flags.staged) {+ usage('pass either --stdin or --staged, not both.');return;}- const brainRoot = findBrainRoot(resolved);- const files = collectFiles(resolved);- if (flags.fix && !flags.dryRun) for (const file of files) assertManagedFilesystemWrite(file);const results: FileValidation[] = [];- const backupRunId = makeFrontmatterBackupRunId();-- for (const file of files) {- const content = readFileSync(file, 'utf8');- const rel = relative(brainRoot, file);- // Files above/outside the brain root fall back to basename rather than- // emitting a "../"-prefixed slug for non-brain files.- const slugPath = rel && !rel.startsWith('..') ? rel : basename(file);- const expectedSlug = slugifyPath(slugPath);- const parsed = parseMarkdown(content, file, { validate: true, expectedSlug });- const errs = parsed.errors ?? [];- const result: FileValidation = {- path: file,- errors: errs.map(e => ({ code: e.code, message: e.message, line: e.line })),- };-- if (flags.fix && errs.length > 0) {- // #5053: the fixer derives the slug from the same path validate used;- // the absolute path re-keyed every declared slug as a mismatch.- const { content: fixed, fixes } = autoFixFrontmatter(content, { filePath: slugPath });- result.fixesApplied = fixes;- if (fixes.length > 0 && !flags.dryRun) {- assertManagedFilesystemWrite(file);- result.backupPath = createFrontmatterBackup(file, { sourcePath: resolved, runId: backupRunId });- writeFileSync(file, fixed, 'utf8');+ let scanned = 0;+ let targetLabel: string;+ let slugCheckSkipped = false;+ const fixedInGit: string[] = [];++ if (flags.stdin) {+ const read = await readStdinBounded({ maxBytes: 2 * MAX_FILE_SIZE, ...(io.stdin ? { stream: io.stdin } : {}) });+ if (read.kind !== 'data' && read.kind !== 'empty') {+ usage(`could not read stdin (${read.kind === 'error' ? read.error.message : read.kind}). Pipe the content in: cat <file> | gbrain frontmatter validate --stdin --path <source-relative path>`);+ return;+ }+ const content = read.kind === 'data' ? read.text : '';+ targetLabel = flags.path ?? '<stdin>';+ slugCheckSkipped = flags.path === undefined;+ const check = checkContent(content, flags.path, flags.importable);+ results.push(toResult(targetLabel, check));+ scanned = 1;+ } else if (flags.staged) {+ let staged: ReturnType<typeof readStagedBlobs>;+ try {+ staged = readStagedBlobs(targets, io.cwd);+ } catch (error) {+ usage(`--staged reads the git index, which failed here (${error instanceof Error ? error.message.split('\n')[0] : String(error)}). Run it inside the repository: cd <repo> && gbrain frontmatter validate --staged`);+ return;+ }+ targetLabel = staged.root;+ for (const file of staged.files) {+ scanned++;+ if (file.content === null) {+ results.push({ path: file.rel, errors: [], failed: true, note: `No staged version of ${file.rel}. Stage it first: git add ${file.rel}` });+ continue;+ }+ const check = checkContent(file.content, file.rel, flags.importable);+ const result = toResult(file.rel, check);+ if (check.failed) {+ const working = join(staged.root, file.rel);+ result.working_copy_ok = existsSync(working) && lstatSync(working).isFile()+ && !checkContent(readFileSync(working, 'utf8'), file.rel, flags.importable).failed;}+ results.push(result);+ }+ } else {+ const target = targets[targets.length - 1];+ if (!target) {+ usage('gbrain frontmatter validate requires a <path> argument (or --stdin, or --staged)');+ return;+ }+ const resolved = resolve(target);+ if (!existsSync(resolved)) {+ usage(`path not found: ${target}`);+ return;+ }+ if (lstatSync(resolved).isFile() && !isMarkdownFilePath(resolved)) {+ usage(`frontmatter validation supports only .md and .mdx files: ${target}`);+ return;+ }+ targetLabel = resolved;++ const brainRoot = findBrainRoot(resolved);+ const inGit = existsSync(join(brainRoot, '.git'));+ const files = collectFiles(resolved);+ if (flags.fix && !flags.dryRun) {+ for (const file of files) {+ try {+ assertManagedFilesystemWrite(file);+ } catch (error) {+ if (error instanceof OperationError && error.code === 'writer_coordinator_required') throw managedFixRefusal(file, error);+ throw error;+ }+ }+ }+ const backupRunId = makeFrontmatterBackupRunId();+ scanned = files.length;++ for (const file of files) {+ const content = readFileSync(file, 'utf8');+ const rel = relative(brainRoot, file);+ // Files above/outside the brain root fall back to basename rather than+ // emitting a "../"-prefixed slug for non-brain files.+ const slugPath = rel && !rel.startsWith('..') ? rel : basename(file);+ const check = checkContent(content, slugPath, flags.importable);+ const result = toResult(file, check);+ const rescuable = flags.includeAmbiguous && check.warnings.some(w => w.code === 'FRONTMATTER_COMMENT_VALUE');++ if (flags.fix && (check.errors.length > 0 || rescuable)) {+ // #5053: the fixer derives the slug from the same path validate used;+ // the absolute path re-keyed every declared slug as a mismatch.+ const auto = autoFixFrontmatter(content, { filePath: slugPath });+ const repaired = repairRecoverableFrontmatter(auto.content, { includeAmbiguous: flags.includeAmbiguous });+ result.fixesApplied = [...auto.fixes, ...repaired.fixes];+ if (result.fixesApplied.length > 0 && !flags.dryRun) {+ assertManagedFilesystemWrite(file);+ result.backupPath = createFrontmatterBackup(file, { sourcePath: resolved, runId: backupRunId });+ writeFileSync(file, repaired.content, 'utf8');+ if (inGit) fixedInGit.push(relative(brainRoot, file));+ }+ const after = result.fixesApplied.length > 0 ? checkContent(repaired.content, slugPath, flags.importable) : check;+ result.remaining_errors = after.errors;+ if (flags.importable) result.remaining_hold = after.hold;+ result.failed = after.failed;+ }+ results.push(result);}-- results.push(result);}const totalErrors = results.reduce((n, r) => n + r.errors.length, 0);const filesWithErrors = results.filter(r => r.errors.length > 0).length;const filesFixed = results.filter(r => (r.fixesApplied?.length ?? 0) > 0).length;+ const failed = results.filter(r => r.failed);if (flags.json) {- const envelope = {- ok: totalErrors === 0,- target: resolved,- total_files: files.length,+ console.log(JSON.stringify({+ ok: failed.length === 0,+ mode: flags.importable ? 'importable' : 'strict',+ target: targetLabel,+ ...(flags.stdin ? { stdin: true, slug_check: slugCheckSkipped ? 'skipped' : 'checked' } : {}),+ ...(flags.staged ? { staged: true } : {}),+ total_files: scanned,files_with_errors: filesWithErrors,total_errors: totalErrors,+ files_failed: failed.length,files_fixed: flags.fix ? filesFixed : undefined,dry_run: flags.dryRun || undefined,+ restage: fixedInGit.length > 0 ? fixedInGit : undefined,results,- };- console.log(JSON.stringify(envelope, null, 2));+ }, null, 2));} else {- if (totalErrors === 0) {- console.log(`OK — ${files.length} file(s) scanned, no frontmatter issues`);- } else {- console.log(`Found ${totalErrors} issue(s) across ${filesWithErrors} file(s) (scanned ${files.length})`);- for (const r of results) {- if (r.errors.length === 0) continue;- console.log(`\n${r.path}`);- for (const e of r.errors) {- const lineHint = e.line !== undefined ? `:${e.line}` : '';- console.log(` [${e.code}]${lineHint} ${e.message}`);- }- if (r.fixesApplied && r.fixesApplied.length > 0) {- const verb = flags.dryRun ? 'would fix' : 'fixed';- for (const f of r.fixesApplied) {- console.log(` ${verb}: ${f.description}`);- }+ printValidateReport(results, { flags, scanned, totalErrors, filesWithErrors, filesFixed, slugCheckSkipped, fixedInGit });+ }++ setCliExitVerdict(failed.length > 0 ? 1 : 0);+}++function toResult(path: string, check: ContentCheck): FileValidation {+ return {+ path,+ errors: check.errors,+ ...(check.warnings.length > 0 ? { warnings: check.warnings } : {}),+ ...(check.hold !== null || check.failed ? { hold: check.hold } : {}),+ ...(check.canonicalOnly ? { importable_but_not_canonical: true } : {}),+ failed: check.failed,+ };+}++function printValidateReport(results: FileValidation[], ctx: {+ flags: ValidateFlags; scanned: number; totalErrors: number; filesWithErrors: number; filesFixed: number;+ slugCheckSkipped: boolean; fixedInGit: string[];+}): void {+ const { flags } = ctx;+ if (ctx.slugCheckSkipped) console.log('Slug check skipped: pass --path <source-relative path> to check a declared slug against its path.');+ const noisy = results.filter(r => r.errors.length > 0 || (r.warnings?.length ?? 0) > 0 || r.failed);+ if (noisy.length === 0) {+ console.log(`OK — ${ctx.scanned} ${flags.staged ? 'staged ' : ''}file(s) scanned, no frontmatter issues`);+ return;+ }+ if (ctx.totalErrors > 0) console.log(`Found ${ctx.totalErrors} issue(s) across ${ctx.filesWithErrors} file(s) (scanned ${ctx.scanned})`);+ else console.log(`${ctx.scanned} file(s) scanned; ${noisy.length} carry warnings only`);+ for (const r of noisy) {+ const label = flags.staged ? `${r.path} (staged version)` : r.path;+ console.log(`\n${label}`);+ if (r.note) console.log(` ${r.note}`);+ for (const e of r.errors) {+ const lineHint = e.line !== undefined ? `:${e.line}` : '';+ console.log(` [${e.code}]${lineHint} ${e.message}${e.recoverable ? ' (gbrain reads it by quoting; still not valid YAML)' : ''}`);+ }+ for (const w of r.warnings ?? []) {+ console.log(` [${w.code}]:${w.line} ${w.message}`);+ if (w.original !== undefined && w.replacement !== undefined) {+ console.log(` line ${w.line}: ${w.original}`);+ console.log(` quoted: ${w.replacement}`);+ }+ }+ if (flags.importable) {+ if (!r.hold) console.log(' importable: gbrain imports this file as it is');+ else {+ console.log(` held on import: ${r.hold.code}${r.hold.reason ? ` (${r.hold.reason})` : ''}${r.hold.line !== undefined ? ` at line ${r.hold.line}` : ''}`);+ console.log(` ${r.hold.message}`);+ if (r.hold.reason === 'needs_interpretation' && !flags.stdin && !flags.staged) {+ console.log(` Preview gbrain's interpretation: gbrain frontmatter validate ${r.path} --fix --include-ambiguous --dry-run`);}}- if (flags.fix && !flags.dryRun) {- console.log(`\nWrote centralized backups for ${filesFixed} file(s) under ~/.gbrain/backups/frontmatter/.`);+ }+ if (r.fixesApplied && r.fixesApplied.length > 0) {+ const verb = flags.dryRun ? 'would fix' : 'fixed';+ for (const f of r.fixesApplied) console.log(` ${verb}: ${f.description}`);+ }+ if (r.remaining_errors && r.failed) {+ for (const e of r.remaining_errors) console.log(` still failing: [${e.code}]${e.line !== undefined ? `:${e.line}` : ''} ${e.message}`);+ if (r.remaining_errors.some(e => e.code === 'YAML_PARSE') && !flags.includeAmbiguous) {+ console.log(` Fix that line by hand (one line per key, the whole value quoted), or preview gbrain's interpretation: gbrain frontmatter validate ${r.path} --fix --include-ambiguous --dry-run`);}}+ if (r.importable_but_not_canonical && !r.fixesApplied) {+ console.log(` importable but not canonical; run gbrain frontmatter validate ${flags.stdin ? (flags.path ?? '<file>') : r.path} --fix (quoting only)`);+ }+ if (flags.staged && r.failed && !r.note) {+ console.log(r.working_copy_ok+ ? ` the staged version of ${r.path} is broken; the working copy passes. Review it and git add ${r.path}`+ : ` the staged version of ${r.path} is broken; fix the file (gbrain frontmatter validate ${r.path} --fix), then git add ${r.path}`);+ }+ }+ if (flags.fix && !flags.dryRun && ctx.filesFixed > 0) {+ console.log(`\nWrote centralized backups for ${ctx.filesFixed} file(s) under ~/.gbrain/backups/frontmatter/.`);+ }+ if (ctx.fixedInGit.length > 0) {+ console.log(`Review the changes, then restage them: git add -- ${ctx.fixedInGit.map(p => shellQuote(p)).join(' ')}`);}-- setCliExitVerdict(totalErrors > 0 && !flags.fix ? 1 : 0);}/**@@ -397,7 +691,8 @@ function printAuditHumanReport(report: AuditReport): void {}console.log(` ${src.total} issue(s)`);for (const [code, n] of Object.entries(src.errors_by_code)) {- console.log(` ${code}: ${n}`);+ const split = src.recoverability_by_code?.[code as ParseValidationCode];+ console.log(` ${code}: ${n}${split ? ` (${split.recoverable} imported anyway, ${split.unrecoverable} held on import)` : ''}`);}if (src.sample.length > 0) {console.log(` sample:`);@@ -408,7 +703,7 @@ function printAuditHumanReport(report: AuditReport): void {}}if (report.total > 0) {- console.log(`\nFix with: gbrain frontmatter validate <source-path> --fix`);+ console.log(`\nFix with: gbrain frontmatter validate <source-path> --fix (on a managed brain: gbrain repair frontmatter --source <id>)`);}}diff --git a/src/core/brain-writer.ts b/src/core/brain-writer.tsindex 0ed94705df..a8f96d9d50 100644--- a/src/core/brain-writer.ts+++ b/src/core/brain-writer.ts@@ -25,9 +25,11 @@ import type { ProgressReporter } from './progress.ts';import { gbrainPath } from './config.ts';import { collectGitVisibleFiles } from './git-visible-files.ts';import {+ classifyImportHold,parseMarkdown,type ParseValidationCode,type ParseValidationError,+ type ParseWarningCode,} from './markdown.ts';import { isMarkdownFilePath, isSyncable, pruneDir, slugifyPath } from './sync.ts';@@ -39,15 +41,24 @@ export function isFrontmatterScannablePath(path: string): boolean {}export interface AuditFix {- code: ParseValidationCode;+ code: ParseValidationCode | ParseWarningCode;description: string;}+/**+ * #5988: per code, how many findings ingestion imports anyway (`recoverable`:+ * e.g. YAML it reads by quoting a value) versus how many make the file a held+ * import (`unrecoverable`: YAML it cannot read safely, a conflicting slug, a+ * protected key in an unclosed fence).+ */+export type RecoverabilityByCode = Partial<Record<ParseValidationCode, { recoverable: number; unrecoverable: number }>>;+export interface PerSourceReport {source_id: string;source_path: string;total: number;errors_by_code: Partial<Record<ParseValidationCode, number>>;+ recoverability_by_code?: RecoverabilityByCode;sample: { path: string; codes: ParseValidationCode[] }[];ignoredMissingOpen: number;/** Did this source finish the walk, get interrupted, or never start?@@ -68,6 +79,7 @@ export interface AuditReport {ok: boolean;total: number;errors_by_code: Partial<Record<ParseValidationCode, number>>;+ recoverability_by_code?: RecoverabilityByCode;per_source: PerSourceReport[];scanned_at: string;ignored_missing_open?: number;@@ -337,6 +349,109 @@ export function autoFixFrontmatter(return { content: working, fixes };}+/** Keys whose `#`-leading value is rescued (quoted) under `includeAmbiguous`. */+const COMMENT_RESCUE_KEYS: ReadonlySet<string> = new Set(['title', 'name', 'description', 'summary']);++/** What ingestion reads from content: the values a safe repair must keep. */+function ingestedReading(content: string): string {+ const parsed = parseMarkdown(content, undefined, { validate: true });+ if (parsed.errors?.some(error => error.code === 'YAML_PARSE' && !error.recoverable)) return '';+ return JSON.stringify([parsed.frontmatter, parsed.title, parsed.type, parsed.tags]);+}++/** Parses with no YAML error at all (strict, no recovery needed) and earns no import hold. */+function strictlyReadable(candidate: string): boolean {+ const parsed = parseMarkdown(candidate, undefined, { validate: true });+ return !parsed.errors?.some(error => error.code === 'YAML_PARSE') && classifyImportHold(parsed) === null;+}++/**+ * Swap the YAML block between the fences for `block` (as `recoverFrontmatter`+ * returns it: rows joined by `\n`, each keeping its own `\r`, a trailing empty+ * row). Every line outside the block stays byte-identical, BOM included.+ */+function replaceFrontmatterBlock(content: string, block: string): string | null {+ const lines = content.split('\n');+ const open = lines.findIndex(line => line.trim().length > 0);+ if (open < 0 || !/^---[ \t]*(?:ya?ml)?[ \t]*$/i.test(lines[open]!.replace(/^\uFEFF/, '').replace(/\r$/, ''))) return null;+ const close = lines.findIndex((line, i) => i > open && /^---[\t ]*\r?$/.test(line));+ const rows = block.split('\n');+ if (close < 0 || rows.pop() !== '') return null;+ return [...lines.slice(0, open + 1), ...rows, ...lines.slice(close)].join('\n');+}++/**+ * #5988: rewrite frontmatter that ingestion can read but a strict YAML parser+ * cannot. Safe by default: only the `quote` recoveries `parseMarkdown`+ * applied, line by line (only recovered lines change; CRLF and BOM kept), and+ * only when the rewritten file strict-parses to exactly the values ingestion+ * read. `includeAmbiguous` adds the interpretive proposals (unquoted+ * continuation lines folded into a value, a duplicated key resolved to the+ * later line, an unclosed `[`/`{` quoted, a `#`-leading title quoted), each+ * applied only when the result strict-parses with no hold.+ */+export function repairRecoverableFrontmatter(+ content: string,+ opts: { includeAmbiguous?: boolean } = {},+): { content: string; fixes: AuditFix[] } {+ const fixes: AuditFix[] = [];+ let working = content;++ const parsed = parseMarkdown(working, undefined, { validate: true });+ const quotes = (parsed.warnings ?? []).filter(w => w.code === 'FRONTMATTER_RECOVERED' && w.kind === 'quote' && w.original !== undefined && w.replacement !== undefined);+ if (quotes.length > 0) {+ const lines = working.split('\n');+ const applied = quotes.every(w => {+ const line = lines[w.line - 1];+ if (line === undefined) return false;+ const eol = line.endsWith('\r') ? '\r' : '';+ if (line.slice(0, line.length - eol.length) !== w.original) return false;+ lines[w.line - 1] = w.replacement + eol;+ return true;+ });+ const candidate = lines.join('\n');+ if (applied && strictlyReadable(candidate) && ingestedReading(candidate) === ingestedReading(working)) {+ working = candidate;+ for (const w of quotes) fixes.push({ code: 'YAML_PARSE', description: `Quoted the value of "${w.key}" at line ${w.line} (value unchanged)` });+ }+ }++ if (!opts.includeAmbiguous) return { content: working, fixes };++ const proposal = parseMarkdown(working, undefined, { validate: true }).recovery;+ if (proposal?.status === 'needs_interpretation') {+ const candidate = replaceFrontmatterBlock(working, proposal.block);+ if (candidate !== null && strictlyReadable(candidate)) {+ working = candidate;+ for (const step of proposal.steps) {+ fixes.push({ code: 'YAML_PARSE', description: step.kind === 'fold' ? `Folded the unquoted lines after "${step.key}" (line ${step.line}) into its value`+ : step.kind === 'dup' ? `Kept the later "${step.key}" (line ${step.line}) and dropped the earlier one (line ${step.otherLine})`+ : step.kind === 'unclosed' ? `Quoted the unclosed [ or { value of "${step.key}" at line ${step.line} as text`+ : `Quoted the value of "${step.key}" at line ${step.line} (value unchanged)` });+ }+ }+ }++ const comments = (parseMarkdown(working, undefined, { validate: true }).warnings ?? [])+ .filter(w => w.code === 'FRONTMATTER_COMMENT_VALUE' && COMMENT_RESCUE_KEYS.has(w.key));+ if (comments.length > 0) {+ const lines = working.split('\n');+ for (const w of comments) {+ const line = lines[w.line - 1]!;+ const eol = line.endsWith('\r') ? '\r' : '';+ const value = line.slice(0, line.length - eol.length).replace(/^[A-Za-z_][\w-]*:[ \t]+/, '').trimEnd();+ lines[w.line - 1] = `${w.key}: ${JSON.stringify(value)}${eol}`;+ }+ const candidate = lines.join('\n');+ if (strictlyReadable(candidate)) {+ working = candidate;+ for (const w of comments) fixes.push({ code: 'FRONTMATTER_COMMENT_VALUE', description: `Quoted the #-leading value of "${w.key}" at line ${w.line} so it is no longer read as a comment` });+ }+ }++ return { content: working, fixes };+}+// ---------------------------------------------------------------------------// writeBrainPage — path-guarded write with centralized backup// ---------------------------------------------------------------------------@@ -450,6 +565,7 @@ export async function scanBrainSources(): Promise<AuditReport> {const sources = await listSources(engine, opts.sourceId);const totals: Partial<Record<ParseValidationCode, number>> = {};+ const recoverabilityTotals: RecoverabilityByCode = {};const perSource: PerSourceReport[] = [];let grandTotal = 0;let ignoredMissingOpen = 0;@@ -582,6 +698,11 @@ export async function scanBrainSources(const k = code as ParseValidationCode;totals[k] = (totals[k] ?? 0) + (n as number);}+ for (const [code, split] of Object.entries(report.recoverability_by_code ?? {})) {+ const into = recoverabilityTotals[code as ParseValidationCode] ??= { recoverable: 0, unrecoverable: 0 };+ into.recoverable += split.recoverable;+ into.unrecoverable += split.unrecoverable;+ }if (report.status === 'partial' && abortedAtSource === null) {abortedAtSource = src.id;}@@ -596,6 +717,7 @@ export async function scanBrainSources(ok: grandTotal === 0 && !hasPartialOrSkipped,total: grandTotal,errors_by_code: totals,+ recoverability_by_code: recoverabilityTotals,per_source: perSource,scanned_at: new Date().toISOString(),ignored_missing_open: ignoredMissingOpen || undefined,@@ -610,6 +732,7 @@ function scanOneSource(opts: ScanOpts,): PerSourceReport {const errorsByCode: Partial<Record<ParseValidationCode, number>> = {};+ const recoverability: RecoverabilityByCode = {};const sample: PerSourceReport['sample'] = [];const rootResolved = resolve(sourcePath);let scanned = 0;@@ -654,9 +777,16 @@ function scanOneSource(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);+ const held = e.code === 'YAML_PARSE' ? !e.recoverable+ : e.code === 'SLUG_MISMATCH' ? hold?.code === 'frontmatter_slug_conflict'+ : e.code === 'MISSING_CLOSE' && hold?.code === 'invalid_frontmatter';+ const split = recoverability[e.code] ??= { recoverable: 0, unrecoverable: 0 };+ if (held) split.unrecoverable++;+ else split.recoverable++;}if (sample.length < SAMPLE_PER_SOURCE) {sample.push({ path: relPath, codes });@@ -687,6 +817,7 @@ function scanOneSource(source_path: sourcePath,total,errors_by_code: errorsByCode,+ recoverability_by_code: recoverability,sample,ignoredMissingOpen,status: interrupted ? 'partial' : 'scanned',diff --git a/src/core/cli-flag-registry.generated.ts b/src/core/cli-flag-registry.generated.tsindex e63ffb78c1..a5c5f147b7 100644--- a/src/core/cli-flag-registry.generated.ts+++ b/src/core/cli-flag-registry.generated.ts@@ -64,7 +64,7 @@ export const CLI_FLAG_REGISTRY: Record<string, readonly string[]> = {'forget': ['--brain', '--help', '--json', '--reason', '--request-id', '--source'],'founder': ['--brain', '--help', '--json', '--mcp-only', '--since', '--source', '--until'],'friction': ['--agent', '--base', '--brain', '--compare', '--help', '--hint', '--json', '--kind', '--message', '--no-redact', '--phase', '--run-id', '--severity', '--source', '--transcript-path', '--transcripts'],- 'frontmatter': ['--allow-catch-all', '--brain', '--cached', '--diff-filter', '--dry-run', '--exclude-standard', '--fix', '--force', '--get', '--git-common-dir', '--help', '--include-catch-all', '--json', '--name-only', '--no-verify', '--others', '--source', '--type', '--uninstall'],+ 'frontmatter': ['--allow-catch-all', '--batch', '--brain', '--cached', '--diff-filter', '--dry-run', '--exclude-standard', '--fix', '--force', '--full-name', '--get', '--git-common-dir', '--help', '--importable', '--include-ambiguous', '--include-catch-all', '--json', '--literal-pathspecs', '--name-only', '--no-verify', '--others', '--path', '--show-prefix', '--show-toplevel', '--source', '--stage', '--staged', '--stdin', '--type', '--uninstall'],'google': ['--access', '--account', '--allow-create-db', '--allow-docker', '--brain', '--calendar-id', '--chat-model', '--client-id', '--client-json', '--client-secret', '--code', '--consent-state', '--content-root', '--db-only', '--embedding-dimensions', '--embedding-model', '--expansion-model', '--force', '--git', '--grant-types', '--help', '--history-days', '--http', '--issuer-url', '--json', '--key', '--kind', '--limit', '--local-postgres', '--mcp-only', '--mcp-url', '--migrate-only', '--model', '--no-browser', '--no-embedding', '--no-git', '--no-probe', '--non-interactive', '--oauth-client-id', '--oauth-client-secret', '--paste', '--path', '--pglite', '--port', '--prefer-postgres', '--provenance', '--purge-client', '--query', '--reauth', '--retry-failed', '--schema-pack', '--scopes', '--services', '--skip-embed-check', '--source', '--status', '--supabase', '--sync-budget-ms', '--timeout-ms', '--to', '--token-command', '--url', '--version', '--via', '--yes'],'graph-query': ['--brain', '--depth', '--direction', '--help', '--include-foreign', '--json', '--mcp-only', '--source', '--type'],'hook': ['--allow-unverified-remote', '--auto', '--brain', '--branch', '--cached', '--count', '--diff-filter', '--end-of-options', '--env', '--get', '--harness', '--help', '--jq', '--json', '--name-only', '--others', '--path', '--porcelain', '--pure', '--quiet', '--seat', '--session', '--show-current', '--show-toplevel', '--source'],diff --git a/test/brain-writer.test.ts b/test/brain-writer.test.tsindex d4a58dbd63..1596cc0607 100644--- a/test/brain-writer.test.ts+++ b/test/brain-writer.test.ts@@ -292,6 +292,21 @@ describe('scanBrainSources (PGLite)', () => {expect(beta.errors_by_code.NESTED_QUOTES).toBeGreaterThanOrEqual(1);});+ test('#5988 splits each code into imported-anyway vs held-on-import', async () => {+ const src = join(tmp, 'mixed');+ mkdirSync(src, { recursive: true });+ writeFileSync(join(src, 'quotable.md'), `${fence}\ntype: x\ntitle: a: b\n${fence}\n\nbody`);+ writeFileSync(join(src, 'folded.md'), `${fence}\ntype: x\ntitle: first\nsecond line\n${fence}\n\nbody`);+ writeFileSync(join(src, 'slugged.md'), `${fence}\ntype: x\ntitle: ok\nslug: elsewhere/page\n${fence}\n\nbody`);+ await registerSource('mixed', src);++ const report = await scanBrainSources(engine, { sourceId: 'mixed' });+ const mixed = report.per_source.find(s => s.source_id === 'mixed')!;+ expect(mixed.recoverability_by_code?.YAML_PARSE).toEqual({ recoverable: 1, unrecoverable: 1 });+ expect(mixed.recoverability_by_code?.SLUG_MISMATCH).toEqual({ recoverable: 0, unrecoverable: 1 });+ expect(report.recoverability_by_code?.YAML_PARSE).toEqual({ recoverable: 1, unrecoverable: 1 });+ });+test('respects sourceId filter', async () => {const srcA = join(tmp, 'a');const srcB = join(tmp, 'b');diff --git a/test/frontmatter-validate-producer.test.ts b/test/frontmatter-validate-producer.test.tsnew file mode 100644index 0000000000..adc030ba55--- /dev/null+++ b/test/frontmatter-validate-producer.test.ts@@ -0,0 +1,254 @@+/**+ * #5988 producer checks: `gbrain frontmatter validate` keeps its strict+ * exit-1-on-any-error contract (YAML that ingestion recovers by quoting still+ * fails), `--importable` reports the ingestion (hold-code) view, `--stdin` /+ * `-` validate piped content with an optional `--path` slug check,+ * `--staged` validates git index blobs, and `--fix` adds the safe quote+ * repair (interpretations only with `--include-ambiguous`), re-validates, and+ * refuses on a managed root with the coordinated repair command.+ *+ * Driven in-process through runFrontmatter's test seams (stdin stream, git+ * cwd) with the console captured, like test/frontmatter-cli.test.ts.+ */+import { afterEach, beforeEach, describe, expect, test } from 'bun:test';+import { execFileSync } from 'node:child_process';+import { existsSync, mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from 'node:fs';+import { tmpdir } from 'node:os';+import { join } from 'node:path';+import { Readable } from 'node:stream';++import { runFrontmatter, type FrontmatterIo } from '../src/commands/frontmatter.ts';+import { repairRecoverableFrontmatter } from '../src/core/brain-writer.ts';+import { currentExitCode, _resetCliExitVerdictForTests } from '../src/core/cli-force-exit.ts';+import { OperationError } from '../src/core/ops/contract.ts';+import { withEnv } from './helpers/with-env.ts';++const RECOVERABLE = '---\ntitle: Acme-example (citing a wire) (original: https://example.com/a)\ntype: note\n---\n\nbody\n';+const FOLDED = '---\ntitle: first line of a post\nsecond line of the post\ntype: note\n---\n\nbody\n';++async function runFm(args: string[], io: FrontmatterIo = {}): Promise<{ out: string; err: string; verdict: number }> {+ const logOrig = console.log;+ const errOrig = console.error;+ const prevExitCode = process.exitCode;+ const out: string[] = [];+ const err: string[] = [];+ _resetCliExitVerdictForTests();+ console.log = (...a: unknown[]) => { out.push(a.map(String).join(' ') + '\n'); };+ console.error = (...a: unknown[]) => { err.push(a.map(String).join(' ') + '\n'); };+ try {+ await runFrontmatter(args, io);+ } finally {+ console.log = logOrig;+ console.error = errOrig;+ }+ const verdict = currentExitCode();+ _resetCliExitVerdictForTests();+ process.exitCode = prevExitCode ?? 0;+ return { out: out.join(''), err: err.join(''), verdict };+}++const stdin = (text: string): FrontmatterIo => ({ stdin: Readable.from([Buffer.from(text)]) });++let tmp: string;+beforeEach(() => { tmp = mkdtempSync(join(tmpdir(), 'fm-producer-')); });+afterEach(() => { rmSync(tmp, { recursive: true, force: true }); });++describe('validate --stdin', () => {+ test('recoverable YAML fails the strict default and passes --importable with FRONTMATTER_RECOVERED', async () => {+ const strict = await runFm(['validate', '--stdin'], stdin(RECOVERABLE));+ expect(strict.verdict).toBe(1);+ expect(strict.out).toContain('[YAML_PARSE]');+ expect(strict.out).toContain('importable but not canonical; run gbrain frontmatter validate <file> --fix (quoting only)');++ const importable = await runFm(['validate', '--stdin', '--importable', '--json'], stdin(RECOVERABLE));+ expect(importable.verdict).toBe(0);+ const env = JSON.parse(importable.out);+ expect(env.ok).toBe(true);+ expect(env.mode).toBe('importable');+ expect(env.results[0].errors[0]).toMatchObject({ code: 'YAML_PARSE', recoverable: true });+ expect(env.results[0].warnings.map((w: { code: string }) => w.code)).toContain('FRONTMATTER_RECOVERED');+ });++ test('an unrecoverable block exits 1 in both views; --importable names the hold', async () => {+ expect((await runFm(['validate', '--stdin'], stdin(FOLDED))).verdict).toBe(1);+ const importable = await runFm(['validate', '--stdin', '--importable', '--json'], stdin(FOLDED));+ expect(importable.verdict).toBe(1);+ expect(JSON.parse(importable.out).results[0].hold).toMatchObject({ code: 'invalid_frontmatter', reason: 'needs_interpretation', key: 'title', line: 2 });+ });++ test("'-' as the path reads stdin", async () => {+ const dash = await runFm(['validate', '-', '--json'], stdin(RECOVERABLE));+ expect(dash.verdict).toBe(1);+ expect(JSON.parse(dash.out)).toMatchObject({ stdin: true, total_files: 1, ok: false });+ const clean = await runFm(['validate', '-'], stdin('---\ntitle: fine\ntype: note\n---\n\nbody\n'));+ expect(clean.verdict).toBe(0);+ });++ test('--path enables the slug check; without it the check is reported as skipped', async () => {+ const page = '---\ntitle: fine\ntype: note\nslug: other/thing\n---\n\nbody\n';+ const skipped = await runFm(['validate', '--stdin'], stdin(page));+ expect(skipped.verdict).toBe(0);+ expect(skipped.out).toContain('Slug check skipped');+ expect(JSON.parse((await runFm(['validate', '--stdin', '--json'], stdin(page))).out).slug_check).toBe('skipped');++ const checked = await runFm(['validate', '--stdin', '--path', 'notes/foo.md', '--json'], stdin(page));+ expect(checked.verdict).toBe(1);+ const env = JSON.parse(checked.out);+ expect(env.slug_check).toBe('checked');+ expect(env.results[0].errors.map((e: { code: string }) => e.code)).toContain('SLUG_MISMATCH');++ const held = await runFm(['validate', '--stdin', '--path=notes/foo.md', '--importable', '--json'], stdin(page));+ expect(held.verdict).toBe(1);+ expect(JSON.parse(held.out).results[0].hold.code).toBe('frontmatter_slug_conflict');++ const matching = await runFm(['validate', '--stdin', '--path', 'other/thing.md'], stdin(page));+ expect(matching.verdict).toBe(0);+ });++ test('--fix on stdin is refused with the file command', async () => {+ const r = await runFm(['validate', '--stdin', '--fix'], stdin(RECOVERABLE));+ expect(r.verdict).toBe(1);+ expect(r.err).toContain('gbrain frontmatter validate <file> --fix');+ });+});++describe('validate --staged', () => {+ function repo(): string {+ const dir = join(tmp, 'repo');+ mkdirSync(join(dir, 'notes'), { recursive: true });+ execFileSync('git', ['init', '-q', dir]);+ return dir;+ }+ const git = (dir: string, ...args: string[]) => execFileSync('git', ['-C', dir, ...args]);++ test('a broken staged blob fails while the fixed working copy passes (partially staged)', async () => {+ const dir = repo();+ writeFileSync(join(dir, 'notes', 'a.md'), RECOVERABLE);+ writeFileSync(join(dir, 'notes', 'b c.md'), '---\ntitle: fine\ntype: note\n---\n\nbody\n');+ git(dir, 'add', '.');+ writeFileSync(join(dir, 'notes', 'a.md'), repairRecoverableFrontmatter(RECOVERABLE).content);++ const r = await runFm(['validate', '--staged'], { cwd: dir });+ expect(r.verdict).toBe(1);+ expect(r.out).toContain('notes/a.md (staged version)');+ expect(r.out).toContain('the staged version of notes/a.md is broken; the working copy passes. Review it and git add notes/a.md');+ expect(r.out).not.toContain('b c.md (staged version)');++ const json = JSON.parse((await runFm(['validate', '--staged', '--json'], { cwd: dir })).out);+ expect(json).toMatchObject({ staged: true, total_files: 2, files_failed: 1 });+ expect(json.results.find((x: { path: string }) => x.path === 'notes/a.md').working_copy_ok).toBe(true);++ git(dir, 'add', 'notes/a.md');+ expect((await runFm(['validate', '--staged'], { cwd: dir })).verdict).toBe(0);+ });++ test('a clean staged blob passes even when the working copy is broken', async () => {+ const dir = repo();+ writeFileSync(join(dir, 'notes', 'a.md'), '---\ntitle: fine\ntype: note\n---\n\nbody\n');+ git(dir, 'add', '.');+ writeFileSync(join(dir, 'notes', 'a.md'), FOLDED);+ const r = await runFm(['validate', '--staged', '--', 'notes/a.md'], { cwd: dir });+ expect(r.verdict).toBe(0);+ expect(r.out).toContain('OK — 1 staged file(s) scanned');+ });++ test('--importable on staged blobs exits 0 for recoverable YAML; a path with no staged version fails', async () => {+ const dir = repo();+ writeFileSync(join(dir, 'notes', 'a.md'), RECOVERABLE);+ git(dir, 'add', '.');+ expect((await runFm(['validate', '--staged', '--importable'], { cwd: dir })).verdict).toBe(0);+ const missing = await runFm(['validate', '--staged', 'notes/nope.md'], { cwd: dir });+ expect(missing.verdict).toBe(1);+ expect(missing.out).toContain('Stage it first: git add notes/nope.md');+ });+});++describe('validate --fix', () => {+ const home = () => join(tmp, 'home');++ test('the old invocation still fixes MISSING_CLOSE and exits 0 once clean', async () => {+ const f = join(tmp, 'note.md');+ writeFileSync(f, '---\ntitle: fine\ntype: note\n# Heading\n\nbody\n');+ const r = await withEnv({ GBRAIN_HOME: home() }, () => runFm(['validate', f, '--fix']));+ expect(r.verdict).toBe(0);+ expect(readFileSync(f, 'utf8')).toContain('---\n\n# Heading');+ });++ test('the safe quote repair changes only the recovered line and keeps CRLF and BOM', async () => {+ const f = join(tmp, 'note.md');+ const original = '\uFEFF---\r\ntitle: a: b\r\ntype: note\r\ntags: [x]\r\n---\r\n\r\nbody\r\n';+ writeFileSync(f, original);+ const r = await withEnv({ GBRAIN_HOME: home() }, () => runFm(['validate', f, '--fix']));+ expect(r.verdict).toBe(0);+ expect(r.out).toContain('fixed: Quoted the value of "title" at line 2');+ expect(readFileSync(f, 'utf8')).toBe(original.replace('title: a: b', 'title: "a: b"'));+ expect((await runFm(['validate', f])).verdict).toBe(0);+ });++ test('an error the fix cannot repair exits 1 and leaves the file unchanged', async () => {+ const f = join(tmp, 'note.md');+ writeFileSync(f, FOLDED);+ const r = await withEnv({ GBRAIN_HOME: home() }, () => runFm(['validate', f, '--fix']));+ expect(r.verdict).toBe(1);+ expect(r.out).toContain('still failing: [YAML_PARSE]');+ expect(r.out).toContain('--fix --include-ambiguous --dry-run');+ expect(readFileSync(f, 'utf8')).toBe(FOLDED);+ });++ test('interpretations apply only with --include-ambiguous (dry-run first, then write)', async () => {+ const f = join(tmp, 'note.md');+ writeFileSync(f, FOLDED);+ const preview = await withEnv({ GBRAIN_HOME: home() }, () => runFm(['validate', f, '--fix', '--include-ambiguous', '--dry-run']));+ expect(preview.verdict).toBe(0);+ expect(preview.out).toContain('would fix: Folded the unquoted lines after "title" (line 2)');+ expect(readFileSync(f, 'utf8')).toBe(FOLDED);++ const applied = await withEnv({ GBRAIN_HOME: home() }, () => runFm(['validate', f, '--fix', '--include-ambiguous']));+ expect(applied.verdict).toBe(0);+ expect(readFileSync(f, 'utf8')).toBe('---\ntitle: "first line of a post\\nsecond line of the post"\ntype: note\n---\n\nbody\n');+ });++ test('a #-leading title is quoted only with --include-ambiguous', async () => {+ const f = join(tmp, 'note.md');+ const page = '---\ntitle: #1 thing\ntype: note\n---\n\nbody\n';+ writeFileSync(f, page);+ await withEnv({ GBRAIN_HOME: home() }, () => runFm(['validate', f, '--fix']));+ expect(readFileSync(f, 'utf8')).toBe(page);+ const r = await withEnv({ GBRAIN_HOME: home() }, () => runFm(['validate', f, '--fix', '--include-ambiguous']));+ expect(r.verdict).toBe(0);+ expect(readFileSync(f, 'utf8')).toBe('---\ntitle: "#1 thing"\ntype: note\n---\n\nbody\n');+ });++ test('a fix inside a git repo prints the restage step', async () => {+ const dir = join(tmp, 'repo');+ mkdirSync(dir);+ execFileSync('git', ['init', '-q', dir]);+ const f = join(dir, 'note.md');+ writeFileSync(f, RECOVERABLE);+ const r = await withEnv({ GBRAIN_HOME: home() }, () => runFm(['validate', f, '--fix']));+ expect(r.verdict).toBe(0);+ expect(r.out).toContain('restage them: git add -- note.md');+ });++ test('on a managed root it refuses with the coordinated repair command and writes nothing', async () => {+ const dir = join(tmp, 'managed');+ mkdirSync(dir);+ writeFileSync(join(dir, '.gbrain-managed'), '{}');+ const f = join(dir, 'note.md');+ writeFileSync(f, RECOVERABLE);+ let thrown: unknown;+ try {+ await withEnv({ GBRAIN_HOME: home() }, () => runFm(['validate', f, '--fix']));+ } catch (error) {+ thrown = error;+ }+ expect(thrown).toBeInstanceOf(OperationError);+ const error = thrown as OperationError;+ expect(error.code).toBe('writer_coordinator_required');+ expect(error.suggestion).toContain('gbrain repair frontmatter');+ expect(error.fix?.argv?.slice(0, 3)).toEqual(['gbrain', 'repair', 'frontmatter']);+ expect(readFileSync(f, 'utf8')).toBe(RECOVERABLE);+ expect(existsSync(join(home(), '.gbrain', 'backups'))).toBe(false);+ expect((await runFm(['validate', f, '--fix', '--dry-run'])).out).toContain('would fix');+ });+});