Garry's Opinionated OpenClaw/Hermes Agent Brain
TypeScript
fix(cli): --source is provenance, not scope, for ops that own a source param, on every route (#5087)
time-attack4f0ffd1a1c73
diff --git a/docs/architecture/brains-and-sources.md b/docs/architecture/brains-and-sources.mdindex 07abd6890e..5c4bbf1066 100644--- a/docs/architecture/brains-and-sources.md+++ b/docs/architecture/brains-and-sources.md@@ -41,6 +41,14 @@ AND under `source=gstack` — they're different pages.Routing: `--source <id>`, `GBRAIN_SOURCE`, `.gbrain-source` dotfile, orregistered `local_path` match in the `sources` table.+A few commands have their own `--source` option for provenance:+`timeline-add`, `ontology-add`, `takes add|update|supersede` and the raw-data+operations. On those, `--source` is the provenance value (a slug, URL or+source name) and never picks the repo, on a local brain, through a running+`gbrain serve` or on a thin client. The write goes to the source that+`GBRAIN_SOURCE`, `.gbrain-source` or the defaults select, and the JSON result+names it in `source_id`.+### When does each axis move?| You want to | Adjust |diff --git a/src/cli.ts b/src/cli.tsindex 2a8c82527a..b03a4ea3e4 100755--- a/src/cli.ts+++ b/src/cli.ts@@ -42,7 +42,7 @@ import { printCuratedHelp } from './cli/help/render.ts';import { curatedFlagError } from './cli/help/validate.ts';import { cliCommandOf, exitCliError, exitOnRepairFailed, unknownFlagError, usageError, writeCliError, writeCliNotice, writeFatalCliError } from './cli/cli-error.ts';import type { Notice } from './core/agent-output.ts';-import { opError } from './core/ops/contract.ts';+import { opError, opOwnsSource } from './core/ops/contract.ts';import { opParamValue } from './cli/op-param-values.ts';import { serializeMarkdown } from './core/markdown.ts';import { parseGlobalFlags, setCliOptions, getCliOptions } from './core/cli-options.ts';@@ -650,7 +650,7 @@ async function runSharedOperation(command: string, subArgs: string[], cliOpts: Clet ctx: Awaited<ReturnType<typeof makeContext>>;try {ctx = await withTimeout(- makeContext(engine, params),+ makeContext(engine, params, op),wallclockMs,`gbrain ${command}: context`,);@@ -1205,7 +1205,7 @@ export function applyThinClientSourceScope(params: Record<string, unknown>,cwd?: string,): AmbientSourceBinding | null {- if ('source' in op.params) return null; // the op owns --source; not a scope flag+ if (opOwnsSource(op)) return null;assertSingleSourceScopeFlag(op, params);const explicit = typeof params.source === 'string' && params.source.length > 0? (params.source as string)@@ -1409,7 +1409,7 @@ export const __testing = {main,};-export async function makeContext(engine: BrainEngine, params: Record<string, unknown>): Promise<OperationContext> {+export async function makeContext(engine: BrainEngine, params: Record<string, unknown>, op?: Pick<Operation, 'params'>): Promise<OperationContext> {// v0.31.8 (D11): resolve sourceId via the canonical 6-tier chain. Honors// --source / GBRAIN_SOURCE / .gbrain-source / path-match / brain default /// 'default'. Wrapped in try/catch so a doctor / single-source brain that@@ -1425,7 +1425,8 @@ export async function makeContext(engine: BrainEngine, params: Record<string, unlet sourceImplicit = true;// params.source is set when a CLI flag was parsed for the op (rare; most// CLI ops don't take --source). Falls through to env/dotfile/path-match.- const explicit = (params.source as string | undefined) ?? null;+ // An op that owns `source` (opOwnsSource) receives it as its own param.+ const explicit = op && opOwnsSource(op) ? null : (params.source as string | undefined) ?? null;const { resolveSourceWithTier, localFederatedSourceIds, SourceTargetError } = await import('./core/source-resolver.ts');try {const resolved = await resolveSourceWithTier(engine, explicit);diff --git a/src/cli/source-scope.ts b/src/cli/source-scope.tsindex 3fdfe38cb8..b0c2e31a8e 100644--- a/src/cli/source-scope.ts+++ b/src/cli/source-scope.ts@@ -5,6 +5,7 @@* scope param, and the ambient-narrowing hint for empty thin-client reads.*/import type { Operation } from '../core/operations.ts';+import { opOwnsSource } from '../core/ops/contract.ts';import { ignoredRemoteParams } from '../core/mcp-client.ts';/** Where an ambient (not flag-supplied) thin-client source scope came from. */@@ -16,7 +17,7 @@ export type AmbientSourceBinding = { sourceId: string; via: 'GBRAIN_SOURCE' | '.* Ops that own a `source` param are exempt: their --source is not scope.*/export function assertSingleSourceScopeFlag(op: Operation, params: Record<string, unknown>): void {- if ('source' in op.params) return;+ if (opOwnsSource(op)) return;const explicit = typeof params.source === 'string' && params.source.length > 0;if (explicit && (params.source_id !== undefined || params.all_sources === true)) {throw new Error('Pass either --source or --source-id/--all-sources, not both.');diff --git a/src/core/ops/contract.ts b/src/core/ops/contract.tsindex 45f440422e..9004da2462 100644--- a/src/core/ops/contract.ts+++ b/src/core/ops/contract.ts@@ -748,3 +748,13 @@ export interface Operation {hidden?: boolean;};}++/**+ * An op that declares its own `source` param (timeline-add, ontology-add,+ * takes add/update/supersede, raw data) takes `--source` as that param, e.g.+ * provenance. Every CLI route (direct, delegated to a resident serve, thin+ * client) then leaves it out of source scoping and passes it to the handler.+ */+export function opOwnsSource(op: Pick<Operation, 'params'>): boolean {+ return 'source' in op.params;+}diff --git a/src/core/persistence/local-client.ts b/src/core/persistence/local-client.tsindex e0c4b40c7c..1cb492dc5c 100644--- a/src/core/persistence/local-client.ts+++ b/src/core/persistence/local-client.ts@@ -8,7 +8,7 @@ import { getCliOptions } from '../cli-options.ts';import { loadMounts, type MountEntry } from '../brain-registry.ts';import { inspectLockHolder, type LockHolderInfo } from '../pglite-lock.ts';import { resolveSourceIdEngineFree } from '../source-resolver.ts';-import { opError, OperationError } from '../ops/contract.ts';+import { opError, opOwnsSource, OperationError } from '../ops/contract.ts';import { readFix, trustedCliRequired } from '../ops/op-fix.ts';import { parseWriteRequestId } from './preconditions.ts';import {@@ -104,6 +104,12 @@ export async function maybeDelegateLocalAdministration(* that answered), every failure is final here: never fall through after an* unavailable owner socket or a lost acknowledgment.*/+async function operationOwnsSource(operation: string): Promise<boolean> {+ const { operationsByName } = await import('../operations.ts');+ const op = operationsByName[operation];+ return op !== undefined && opOwnsSource(op);+}+export async function maybeDelegateLocalOperation(operation: string,params: Record<string, unknown>,@@ -123,8 +129,8 @@ export async function maybeDelegateLocalOperation(const socketPath = persistenceSocketPathForConfig(config);if (!socketPath) throw noDiscoveryPath('The selected PGLite owner has no persistence discovery path.', holder, brainId);- // Takes' source is claim provenance, independent of the CLI source routing axis.- const sourceInParams = options.source === undefined && !operation.startsWith('takes_');+ // An op that owns `source` (claim or timeline provenance) gets it on the wire, never as routing scope.+ const sourceInParams = options.source === undefined && !(await operationOwnsSource(operation));const explicit = options.source ?? (sourceInParams && typeof params.source === 'string' ? params.source : null);const source = resolveSourceIdEngineFree(explicit, cwd);const wireParams = { ...params };diff --git a/test/cli-op-owned-source.test.ts b/test/cli-op-owned-source.test.tsnew file mode 100644index 0000000000..af62c8d740--- /dev/null+++ b/test/cli-op-owned-source.test.ts@@ -0,0 +1,122 @@+/**+ * #5087: an op that owns a `source` param (timeline-add) takes `--source`+ * as provenance on every CLI route, never as the write's source scope.+ * Authoring gate: (1) protects the direct local route, the route delegated+ * to a resident serve, and the thin-client route; (2) fails when a+ * provenance URL is refused as an invalid source id, when a provenance+ * value that is also a source id redirects the write to that source, or+ * when the delegated route drops the provenance from the wire; (3) existing+ * source-scope tests cover only ops without their own `source` param;+ * (4) no production seam (the CLI runs as a real subprocess).+ */+import { afterAll, beforeAll, describe, expect, test } from 'bun:test';+import { once } from 'node:events';+import { mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from 'node:fs';+import { tmpdir } from 'node:os';+import { join } from 'node:path';+import { PGLiteEngine } from '../src/core/pglite-engine.ts';+import { acquireLock, releaseLock } from '../src/core/pglite-lock.ts';+import { maybeDelegateLocalOperation } from '../src/core/persistence/local-client.ts';+import { startPersistenceIpcServer, persistenceSocketPathForConfig, type PersistenceIpcRequest } from '../src/core/persistence/ipc.ts';+import { operations } from '../src/core/operations.ts';+import { applyThinClientSourceScope } from '../src/cli.ts';+import { withEnv } from './helpers/with-env.ts';++const CLI = join(import.meta.dir, '../src/cli.ts');+const BRAIN = '10000000-0000-4000-8000-000000000001';+const addTimelineEntry = operations.find(op => op.name === 'add_timeline_entry')!;++describe('timeline-add --source on the direct local route', () => {+ let dir: string;+ let config: { engine: 'pglite'; database_path: string };+ beforeAll(async () => {+ dir = mkdtempSync(join(tmpdir(), 'gbrain-op-source-'));+ config = { engine: 'pglite', database_path: join(dir, 'db') };+ const engine = new PGLiteEngine();+ await engine.connect(config);+ await engine.initSchema();+ await engine.putPage('concepts/probe', { type: 'concept', title: 'Probe', compiled_truth: 'Probe body.' });+ await engine.executeRaw("INSERT INTO sources (id, name) VALUES ('meetings', 'meetings') ON CONFLICT DO NOTHING");+ await engine.disconnect();+ mkdirSync(join(dir, '.gbrain'), { recursive: true });+ writeFileSync(join(dir, '.gbrain', 'config.json'), JSON.stringify({ ...config, embedding: { disabled: true } }));+ }, 120_000);+ afterAll(() => rmSync(dir, { recursive: true, force: true }));++ const cli = async (args: string[]) => {+ const env: Record<string, string | undefined> = { ...process.env, GBRAIN_HOME: dir, GBRAIN_NO_BANNER: '1', GBRAIN_BACKUP_CHECK: '0',+ GBRAIN_SKIP_UPGRADE_CHECK: '1', GBRAIN_SOURCE: undefined, GBRAIN_BRAIN_ID: undefined, DATABASE_URL: undefined, GBRAIN_DATABASE_URL: undefined };+ const child = Bun.spawn([process.execPath, CLI, ...args], { cwd: dir, env, stdout: 'pipe', stderr: 'pipe' });+ const [stdout, stderr, code] = await Promise.all([new Response(child.stdout).text(), new Response(child.stderr).text(), child.exited]);+ return { stdout, stderr, code };+ };+ const entries = async () => {+ const engine = new PGLiteEngine();+ await engine.connect(config);+ try {+ return await engine.executeRaw<{ source_id: string; source: string; summary: string }>(+ `SELECT p.source_id, t.source, t.summary FROM timeline_entries t JOIN pages p ON p.id = t.page_id+ WHERE p.slug = 'concepts/probe' ORDER BY t.summary`);+ } finally { await engine.disconnect(); }+ };++ test('a provenance URL is written as provenance on the ambient source', async () => {+ const run = await cli(['timeline-add', 'concepts/probe', '2026-09-14', 'probe url', '--source', 'https://example.com/notes/x', '--json']);+ expect({ code: run.code, stderr: run.stderr }).toMatchObject({ code: 0 });+ expect(JSON.parse(run.stdout)).toMatchObject({ source_id: 'default', entry: { source: 'https://example.com/notes/x' } });+ expect(await entries()).toContainEqual({ source_id: 'default', source: 'https://example.com/notes/x', summary: 'probe url' });+ }, 60_000);++ test('a provenance value that is also a source id does not redirect the write', async () => {+ const run = await cli(['timeline-add', 'concepts/probe', '2026-09-15', 'probe id', '--source', 'meetings', '--json']);+ expect({ code: run.code, stderr: run.stderr }).toMatchObject({ code: 0 });+ expect(JSON.parse(run.stdout)).toMatchObject({ source_id: 'default', entry: { source: 'meetings' } });+ expect(await entries()).toContainEqual({ source_id: 'default', source: 'meetings', summary: 'probe id' });+ }, 60_000);+});++describe('timeline-add --source delegated to a resident serve', () => {+ test('the provenance stays on the wire and the ambient source routes the write', async () => {+ const dir = mkdtempSync(join(tmpdir(), 'gbrain-op-source-ipc-'));+ const config = { engine: 'pglite' as const, database_path: join(dir, 'db') };+ mkdirSync(join(dir, '.gbrain', 'persistence'), { recursive: true });+ mkdirSync(config.database_path, { recursive: true });+ const lock = await acquireLock(config.database_path);+ const metadataPath = lock.lockPath ?? join(config.database_path, '.gbrain-lock', 'lock');+ writeFileSync(metadataPath, JSON.stringify({ ...JSON.parse(readFileSync(metadataPath, 'utf8')), subcommand: 'serve' }));+ writeFileSync(join(dir, '.gbrain', 'config.json'), JSON.stringify(config));+ writeFileSync(join(dir, '.gbrain', 'persistence', `${BRAIN}.cli.json`), JSON.stringify({ id: BRAIN, credential: 'a'.repeat(64), lane: 'cli' }), { mode: 0o600 });+ const calls: PersistenceIpcRequest[] = [];+ const binding = await startPersistenceIpcServer(persistenceSocketPathForConfig(config)!, {+ brainId: BRAIN,+ dispatch: async request => {+ calls.push(request);+ return { slug: request.params.slug, status: 'ok', write_request: { request_id: request.params.request_id, state: 'committed', retry_after_ms: null } };+ },+ });+ try {+ await withEnv({ GBRAIN_HOME: dir, GBRAIN_BRAIN_ID: 'host', GBRAIN_SOURCE: 'client-source', GBRAIN_DATABASE_URL: undefined, DATABASE_URL: undefined }, async () => {+ for (const provenance of ['https://example.com/notes/x', 'meetings']) {+ const delegated = await maybeDelegateLocalOperation('add_timeline_entry',+ { slug: 'concepts/probe', date: '2026-09-14', summary: 'probe', source: provenance }, config, { brain: 'host', cwd: dir });+ expect(delegated.handled).toBe(true);+ const call = calls.at(-1)!;+ expect(call.params.source).toBe(provenance);+ expect(call.routing.source).toBe('client-source');+ }+ });+ } finally {+ if (binding) { const closed = once(binding.server, 'close'); binding.close(); await closed; }+ await releaseLock(lock);+ rmSync(dir, { recursive: true, force: true });+ }+ }, 60_000);+});++describe('timeline-add --source on the thin-client route', () => {+ test('the provenance is sent as the op param and never becomes a scope', () => {+ const params: Record<string, unknown> = { slug: 'concepts/probe', date: '2026-09-14', summary: 'probe', source: 'meetings' };+ expect(applyThinClientSourceScope(addTimelineEntry, params)).toBeNull();+ expect(params).toEqual({ slug: 'concepts/probe', date: '2026-09-14', summary: 'probe', source: 'meetings' });+ });+});