Skip to content

Garry's Opinionated OpenClaw/Hermes Agent Brain

TypeScript

fix(frontmatter): refuse undefined fields instead of letting js-yaml 4 drop them; test(deactivate): settle the source's effects before rewriting effect rows

garrytan81c635364378
diff --git a/src/core/data-frontmatter.ts b/src/core/data-frontmatter.ts
index 59eb333430..5fc4b5421c 100644
--- a/src/core/data-frontmatter.ts
+++ b/src/core/data-frontmatter.ts
@@ -79,9 +79,23 @@ export function parseDataFrontmatter(input: string): DataFrontmatter {
};
}
+/**
+ * YAML dump that refuses `undefined`. js-yaml 4 silently drops an undefined
+ * mapping value, so a field a caller meant to write would vanish; a write site
+ * omits the key (conditional spread) or writes null instead.
+ */
+export function dumpFrontmatterYaml(data: unknown, opts: { lineWidth?: number } = {}): string {
+ return dump(data, { ...opts, replacer: (key: string, value: unknown) => {
+ if (value === undefined) {
+ throw new TypeError(`Frontmatter field "${key}" is undefined. Why: YAML has no undefined, so the field would be dropped silently. Fix: omit the key at the write site (\`...(v ? { ${key}: v } : {})\`) or pass null.`);
+ }
+ return value;
+ } });
+}
+
/** Serialize metadata without ever interpreting the body as frontmatter. */
export function stringifyDataFrontmatter(content: string, data: Record<string, unknown>): string {
- const yaml = dump(data).trim();
+ const yaml = dumpFrontmatterYaml(data).trim();
const header = yaml === '{}' ? '' : `---\n${yaml}\n---\n`;
return header + (content.endsWith('\n') ? content : content + '\n');
}
diff --git a/src/core/transcripts/render.ts b/src/core/transcripts/render.ts
index 8afc6b85aa..a0637377e3 100644
--- a/src/core/transcripts/render.ts
+++ b/src/core/transcripts/render.ts
@@ -27,7 +27,7 @@
* per-session id would make parts 2..N skip as cross-slug duplicates.
*/
-import { dump } from 'js-yaml';
+import { dumpFrontmatterYaml } from '../data-frontmatter.ts';
import { homedir } from 'node:os';
import { join } from 'node:path';
import { DEFAULT_BYTES_WARN } from '../content-sanity.ts';
@@ -278,7 +278,7 @@ export interface RenderedPart {
}
export function renderPartContent(frontmatter: Record<string, unknown>, body: string): string {
- return `---\n${dump(frontmatter, { lineWidth: 1000 })}---\n\n${body}\n`;
+ return `---\n${dumpFrontmatterYaml(frontmatter, { lineWidth: 1000 })}---\n\n${body}\n`;
}
export interface RenderSessionResult {
diff --git a/test/persistence-deactivate.test.ts b/test/persistence-deactivate.test.ts
index 859f85e760..24a6aa29c0 100644
--- a/test/persistence-deactivate.test.ts
+++ b/test/persistence-deactivate.test.ts
@@ -27,6 +27,7 @@ import type { OperationContext } from '../src/core/ops/contract.ts';
import { managedBrain } from './helpers/managed-brain.ts';
import { declarePersistenceProtocol } from '../src/core/persistence/protocol.ts';
import { put } from './helpers/wave-fixture.ts';
+import { waitFor } from './helpers/wait-for.ts';
const admin = (engine: BrainEngine, operation: string, params: Record<string, unknown> = {}) =>
runPersistenceAdministration(engine, operation as never, params) as Promise<Record<string, any>>;
@@ -34,6 +35,12 @@ const deactivate = async (engine: BrainEngine, extra: Record<string, unknown> =
admin(engine, 'writer_deactivate', { admin_intent: 'writer_deactivate', expected_state: await writerAdminState(engine), ...extra });
const protocol = (engine: BrainEngine, sql: string, params: unknown[] = []) =>
engine.transaction(async tx => { await declarePersistenceProtocol(tx); await tx.executeRaw(sql, params); });
+// The consumer started by put keeps running its effects. Rewriting effect rows
+// while one is in flight lets its completion overwrite the rewrite (a requeued
+// embedding effect read back as committed), so settle the source first.
+const settleEffects = (engine: BrainEngine) => waitFor(async () => (await engine.executeRaw(
+ "SELECT 1 FROM persistence_effects e JOIN persistence_requests r ON r.id=e.request_id WHERE r.source_id='default' AND e.state IN ('queued','running')")).length === 0,
+ { label: `${engine.kind}: default source effects settled` });
const registry = () => { const dir = join(configDir(), 'persistence', 'managed-roots'); return existsSync(dir) ? readdirSync(dir).map(f => join(dir, f)) : []; };
const brainRow = async (engine: BrainEngine) => (await engine.executeRaw<{ brain_id: string; enabled: boolean; mode_epoch: string }>(
'SELECT brain_id, enabled, mode_epoch::text FROM persistence_brain WHERE singleton=1'))[0];
@@ -41,6 +48,7 @@ const brainRow = async (engine: BrainEngine) => (await engine.executeRaw<{ brain
for (const databaseUrl of process.env.DATABASE_URL ? [undefined, process.env.DATABASE_URL] : [undefined]) describe(`#5455 sources writer deactivate (${databaseUrl ? 'postgres' : 'pglite'})`, () => {
test('dry run lists every blocker and changes nothing; each blocker refuses with its exit', () => managedBrain(async ({ engine, ctx }) => {
await put(ctx, 'notes/one', 'Body.');
+ await settleEffects(engine);
const [request] = await engine.executeRaw<{ request_id: string; id: string }>("SELECT request_id::text, id::text FROM persistence_requests WHERE slug='notes/one'");
await protocol(engine, "UPDATE persistence_effects SET state='committed'");
await protocol(engine, "UPDATE persistence_effects SET state='queued', next_attempt_at=now()+interval '1 day' WHERE request_id=$1::uuid AND kind='embedding'", [request.id]);
@@ -78,6 +86,7 @@ for (const databaseUrl of process.env.DATABASE_URL ? [undefined, process.env.DAT
test('success: classic mode, retired worktrees keep receipts, markers from the real activation are removed, content unchanged; rerun is a no-op', () => managedBrain(async ({ engine, ctx, root }) => {
await put(ctx, 'notes/one', 'Body one.');
+ await settleEffects(engine);
await protocol(engine, "UPDATE persistence_effects SET state='committed'");
const file = readFileSync(join(root, 'notes', 'one.md'), 'utf8');
const page = await engine.getPage('notes/one', { sourceId: 'default' });
diff --git a/test/yaml-1-2-frontmatter.test.ts b/test/yaml-1-2-frontmatter.test.ts
index 9422b2ed76..5cfb1b1345 100644
--- a/test/yaml-1-2-frontmatter.test.ts
+++ b/test/yaml-1-2-frontmatter.test.ts
@@ -50,6 +50,12 @@ describe('frontmatter writes round-trip', () => {
}
});
+ test('an undefined field is refused, not dropped (js-yaml 4 would skip it)', () => {
+ expect(() => stringifyDataFrontmatter('body\n', { title: 't', lesson: undefined })).toThrow(/"lesson" is undefined/);
+ expect(() => stringifyDataFrontmatter('body\n', { tags: ['a', undefined] })).toThrow(/is undefined/);
+ expect(() => stringifyDataFrontmatter('body\n', { nested: { x: undefined } })).toThrow(/"x" is undefined/);
+ });
+
test('dump never emits a value that load reads back as a different type', () => {
for (const value of risky) expect(load(dump({ value }))).toEqual({ value });
});