Garry's Opinionated OpenClaw/Hermes Agent Brain
TypeScript
fix(frontmatter): never flag or rewrite valid YAML block scalars (#6157)
garrytan343fc2203172
diff --git a/docs/architecture/key-files/files-and-sync-1.md b/docs/architecture/key-files/files-and-sync-1.mdindex 2f9d213d10..afbb7258d3 100644--- a/docs/architecture/key-files/files-and-sync-1.md+++ b/docs/architecture/key-files/files-and-sync-1.md@@ -33,7 +33,7 @@ Current behavior and load-bearing invariants; history belongs in Git and CHANGEL- `src/core/link-source-check-repair.ts` — schema-drift self-heal for the `links_link_source_check` CHECK constraint (third instance of the `timeline-dedup-repair.ts` / `pages-upsert-arbiter.ts` class). Migration v114 opened `link_source` from a closed allowlist to the kebab-case gate; the migrator trusts the version ledger, so a brain stamped >= 114 whose live constraint reverted to the pre-v114 allowlist (drifted restore, manual DDL) rejects every kebab provenance write (`atom-provenance`, `concept-provenance`) while the ledger reads current. `LINK_SOURCE_KEBAB_RE` is the ONE exported copy of the regex (a drift-guard test pins it to the literal in migrate.ts v114, `schema.sql`, `pglite-schema.ts`). `checkLinkSourceCheck(engine)` probes `pg_constraint` (`pg_get_constraintdef` + `convalidated`) and classifies the drift as `absent` / `wrong_def` / `not_validated` (read-only; powers the `links_link_source_check` doctor check in `doctor/checks/core-health.ts`, whose severity follows what writes do: only `wrong_def` rejects kebab writes → fail; `absent` / `not_validated` still accept them → warn). `repairLinkSourceCheck(engine)` first COUNTs rows that fail the gate and returns `reason: 'violations'` WITHOUT any DDL when there are any (the prior constraint survives; rows are never touched; a brain with a bad row never pays for a failing ALTER at every engine open), then restores v114's definition mirroring the migration's engine split: Postgres runs DROP + `ADD ... NOT VALID` in one `engine.transaction` (atomic, no scan) and `VALIDATE CONSTRAINT` as a separate `engine.runMigration` outside it (SHARE UPDATE EXCLUSIVE, never a plain ADD's ACCESS EXCLUSIVE + full-table scan), with a `not_validated` drift getting the VALIDATE only; PGLite keeps the one-shot DROP+ADD transaction. A DDL failure re-counts violators (a row written between probe and ALTER) and rethrows when there are none. `LINK_SOURCE_GATE_MIGRATION_VERSION` (114) is the ledger gate `runMigrations` applies before calling it. Pinned by `test/link-source-check-repair.test.ts` (PGLite, incl. a recording-engine assertion that violators trigger no DDL and that a sub-114 ledger never probes) and the DATABASE_URL-gated `test/e2e/link-source-check-repair-postgres.test.ts` (two-phase DDL sequence on real Postgres).-- `src/core/markdown.ts` — Frontmatter parsing + body splitter. `coerceFrontmatterString(v)` coerces a non-string `title`/`slug`/`type` to a deterministic string at parse time so a YAML-typed value never reaches `.toLowerCase()` and throws (`title: 2024-06-01` parses as a `Date`, `title: 1458` as a number, and a throw would block the sync bookmark from advancing); a `Date` becomes its UTC ISO date (`2024-06-01`, machine-independent and matching the on-disk token, unlike `String(date)`), `null`/`undefined` become `''`, everything else uses `String()`. `splitBody` requires an explicit timeline sentinel (`<!-- timeline -->`, `--- timeline ---`, or `---` immediately before `## Timeline`/`## History`). Plain `---` in body text is a markdown horizontal rule, not a separator. `inferType` auto-types `/wiki/analysis/` → analysis, `/wiki/guides/` → guide, `/wiki/hardware/` → hardware, `/wiki/architecture/` → architecture, `/writing/` → writing (plus existing people/companies/deals/etc heuristics). `resolveSourceLocalFilePath` maps Git-root-relative `pages.source_path` values into a source whose `local_path` scopes a repo subdirectory; it finds the Git root with filesystem checks only, strips the exact root-relative scope, rejects unsafe/non-markdown paths, and when given a slug it tolerates historical basename-relative `source_path` rows by checking the slug directory only after the direct path is absent. It leaves write containment to the caller. After its pre-quote pass, a block the strict parse refuses goes to `recoverFrontmatter`; only `quote` recoveries are applied. Under `validate`, YAML_PARSE stays in `errors` (location-only message, `recoverable` plus a content-free `recovery` record), advisories go to `warnings` (`FRONTMATTER_RECOVERED`, `FRONTMATTER_COMMENT_VALUE`), and `recovery` carries interpretive, protected-key and identity-key findings. `HOLD_CODES` and `classifyImportHold(parsed, ctx)` define the ingestion hold set once; `isFrontmatterHoldMessage` recognizes its exact messages. Tests: `test/frontmatter-recovery.test.ts`.+- `src/core/markdown.ts` — Frontmatter parsing + body splitter. `coerceFrontmatterString(v)` coerces a non-string `title`/`slug`/`type` to a deterministic string at parse time so a YAML-typed value never reaches `.toLowerCase()` and throws (`title: 2024-06-01` parses as a `Date`, `title: 1458` as a number, and a throw would block the sync bookmark from advancing); a `Date` becomes its UTC ISO date (`2024-06-01`, machine-independent and matching the on-disk token, unlike `String(date)`), `null`/`undefined` become `''`, everything else uses `String()`. `splitBody` requires an explicit timeline sentinel (`<!-- timeline -->`, `--- timeline ---`, or `---` immediately before `## Timeline`/`## History`). Plain `---` in body text is a markdown horizontal rule, not a separator. `inferType` auto-types `/wiki/analysis/` → analysis, `/wiki/guides/` → guide, `/wiki/hardware/` → hardware, `/wiki/architecture/` → architecture, `/writing/` → writing (plus existing people/companies/deals/etc heuristics). `resolveSourceLocalFilePath` maps Git-root-relative `pages.source_path` values into a source whose `local_path` scopes a repo subdirectory; it finds the Git root with filesystem checks only, strips the exact root-relative scope, rejects unsafe/non-markdown paths, and when given a slug it tolerates historical basename-relative `source_path` rows by checking the slug directory only after the direct path is absent. It leaves write containment to the caller. After its pre-quote pass, a block the strict parse refuses goes to `recoverFrontmatter`; only `quote` recoveries are applied. Under `validate`, YAML_PARSE stays in `errors` (location-only message, `recoverable` plus a content-free `recovery` record), advisories go to `warnings` (`FRONTMATTER_RECOVERED`, `FRONTMATTER_COMMENT_VALUE`), and `recovery` carries interpretive, protected-key and identity-key findings. `HOLD_CODES` and `classifyImportHold(parsed, ctx)` define the ingestion hold set once; `isFrontmatterHoldMessage` recognizes its exact messages. `yamlBlockError(block)` parses a whole frontmatter block once; the per-line NESTED_QUOTES heuristic runs only when it fails, and `autoFixFrontmatter` (brain-writer.ts) uses it to skip the NESTED_QUOTES rewrite and keeps a tags/aliases re-quote only when the line reads back as the same value, so valid YAML is never rewritten (#6157). Tests: `test/frontmatter-recovery.test.ts`, `test/markdown-validation.test.ts`, `test/brain-writer.test.ts`.- `src/core/quarantine.ts` — the two frontmatter markers the content-quality gate writes, sibling of `src/core/embed-skip.ts` (same marker-as-JSONB-object pattern, same JSONB `?` existence check that works on Postgres AND PGLite; no schema migration — both are frontmatter JSONB keys). `quarantine` (key `QUARANTINE_KEY`) HIDES: set ONLY for high-confidence junk, writes zero chunks, excluded from search via `quarantineFilterFragment(pageAlias)` / `QUARANTINE_FILTER_FRAGMENT` (the `p`-aliased constant), the single source of truth `buildVisibilityClause` calls so the search filter and marker key can't drift. `content_flag` (key `CONTENT_FLAG_KEY`) WARNS, does NOT hide: set for fuzzy markup-heavy / oversize, page stays searchable, marker is READ INTO search/get_page output — deliberately NO SQL filter fragment. Three distinct markers, three reasons (never overloaded): `embed_skip` = oversized-but-clean, `quarantine` = junk hidden, `content_flag` = odd-examine-still-here; a page can carry more than one (oversize → embed_skip + content_flag:oversized) and each clears independently. Exports `buildQuarantineMarker` / `isQuarantined` / `filterOutQuarantined`, `buildContentFlagMarker` / `getContentFlag` / `hasContentFlag`, plus the two key constants. Pinned by `test/quarantine.test.ts`. A quarantined page is skipped by every derived-data scan (stale listing via the engine-sql stale predicate, NER, meeting timeline projection, file walks via `quarantinedSlugs`, DB walks, the managed link derivation) and is not in the `links_extraction_lag` denominator. Pinned by `test/quarantine-extraction.test.ts`.diff --git a/src/core/behavior-change-notice.ts b/src/core/behavior-change-notice.tsindex 449dee9b44..370e1645e8 100644--- a/src/core/behavior-change-notice.ts+++ b/src/core/behavior-change-notice.ts@@ -257,6 +257,7 @@ export const BEHAVIOR_CHANGES: ReadonlyArray<{ since: string; text: ChangeText }{ since: '0.60.97.0', text: 'Google Calendar sync writes only events between `historyDays` back and 60 days ahead; `gbrain sync --full` removes pages for in-window events the calendar no longer lists (more than 200 is refused and reported partial).' },{ since: '0.60.98.0', text: 'Managed sync now holds a file whose facts or takes fence cannot be imported (code `invalid_fence`; `gbrain sources status <id>` names the fence, section and rows) instead of blocking the whole source, and a source such a fence blocked before recovers on its next sync. Coordinated writes refuse such a fence with `invalid_fence` (wire `error` stays `invalid_params`, or `take_row_collision`). `gbrain config set sync.holds fail` keeps fail-closed blocking.' },{ since: '0.60.99.0', text: 'Fixable facts and takes fences are now rewritten instead of held or refused: managed sync, put_page and the fact and take writers normalize a fence whose meaning is unambiguous (a missing end marker after the table, two-dash takes markers, zero or duplicate row numbers, header aliases, invented kinds and enum synonyms, assistant holders, percent confidences) without changing a claim or an existing row number, and managed sync commits the rewritten file. Results report `fences_normalized`; `gbrain sync --dry-run` lists `would_normalize`. `gbrain config set fences.normalize false` turns it off (such fences are then held or refused).' },+ { since: '0.0.0-wave11', text: 'Frontmatter validation and `--fix` no longer flag or rewrite valid YAML (a block-scalar line shaped like `Key: "a", then "b"`); a file an earlier `gbrain frontmatter validate --fix` rewrote can be restored from its backup under ~/.gbrain/backups/frontmatter/.' },];/** The newest disclosed change's release: the notice id moves only when a release adds rows. */diff --git a/src/core/brain-writer.ts b/src/core/brain-writer.tsindex 3c6085d1a9..277f4ede63 100644--- a/src/core/brain-writer.ts+++ b/src/core/brain-writer.ts@@ -18,6 +18,7 @@ import { assertManagedFilesystemWrite } from './persistence/filesystem-guard.ts'*/import { createHash } from 'crypto';+import { load as yamlLoad } from 'js-yaml';import { existsSync, readFileSync, readdirSync, copyFileSync, writeFileSync, mkdirSync, lstatSync } from 'fs';import { join, relative, resolve, dirname, basename, isAbsolute } from 'path';import type { BrainEngine } from './engine.ts';@@ -30,6 +31,7 @@ import {type ParseValidationCode,type ParseValidationError,type ParseWarningCode,+ yamlBlockError,} from './markdown.ts';import { isMarkdownFilePath, isSyncable, pruneDir, slugifyPath } from './sync.ts';@@ -151,6 +153,25 @@ export function createFrontmatterBackup(filePath: string, opts: FrontmatterBacku// autoFixFrontmatter// ---------------------------------------------------------------------------+/**+ * A cosmetic line rewrite is kept only when it reads back as the same value+ * (#6157). A line that does not parse on its own is a repair target, so the+ * rewrite is allowed.+ */+function rewriteKeepsYamlValue(before: string, after: string): boolean {+ let original: unknown;+ try {+ original = yamlLoad(before);+ } catch {+ return true;+ }+ try {+ return JSON.stringify(yamlLoad(after)) === JSON.stringify(original);+ } catch {+ return false;+ }+}+/*** Mechanical auto-repair for the fixable subset of validation codes:* - NULL_BYTES — strip \x00 characters@@ -283,7 +304,9 @@ export function autoFixFrontmatter(if (!clean) return "''";return clean.includes("'") ? `"${clean}"` : `'${clean}'`;});- lines[i] = `${prefix}[${reQuoted.join(', ')}]`;+ const rewritten = `${prefix}[${reQuoted.join(', ')}]`;+ if (!rewriteKeepsYamlValue(lines[i], rewritten)) continue;+ lines[i] = rewritten;fixedAny = true;}if (fixedAny) {@@ -299,7 +322,9 @@ export function autoFixFrontmatter(// 3. NESTED_QUOTES — rewrite `key: "...inner..."` lines that have 3+ unescaped// double-quotes by switching the outer wrapper to single quotes and- // leaving inner quotes alone.+ // leaving inner quotes alone. Only when the closed block fails to parse+ // (#6157): valid YAML, such as a block-scalar continuation line shaped+ // like `Key: "a", then "b"`, is never rewritten.{const lines = working.split('\n');let firstNonEmpty = -1;@@ -311,8 +336,9 @@ export function autoFixFrontmatter(for (let i = firstNonEmpty + 1; i < lines.length; i++) {if (lines[i].trim() === '---') { closeIdx = i; break; }}+ const blockParses = closeIdx < lines.length && yamlBlockError(lines.slice(firstNonEmpty + 1, closeIdx).join('\n')) === null;let fixedAny = false;- for (let i = firstNonEmpty + 1; i < closeIdx; i++) {+ for (let i = firstNonEmpty + 1; !blockParses && i < closeIdx; i++) {const m = lines[i].match(/^(\s*[A-Za-z_][\w-]*\s*:\s*)"(.*)"\s*(.*)$/);if (!m) continue;const [, prefix, inner, trailing] = m;diff --git a/src/core/markdown.ts b/src/core/markdown.tsindex 0147b59667..b50b9bd678 100644--- a/src/core/markdown.ts+++ b/src/core/markdown.ts@@ -649,6 +649,11 @@ function collectValidationErrors(});}+ // #6157: parse the whole block once. The per-line NESTED_QUOTES heuristic+ // below only runs when the block fails to parse; a block-scalar+ // continuation line that looks like `Key: "a", "b"` is valid YAML.+ const blockParseError = yamlBlockError(fmBody);+// 5. NESTED_QUOTES — common breakage pattern: `title: "Name "Nick" Last"`.// The heuristic: a frontmatter `key: value` line with 3+ unescaped// double-quote characters is suspicious. But raw quote-counting is@@ -658,7 +663,7 @@ function collectValidationErrors(// Disambiguate by running js-yaml on just the value; only flag// lines that genuinely fail to parse. The full-frontmatter YAML// parse error is caught separately by check 6 (YAML_PARSE) below.- for (let i = firstNonEmpty + 1; i < closeLine; i++) {+ for (let i = firstNonEmpty + 1; blockParseError && i < closeLine; i++) {const line = lines[i];const m = line.match(/^\s*[A-Za-z_][\w-]*\s*:\s*(.*)$/);if (!m) continue;@@ -696,14 +701,7 @@ function collectValidationErrors(// body with empty data, so the validation surface must not depend only on// gray-matter's parse path. Gate this on frontmatter-shaped fields so a// leading Markdown thematic break / epigraph is preserved as body content.- let detectedYamlParseError = looksLikeFrontmatter ? ctx.yamlParseError : null;- if (!detectedYamlParseError && looksLikeFrontmatter) {- try {- yamlLoad(fmBody);- } catch (e) {- detectedYamlParseError = e as Error;- }- }+ const detectedYamlParseError = looksLikeFrontmatter ? (ctx.yamlParseError ?? blockParseError) : null;if (detectedYamlParseError) {// #5988: location only. js-yaml's own message quotes the document, and// this text reaches receipts, sync results and remote callers.@@ -750,6 +748,16 @@ function collectValidationErrors(}}+/** The js-yaml error for a frontmatter block, or null when the whole block parses. */+export function yamlBlockError(block: string): Error | null {+ try {+ yamlLoad(block);+ return null;+ } catch (e) {+ return e as Error;+ }+}+/** 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 {diff --git a/test/brain-writer.test.ts b/test/brain-writer.test.tsindex 1596cc0607..de32f7269c 100644--- a/test/brain-writer.test.ts+++ b/test/brain-writer.test.ts@@ -53,6 +53,21 @@ describe('autoFixFrontmatter', () => {expect(fixes).toEqual([]);});+ // #6157: valid YAML is never rewritten. A folded continuation line that+ // looks like `Key: "a", then "b"` used to be re-quoted, changing the value.+ test('leaves a valid folded block scalar byte-identical (#6157)', () => {+ const input = `${fence}\ntype: concept\ntitle: Interview notes\nclaim: >-\n The founder said\n Reply: "Ship it", then "measure it" twice\n${fence}\n\nbody`;+ const { content, fixes } = autoFixFrontmatter(input);+ expect(content).toBe(input);+ expect(fixes).toEqual([]);+ });++ test('tag normalization never changes a parsed value (#6157)', () => {+ const input = `${fence}\ntype: person\ntags: ["a\\"b", "yc"]\n${fence}\n\nbody`;+ const { content } = autoFixFrontmatter(input);+ expect(content).toBe(input);+ });+test('does not corrupt closed frontmatter with an indented `#` line inside a YAML block scalar', () => {const input = `${fence}\ndescription: |\n # not a heading, just literal block-scalar text\ntitle: ok\n${fence}\nBody`;const { content, fixes } = autoFixFrontmatter(input);diff --git a/test/frontmatter-cli.test.ts b/test/frontmatter-cli.test.tsindex c5a13577e1..bbea064a50 100644--- a/test/frontmatter-cli.test.ts+++ b/test/frontmatter-cli.test.ts@@ -170,6 +170,21 @@ describe('gbrain frontmatter CLI (B4)', () => {expect(readFileSync(f, 'utf8')).toMatch(/^title: '.*'\s*$/m);}, 60_000);+ // #6157: a valid folded value whose continuation line looks like+ // `Key: "a", then "b"` is neither reported nor rewritten by --fix.+ test('validate --fix writes nothing on a valid folded block scalar (#6157)', async () => {+ const f = join(tmp, 'folded.md');+ const original = `${fence}\ntype: concept\ntitle: Interview notes\nclaim: >-\n The founder said\n Reply: "Ship it", then "measure it" twice\n${fence}\n\nbody`;+ writeFileSync(f, original);+ await withEnv({ GBRAIN_HOME: join(tmp, 'home') }, async () => {+ const { out, verdict } = await runFm(['validate', f, '--fix']);+ expect(verdict).toBe(0);+ expect(out).not.toContain('NESTED_QUOTES');+ });+ expect(readFileSync(f, 'utf8')).toBe(original);+ expect(existsSync(join(tmp, 'home', '.gbrain', 'backups', 'frontmatter'))).toBe(false);+ });+test('validate --fix succeeds on a non-git path (no dirty-tree guard)', async () => {// tmp is not a git repo; --fix must still work.const f = join(tmp, 'broken.md');diff --git a/test/markdown-validation.test.ts b/test/markdown-validation.test.tsindex 4ac8904ad8..5b024a8519 100644--- a/test/markdown-validation.test.ts+++ b/test/markdown-validation.test.ts@@ -192,6 +192,20 @@ body`;expect(parsed.errors!.filter(e => e.code === 'NESTED_QUOTES')).toHaveLength(0);});+ // #6157: a block-scalar continuation line can look like `Key: "a", "b"`.+ // When the whole block parses, the per-line heuristic must not run.+ test('folded block-scalar continuation that looks like key: "a" "b" does NOT trigger (#6157)', () => {+ const md = `${fence}\ntype: concept\ntitle: Interview notes\nclaim: >-\n The founder said\n Reply: "Ship it", then "measure it" twice\n${fence}\n\nbody`;+ const parsed = parseMarkdown(md, undefined, { validate: true });+ expect(parsed.errors!.filter(e => e.code === 'NESTED_QUOTES' || e.code === 'YAML_PARSE')).toHaveLength(0);+ });++ test('literal block-scalar lines with Key: "a" "b" do NOT trigger (#6157)', () => {+ const md = `${fence}\ntype: concept\ntitle: x\nnotes: |\n Q: "why" and "how"\n A: "later" "maybe"\n${fence}\n\nbody`;+ const parsed = parseMarkdown(md, undefined, { validate: true });+ expect(parsed.errors!.filter(e => e.code === 'NESTED_QUOTES' || e.code === 'YAML_PARSE')).toHaveLength(0);+ });+test('genuinely broken nested quotes STILL trigger', () => {// Outer " followed by stray inner " — yaml.safeLoad throws.const md = `${fence}\ntype: concept\ntitle: "Foo "bar" baz "qux" end"\n${fence}\n\nbody`;