Skip to content

Garry's Opinionated OpenClaw/Hermes Agent Brain

TypeScript

feat(markdown): recover quote-readable frontmatter and classify holds (#5988)

garrytanfce5c9a476d2
diff --git a/src/core/data-frontmatter.ts b/src/core/data-frontmatter.ts
index 3b2f8ebcbd..5222b4d3bb 100644
--- a/src/core/data-frontmatter.ts
+++ b/src/core/data-frontmatter.ts
@@ -27,7 +27,7 @@ const calendarTimestamp = new Type('tag:yaml.org,2002:timestamp', {
instanceOf: Date,
represent: baseTimestamp.represent,
});
-const FRONTMATTER_SCHEMA = new Schema({ include: [DEFAULT_SAFE_SCHEMA], implicit: [calendarTimestamp] });
+export const FRONTMATTER_SCHEMA = new Schema({ include: [DEFAULT_SAFE_SCHEMA], implicit: [calendarTimestamp] });
export interface DataFrontmatter {
data: Record<string, unknown>;
diff --git a/src/core/frontmatter-recovery.ts b/src/core/frontmatter-recovery.ts
new file mode 100644
index 0000000000..aa5ce2435e
--- /dev/null
+++ b/src/core/frontmatter-recovery.ts
@@ -0,0 +1,242 @@
+/**
+ * Recovery for frontmatter blocks js-yaml refuses (#5988).
+ *
+ * `parseMarkdown` calls `recoverFrontmatter` only after its unconditional
+ * pre-quote pass and a strict parse have failed, so a block that parses today
+ * is never re-read. Rules touch only the suspect run (the key line nearest the
+ * parser's error mark plus its non-key continuation lines); every other line
+ * stays byte-identical, and each line keeps its own CRLF ending.
+ *
+ * `quote` keeps the value text exactly and re-emits it as one double-quoted
+ * scalar, so it is the only kind an import accepts. `fold`, `dup` and
+ * `unclosed` guess at meaning: the block is classified `needs_interpretation`
+ * and the proposed block is kept for an approved repair, never imported.
+ * Protected keys (who may read a page, where it came from) are never
+ * rewritten, folded into or guessed; identity keys are never resolved from a
+ * duplicate.
+ */
+import { safeLoad } from 'js-yaml';
+import { FRONTMATTER_SCHEMA } from './data-frontmatter.ts';
+
+/** Bump when a rule widens; older holds are re-screened. */
+export const RECOVERY_VERSION = 1;
+
+/**
+ * Keys read by access-control and provenance code (`search/private-visibility.ts`,
+ * `repair/visibility.ts`, connector publication). `test/frontmatter-recovery.test.ts`
+ * greps those readers so a new key cannot be missed.
+ */
+export const PROTECTED_FRONTMATTER_KEYS: readonly string[] = ['visibility', 'derived_from', 'source_slug', 'synthesized_by', 'concepts'];
+/** Keys that decide which page a file is. A duplicate is never resolved. */
+export const IDENTITY_FRONTMATTER_KEYS: readonly string[] = ['slug', 'type', 'id', 'source_id'];
+
+export type RecoveryKind = 'quote' | 'fold' | 'dup' | 'unclosed';
+export type FrontmatterRecoveryStatus =
+ | 'clean' | 'recovered' | 'needs_interpretation' | 'ambiguous_identity_key' | 'ambiguous_protected_key' | 'unrecoverable';
+
+export interface FrontmatterRecoveryStep {
+ kind: RecoveryKind;
+ key: string;
+ /** File line of the rewritten key line (for `dup`, the later occurrence, which wins). */
+ line: number;
+ /** For `dup`: the earlier occurrence, which the proposal drops. */
+ otherLine?: number;
+ original: string;
+ replacement: string | null;
+}
+
+export interface FrontmatterRecovery {
+ status: FrontmatterRecoveryStatus;
+ /** `recovered`: the block to import. `needs_interpretation`: the proposed block. Otherwise the input. */
+ block: string;
+ steps: FrontmatterRecoveryStep[];
+ key?: string;
+ line?: number;
+ column?: number;
+ /** js-yaml's reason phrase for the last failure; it never quotes the document. */
+ yamlReason?: string;
+ recovery_version: number;
+}
+
+const KEY_LINE = /^([A-Za-z_][\w-]*):(?=[ \t]|$)/;
+
+interface Row { text: string; eol: string }
+interface YamlFailure { reason: string; line: number | null; column: number | null }
+
+function loadBlock(text: string): { ok: true; data: unknown } | { ok: false; failure: YamlFailure } {
+ try {
+ return { ok: true, data: safeLoad(text, { schema: FRONTMATTER_SCHEMA }) };
+ } catch (error) {
+ const e = error as { reason?: string; mark?: { line?: number; column?: number } };
+ return { ok: false, failure: { reason: e.reason ?? 'malformed YAML', line: e.mark?.line ?? null, column: e.mark?.column ?? null } };
+ }
+}
+
+function toRows(block: string): Row[] {
+ return block.split('\n').map(raw => raw.endsWith('\r') ? { text: raw.slice(0, -1), eol: '\r' } : { text: raw, eol: '' });
+}
+
+function fromRows(rows: Row[]): string {
+ return rows.map(row => row.text + row.eol).join('\n');
+}
+
+function keyOf(text: string): string | null {
+ return KEY_LINE.exec(text)?.[1] ?? null;
+}
+
+/** Location only: js-yaml's reason phrase plus line and column, never a document excerpt. */
+export function yamlLocationMessage(reason: string, line: number | null | undefined, column?: number | null): string {
+ return `${reason}${typeof line === 'number' ? ` at line ${line}${typeof column === 'number' ? `, column ${column}` : ''}` : ''}`;
+}
+
+/** A value whose meaning is fixed, re-emitted as one double-quoted scalar. */
+function quotedScalarText(value: string): string {
+ const q = value[0];
+ if ((q === '"' || q === "'") && value.length >= 2 && value.endsWith(q)) {
+ const inner = value.slice(1, -1);
+ if (new RegExp(q === '"' ? '(^|[^\\\\])"' : "'").test(inner)) return inner;
+ }
+ return value;
+}
+
+interface Rule { kind: RecoveryKind; replace: Row[]; removeThrough: number }
+
+function ruleFor(rows: Row[], k: number, end: number): Rule | null {
+ const match = KEY_LINE.exec(rows[k]!.text)!;
+ const key = match[1]!;
+ const value = rows[k]!.text.slice(match[0].length).trim();
+ const continuation = rows.slice(k + 1, end);
+ const lastContent = continuation.reduce((last, row, i) => row.text.trim() === '' ? last : i, -1);
+ const content = continuation.slice(0, lastContent + 1);
+ const unindented = content.filter(row => row.text.trim() !== '' && !/^[ \t]/.test(row.text) && !/^-(?:[ \t]|$)/.test(row.text) && !row.text.startsWith('#'));
+ const standaloneOk = value === '' || loadBlock(`${key}: ${value}`).ok;
+ const emit = (text: string): Row[] => [{ text: `${key}: ${JSON.stringify(text)}`, eol: rows[k]!.eol }];
+ if (unindented.length > 0) {
+ if (unindented.length !== content.filter(row => row.text.trim() !== '').length) return null;
+ const head = standaloneOk && /^["']/.test(value) ? String((loadBlock(`v: ${value}`) as { data: { v: unknown } }).data.v) : value;
+ return { kind: 'fold', replace: emit([head, ...unindented.map(row => row.text)].filter(part => part !== '').join('\n')), removeThrough: k + 1 + lastContent };
+ }
+ if (standaloneOk || content.length > 0) return null;
+ if (/^["']/.test(value)) return { kind: 'quote', replace: emit(quotedScalarText(value)), removeThrough: k };
+ if (/^[[{]/.test(value)) return { kind: 'unclosed', replace: emit(value), removeThrough: k };
+ if (value.includes(': ') || value.endsWith(':') || /^[@`]/.test(value)) return { kind: 'quote', replace: emit(value), removeThrough: k };
+ return null;
+}
+
+/**
+ * Recover one frontmatter block (the text between the fences). `lineOffset`
+ * is the file line before the block's first row, so reported lines are file
+ * lines. Callers run it only after a strict parse failed.
+ */
+export function recoverFrontmatter(block: string, lineOffset = 0): FrontmatterRecovery {
+ let rows = toRows(block);
+ const steps: FrontmatterRecoveryStep[] = [];
+ const seen = new Set<string>();
+ let interpretive = false;
+ const done = (status: FrontmatterRecoveryStatus, extra: Partial<FrontmatterRecovery> = {}): FrontmatterRecovery =>
+ ({ status, block: status === 'recovered' || status === 'needs_interpretation' ? fromRows(rows) : block, steps, recovery_version: RECOVERY_VERSION, ...extra });
+ const keyLines = rows.filter(row => keyOf(row.text) !== null).length;
+ for (let pass = 0; pass <= keyLines + 1; pass++) {
+ const loaded = loadBlock(fromRows(rows));
+ if (loaded.ok) return done(steps.length === 0 ? 'clean' : interpretive ? 'needs_interpretation' : 'recovered');
+ const failure = loaded.failure;
+ const mark = Math.min(Math.max(failure.line ?? rows.length - 1, 0), rows.length - 1);
+ const location = { yamlReason: failure.reason, column: failure.column === null ? undefined : failure.column + 1 };
+ let nearest = mark;
+ while (nearest > 0 && keyOf(rows[nearest]!.text) === null) nearest--;
+ const nearestKey = keyOf(rows[nearest]!.text) ?? undefined;
+ const at = { ...location, key: nearestKey, line: lineOffset + (nearestKey ? nearest : mark) + 1 };
+ if (/duplicated mapping key/.test(failure.reason) && nearestKey) {
+ const line = lineOffset + nearest + 1;
+ if (PROTECTED_FRONTMATTER_KEYS.includes(nearestKey)) return done('ambiguous_protected_key', { ...at, line });
+ if (IDENTITY_FRONTMATTER_KEYS.includes(nearestKey)) return done('ambiguous_identity_key', { ...at, line });
+ const earlier = rows.findIndex((row, i) => i < nearest && keyOf(row.text) === nearestKey);
+ if (earlier < 0 || seen.has(`dup:${nearestKey}`)) return done('unrecoverable', at);
+ seen.add(`dup:${nearestKey}`);
+ let earlierEnd = earlier + 1;
+ while (earlierEnd < rows.length && keyOf(rows[earlierEnd]!.text) === null && /^([ \t]|-(?:[ \t]|$))/.test(rows[earlierEnd]!.text)) earlierEnd++;
+ steps.push({ kind: 'dup', key: nearestKey, line: lineOffset + nearest + 1, otherLine: lineOffset + earlier + 1, original: rows[earlier]!.text, replacement: null });
+ interpretive = true;
+ rows = [...rows.slice(0, earlier), ...rows.slice(earlierEnd)];
+ continue;
+ }
+ let chosen: { k: number; rule: Rule } | null = null;
+ for (let k = mark; k >= 0 && !chosen; k--) {
+ const key = keyOf(rows[k]!.text);
+ if (key === null || seen.has(`line:${k}:${rows[k]!.text}`)) continue;
+ let end = k + 1;
+ while (end < rows.length && keyOf(rows[end]!.text) === null) end++;
+ const rule = ruleFor(rows, k, end);
+ if (rule) chosen = { k, rule };
+ }
+ if (!chosen) return done('unrecoverable', at);
+ const { k, rule } = chosen;
+ const key = keyOf(rows[k]!.text)!;
+ const line = lineOffset + k + 1;
+ if (PROTECTED_FRONTMATTER_KEYS.includes(key)) return done('ambiguous_protected_key', { ...location, key, line });
+ if (rule.kind !== 'quote' && IDENTITY_FRONTMATTER_KEYS.includes(key)) return done('ambiguous_identity_key', { ...location, key, line });
+ seen.add(`line:${k}:${rule.replace[0]!.text}`);
+ steps.push({ kind: rule.kind, key, line, original: rows[k]!.text, replacement: rule.replace[0]!.text });
+ if (rule.kind !== 'quote') interpretive = true;
+ rows = [...rows.slice(0, k), ...rule.replace, ...rows.slice(rule.removeThrough + 1)];
+ }
+ return done('unrecoverable', { yamlReason: 'too many recovery passes' });
+}
+
+/**
+ * A successfully parsed block can still hide who may read the page: a
+ * protected value the pre-quote pass rewrote (`visibility: private # note: x`
+ * imports as a different string), or a protected or identity key line that a
+ * multi-line quoted scalar swallowed. `quotedKeys` are the key names the
+ * pre-quote pass rewrote.
+ */
+export function frontmatterKeyHazard(
+ block: string,
+ data: Record<string, unknown>,
+ quotedKeys: ReadonlySet<string>,
+ lineOffset = 0,
+): { status: 'ambiguous_protected_key' | 'ambiguous_identity_key'; key: string; line: number } | null {
+ const rows = toRows(block);
+ for (let i = 0; i < rows.length; i++) {
+ const key = keyOf(rows[i]!.text);
+ if (key === null) continue;
+ const line = lineOffset + i + 1;
+ const present = Object.prototype.hasOwnProperty.call(data, key);
+ if (PROTECTED_FRONTMATTER_KEYS.includes(key) && (quotedKeys.has(key) || !present)) return { status: 'ambiguous_protected_key', key, line };
+ if (IDENTITY_FRONTMATTER_KEYS.includes(key) && !present) return { status: 'ambiguous_identity_key', key, line };
+ }
+ return null;
+}
+
+/**
+ * An unclosed fence imports with no frontmatter at all, which would drop a
+ * protected key such as `visibility`. `lines` are the file lines after the
+ * opening fence; only the leading YAML-shaped run is inspected.
+ */
+export function unclosedFenceProtectedKey(lines: readonly string[], lineOffset = 0): { key: string; line: number } | null {
+ for (let i = 0; i < lines.length; i++) {
+ const text = lines[i]!.replace(/\r$/, '');
+ const key = keyOf(text);
+ if (key !== null) {
+ if (PROTECTED_FRONTMATTER_KEYS.includes(key)) return { key, line: lineOffset + i + 1 };
+ continue;
+ }
+ if (text.trim() === '' || /^[ \t]/.test(text) || /^-(?:[ \t]|$)/.test(text) || text.startsWith('#')) continue;
+ return null;
+ }
+ return null;
+}
+
+/**
+ * `title: #1 thing` is valid YAML whose value is a comment, so the key reads
+ * as null. Detection only: the parse is unchanged. `description: # TODO`
+ * (a space after `#`) is an ordinary empty value and is not reported.
+ */
+export function commentValueKeys(block: string, data: Record<string, unknown>, lineOffset = 0): Array<{ key: string; line: number }> {
+ const found: Array<{ key: string; line: number }> = [];
+ toRows(block).forEach((row, i) => {
+ const m = /^([A-Za-z_][\w-]*):[ \t]+#\S/.exec(row.text);
+ if (m && Object.prototype.hasOwnProperty.call(data, m[1]!) && data[m[1]!] === null) found.push({ key: m[1]!, line: lineOffset + i + 1 });
+ });
+ return found;
+}
diff --git a/src/core/markdown.ts b/src/core/markdown.ts
index 1c4e57cb1c..7ec6d4d00b 100644
--- a/src/core/markdown.ts
+++ b/src/core/markdown.ts
@@ -2,6 +2,15 @@ import { dataFrontmatter as matter, FrontmatterLanguageError } from './data-fron
import { safeLoad as yamlSafeLoad } from 'js-yaml';
import type { Page, PageType } from './types.ts';
import { resolveSlugForPath, slugifyPath } from './sync.ts';
+import {
+ commentValueKeys, frontmatterKeyHazard, recoverFrontmatter, unclosedFenceProtectedKey, yamlLocationMessage,
+ RECOVERY_VERSION, type FrontmatterRecovery, type RecoveryKind,
+} from './frontmatter-recovery.ts';
+
+export {
+ recoverFrontmatter, RECOVERY_VERSION, PROTECTED_FRONTMATTER_KEYS, IDENTITY_FRONTMATTER_KEYS,
+ type FrontmatterRecovery, type FrontmatterRecoveryStatus, type FrontmatterRecoveryStep, type RecoveryKind,
+} from './frontmatter-recovery.ts';
export type ParseValidationCode =
| 'MISSING_OPEN'
@@ -17,6 +26,23 @@ export interface ParseValidationError {
code: ParseValidationCode;
message: string;
line?: number;
+ /** YAML_PARSE only: true when ingestion reads the block anyway (quoting only). Producer checks still fail on it. */
+ recoverable?: boolean;
+ /** YAML_PARSE only: what ingestion changed to read it; content-free, so it can be recorded as provenance. */
+ recovery?: Array<{ kind: RecoveryKind; key: string; line: number; recovery_version: number }>;
+}
+
+export type ParseWarningCode = 'FRONTMATTER_RECOVERED' | 'FRONTMATTER_COMMENT_VALUE';
+
+/** Advisories that never block ingestion. Local only: `original`/`replacement` carry raw frontmatter text. */
+export interface ParseValidationWarning {
+ code: ParseWarningCode;
+ message: string;
+ key: string;
+ line: number;
+ kind?: RecoveryKind;
+ original?: string;
+ replacement?: string;
}
export interface ParseOpts {
@@ -64,6 +90,13 @@ export interface ParsedMarkdown {
tags: string[];
/** Present iff opts.validate. Empty array means no errors. */
errors?: ParseValidationError[];
+ /** Present iff opts.validate. Never blocks ingestion; `errors` keeps its meaning. */
+ warnings?: ParseValidationWarning[];
+ /**
+ * Present iff opts.validate and the block needed recovery or hides an
+ * ambiguous protected or identity key. `classifyImportHold` reads it.
+ */
+ recovery?: FrontmatterRecovery;
}
/**
@@ -166,7 +199,7 @@ export function frontmatterBodyOffset(content: string): number {
* writers (agents, scripts, humans) no longer have to remember to quote
* colon-bearing titles themselves.
*/
-function quoteAmbiguousFrontmatterScalars(content: string): string {
+function quoteAmbiguousFrontmatterScalars(content: string, quoted?: Array<{ key: string; index: number; original: string; replacement: string }>): string {
const fenceMatch = content.match(/^---\r?\n([\s\S]*?)\r?\n---(\r?\n|$)/);
if (!fenceMatch) return content;
const fenceBody = fenceMatch[1]!;
@@ -175,7 +208,7 @@ function quoteAmbiguousFrontmatterScalars(content: string): string {
const fixedBody = fenceBody
.split('\n')
- .map(line => {
+ .map((line, index) => {
// Top-level `key: value` only — indented lines (list items, nested
// maps) never match this anchor, so they pass through untouched.
const kv = line.match(/^([a-zA-Z_][a-zA-Z0-9_]*):[ \t]+(.+)$/);
@@ -189,6 +222,7 @@ function quoteAmbiguousFrontmatterScalars(content: string): string {
// ": " (looks like a nested mapping key) or a trailing ":".
if (!value.includes(': ') && !value.endsWith(':')) return line;
const escaped = value.replace(/\\/g, '\\\\').replace(/"/g, '\\"');
+ quoted?.push({ key, index, original: line, replacement: `${key}: "${escaped}"` });
return `${key}: "${escaped}"`;
})
.join('\n');
@@ -215,6 +249,23 @@ function stripLeadingBlanksBeforeFence(content: string): string {
return lines.slice(i).join('\n');
}
+/**
+ * The YAML block of a fenced document, found as `parseDataFrontmatter` finds
+ * it; a BOM and the opening fence stay in `head`, so recovery rewrites only
+ * block lines and keeps every line ending. Null for an unclosed fence or a
+ * JSON/other language selector. `blockLine` is the block's first file line.
+ */
+function splitFrontmatterBlock(content: string): { head: string; block: string; tail: string; blockLine: number } | null {
+ const bom = content.startsWith('\uFEFF') ? '\uFEFF' : '';
+ const body = content.slice(bom.length);
+ const opening = /^---([^\r\n]*)(?:\r?\n|$)/.exec(body);
+ if (!opening || !['', 'yaml', 'yml'].includes(opening[1]!.trim().toLowerCase())) return null;
+ const rest = body.slice(opening[0].length);
+ const closing = /^---[\t ]*(?:\r?\n|$)/m.exec(rest);
+ if (!closing) return null;
+ return { head: bom + opening[0], block: rest.slice(0, closing.index), tail: rest.slice(closing.index), blockLine: 2 };
+}
+
/**
* #4526 (second arm): pages already corrupted by the pre-fix parse carry
* their real frontmatter EMBEDDED at the top of the body (double-frontmatter
@@ -263,26 +314,71 @@ export function parseMarkdown(
// its broken shape.
// #4526: lift the fence to byte 0 first (leading blank lines are legal per
// the validators), THEN quote ambiguous scalars (whose regex anchors ^---).
- const safeContent = quoteAmbiguousFrontmatterScalars(stripLeadingBlanksBeforeFence(content));
+ const lifted = stripLeadingBlanksBeforeFence(content);
+ const liftedLines = content.slice(0, content.length - lifted.length).split('\n').length - 1;
+ const quoted: Array<{ key: string; index: number; original: string; replacement: string }> = [];
+ const safeContent = quoteAmbiguousFrontmatterScalars(lifted, quoted);
let parsed: ReturnType<typeof matter> | null = null;
let yamlParseError: Error | null = null;
+ let recovery: FrontmatterRecovery | undefined;
+ let fenced: ReturnType<typeof splitFrontmatterBlock> | undefined;
try {
parsed = matter(safeContent);
} catch (e) {
if (e instanceof FrontmatterLanguageError && !opts?.validate) throw e;
yamlParseError = e as Error;
+ // #5988: only a block the strict parse refuses is recovered, so every file
+ // that parses today keeps its values. Only quoting is applied here.
+ fenced = e instanceof FrontmatterLanguageError ? null : splitFrontmatterBlock(safeContent);
+ if (fenced) {
+ recovery = recoverFrontmatter(fenced.block, liftedLines + fenced.blockLine - 1);
+ if (recovery.status === 'recovered') {
+ try { parsed = matter(fenced.head + recovery.block + fenced.tail); } catch { recovery = { ...recovery, status: 'unrecoverable' }; }
+ }
+ }
}
+ const warnings: ParseValidationWarning[] = [];
if (opts?.validate) {
+ if (fenced === undefined) fenced = splitFrontmatterBlock(safeContent);
+ const blockOffset = fenced ? liftedLines + fenced.blockLine - 1 : 0;
+ if (parsed && fenced) {
+ const block = recovery?.status === 'recovered' ? recovery.block : fenced.block;
+ const data = parsed.data as Record<string, unknown>;
+ const hazard = frontmatterKeyHazard(block, data, new Set(quoted.map(q => q.key)), blockOffset);
+ if (hazard) recovery = { ...(recovery ?? { block, steps: [], recovery_version: RECOVERY_VERSION }), status: hazard.status, key: hazard.key, line: hazard.line };
+ for (const found of commentValueKeys(block, data, blockOffset)) {
+ warnings.push({ code: 'FRONTMATTER_COMMENT_VALUE', key: found.key, line: found.line,
+ message: `Frontmatter "${found.key}" at line ${found.line} starts with # and reads as a YAML comment, so its value is empty; quote the value to keep it.` });
+ }
+ }
+ const recovered = parsed === null ? [] : [
+ ...quoted.map(q => ({ kind: 'quote' as const, key: q.key, line: liftedLines + 2 + q.index, original: q.original, replacement: q.replacement })),
+ ...(recovery?.steps ?? []),
+ ];
collectValidationErrors(content, errors, {
yamlParseError,
expectedSlug: opts.expectedSlug,
parsedFrontmatter: parsed?.data ?? {},
+ recovered,
+ recovery,
});
// Language selectors do not look like the plain YAML fence expected by
// structural validation. Keep their rejection visible to ingestion callers.
if (yamlParseError instanceof FrontmatterLanguageError && !errors.some(error => error.code === 'YAML_PARSE')) {
- errors.push({ code: 'YAML_PARSE', line: 1, message: `YAML parse failed: ${yamlParseError.message}` });
+ errors.push({ code: 'YAML_PARSE', line: 1, message: `YAML parse failed: ${yamlParseError.message}`, recoverable: false });
+ }
+ if (errors.some(error => error.code === 'YAML_PARSE' && error.recoverable)) {
+ for (const step of recovered) {
+ warnings.push({ code: 'FRONTMATTER_RECOVERED', key: step.key, line: step.line, kind: step.kind, original: step.original, replacement: step.replacement ?? undefined,
+ message: `Frontmatter "${step.key}" at line ${step.line} is not valid YAML; it was read by quoting its value. Quote it in the file.` });
+ }
+ }
+ if (errors.some(error => error.code === 'MISSING_CLOSE')) {
+ const lines = content.split('\n');
+ const opener = lines.findIndex(line => line.trim().length > 0);
+ const unclosed = unclosedFenceProtectedKey(lines.slice(opener + 1), opener + 1);
+ if (unclosed) recovery = { block: '', steps: [], recovery_version: RECOVERY_VERSION, status: 'ambiguous_protected_key', key: unclosed.key, line: unclosed.line };
}
}
@@ -338,7 +434,11 @@ export function parseMarkdown(
title,
tags,
};
- if (opts?.validate) result.errors = errors;
+ if (opts?.validate) {
+ result.errors = errors;
+ result.warnings = warnings;
+ if (recovery && recovery.status !== 'clean') result.recovery = recovery;
+ }
return result;
}
@@ -357,6 +457,90 @@ export function resolveParsedSubtype(
if (parsed.inferredSubtype?.type === parsed.type) parsed.frontmatter.subtype = parsed.inferredSubtype.name;
}
+/**
+ * #5988 hold codes: deterministic content refusals. Ingestion holds the one
+ * file and keeps going instead of failing the whole sync. Defined once here;
+ * managed and legacy sync, import and `validate --importable` share it.
+ */
+export const HOLD_CODES = ['invalid_frontmatter', 'frontmatter_slug_conflict', 'file_too_large', 'rename_held', 'parser_regression'] as const;
+export type HoldCode = typeof HOLD_CODES[number];
+export const INVALID_FRONTMATTER_REASONS = ['yaml_parse', 'needs_interpretation', 'ambiguous_identity_key', 'ambiguous_protected_key'] as const;
+export type InvalidFrontmatterReason = typeof INVALID_FRONTMATTER_REASONS[number];
+
+export interface ContentHold {
+ code: HoldCode;
+ reason?: InvalidFrontmatterReason;
+ key?: string;
+ line?: number;
+ /** Safe to persist and show remotely: names the key, line and cause, never a frontmatter value. */
+ message: string;
+}
+
+/** Markdown over its limit refuses as `Content too large (`; a code file as `Code file too large (`. */
+export function contentSizeHold(byteLength: number, maxBytes: number, codeFile = false): ContentHold | null {
+ if (byteLength <= maxBytes) return null;
+ return { code: 'file_too_large', message: codeFile ? `Code file too large (${byteLength} bytes)`
+ : `Content too large (${byteLength} bytes, max ${maxBytes}). Split the content into smaller files or remove large embedded assets.` };
+}
+
+const HOLD_GUIDANCE: Record<InvalidFrontmatterReason, string> = {
+ yaml_parse: 'Fix that line in the file (quote a value that contains ": " or starts with a special character), then import it again.',
+ needs_interpretation: 'Reading it would mean guessing, so it was not imported. Keep one line per key with its whole value quoted on that line, then import it again.',
+ ambiguous_identity_key: 'gbrain never guesses which page a file is. Keep exactly one line for that key, then import it again.',
+ ambiguous_protected_key: 'gbrain never guesses who may read a page or where it came from. Write that key on its own line with one quoted value, then import it again.',
+};
+
+const HOLD_MESSAGE = new RegExp(`^Invalid YAML frontmatter: (?:ambiguous (?:protected|identity) key "[\\w-]{1,100}" at line \\d+`
+ + `|key "[\\w-]{1,100}" at line \\d+ (?:continues on unquoted lines|appears more than once|opens \\[ or \\{ without closing it)`
+ + `|[a-z ;,'-]{1,200}(?: at line \\d+(?:, column \\d+)?)?(?: \\(key "[\\w-]{1,100}"\\))?)\\. `
+ + `(?:${Object.values(HOLD_GUIDANCE).map(text => text.replace(/[.*+?^${}()|[\]\\]/g, '\\$&')).join('|')})$`);
+
+/** True for a frontmatter hold message exactly as `classifyImportHold` builds it: key, line and cause only, safe to show. */
+export function isFrontmatterHoldMessage(message: string | null | undefined): boolean {
+ return typeof message === 'string' && HOLD_MESSAGE.test(message);
+}
+
+/**
+ * Map a validated parse (plus size and path context) to the one hold it
+ * earns, or null when ingestion accepts it. Recovered (quoted) YAML, comment
+ * values, a missing close, null bytes and nested quotes are not holds.
+ */
+export function classifyImportHold(parsed: ParsedMarkdown, ctx: {
+ byteLength?: number;
+ maxBytes?: number;
+ codeFile?: boolean;
+ expectedSlug?: string | null;
+ /** The sync exemption: a page keeping its recorded origin keeps its declared slug. */
+ slugExempt?: (declared: string) => boolean;
+ slugConflictMessage?: (found: string, expected: string) => string;
+} = {}): ContentHold | null {
+ const size = ctx.byteLength !== undefined && ctx.maxBytes !== undefined ? contentSizeHold(ctx.byteLength, ctx.maxBytes, ctx.codeFile) : null;
+ if (size) return size;
+ const recovery = parsed.recovery;
+ const yaml = parsed.errors?.find(error => error.code === 'YAML_PARSE' && !error.recoverable);
+ let reason: InvalidFrontmatterReason | null = null;
+ if (recovery?.status === 'ambiguous_protected_key' || recovery?.status === 'ambiguous_identity_key') reason = recovery.status;
+ else if (yaml) reason = recovery?.status === 'needs_interpretation' ? 'needs_interpretation' : 'yaml_parse';
+ if (reason) {
+ const step = reason === 'needs_interpretation' ? recovery!.steps.find(s => s.kind !== 'quote') : undefined;
+ const key = step?.key ?? recovery?.key;
+ const line = step?.line ?? recovery?.line ?? yaml?.line;
+ const where = `${line !== undefined ? ` at line ${line}` : ''}`;
+ const detail = reason === 'ambiguous_protected_key' ? `ambiguous protected key "${key}"${where}`
+ : reason === 'ambiguous_identity_key' ? `ambiguous identity key "${key}"${where}`
+ : reason === 'needs_interpretation' ? `key "${key}"${where} ${step!.kind === 'dup' ? 'appears more than once' : step!.kind === 'fold' ? 'continues on unquoted lines' : 'opens [ or { without closing it'}`
+ : `${(yaml?.message ?? '').replace(/^YAML parse failed:\s*/, '') || 'malformed YAML'}${key ? ` (key "${key}")` : ''}`;
+ return { code: 'invalid_frontmatter', reason, ...(key ? { key } : {}), ...(line !== undefined ? { line } : {}),
+ message: `Invalid YAML frontmatter: ${detail}. ${HOLD_GUIDANCE[reason]}` };
+ }
+ const expected = ctx.expectedSlug;
+ if (expected && parsed.slug !== expected && slugifyPath(parsed.slug) !== expected && !ctx.slugExempt?.(parsed.slug)) {
+ return { code: 'frontmatter_slug_conflict', key: 'slug',
+ message: ctx.slugConflictMessage?.(parsed.slug, expected) ?? `Frontmatter slug "${parsed.slug}" does not match path-derived slug "${expected}".` };
+ }
+ return null;
+}
+
/**
* Inspect raw content for the 7 frontmatter validation classes that gray-matter
* silently accepts. Mutates `errors` in place. The order of checks is
@@ -370,6 +554,9 @@ function collectValidationErrors(
yamlParseError: Error | null;
expectedSlug?: string;
parsedFrontmatter: Record<string, unknown>;
+ /** What ingestion changed to read the block; empty when it could not be read. */
+ recovered: ReadonlyArray<{ kind: RecoveryKind; key: string; line: number }>;
+ recovery?: FrontmatterRecovery;
},
): void {
// 1. NULL_BYTES — binary corruption indicator.
@@ -512,10 +699,18 @@ function collectValidationErrors(
}
}
if (detectedYamlParseError) {
+ // #5988: location only. js-yaml's own message quotes the document, and
+ // this text reaches receipts, sync results and remote callers.
+ const located = yamlFailureLocation(lines.slice(firstNonEmpty + 1, closeLine).join('\n'), firstNonEmpty + 1);
+ const recoverable = ctx.recovered.length > 0;
+ const reason = detectedYamlParseError.name === 'FrontmatterLanguageError' ? detectedYamlParseError.message
+ : yamlLocationMessage(located?.reason ?? 'malformed YAML', located?.line ?? ctx.recovery?.line, located?.column);
errors.push({
code: 'YAML_PARSE',
- message: `YAML parse failed: ${detectedYamlParseError.message}`,
- line: firstNonEmpty + 1,
+ message: `YAML parse failed: ${reason}`,
+ line: ctx.recovery?.line ?? (recoverable ? ctx.recovered[0]!.line : located?.line) ?? firstNonEmpty + 1,
+ recoverable,
+ ...(recoverable ? { recovery: ctx.recovered.map(step => ({ kind: step.kind, key: step.key, line: step.line, recovery_version: RECOVERY_VERSION })) } : {}),
});
}
@@ -549,6 +744,18 @@ function collectValidationErrors(
}
}
+/** Where js-yaml refuses a raw block: its reason phrase and the file line and column. */
+function yamlFailureLocation(block: string, lineOffset: number): { reason: string; line: number; column: number } | null {
+ try {
+ yamlSafeLoad(block);
+ return null;
+ } catch (e) {
+ const err = e as { reason?: string; mark?: { line?: number; column?: number } };
+ if (typeof err.mark?.line !== 'number') return null;
+ return { reason: err.reason ?? 'malformed YAML', line: lineOffset + err.mark.line + 1, column: (err.mark.column ?? 0) + 1 };
+ }
+}
+
function hasFrontmatterFieldSyntax(fmBody: string): boolean {
for (const line of fmBody.split('\n')) {
const trimmed = line.trim();
diff --git a/test/frontmatter-recovery.test.ts b/test/frontmatter-recovery.test.ts
new file mode 100644
index 0000000000..1de1bee9a2
--- /dev/null
+++ b/test/frontmatter-recovery.test.ts
@@ -0,0 +1,224 @@
+/**
+ * #5988 Lane A: the frontmatter reader recovers what it can read exactly
+ * (quoting a value), holds what it would have to guess, and never reads a
+ * protected key as a broader value.
+ *
+ * Protects: import of the issue's files, the hold classification every
+ * ingestion path shares, and the upgrade invariant (a file that imports today
+ * parses to the same values). Regressions it catches: the validator rejecting
+ * files the parser reads (R2), a guessed value or a swallowed `visibility`
+ * being imported, a rule rewriting a valid line, raw values leaking into
+ * persisted messages.
+ */
+import { describe, expect, test } from 'bun:test';
+import { readFileSync } from 'node:fs';
+import { join } from 'node:path';
+import {
+ classifyImportHold, parseMarkdown, recoverFrontmatter, HOLD_CODES, PROTECTED_FRONTMATTER_KEYS,
+ IDENTITY_FRONTMATTER_KEYS, RECOVERY_VERSION, type ParsedMarkdown,
+} from '../src/core/markdown.ts';
+import { isPrivatePage } from '../src/core/search/private-visibility.ts';
+
+const doc = (block: string, body = 'Body text.\n') => `---\n${block}\n---\n\n${body}`;
+const parse = (content: string, path = 'notes/example.md') => parseMarkdown(content, path, { validate: true });
+const hold = (parsed: ParsedMarkdown) => classifyImportHold(parsed);
+const allFrontmatter = (parsed: ParsedMarkdown) => ({ ...parsed.frontmatter, title: parsed.title, type: parsed.type });
+
+describe('recoverable shapes import with their exact text', () => {
+ test("the issue's exact author line (unquoted ': ') imports and is not held", () => {
+ const parsed = parse(doc('title: Payments roundup\nauthor: PYMNTS (citing Reuters / Bloomberg) (original: https://x.com/a/status/1)'));
+ expect(parsed.frontmatter.author).toBe('PYMNTS (citing Reuters / Bloomberg) (original: https://x.com/a/status/1)');
+ expect(hold(parsed)).toBeNull();
+ const yaml = parsed.errors!.find(e => e.code === 'YAML_PARSE')!;
+ expect(yaml.recoverable).toBe(true);
+ expect(yaml.recovery).toEqual([{ kind: 'quote', key: 'author', line: 3, recovery_version: RECOVERY_VERSION }]);
+ expect(parsed.warnings!.map(w => [w.code, w.key, w.line])).toEqual([['FRONTMATTER_RECOVERED', 'author', 3]]);
+ });
+
+ test('"quoted" trailing text keeps the whole value text', () => {
+ const parsed = parse(doc('title: "Quoted" trailing words\ntype: note'));
+ expect(parsed.title).toBe('"Quoted" trailing words');
+ expect(parsed.recovery?.status).toBe('recovered');
+ expect(hold(parsed)).toBeNull();
+ });
+
+ test('nested quotes keep the inner text, as the NESTED_QUOTES fix does', () => {
+ const parsed = parse(doc('title: "Name "Nick" Last"'));
+ expect(parsed.title).toBe('Name "Nick" Last');
+ expect(parsed.errors!.map(e => e.code)).toContain('NESTED_QUOTES');
+ expect(hold(parsed)).toBeNull();
+ });
+
+ test('a single-quoted scalar followed by text and an unclosed leading quote are quoted', () => {
+ expect(parse(doc("title: 'it' s here")).title).toBe("'it' s here");
+ expect(parse(doc('title: "Hello\ntype: note')).title).toBe('"Hello');
+ });
+
+ test('CRLF files recover and keep CRLF on every line, including the rewritten one', () => {
+ const block = 'title: Re: hello\r\nstatus: draft # todo\r\n';
+ const recovered = recoverFrontmatter(block);
+ expect(recovered.status).toBe('recovered');
+ expect(recovered.block).toBe('title: "Re: hello"\r\nstatus: draft # todo\r\n');
+ const parsed = parse('---\r\ntitle: Re: hello\r\ntype: note\r\n---\r\nbody\r\n');
+ expect(parsed.title).toBe('Re: hello');
+ expect(hold(parsed)).toBeNull();
+ });
+
+ test('a BOM-prefixed file recovers', () => {
+ const parsed = parse('\uFEFF---\ntitle: Re: hello\n---\nbody\n');
+ expect(parsed.title).toBe('Re: hello');
+ expect(hold(parsed)).toBeNull();
+ });
+
+ test('valid lines stay byte-identical; only the suspect line is rewritten', () => {
+ const block = 'status: draft # todo\ntitle: "Hello" world\ntags: [a, b]\ndate: 2024-06-01\n';
+ const recovered = recoverFrontmatter(block);
+ expect(recovered.status).toBe('recovered');
+ expect(recovered.block.split('\n')).toEqual(['status: draft # todo', 'title: "\\"Hello\\" world"', 'tags: [a, b]', 'date: 2024-06-01', '']);
+ expect(recovered.steps.map(s => [s.kind, s.key, s.line])).toEqual([['quote', 'title', 2]]);
+ });
+
+ test('a recovered visibility-bearing file keeps its private visibility end to end', () => {
+ const parsed = parse(doc('title: "Hello" world\nvisibility: private'));
+ expect(hold(parsed)).toBeNull();
+ expect(isPrivatePage({ type: parsed.type, frontmatter: parsed.frontmatter })).toBe(true);
+ });
+});
+
+describe('interpretive shapes are held, never imported', () => {
+ test('a value continuing on unquoted lines (fold) is needs_interpretation, with the proposal kept', () => {
+ const parsed = parse(doc('title: First line of a post\nsecond line of the post\ntype: note'));
+ expect(parsed.frontmatter).toEqual({});
+ expect(hold(parsed)).toMatchObject({ code: 'invalid_frontmatter', reason: 'needs_interpretation', key: 'title', line: 2 });
+ expect(parsed.recovery!.block).toContain('title: "First line of a post\\nsecond line of the post"');
+ });
+
+ test('a duplicated non-identity key is needs_interpretation naming both lines', () => {
+ const parsed = parse(doc('title: a\ntype: note\ntitle: b'));
+ expect(hold(parsed)).toMatchObject({ code: 'invalid_frontmatter', reason: 'needs_interpretation', key: 'title', line: 4 });
+ expect(parsed.recovery!.steps[0]).toMatchObject({ kind: 'dup', key: 'title', line: 4, otherLine: 2 });
+ });
+
+ test('an unclosed [ is needs_interpretation', () => {
+ expect(hold(parse(doc('tags: [a, b\ntype: note')))).toMatchObject({ reason: 'needs_interpretation', key: 'tags' });
+ });
+
+ test('shapes with no rule are unrecoverable yaml_parse holds', () => {
+ expect(hold(parse(doc('tags:\n - a\n - b')))).toMatchObject({ code: 'invalid_frontmatter', reason: 'yaml_parse', key: 'tags' });
+ expect(recoverFrontmatter('title: ok\n bad: indent\n').status).toBe('unrecoverable');
+ });
+
+ test('duplicated identity keys are held as ambiguous_identity_key', () => {
+ for (const key of IDENTITY_FRONTMATTER_KEYS) {
+ const h = hold(parse(doc(`${key}: one\ntitle: a\n${key}: two`)));
+ expect(h).toMatchObject({ code: 'invalid_frontmatter', reason: 'ambiguous_identity_key', key, line: 4 });
+ expect(h!.message.startsWith('Invalid YAML frontmatter: ambiguous identity key')).toBe(true);
+ }
+ });
+});
+
+describe('protected keys are never guessed', () => {
+ test('a visibility swallowed by an unclosed quote is held although YAML parses it', () => {
+ const parsed = parse(doc('title: "Hello\nvisibility: private\nsummary: x"'));
+ expect(parsed.errors!.some(e => e.code === 'YAML_PARSE')).toBe(false);
+ expect(isPrivatePage({ type: parsed.type, frontmatter: parsed.frontmatter })).toBe(false);
+ expect(hold(parsed)).toMatchObject({ code: 'invalid_frontmatter', reason: 'ambiguous_protected_key', key: 'visibility', line: 3 });
+ });
+
+ test('a protected value the pre-quote pass rewrote is held', () => {
+ const parsed = parse(doc('title: a\nvisibility: private # note: x'));
+ expect(hold(parsed)).toMatchObject({ reason: 'ambiguous_protected_key', key: 'visibility', line: 3 });
+ });
+
+ test('an unclosed fence carrying visibility is held instead of importing with no frontmatter', () => {
+ const parsed = parse('---\ntitle: a\nvisibility: private\n\n# Heading\nbody\n');
+ expect(parsed.errors!.map(e => e.code)).toContain('MISSING_CLOSE');
+ expect(hold(parsed)).toMatchObject({ reason: 'ambiguous_protected_key', key: 'visibility', line: 3 });
+ });
+
+ test('duplicated visibility, a quoted visibility with trailing text and a fold into derived_from are held', () => {
+ expect(hold(parse(doc('visibility: private\ntitle: a\nvisibility: world')))).toMatchObject({ reason: 'ambiguous_protected_key', key: 'visibility' });
+ expect(hold(parse(doc('visibility: "private" trailing')))).toMatchObject({ reason: 'ambiguous_protected_key', key: 'visibility' });
+ expect(hold(parse(doc('derived_from: notes/a\nnotes/b\ntitle: x')))).toMatchObject({ reason: 'ambiguous_protected_key', key: 'derived_from' });
+ });
+
+ test('every frontmatter key the access-control and provenance readers use is protected', () => {
+ const readers = ['src/core/search/private-visibility.ts', 'src/core/repair/visibility.ts', 'src/core/persistence/connector-sync.ts'];
+ const keys = new Set<string>();
+ for (const file of readers) {
+ const text = readFileSync(join(import.meta.dir, '..', file), 'utf8');
+ for (const m of text.matchAll(/frontmatter(?:->>?'|\??\.)([a-z_]+)/g)) keys.add(m[1]!);
+ }
+ expect(keys.size).toBeGreaterThan(3);
+ for (const key of keys) expect(PROTECTED_FRONTMATTER_KEYS).toContain(key);
+ });
+});
+
+describe('contract surfaces', () => {
+ test('producer checks stay strict: recoverable YAML_PARSE stays in errors; warnings are separate', () => {
+ const parsed = parse(doc('title: Re: hello'));
+ expect(parsed.errors!.map(e => e.code)).toEqual(['YAML_PARSE']);
+ expect(parsed.warnings!.map(w => w.code)).toEqual(['FRONTMATTER_RECOVERED']);
+ expect(parse(doc('title: fine')).warnings).toEqual([]);
+ });
+
+ test('#-comment values are detected without changing the parse; a spaced comment is left alone', () => {
+ const parsed = parse(doc('title: #1 thing\ndescription: # TODO'));
+ expect(parsed.frontmatter.description).toBeNull();
+ expect(parsed.title).toBe('Example');
+ expect(parsed.warnings!.map(w => [w.code, w.key, w.line])).toEqual([['FRONTMATTER_COMMENT_VALUE', 'title', 2]]);
+ expect(hold(parsed)).toBeNull();
+ });
+
+ test('hold messages and YAML_PARSE messages are location-only', () => {
+ const secret = 'alice-example private note';
+ for (const block of [`title: ${secret}\nmore of ${secret}`, `tags:\n - ${secret}\n - b`, `title: "${secret}" x\ntitle: y`]) {
+ const parsed = parse(doc(block));
+ const h = hold(parsed)!;
+ expect(h.message.startsWith('Invalid YAML frontmatter:')).toBe(true);
+ expect(h.message).not.toContain('alice-example');
+ for (const e of parsed.errors!) expect(e.message).not.toContain('alice-example');
+ }
+ });
+
+ test('HOLD_CODES is the canonical hold set', () => {
+ expect([...HOLD_CODES]).toEqual(['invalid_frontmatter', 'frontmatter_slug_conflict', 'file_too_large', 'rename_held', 'parser_regression']);
+ });
+
+ test('slug conflicts hold unless the recorded-origin exemption applies', () => {
+ const parsed = parse(doc('slug: other/page'), 'notes/page.md');
+ expect(classifyImportHold(parsed, { expectedSlug: 'notes/page' })).toMatchObject({ code: 'frontmatter_slug_conflict', key: 'slug' });
+ expect(classifyImportHold(parsed, { expectedSlug: 'notes/page', slugExempt: slug => slug === 'other/page' })).toBeNull();
+ });
+});
+
+describe('upgrade invariant: files that import today parse to identical values', () => {
+ const corpus: Array<[string, Record<string, unknown>]> = [
+ ['title: foo # note: x\ntype: note', { title: 'foo # note: x', type: 'note' }],
+ ['title: #1 thing\ntype: note', { title: 'Example', type: 'note' }],
+ ['status: draft # todo\ntitle: Plain', { status: 'draft', title: 'Plain', type: 'note' }],
+ ['title: Re: October booking\ntype: email', { title: 'Re: October booking', type: 'email' }],
+ ['title: "Quoted: fine"\ntags: [a, "b c"]', { title: 'Quoted: fine', type: 'note' }],
+ ["title: 'single \"inner\" quotes'", { title: 'single "inner" quotes', type: 'note' }],
+ ['title: Ends with colon:\nvisibility: world', { title: 'Ends with colon:', visibility: 'world', type: 'note' }],
+ ['title: >\n folded block\n text\ntype: concept', { title: 'folded block text', type: 'concept' }],
+ ['description: |\n line one\n line two\ntitle: Block', { description: 'line one\nline two\n', title: 'Block', type: 'note' }],
+ ['title: Multi\n line plain\ntype: note', { title: 'Multi line plain', type: 'note' }],
+ ['title: "Hello\n continued"', { title: 'Hello continued', type: 'note' }],
+ ['tags:\n- a\n- b\ntitle: Seq', { title: 'Seq', type: 'note' }],
+ ['title: 2024-06-01', { title: '2024-06-01', type: 'note' }],
+ ['date: 2024-02-30\ntitle: Bad date', { date: '2024-02-30', title: 'Bad date', type: 'note' }],
+ ];
+ for (const [block, expected] of corpus) {
+ test(JSON.stringify(block), () => {
+ const content = doc(block);
+ const parsed = parse(content, 'notes/example.md');
+ expect(parsed.recovery?.steps ?? []).toEqual([]);
+ expect(parsed.recovery).toBeUndefined();
+ expect(allFrontmatter(parsed)).toMatchObject(expected);
+ expect(hold(parsed)).toBeNull();
+ const plain = parseMarkdown(content, 'notes/example.md');
+ expect(allFrontmatter(plain)).toEqual(allFrontmatter(parsed));
+ });
+ }
+});