Garry's Opinionated OpenClaw/Hermes Agent Brain
TypeScript
fix(takes): fail closed when takes-write source resolution errors (#2698 follow-up) (#2973)
Masa354c8c36a98a
diff --git a/src/commands/takes.ts b/src/commands/takes.tsindex 5dd24911e4..4cad6b7a7b 100644--- a/src/commands/takes.ts+++ b/src/commands/takes.ts@@ -101,12 +101,18 @@ async function getPageId(engine: BrainEngine, slug: string, sourceId?: string):return rows[0].id;}-async function resolveTakesSourceId(engine: BrainEngine): Promise<string | undefined> {- try {- return await resolveSourceId(engine, null);- } catch {- return undefined;- }+// Fail-closed (#2698 residual, TODOS.md): `resolveSourceId` only ever+// throws when a source WAS explicitly in play — an invalid or+// unregistered `GBRAIN_SOURCE`, a `.gbrain-source` dotfile pointing at a+// source that doesn't exist, or a genuine DB error — never for "nothing+// configured" (that path resolves cleanly to the seeded `'default'`+// source, tier 6 of resolveSourceId). Swallowing those errors here used+// to fall back to the unscoped slug-only page lookup, silently+// reintroducing the pre-#2698 cross-source write bug whenever resolution+// merely errored instead of resolving cleanly. Let it propagate so the+// write is blocked instead of silently unscoped.+async function resolveTakesSourceId(engine: BrainEngine): Promise<string> {+ return resolveSourceId(engine, null);}function readBodyOrEmpty(path: string): string {diff --git a/test/takes-command-source-scope.test.ts b/test/takes-command-source-scope.test.tsindex 9c88d54f49..3c970be084 100644--- a/test/takes-command-source-scope.test.ts+++ b/test/takes-command-source-scope.test.ts@@ -14,14 +14,29 @@ afterEach(() => {}});-function makeEngine() {+function makeEngine(opts: { knownSources?: string[] } = {}) {const added: TakeBatchInput[][] = [];const pageLookups: unknown[][] = [];const engine = {getConfig: async () => null,executeRaw: async (sql: string, params: unknown[] = []) => {if (sql.includes('FROM sources WHERE id = $1')) {- return [{ id: params[0] as string }];+ // Default (no `knownSources` override): every id "exists", matching+ // the original test's assumption. When `knownSources` is passed,+ // only ids in that list resolve — used to simulate a source that+ // was explicitly requested (via GBRAIN_SOURCE) but isn't registered.+ if (!opts.knownSources) return [{ id: params[0] as string }];+ return opts.knownSources.includes(params[0] as string) ? [{ id: params[0] as string }] : [];+ }+ if (sql.includes('FROM sources WHERE local_path IS NOT NULL AND id != ')) {+ // resolveSourceId tier 5.5 (sole-non-default-source). No registered+ // sources with a local_path in these tests.+ return [];+ }+ if (sql.includes('FROM sources WHERE local_path IS NOT NULL')) {+ // resolveSourceId tier 4 (registered source whose local_path+ // contains CWD). No registered sources in these tests.+ return [];}if (sql.includes('FROM pages WHERE slug = $1 AND source_id = $2')) {pageLookups.push(params);@@ -73,4 +88,66 @@ describe('gbrain takes CLI source scoping', () => {expect(existsSync(written)).toBe(true);expect(readFileSync(written, 'utf-8')).toContain('Dept-scoped claim');});++ test('add with no source configuration at all still resolves cleanly (no regression)', async () => {+ const brainDir = mkdtempSync(join(tmpdir(), 'gbrain-takes-source-'));+ const home = mkdtempSync(join(tmpdir(), 'gbrain-takes-home-'));+ tmpRoots.push(brainDir, home);+ const { engine, added, pageLookups } = makeEngine();++ // No GBRAIN_SOURCE, no dotfile, no registered local_path match, no+ // sources.default config, no sole non-default source — resolveSourceId+ // falls through every tier to the seeded 'default' source (tier 6) and+ // never throws. `resolveTakesSourceId` must resolve, not error.+ await withEnv({ GBRAIN_SOURCE: undefined, GBRAIN_HOME: home }, async () => {+ await runTakes(engine, [+ 'add',+ 'shared/page',+ '--claim',+ 'Unscoped-default claim',+ '--kind',+ 'take',+ '--who',+ 'self',+ '--dir',+ brainDir,+ ]);+ });++ expect(pageLookups).toEqual([['shared/page', 'default']]);+ expect(added).toHaveLength(1);+ expect(added[0]![0]!.page_id).toBe(11);+ });++ test('add fails closed (blocks the write) when GBRAIN_SOURCE names a source that does not resolve (#2684 residual)', async () => {+ const brainDir = mkdtempSync(join(tmpdir(), 'gbrain-takes-source-'));+ const home = mkdtempSync(join(tmpdir(), 'gbrain-takes-home-'));+ tmpRoots.push(brainDir, home);+ // 'ghost' is a well-formed source id (passes SOURCE_ID_RE) but is not a+ // registered source — resolveSourceId's assertSourceExists throws.+ const { engine, added, pageLookups } = makeEngine({ knownSources: ['dept', 'default'] });++ await withEnv({ GBRAIN_SOURCE: 'ghost', GBRAIN_HOME: home }, async () => {+ await expect(+ runTakes(engine, [+ 'add',+ 'shared/page',+ '--claim',+ 'Should never land',+ '--kind',+ 'take',+ '--who',+ 'self',+ '--dir',+ brainDir,+ ]),+ ).rejects.toThrow(/Source "ghost" not found/);+ });++ // Fail-closed: the write must be blocked entirely, not silently+ // downgraded to an unscoped cross-source lookup.+ expect(pageLookups).toHaveLength(0);+ expect(added).toHaveLength(0);+ expect(existsSync(join(brainDir, 'shared/page.md'))).toBe(false);+ });});