Garry's Opinionated OpenClaw/Hermes Agent Brain
TypeScript
fix(writers): serialize frontmatter scalars through yamlScalar (#5988)
garrytan713ebca51474
diff --git a/src/commands/schema.ts b/src/commands/schema.tsindex 02e02ff264..a1757bce66 100644--- a/src/commands/schema.ts+++ b/src/commands/schema.ts@@ -57,6 +57,7 @@ import { gbrainPath, loadConfig, configPath, toEngineConfig, isThinClient, typeimport { opError } from '../core/ops/contract.ts';import { readDbSchemaPack } from '../core/schema-pack/best-effort.ts';import { sanitizeTypeForDisplay } from '../core/schema-pack/type-usage.ts';+import { yamlScalar } from '../core/frontmatter-inference.ts';export async function runSchema(args: string[]): Promise<void> {const sub = args[0];@@ -605,7 +606,7 @@ async function runInitCmd(args: string[]): Promise<void> {};const yaml = `# Stub pack — extends gbrain-base by default. Add your own page_types below.api_version: ${stub.api_version}-name: ${stub.name}+name: ${yamlScalar(stub.name)}version: ${stub.version}gbrain_min_version: ${stub.gbrain_min_version}extends: gbrain-basediff --git a/src/core/facts/fence-write.ts b/src/core/facts/fence-write.tsindex 312ff53779..921f421147 100644--- a/src/core/facts/fence-write.ts+++ b/src/core/facts/fence-write.ts@@ -41,6 +41,7 @@ import { dirname, isAbsolute, relative } from 'node:path';import type { BrainEngine, NewFact, FactVisibility, FactKind } from '../engine.ts';import type { ResolutionSource } from '../entities/resolve.ts';import { inferTypeFromPack, parseMarkdown } from '../markdown.ts';+import { yamlScalar } from '../frontmatter-inference.ts';import { sanitizeText } from '../batch-rows.ts';import { loadActivePackBestEffort } from '../schema-pack/best-effort.ts';import { withPageLock } from '../page-lock.ts';@@ -235,7 +236,7 @@ async function commitFactFenceFile(* (e.g. `people/alice` → 'person'); unknown prefixes fall back to* 'concept' which is the most permissive PageType.*/-function stubEntityPage(+export function stubEntityPage(slug: string,pack: Parameters<typeof inferTypeFromPack>[1] | null,): string {@@ -257,7 +258,7 @@ function stubEntityPage(const title = tail.replace(/[-_/]+/g, ' ').replace(/\b\w/g, c => c.toUpperCase()) || slug;- return `---\ntype: ${type}\ntitle: ${title}\nslug: ${slug}\n---\n\n# ${title}\n`;+ return `---\ntype: ${yamlScalar(type)}\ntitle: ${yamlScalar(title)}\nslug: ${yamlScalar(slug)}\n---\n\n# ${title}\n`;}/**diff --git a/src/core/frontmatter-inference.ts b/src/core/frontmatter-inference.tsindex ca06d7b0ac..6d484b0911 100644--- a/src/core/frontmatter-inference.ts+++ b/src/core/frontmatter-inference.ts@@ -365,6 +365,15 @@ export function isSafePlainYamlScalar(title: string): boolean {return !/^(y|yes|n|no|true|false|on|off|null)$/i.test(title);}+/**+ * One YAML scalar for a frontmatter (or pack YAML) line: plain when+ * `isSafePlainYamlScalar` proves it safe, otherwise a JSON double-quoted+ * string (valid YAML for every string, newlines and `---` included).+ */+export function yamlScalar(value: string): string {+ return isSafePlainYamlScalar(value) ? value : JSON.stringify(value);+}+/*** Generate a YAML frontmatter block from inferred fields.* Returns the `---\n...\n---\n` string to prepend to content.@@ -377,7 +386,7 @@ export function serializeFrontmatter(fm: InferredFrontmatter): string {// Title — emit as a plain scalar ONLY when provably safe (see// isSafePlainYamlScalar). Everything else is quoted.lines.push(- `title: ${isSafePlainYamlScalar(fm.title) ? fm.title : JSON.stringify(fm.title)}`,+ `title: ${yamlScalar(fm.title)}`,);lines.push(`type: ${fm.type}`);diff --git a/src/core/skillify/templates.ts b/src/core/skillify/templates.tsindex e6a87d4fdc..56e9b79d74 100644--- a/src/core/skillify/templates.ts+++ b/src/core/skillify/templates.ts@@ -4,6 +4,8 @@* Pure-string generators. No I/O here; the caller writes files.*/+import { yamlScalar } from '../frontmatter-inference.ts';+/*** SKILLIFY_STUB sentinel (D-CX-9). Every scaffolded script body* carries this marker until an implementer replaces it. `gbrain@@ -31,16 +33,16 @@ export interface ScaffoldVars {export function skillMdTemplate(v: ScaffoldVars): string {const triggerLines =v.triggers.length > 0- ? v.triggers.map(t => ` - "${t.replace(/"/g, '\\"')}"`).join('\n')+ ? v.triggers.map(t => ` - ${JSON.stringify(t)}`).join('\n'): ' - "TBD-trigger — replace with phrases users actually type"';const writesToLines =- v.writesTo.length > 0 ? v.writesTo.map(d => ` - ${d}`).join('\n') : '';+ v.writesTo.length > 0 ? v.writesTo.map(d => ` - ${yamlScalar(d)}`).join('\n') : '';const lines: string[] = ['---',- `name: ${v.name}`,+ `name: ${yamlScalar(v.name)}`,'version: 0.1.0',- `description: ${v.description}`,+ `description: ${yamlScalar(v.description)}`,'triggers:',triggerLines,];diff --git a/test/frontmatter-writers-roundtrip.test.ts b/test/frontmatter-writers-roundtrip.test.tsnew file mode 100644index 0000000000..95c63a101a--- /dev/null+++ b/test/frontmatter-writers-roundtrip.test.ts@@ -0,0 +1,82 @@+/**+ * #5988 prevention: every gbrain frontmatter writer serializes caller strings+ * through a YAML-safe scalar, so a hostile value (`: `, `#`, `[x]`, quotes,+ * newlines, `---`, YAML keywords) strict-parses back to exactly the string it+ * was given. A strict parse (js-yaml with gbrain's FRONTMATTER_SCHEMA, no+ * pre-quoting, no recovery) is the bar: what an external YAML reader sees.+ */+import { afterEach, beforeEach, describe, expect, test } from 'bun:test';+import { mkdtempSync, readFileSync, rmSync } from 'node:fs';+import { tmpdir } from 'node:os';+import { join } from 'node:path';+import { safeLoad } from 'js-yaml';++import { FRONTMATTER_SCHEMA } from '../src/core/data-frontmatter.ts';+import { serializeFrontmatter, yamlScalar } from '../src/core/frontmatter-inference.ts';+import { skillMdTemplate } from '../src/core/skillify/templates.ts';+import { stubEntityPage } from '../src/core/facts/fence-write.ts';+import { serializeMarkdown } from '../src/core/markdown.ts';+import { runSchema } from '../src/commands/schema.ts';+import { withEnv } from './helpers/with-env.ts';++const HOSTILE = [+ 'a: b', 'ends with colon:', '#1 thing', 'tag #inline', '[x]', '{y: z}', '"quoted" trailing', "it's", 'say "hi"',+ 'line one\nline two', '---', 'a\n---\nb', '- item', 'yes', 'null', '2026', ' leading space', 'trailing space ',+ '@handle', '`tick`', '| pipe', '> folded', '*alias', '&anchor', '!tag', '%directive', 'back\\slash', 'tab\there', 'emoji ✓',+];++/** The YAML block between the opening and closing fences, strictly parsed. */+function strictFrontmatter(doc: string): Record<string, unknown> {+ const m = /^---\n([\s\S]*?)\n---(?:\n|$)/.exec(doc);+ if (!m) throw new Error(`no frontmatter block in:\n${doc}`);+ return safeLoad(m[1]!, { schema: FRONTMATTER_SCHEMA }) as Record<string, unknown>;+}++describe('frontmatter writers round-trip hostile strings under a strict YAML parse', () => {+ const writers: Array<{ name: string; write: (value: string) => string; read: (fm: Record<string, unknown>) => unknown[]; expect: (value: string) => unknown[] }> = [+ { name: 'yamlScalar', write: v => `---\nvalue: ${yamlScalar(v)}\n---\n`, read: fm => [fm.value], expect: v => [v] },+ { name: 'serializeFrontmatter (frontmatter generate)', write: v => serializeFrontmatter({ title: v, type: 'note' }),+ read: fm => [fm.title], expect: v => [v] },+ { name: 'skillMdTemplate (skillify scaffold)', write: v => skillMdTemplate({ name: v, description: v, triggers: [v], writesTo: [v], writesPages: true, mutating: false }),+ read: fm => [fm.name, fm.description, (fm.triggers as unknown[])[0], (fm.writes_to as unknown[])[0]], expect: v => [v, v, v, v] },+ { name: 'stubEntityPage (facts fence stub)', write: v => stubEntityPage(`concepts/${v}`, null),+ read: fm => [fm.slug, typeof fm.title], expect: v => [`concepts/${v}`, 'string'] },+ { name: 'serializeMarkdown (put_page write-through)', write: v => serializeMarkdown({ summary: v }, 'body', '', { type: 'note', title: v, tags: [v] }),+ read: fm => [fm.title, fm.summary, (fm.tags as unknown[])[0]], expect: v => [v, v, v] },+ ];++ for (const writer of writers) {+ test(writer.name, () => {+ for (const value of HOSTILE) {+ const doc = writer.write(value);+ let fm: Record<string, unknown>;+ try {+ fm = strictFrontmatter(doc);+ } catch (error) {+ throw new Error(`${writer.name} wrote unparseable YAML for ${JSON.stringify(value)}: ${(error as Error).message}\n${doc}`);+ }+ expect({ value, got: writer.read(fm) }).toEqual({ value, got: writer.expect(value) });+ }+ });+ }+});++describe('schema init pack.yaml', () => {+ let home: string;+ beforeEach(() => { home = mkdtempSync(join(tmpdir(), 'fm-writers-schema-')); });+ afterEach(() => { rmSync(home, { recursive: true, force: true }); });++ test('a hostile pack name strict-parses back to itself', async () => {+ const logOrig = console.log;+ console.log = () => {};+ try {+ for (const name of ['a: b #c', '[x]', '"q" tail', '---', 'yes']) {+ await withEnv({ GBRAIN_HOME: home }, () => runSchema(['init', name, '--json']));+ const yaml = readFileSync(join(home, '.gbrain', 'schema-packs', name, 'pack.yaml'), 'utf8');+ expect((safeLoad(yaml, { schema: FRONTMATTER_SCHEMA }) as { name: unknown }).name).toBe(name);+ }+ } finally {+ console.log = logOrig;+ }+ });+});