Skip to content

Garry's Opinionated OpenClaw/Hermes Agent Brain

TypeScript

fix(frontmatter): ignore multimodal image assets (#4515)

zsimovanforgeopsbad77b18af63
diff --git a/src/commands/frontmatter.ts b/src/commands/frontmatter.ts
index 3e8e93d2a6..c3416cd49f 100644
--- a/src/commands/frontmatter.ts
+++ b/src/commands/frontmatter.ts
@@ -25,13 +25,14 @@ import { parseMarkdown, type ParseValidationCode } from '../core/markdown.ts';
import {
autoFixFrontmatter,
createFrontmatterBackup,
+ isFrontmatterScannablePath,
makeFrontmatterBackupRunId,
scanBrainSources,
type AuditReport,
type AuditFix,
} from '../core/brain-writer.ts';
import { collectGitVisibleFiles } from '../core/git-visible-files.ts';
-import { isSyncable, pruneDir, slugifyPath } from '../core/sync.ts';
+import { isMarkdownFilePath, pruneDir, slugifyPath } from '../core/sync.ts';
export async function runFrontmatter(args: string[]): Promise<void> {
const sub = args[0];
@@ -197,6 +198,11 @@ async function runValidate(rest: string[]): Promise<void> {
setCliExitVerdict(1);
return;
}
+ if (lstatSync(resolved).isFile() && !isMarkdownFilePath(resolved)) {
+ console.error(`error: frontmatter validation supports only .md and .mdx files: ${target}`);
+ setCliExitVerdict(1);
+ return;
+ }
const brainRoot = findBrainRoot(resolved);
const files = collectFiles(resolved);
@@ -296,10 +302,12 @@ export function collectFiles(
): string[] {
const st = lstatSync(target);
if (st.isFile()) {
- return [target];
+ // An explicit Markdown target is operator intent, even for structural
+ // basenames that bulk scans intentionally skip.
+ return isMarkdownFilePath(basename(target)) ? [target] : [];
}
- const gitFiles = collectGitVisibleFiles(target, (rel) => isSyncable(rel, { strategy: 'markdown' }));
+ const gitFiles = collectGitVisibleFiles(target, isFrontmatterScannablePath);
if (gitFiles) {
if (visitDir) visitDir(target);
return gitFiles;
@@ -333,7 +341,7 @@ export function collectFiles(
stack.push(full);
} else if (entryStat.isFile()) {
const rel = relative(target, full);
- if (isSyncable(rel, { strategy: 'markdown' })) {
+ if (isFrontmatterScannablePath(rel)) {
out.push(full);
}
}
@@ -422,6 +430,11 @@ async function runGenerate(args: string[]): Promise<void> {
const rootPath = resolve(targetPath);
const isDir = statSync(rootPath).isDirectory();
+ if (!isDir && !isMarkdownFilePath(rootPath)) {
+ console.error(`error: frontmatter generation supports only .md and .mdx files: ${targetPath}`);
+ setCliExitVerdict(1);
+ return;
+ }
// Find the brain root — walk up from targetPath looking for .git or known brain markers.
// Inference rules match against brain-root-relative paths (e.g., "people/alice.md").
@@ -459,7 +472,7 @@ async function runGenerate(args: string[]): Promise<void> {
function processFile(absPath: string, relPath: string) {
scanned++;
- if (!isSyncable(relPath, { strategy: 'markdown' })) return;
+ if (!isFrontmatterScannablePath(relPath)) return;
// Skip symlinks
try { if (lstatSync(absPath).isSymbolicLink()) return; } catch { return; }
diff --git a/src/core/brain-writer.ts b/src/core/brain-writer.ts
index 3819b10396..58441c9ed4 100644
--- a/src/core/brain-writer.ts
+++ b/src/core/brain-writer.ts
@@ -28,10 +28,15 @@ import {
type ParseValidationCode,
type ParseValidationError,
} from './markdown.ts';
-import { isSyncable, pruneDir, slugifyPath } from './sync.ts';
+import { isMarkdownFilePath, isSyncable, pruneDir, slugifyPath } from './sync.ts';
export type { ParseValidationCode };
+/** Frontmatter validation is defined only for Markdown page files. */
+export function isFrontmatterScannablePath(path: string): boolean {
+ return isMarkdownFilePath(path) && isSyncable(path, { strategy: 'markdown' });
+}
+
export interface AuditFix {
code: ParseValidationCode;
description: string;
@@ -622,7 +627,10 @@ function scanOneSource(
// visitDir is consulted from walkDir directly (passed below). The
// per-file visit closure doesn't need it.
const relPath = relative(rootResolved, absPath);
- if (!isSyncable(relPath, { strategy: 'markdown' })) return true;
+ // Frontmatter is a Markdown-only contract. Multimodal sync deliberately
+ // admits images under the markdown strategy, but parsing JPEG/PNG bytes as
+ // UTF-8 turns ordinary binary NULs into false NULL_BYTES findings.
+ if (!isFrontmatterScannablePath(relPath)) return true;
scanned++;
let content: string;
try {
diff --git a/test/brain-writer-walk-prune.test.ts b/test/brain-writer-walk-prune.test.ts
index 59555fdf50..1d6e89bf88 100644
--- a/test/brain-writer-walk-prune.test.ts
+++ b/test/brain-writer-walk-prune.test.ts
@@ -24,6 +24,7 @@ import { join, sep } from 'path';
import { tmpdir } from 'os';
import { scanBrainSources, walkDir } from '../src/core/brain-writer.ts';
import { collectFiles } from '../src/commands/frontmatter.ts';
+import { withEnv } from './helpers/with-env.ts';
/**
* Build a separator-prefixed path fragment for suffix/substring predicates.
@@ -43,6 +44,8 @@ beforeAll(() => {
writeFileSync(join(root, 'people', 'alice.md'), '---\ntitle: Alice\n---\n\nbody\n');
mkdirSync(join(root, 'concepts', 'subdir'), { recursive: true });
writeFileSync(join(root, 'concepts', 'subdir', 'thing.md'), '---\ntitle: Thing\n---\n\nbody\n');
+ writeFileSync(join(root, 'index.md'), '---\ntitle: Structural index\n---\n\nbody\n');
+ writeFileSync(join(root, 'photo.jpg'), Buffer.from([0xff, 0xd8, 0xff, 0x00, 0x01, 0xd9]));
// Vendor / hidden / generated trees — walker MUST NOT descend.
mkdirSync(join(root, 'node_modules', 'fake-pkg'), { recursive: true });
writeFileSync(join(root, 'node_modules', 'fake-pkg', 'README.md'), '# Should not be visited\n');
@@ -169,10 +172,30 @@ describe('collectFiles (frontmatter.ts) — descent-time pruning parity', () =>
const files = collectFiles(target);
expect(files).toEqual([target]);
});
+
+ test('explicit structural Markdown target remains valid operator intent', () => {
+ const target = join(root, 'index.md');
+ expect(collectFiles(target)).toEqual([target]);
+ });
+
+ test('multimodal mode does not admit image assets for directory validation', async () => {
+ await withEnv({ GBRAIN_EMBEDDING_MULTIMODAL: 'true' }, async () => {
+ const files = collectFiles(root);
+ expect(files.some(f => f.endsWith(seg('photo.jpg')))).toBe(false);
+ expect(files.some(f => f.endsWith(seg('people', 'alice.md')))).toBe(true);
+ });
+ });
+
+ test('single-file validation refuses a non-Markdown target in multimodal mode', async () => {
+ const target = join(root, 'photo.jpg');
+ await withEnv({ GBRAIN_EMBEDDING_MULTIMODAL: 'true' }, async () => {
+ expect(collectFiles(target)).toEqual([]);
+ });
+ });
});
describe('frontmatter walkers — git-visible file parity', () => {
- test('collectFiles respects .git/info/exclude like sync/import', () => {
+ test('collectFiles respects .git/info/exclude like sync/import', async () => {
const repo = mkdtempSync(join(tmpdir(), 'frontmatter-git-visible-'));
try {
execFileSync('git', ['init'], { cwd: repo, stdio: 'ignore' });
@@ -181,10 +204,14 @@ describe('frontmatter walkers — git-visible file parity', () => {
writeFileSync(join(repo, '.git', 'info', 'exclude'), 'local-skills/\n');
writeFileSync(join(repo, 'people', 'alice.md'), '---\ntitle: Alice\n---\n\nbody\n');
writeFileSync(join(repo, 'local-skills', 'SKILL.md'), '---\nname: bad\n# malformed frontmatter\n');
-
- const files = collectFiles(repo).map((f) => f.replace(repo + sep, ''));
- expect(files).toContain(join('people', 'alice.md'));
- expect(files).not.toContain(join('local-skills', 'SKILL.md'));
+ writeFileSync(join(repo, 'photo.jpg'), Buffer.from([0xff, 0xd8, 0xff, 0x00, 0x01, 0xd9]));
+
+ await withEnv({ GBRAIN_EMBEDDING_MULTIMODAL: 'true' }, async () => {
+ const files = collectFiles(repo).map((f) => f.replace(repo + sep, ''));
+ expect(files).toContain(join('people', 'alice.md'));
+ expect(files).not.toContain(join('local-skills', 'SKILL.md'));
+ expect(files).not.toContain('photo.jpg');
+ });
} finally {
rmSync(repo, { recursive: true, force: true });
}
diff --git a/test/brain-writer.test.ts b/test/brain-writer.test.ts
index 733100f63a..d4a58dbd63 100644
--- a/test/brain-writer.test.ts
+++ b/test/brain-writer.test.ts
@@ -10,6 +10,7 @@ import {
} from '../src/core/brain-writer.ts';
import { PGLiteEngine } from '../src/core/pglite-engine.ts';
import { resetPgliteState } from './helpers/reset-pglite.ts';
+import { withEnv } from './helpers/with-env.ts';
const fence = '---';
@@ -234,7 +235,7 @@ describe('scanBrainSources (PGLite)', () => {
let engine: PGLiteEngine;
// One PGLite per file — beforeEach wipes data only. PGLite cold-start is
- // ~20s on CI; sharing one engine across 6 tests in this block saves ~2 min.
+ // ~20s on CI; sharing one engine across 7 tests in this block saves ~2 min.
beforeAll(async () => {
engine = new PGLiteEngine();
await engine.connect({});
@@ -330,6 +331,20 @@ describe('scanBrainSources (PGLite)', () => {
expect(report.per_source[0]!.total).toBe(0);
});
+ test('does not parse multimodal image assets as Markdown frontmatter', async () => {
+ writeFileSync(join(tmp, 'good.md'), `${fence}\ntype: concept\ntitle: ok\n${fence}\n\nbody`);
+ writeFileSync(join(tmp, 'photo.jpg'), Buffer.from([0xff, 0xd8, 0xff, 0x00, 0x01, 0xd9]));
+ await registerSource('multimodal', tmp);
+
+ await withEnv({ GBRAIN_EMBEDDING_MULTIMODAL: 'true' }, async () => {
+ const report = await scanBrainSources(engine);
+ const source = report.per_source.find(s => s.source_id === 'multimodal')!;
+ expect(source.total).toBe(0);
+ expect(source.errors_by_code.NULL_BYTES).toBeUndefined();
+ expect(source.files_scanned).toBe(1);
+ });
+ });
+
test('AbortSignal before scan: every source marked skipped (v0.38.2.0 partial-state contract)', async () => {
const src = join(tmp, 'big');
mkdirSync(src, { recursive: true });