Garry's Opinionated OpenClaw/Hermes Agent Brain
TypeScript
fix(security): bound YAML alias expansion at every js-yaml load site (S-47)
garrytan788f80bf300a
diff --git a/docs/architecture/key-files/files-and-sync-1.md b/docs/architecture/key-files/files-and-sync-1.mdindex 7bb25c0ca0..f4a9813c81 100644--- a/docs/architecture/key-files/files-and-sync-1.md+++ b/docs/architecture/key-files/files-and-sync-1.md@@ -11,7 +11,7 @@ Current behavior and load-bearing invariants; history belongs in Git and CHANGEL- `src/core/content-sanity.ts` — pure assessor for the content-sanity defense. `assessContent(content, opts): SanityVerdict` returns one of `ok | warn_oversize | hard_block_junk_pattern | soft_block_oversize` with `{reason, bytes, matched_pattern_name?}`. Six built-in junk patterns (Cloudflare challenge dumps, CAPTCHAs, 403 dumps, bare error-page titles) compiled at module load; operator literal substrings via `loadOperatorLiterals()` from `src/core/content-sanity-literals.ts`. `ContentSanityBlockError` tagged class is the typed throw shape every wrapper site (`gbrain import`, `put_page` MCP op, `gbrain sync`, `/ingest` webhook) catches via the existing exception flow. The bytes-parity contract pins `Buffer.byteLength(content, 'utf8')` against the embedder's actual byte count so a 499K-byte page can't be soft-blocked on assessment then overflow on embed. Knob resolution chain env > file (`~/.gbrain/config.json`) > DB > defaults. Four knobs: `content_sanity.bytes_warn` (50_000), `content_sanity.bytes_block` (500_000), `content_sanity.junk_patterns_enabled` (true), `content_sanity.disabled` (false; `GBRAIN_NO_SANITY=1` is the loud-stderr kill-switch). `assessContentSanity(opts): SanityAssessment` returns the three-tier disposition (`shouldQuarantine` / `shouldFlag` + reason/detail) consumed by `importFromContent` and `gbrain quarantine scan`; adds the fuzzy prose-vs-markup ratio pass (markup chars / total above `max_markup_ratio`; code pages exempt; gated by `prose_check_enabled`) on top of the byte + junk-pattern passes. Three more knobs: `content_sanity.junk_disposition` (`quarantine` default | `reject`; no env override — a destructive flip belongs in explicit config), `content_sanity.max_markup_ratio` (0.85, env `GBRAIN_MAX_MARKUP_RATIO`, clamped `(0,1]`), `content_sanity.prose_check_enabled` (true). Pinned by `test/content-sanity.test.ts`. Per-pattern opt-out without the kill-switch: `content_sanity.disabled_patterns` names built-in junk patterns to skip (a JSON array `["access_denied"]` or a comma list `access_denied,error_title`; malformed JSON falls back to the comma parse so a hand-typed value still lands) — the file plane takes the array, the DB plane the string.-- `src/core/data-frontmatter.ts` — shared data-only YAML/JSON parsing and serialization. Rejects unsupported language selectors before parsing, uses js-yaml safe schema (exported `FRONTMATTER_SCHEMA`) with existing scalar types (a calendar-invalid timestamp such as `2024-02-30` stays a string instead of rolling over to March 1), sanitizes parser errors, and keeps body text opaque. Used by markdown, capture, recipes, plugins, and greenfield ingestion. Independent fixtures: `test/data-frontmatter.test.ts`, `test/frontmatter-security.test.ts`.+- `src/core/data-frontmatter.ts` — shared data-only YAML/JSON parsing and serialization. Rejects unsupported language selectors before parsing, uses js-yaml safe schema (exported `FRONTMATTER_SCHEMA`) with existing scalar types (a calendar-invalid timestamp such as `2024-02-30` stays a string instead of rolling over to March 1), sanitizes parser errors, and keeps body text opaque. `loadBoundedYaml` is the only js-yaml `load` call for content gbrain did not write (frontmatter, recovery, brain-writer, skill and rename-identity readers): after load it sizes the value as if every alias were copied out, memoized and cycle-safe, and throws `YamlAliasBoundError` (js-yaml-shaped `reason` and `mark` at the first alias) past text length + `MAX_YAML_ALIAS_EXPANSION` (65,536), so an alias bomb is a YAML_PARSE / `invalid_frontmatter` refusal before anything serializes it. Used by markdown, capture, recipes, plugins, and greenfield ingestion. Independent fixtures: `test/data-frontmatter.test.ts`, `test/frontmatter-security.test.ts`, `test/pathological/s-47-yaml-alias-bomb.test.ts`.- `src/core/default-source-path-check.ts` — pure `assessDefaultSourcePath(input)` verdict for the `default_source_local_path` doctor check (no DB/FS access — caller supplies gathered inputs, the npm-squat-check.ts shape). INVARIANT: `default.local_path: null` is the DESIGNED fallback topology (write-through nests under `sync.repo_path`), NOT an error — the check warns ONLY when the null pointer provably breaks something: the fallback repo is another source's own working tree (the leak-guard collision: every unscoped default write-through silently skipped), or default has file-backed pages and no resolvable root. Everything else (no pages, resolvable fallback, deliberate DB-only brain) is ok. The repair it names is the non-destructive `gbrain sources set-path default <path>`.diff --git a/src/core/brain-writer.ts b/src/core/brain-writer.tsindex 2825b421eb..593cc9c1ab 100644--- a/src/core/brain-writer.ts+++ b/src/core/brain-writer.ts@@ -18,7 +18,7 @@ import { assertManagedFilesystemWrite } from './persistence/filesystem-guard.ts'*/import { createHash } from 'crypto';-import { load as yamlLoad } from 'js-yaml';+import { loadBoundedYaml as yamlLoad } from './data-frontmatter.ts';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';diff --git a/src/core/data-frontmatter.ts b/src/core/data-frontmatter.tsindex 6e661f2092..3ed47b70b5 100644--- a/src/core/data-frontmatter.ts+++ b/src/core/data-frontmatter.ts@@ -1,4 +1,4 @@-import { load, dump, Type, DEFAULT_SCHEMA } from 'js-yaml';+import { load, dump, Type, DEFAULT_SCHEMA, type Schema } from 'js-yaml';import { NAIVE_DATETIME } from './effective-date.ts';// js-yaml's timestamp type builds `2024-02-30` as March 1 (Date.UTC rolls the@@ -29,6 +29,57 @@ const calendarTimestamp = new Type('tag:yaml.org,2002:timestamp', {});export const FRONTMATTER_SCHEMA = DEFAULT_SCHEMA.extend({ implicit: [calendarTimestamp] });+/**+ * Most characters a YAML document's aliases may add once expanded. js-yaml+ * keeps an alias as a reference to its anchor, so a few hundred bytes of nested+ * anchors (`&a2 [*a1, *a1, ...]`) load instantly and expand exponentially the+ * first time anything serializes or walks the value. Without aliases the+ * expanded size never exceeds the text, so the bound is the text length plus+ * this; real frontmatter that uses anchors at all adds a few hundred.+ */+export const MAX_YAML_ALIAS_EXPANSION = 65_536;++/** Shaped like js-yaml's own error (`reason`, `mark`) so every caller's location handling reads it unchanged. */+export class YamlAliasBoundError extends Error {+ readonly reason = 'yaml aliases expand past the frontmatter size limit';+ constructor(readonly mark: { line: number; column: number }) {+ super('YAML aliases expand past the frontmatter size limit');+ this.name = 'YamlAliasBoundError';+ }+}++/**+ * The one js-yaml entry point for content gbrain did not write. Loads, then+ * measures the value as if every alias were copied out (strings by length,+ * keys by length, other nodes as one; shared nodes memoized, a cycle infinite)+ * and throws YamlAliasBoundError past the bound, before any caller can walk it.+ */+export function loadBoundedYaml(text: string, opts: { schema?: Schema } = {}): unknown {+ const value = load(text, opts);+ const limit = text.length + MAX_YAML_ALIAS_EXPANSION;+ const sizes = new Map<object, number>();+ const size = (node: unknown): number => {+ if (typeof node === 'string') return node.length;+ if (node === null || typeof node !== 'object') return 1;+ if (ArrayBuffer.isView(node)) return node.byteLength;+ const known = sizes.get(node);+ if (known !== undefined) return known;+ sizes.set(node, Infinity);+ let total = 1;+ if (Array.isArray(node)) for (const child of node) { total += size(child); if (total > limit) break; }+ else for (const [key, child] of Object.entries(node)) { total += key.length + size(child); if (total > limit) break; }+ sizes.set(node, total);+ return total;+ };+ if (size(value) <= limit) return value;+ const lines = text.split('\n');+ const line = Math.max(0, lines.findIndex(row => ALIAS_TOKEN.test(row.replace(QUOTED_SCALAR, ''))));+ const at = ALIAS_TOKEN.exec((lines[line] ?? '').replace(QUOTED_SCALAR, ''));+ throw new YamlAliasBoundError({ line, column: at ? at.index + at[0].indexOf('*') : 0 });+}+const ALIAS_TOKEN = /(?:^|[\s,[{])\*[^\s,[\]{}]/;+const QUOTED_SCALAR = /"(?:[^"\\]|\\.)*"|'(?:[^']|'')*'/g;+export interface DataFrontmatter {data: Record<string, unknown>;content: string;@@ -84,7 +135,7 @@ export function parseDataFrontmatter(input: string): DataFrontmatter {const { language, block } = fenced;let value: unknown;try {- value = block.trim() === '' ? {} : language === 'json' ? JSON.parse(block) : load(block, { schema: FRONTMATTER_SCHEMA });+ value = block.trim() === '' ? {} : language === 'json' ? JSON.parse(block) : loadBoundedYaml(block, { schema: FRONTMATTER_SCHEMA });} catch (error) {// Parser messages can contain the document itself. Report only location,// so request/job diagnostics never copy private frontmatter into logs.diff --git a/src/core/frontmatter-recovery.ts b/src/core/frontmatter-recovery.tsindex 8315510b93..c034ac7509 100644--- a/src/core/frontmatter-recovery.ts+++ b/src/core/frontmatter-recovery.ts@@ -15,8 +15,7 @@* rewritten, folded into or guessed; identity keys are never resolved from a* duplicate.*/-import { load } from 'js-yaml';-import { FRONTMATTER_SCHEMA } from './data-frontmatter.ts';+import { FRONTMATTER_SCHEMA, loadBoundedYaml as load } from './data-frontmatter.ts';/** Bump when a rule widens; older holds are re-screened. */export const RECOVERY_VERSION = 1;diff --git a/src/core/markdown.ts b/src/core/markdown.tsindex 821464ee5d..9c3b78eb80 100644--- a/src/core/markdown.ts+++ b/src/core/markdown.ts@@ -1,5 +1,4 @@-import { dataFrontmatter as matter, FrontmatterLanguageError } from './data-frontmatter.ts';-import { load as yamlLoad } from 'js-yaml';+import { dataFrontmatter as matter, FrontmatterLanguageError, loadBoundedYaml as yamlLoad } from './data-frontmatter.ts';import type { Page, PageType } from './types.ts';import { resolveSlugForPath, slugifyPath } from './sync.ts';import {diff --git a/src/core/shared-skills/manifest.ts b/src/core/shared-skills/manifest.tsindex 9802df37a1..9b8a922492 100644--- a/src/core/shared-skills/manifest.ts+++ b/src/core/shared-skills/manifest.ts@@ -1,6 +1,7 @@import { opError } from '../ops/contract.ts';import { sha256 } from '../persistence/digest.ts';-import { FAILSAFE_SCHEMA, load } from 'js-yaml';+import { FAILSAFE_SCHEMA } from 'js-yaml';+import { loadBoundedYaml as load } from '../data-frontmatter.ts';import { SHARED_SKILL_LIMITS, type SharedSkillFileInput, type SkillFileClass, type SkillMetadata, type StoredSkillFile } from './model.ts';export function skillName(value: unknown, field = 'name'): string {diff --git a/src/core/skill-catalog.ts b/src/core/skill-catalog.tsindex f0abb26987..27c4381a28 100644--- a/src/core/skill-catalog.ts+++ b/src/core/skill-catalog.ts@@ -38,7 +38,8 @@import { existsSync, readFileSync, realpathSync, statSync } from 'fs';import { basename, join, relative, resolve } from 'path';-import { FAILSAFE_SCHEMA, load } from 'js-yaml';+import { FAILSAFE_SCHEMA } from 'js-yaml';+import { loadBoundedYaml as load } from './data-frontmatter.ts';import {autoDetectSkillsDir,autoDetectSkillsDirReadOnly,diff --git a/src/core/skill-frontmatter.ts b/src/core/skill-frontmatter.tsindex b0e473967d..4c24fa34b6 100644--- a/src/core/skill-frontmatter.ts+++ b/src/core/skill-frontmatter.ts@@ -27,7 +27,8 @@* not a silent failure to exempt.*/-import { FAILSAFE_SCHEMA, load as yamlLoad } from 'js-yaml';+import { FAILSAFE_SCHEMA } from 'js-yaml';+import { loadBoundedYaml as yamlLoad } from './data-frontmatter.ts';// ---------------------------------------------------------------------------// Typesdiff --git a/src/core/sync-rename-identity.ts b/src/core/sync-rename-identity.tsindex 0882d6e0f2..4f572b5260 100644--- a/src/core/sync-rename-identity.ts+++ b/src/core/sync-rename-identity.ts@@ -30,7 +30,8 @@import { createHash } from 'node:crypto';import { lstatSync, openSync, readSync, closeSync } from 'node:fs';import { resolve, sep } from 'node:path';-import { JSON_SCHEMA, load as yamlLoad } from 'js-yaml';+import { JSON_SCHEMA } from 'js-yaml';+import { loadBoundedYaml as yamlLoad } from './data-frontmatter.ts';import type { BrainEngine } from './engine.ts';import { spawn } from './spawn.ts';import { gitChildEnv } from './git-env.ts';diff --git a/test/e2e/s-47-yaml-alias-bomb-postgres.test.ts b/test/e2e/s-47-yaml-alias-bomb-postgres.test.tsnew file mode 100644index 0000000000..34290fd215--- /dev/null+++ b/test/e2e/s-47-yaml-alias-bomb-postgres.test.ts@@ -0,0 +1,3 @@+import { registerPostgresTests } from '../helpers/test-backends.ts';++await registerPostgresTests(() => import('../pathological/s-47-yaml-alias-bomb.test.ts'));diff --git a/test/pathological/s-47-yaml-alias-bomb.test.ts b/test/pathological/s-47-yaml-alias-bomb.test.tsnew file mode 100644index 0000000000..e782e31f63--- /dev/null+++ b/test/pathological/s-47-yaml-alias-bomb.test.ts@@ -0,0 +1,163 @@+/**+ * S-47 (GBRA-133): a YAML alias bomb in frontmatter. js-yaml's `load` keeps an+ * alias as a reference to its anchor, so a few hundred bytes of nested+ * `&aN [*aN-1, ...]` anchors parse instantly and expand exponentially the+ * first time the value is serialized (stored as frontmatter JSON, hashed,+ * compared). Nine levels of nine references OOM-killed sync at 15.5 GB in+ * every arm.+ *+ * Protects: the frontmatter loader refuses an expansion past its bound right+ * after load, before anything walks the value. A remote (remote=true) put_page+ * or edit_page is refused invalid_frontmatter and stores nothing; classic and+ * managed sync hold the one file invalid_frontmatter and import its sibling.+ * A nine-level bomb is refused at parse time without being expanded.+ * Fails when: a load site that sees page content calls js-yaml's `load`+ * without the expansion bound (the six-level bomb below is stored as ~3.7 MB+ * of frontmatter JSON instead of refused).+ * Bomb sizes: six levels (~530k nodes) end to end, so a regression fails here+ * instead of OOMing the runner; nine levels only at parse time, which never+ * serializes the value. PGLite always, Postgres when DATABASE_URL is set.+ */+import { describe, expect, test } from 'bun:test';+import { execFileSync } from 'node:child_process';+import { randomUUID } from 'node:crypto';+import { mkdirSync, mkdtempSync, rmSync, writeFileSync } from 'node:fs';+import { tmpdir } from 'node:os';+import { join } from 'node:path';+import type { BrainEngine } from '../../src/core/engine.ts';+import { classifyImportHold, isFrontmatterHoldMessage, parseMarkdown } from '../../src/core/markdown.ts';+import { operations } from '../../src/core/operations.ts';+import { dispatchToolCall } from '../../src/mcp/dispatch.ts';+import { performSync } from '../../src/commands/sync.ts';+import { performManagedSync } from '../../src/core/persistence/sync-run.ts';+import { readGitSourceHolds } from '../../src/core/persistence/sync-holds.ts';+import { cpuMs } from '../helpers/cpu-time.ts';+import { isolatedSharedSkillsEngine } from '../helpers/shared-skills-engine.ts';+import { withEnv } from '../helpers/with-env.ts';+import { expectItemFailure, expectOthersUnchanged, expectUnitNotAborted, managedBrain, pathologicalArms, snapshotItems } from './harness.ts';++const op = (name: string) => operations.find(o => o.name === name)!;+const git = (root: string, ...args: string[]) => execFileSync('git', ['-C', root, ...args], { encoding: 'utf8' }).trim();++/** `levels` nested anchors, each a flow sequence of nine aliases to the one before: 9^levels leaves once expanded. */+function aliasBomb(levels: number): string {+ const lines = ['a0: &a0 [leaf]'];+ for (let i = 1; i <= levels; i++) lines.push(`a${i}: &a${i} [${Array(9).fill(`*a${i - 1}`).join(', ')}]`);+ return lines.join('\n');+}+const note = (title: string, extra = '') => `---\ntitle: ${title}\ntype: note\n${extra ? `${extra}\n` : ''}---\n# ${title}\n\nBody of ${title}.\n`;+const BOMB_6 = note('Bomb note', aliasBomb(6));++/** Largest stored frontmatter (characters of its JSON text) in a source: a regression stores megabytes here. */+async function largestFrontmatter(engine: BrainEngine, sourceId: string): Promise<number> {+ const [row] = await engine.executeRaw<{ n: number | null }>('SELECT max(length(frontmatter::text))::int AS n FROM pages WHERE source_id=$1', [sourceId]);+ return row?.n ?? 0;+}++/** Whether a live page row exists, without loading (and printing) a frontmatter a regression made megabytes long. */+async function stored(engine: BrainEngine, sourceId: string, slug: string): Promise<boolean> {+ return (await engine.executeRaw('SELECT 1 FROM pages WHERE source_id=$1 AND slug=$2 AND deleted_at IS NULL', [sourceId, slug])).length > 0;+}++const holdsOf = async (engine: BrainEngine, sourceId: string) =>+ ((await readGitSourceHolds(engine, { sourceIds: [sourceId] }))[0]?.holds ?? []).map(h => ({ path: h.path, code: h.code, reason: h.meta.reason, message: h.message }));++function commitFixture(root: string): void {+ git(root, 'init', '-q'); git(root, 'config', 'user.name', 'Example'); git(root, 'config', 'user.email', '[email protected]');+ mkdirSync(join(root, 'notes'), { recursive: true });+ writeFileSync(join(root, 'notes', 'good.md'), note('Good'));+ writeFileSync(join(root, 'notes', 'bomb.md'), BOMB_6);+ git(root, 'add', '-A'); git(root, 'commit', '-qm', 'fixture');+}++async function expectBombHeld(engine: BrainEngine, sourceId: string): Promise<void> {+ expect(await stored(engine, sourceId, 'notes/good')).toBe(true);+ expect(await stored(engine, sourceId, 'notes/bomb')).toBe(false);+ const hold = (await holdsOf(engine, sourceId)).find(h => h.path === 'notes/bomb.md');+ expectItemFailure(hold && { key: hold.path, code: hold.code }, { key: 'notes/bomb.md', code: 'invalid_frontmatter' });+ expect(hold!.reason).toBe('yaml_parse');+ expect(hold!.message).toMatch(/alias/);+ expect(await largestFrontmatter(engine, sourceId)).toBeLessThan(10_000);+}++describe('S-47 alias bomb at parse time (no engine)', () => {+ test('S-47 guard: a nine-level bomb is refused invalid_frontmatter naming the alias bound, without being expanded', () => {+ const content = note('Bomb note', aliasBomb(9));+ expect(content.length).toBeLessThan(700);+ let parsed!: ReturnType<typeof parseMarkdown>;+ expect(cpuMs(() => { parsed = parseMarkdown(content, 'notes/bomb.md', { validate: true }); })).toBeLessThan(1000);+ const hold = classifyImportHold(parsed);+ expect({ code: hold?.code, reason: hold?.reason }).toEqual({ code: 'invalid_frontmatter', reason: 'yaml_parse' });+ expect(hold!.message).toMatch(/alias/);+ expect(isFrontmatterHoldMessage(hold!.message)).toBe(true);+ });++ test('S-47 guard: ordinary anchors and merge keys stay readable', () => {+ const parsed = parseMarkdown(note('Anchors note', 'defaults: &d\n status: active\n owner: team-example\nfirst: *d\nsecond:\n <<: *d\n status: done'), 'notes/anchors.md', { validate: true });+ expect(classifyImportHold(parsed)).toBeNull();+ expect(parsed.frontmatter.first).toEqual({ status: 'active', owner: 'team-example' });+ expect(parsed.frontmatter.second).toEqual({ status: 'done', owner: 'team-example' });+ });+});++for (const { backend, databaseUrl } of pathologicalArms()) {+ describe(`S-47 alias bomb (${backend})`, () => {+ test('S-47 item: a remote put_page and edit_page carrying a six-level bomb are refused invalid_frontmatter and store nothing; a sibling lands', async () => {+ await managedBrain(async ({ engine, ctx }) => {+ await op('put_page').handler(ctx, { slug: 'notes/kept', content: note('Kept') });+ const remote = { remote: true as const, transport: 'http' as const, config: ctx.config, sourceId: 'default', logger: ctx.logger,+ auth: { token: 'fixture', clientId: 'fixture-client', scopes: ['read', 'write'], sourceId: 'default' } };+ const call = async (name: string, params: Record<string, unknown>) => {+ const response = await dispatchToolCall(engine, name, { request_id: randomUUID(), ...params }, remote);+ return { isError: response.isError === true, payload: JSON.parse((response.content[0] as { text: string }).text) as Record<string, any> };+ };+ const before = await snapshotItems(engine, 'default');+ const put = await call('put_page', { slug: 'notes/bomb', content: BOMB_6 });+ expect(put.isError).toBe(true);+ expectItemFailure({ key: 'notes/bomb', code: put.payload.code, fix: put.payload.fix }, { key: 'notes/bomb', code: 'invalid_frontmatter' });+ expect(put.payload).toMatchObject({ class: 'caller', reason: 'yaml_parse', retryable: false, message: expect.stringMatching(/alias/),+ suggestion: expect.any(String), fix: { next: expect.any(String), why: expect.any(String) } });+ expect(await stored(engine, 'default', 'notes/bomb')).toBe(false);++ const kept = (await engine.readPageSnapshot('notes/kept', { sourceId: 'default' }))!;+ const edit = await call('edit_page', { slug: 'notes/kept', expected_revision: kept.revision,+ edits: [{ old_text: 'type: note\n', new_text: `type: note\n${aliasBomb(6)}\n` }] });+ expect(edit.isError).toBe(true);+ expectItemFailure({ key: 'notes/kept', code: edit.payload.code }, { key: 'notes/kept', code: 'invalid_frontmatter' });+ expect(edit.payload.message).toMatch(/alias/);++ const sibling = await call('put_page', { slug: 'notes/sibling', content: note('Sibling') });+ expect({ isError: sibling.isError, state: sibling.payload.state }).toEqual({ isError: false, state: 'committed' });+ expectOthersUnchanged(before, await snapshotItems(engine, 'default'), { changed: ['notes/sibling'], expectProgress: ['notes/sibling'] });+ expect(await largestFrontmatter(engine, 'default')).toBeLessThan(10_000);+ }, { databaseUrl });+ }, 120_000);++ test('S-47 item: classic sync holds the bomb file invalid_frontmatter and imports its sibling', async () => {+ const home = mkdtempSync(join(tmpdir(), 'gbrain-s47-'));+ const root = join(home, 'repo');+ try {+ await withEnv({ GBRAIN_HOME: home, GBRAIN_SYNC_FAILURES_DIR: home }, async () => {+ const { engine, close } = await isolatedSharedSkillsEngine(databaseUrl);+ try {+ await engine.executeRaw('UPDATE persistence_brain SET enabled=false WHERE singleton=1');+ mkdirSync(root);+ commitFixture(root);+ const sourceId = `s47${randomUUID().replace(/-/g, '').slice(0, 12)}`;+ await engine.executeRaw("INSERT INTO sources(id,name,local_path,config) VALUES($1,$1,$2,'{}')", [sourceId, root]);+ // concurrency 1: parallel import workers would connect to the configured database, not this isolated one.+ await expectUnitNotAborted(() => performSync(engine, { repoPath: root, sourceId, noPull: true, noEmbed: true, noExtract: true, concurrency: 1 }));+ await expectBombHeld(engine, sourceId);+ } finally { await close(); }+ });+ } finally { rmSync(home, { recursive: true, force: true }); }+ }, 120_000);++ test('S-47 item: managed sync holds the bomb file invalid_frontmatter and imports its sibling', async () => {+ await managedBrain(async ({ engine }) => {+ await expectUnitNotAborted(() => performManagedSync(engine, { sourceId: 'default', noPull: true, noEmbed: true, noExtract: true }));+ await expectBombHeld(engine, 'default');+ }, { databaseUrl, setup: ({ root }) => commitFixture(root) });+ }, 120_000);+ });+}