Garry's Opinionated OpenClaw/Hermes Agent Brain
TypeScript
fix(capture): declare the CLI's provenance params on the capture op so a running serve and thin clients accept gbrain capture (#6524)
garrytan5725414ab6cf
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex 23d288b5e0..b2509ae44a 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -10,6 +10,18 @@ credits are retained; no result has been reassigned to another provider. Originaidentifiers and attribution are available in the pre-removal Git revision`6040075c6cb95be5881cc2e1b76ef7d71f4e5d29` (retained on 2026-09-23).+## [0.60.180.0] - 2026-10-12++**`gbrain capture` works again on a brain with a running `gbrain serve` and on every thin client (#6524).** Since v0.60.162.0 (#5970) every capture through those two transports refused `invalid_params: 3 unknown parameters not declared in the capture tool schema (write operations always reject unknown parameters; nothing was written)`, and nothing was written. The CLI has stamped its own provenance on each capture since #5622 (`source_kind: capture-cli`, `source_uri: stdin|cli-positional`, `ingested_via: capture-cli`); the capture op never declared those three fields, and #5970 made dispatch reject any undeclared key on a write. A CLI with no serve running (and every Postgres brain) calls the handler directly, bypassing dispatch, which is why the breakage never reproduced on a developer's own machine while every CLI call delegated to a resident PGLite owner and every thin-client call went through dispatch and failed. The three fields are now declared on the op as trusted-local-CLI provenance; nothing else changes, so the trust posture holds: a trusted local caller's values reach the row as before, and a remote caller's are still replaced with the server-stamped `mcp:capture` at submission. No migration, no paid call.++### Itemized changes++- **The capture op declares the CLI's provenance fields.** `source_kind`, `source_uri` and `ingested_via` are optional strings on `capture` (`CAPTURE_CLI_PROVENANCE_PARAMS` in `src/core/persistence/params.ts`), `fullSurfaceOnly` like `content_origin`: dispatch admits them on every transport, the full surface advertises them, and the starter tool list does not carry them, so its size budget is unchanged (`test/mcp-schema-budget.test.ts`). The operation manifest is regenerated.+- **A thin client sends no provenance.** `gbrain capture` builds its parameters in one place (`captureParams`) and attaches the trio only on a local install; a thin client never claimed trusted provenance that the owner would replace anyway, and an older host that predates this release no longer rejects its captures for sending it.+- Tests, each failing on the previous release with the exact refusal above: `test/capture-dispatch-provenance-6524.test.ts` dispatches the CLI's shape as a trusted local caller (row keeps `capture-cli` / `cli-positional`) and as a remote caller (row is `mcp:capture`), on PGLite and Postgres; `test/capture-cli-params-contract-6524.test.ts` checks every CLI shape (positional, `--stdin`, `--file` local, `--file` and positional on a thin client) against the server's own unknown-parameter check and pins the full-surface-only declaration; `test/capture-live-transports-6524.test.ts` runs the real `gbrain capture` subprocess against a running stdio `gbrain serve` (resident PGLite owner, delegated over IPC) and from a thin-client home against a running `gbrain serve --http`.++Fixes #6524. Diagnosis by @james810408, whose report named both sides of the drift and the `fullSurfaceOnly` shape.+## [0.60.179.0] - 2026-10-12**A managed sync cursor can no longer deadlock on its own canonical correction (#6513).** On a live checkout, a pinned import whose sanitization (a fixable fence, reflowed frontmatter) has to rewrite the file used to refuse `source_changed` / `pinned_git_worktree_conflict` ("Canonical sanitization cannot overwrite newer working-tree bytes.") when the file already held newer uncommitted bytes, and that refusal blocked the cursor with no exit: `--retry-failed` replayed the same pin against the same bytes, `sources refresh` refused `sync_in_progress` on the unfinished cursor, `--acknowledge-managed` refused `cursor_unfinished`, and doctor called the cursor `resumable`. The production brain's `default` source went 38 hours without a sync and recurred the same day; the only way out was deleting `op_checkpoints` rows by hand. The refusal is now the `worktree_dirty` hold the other pinned-worktree conflict already earned (#6340): the file is held, the local edit is untouched, the rest of the source syncs and the cursor finishes, so the checkout is movable again; committing the file (or `gbrain sync unblock --source <id> --apply`) imports it with its correction, and a file committed at HEAD meanwhile is re-frozen and imported as HEAD has it. A cursor an older release left blocked this way converts in place on its next `--retry-failed` run, without rediscovery. Working-tree bytes that already *are* the correction (gbrain's own writeback, published before the request that carried it settled) are no longer a conflict: the page imports and the file is left as it is.diff --git a/src/commands/capture.ts b/src/commands/capture.tsindex 8ed4ea775f..cc624ccf9b 100644--- a/src/commands/capture.ts+++ b/src/commands/capture.ts@@ -256,6 +256,36 @@ function printReceipt(result: CaptureResult, quiet: boolean, json: boolean): voiif (result.write_request) console.log(` request_id: ${result.write_request.request_id}`);}+/**+ * The `capture` operation parameters one CLI invocation submits, on every+ * transport (direct handler, resident-owner IPC, thin-client HTTP). The+ * provenance trio (`source_kind`, `source_uri`, `ingested_via`) is trusted+ * local CLI provenance: the owner stores it for a local caller and replaces it+ * with `mcp:capture` for a remote one (page-mutations.ts), so a thin client+ * sends none of it. #6524: every key here is declared on the op, which the+ * dispatch unknown-parameter check requires of a write+ * (test/capture-cli-params-contract-6524.test.ts).+ */+function captureParams(parsed: RunOpts, content: string, precondition: Record<string, unknown>, thinClient: boolean): Record<string, unknown> {+ return {+ content,+ ...precondition,+ ...(parsed.slug ? { slug: parsed.slug } : {}),+ ...(parsed.type ? { type: parsed.type } : {}),+ ...(parsed.who ? { who: parsed.who } : {}),+ ...(parsed.what ? { what: parsed.what } : {}),+ ...(parsed.where ? { where: parsed.where } : {}),+ ...(parsed.kind ? { kind: parsed.kind } : {}),+ ...(parsed.depth ? { depth: parsed.depth } : {}),+ ...(thinClient ? {} : {+ source_kind: 'capture-cli',+ // #5622: the owner maps a local file to its source-relative origin (or 'cli-file'); no file URI or home path is stored.+ ...(parsed.filePath ? { local_file: resolve(parsed.filePath) } : { source_uri: parsed.stdin ? 'stdin' : 'cli-positional' }),+ ingested_via: 'capture-cli',+ }),+ };+}+export async function runCapture(engine: BrainEngine | null, args: string[], options: { getEngine?: () => Promise<BrainEngine> } = {}): Promise<void> {const parsed = parseArgs(args);if ('help' in parsed) {@@ -369,22 +399,7 @@ export async function runCapture(engine: BrainEngine | null, args: string[], opttry {const precondition = parseMutationPrecondition(parsed as unknown as Record<string, unknown>);requestId = precondition.request_id ?? randomUUID();- const params: Record<string, unknown> = {- content: rawBody,- ...precondition,- request_id: requestId,- ...(parsed.slug ? { slug: parsed.slug } : {}),- ...(parsed.type ? { type: parsed.type } : {}),- ...(parsed.who ? { who: parsed.who } : {}),- ...(parsed.what ? { what: parsed.what } : {}),- ...(parsed.where ? { where: parsed.where } : {}),- ...(parsed.kind ? { kind: parsed.kind } : {}),- ...(parsed.depth ? { depth: parsed.depth } : {}),- source_kind: 'capture-cli',- // #5622: the owner maps a local file to its source-relative origin (or 'cli-file'); no file URI or home path is stored.- ...(parsed.filePath ? isThinClient(cfg) ? {} : { local_file: resolve(parsed.filePath) } : { source_uri: parsed.stdin ? 'stdin' : 'cli-positional' }),- ingested_via: 'capture-cli',- };+ const params = captureParams(parsed, rawBody, { ...precondition, request_id: requestId }, isThinClient(cfg));let result: Record<string, unknown>;if (isThinClient(cfg)) {const raw = await callRemoteTool(cfg!, 'capture', params, { timeoutMs: getCliOptions().timeoutMs ?? 30_000, writeWaitMs: currentCliWriteWait().waitMs });@@ -461,6 +476,7 @@ export const __testing = {deriveTitle,explicitCaptureType,parseArgs,+ captureParams,detectBinaryNullByte,detectBinarySignature,normalizeForHash,diff --git a/src/core/operation-manifest.generated.ts b/src/core/operation-manifest.generated.tsindex 4ffff38307..a602ba4632 100644--- a/src/core/operation-manifest.generated.ts+++ b/src/core/operation-manifest.generated.ts@@ -590,6 +590,24 @@ export const OPERATION_MANIFEST: OperationMeta[] = ["type": "string","description": "Event depth page to link."},+ "source_kind": {+ "type": "string",+ "required": false,+ "fullSurfaceOnly": true,+ "description": "Trusted local CLI provenance (capture-cli); a remote caller's value is replaced by the server-stamped mcp:capture."+ },+ "source_uri": {+ "type": "string",+ "required": false,+ "fullSurfaceOnly": true,+ "description": "Trusted local CLI provenance (stdin, cli-positional); a remote caller's value is replaced by the server-stamped mcp:capture."+ },+ "ingested_via": {+ "type": "string",+ "required": false,+ "fullSurfaceOnly": true,+ "description": "Trusted local CLI provenance (capture-cli); a remote caller's value is replaced by the server-stamped mcp:capture."+ },"content": {"type": "string","required": true,diff --git a/src/core/ops/pages.ts b/src/core/ops/pages.tsindex 72ae272e22..e65a02bbd0 100644--- a/src/core/ops/pages.ts+++ b/src/core/ops/pages.ts@@ -1,6 +1,6 @@import { pageMutationSource, submitPageMutation, validateMutationSlug } from '../persistence/page-mutations.ts';import { suffixedSlugDryRun } from '../persistence/suffixed-slug.ts';-import { AGENT_CONTENT_PARAMS, PAGE_MUTATION_PARAMS, CAPTURE_EVENT_PARAMS, WRITE_WAIT_PARAM } from '../persistence/params.ts';+import { AGENT_CONTENT_PARAMS, PAGE_MUTATION_PARAMS, CAPTURE_EVENT_PARAMS, CAPTURE_CLI_PROVENANCE_PARAMS, WRITE_WAIT_PARAM } from '../persistence/params.ts';import { assertPurgeParams } from '../persistence/purge-params.ts';/*** Page CRUD operation cluster — pure move from operations.ts (v0.46.x@@ -648,7 +648,7 @@ const capture: Operation = {description: CAPTURE_DESCRIPTION,params: {...AGENT_CONTENT_PARAMS,- ...CAPTURE_EVENT_PARAMS,+ ...CAPTURE_EVENT_PARAMS, ...CAPTURE_CLI_PROVENANCE_PARAMS,content: { type: 'string', required: true, description: 'Markdown or text (not a file path).' },local_file: { type: 'string', description: 'Local CLI only.', required: false },slug: { type: 'string', required: false, description: 'Default inbox/<date>-<hash>.' },diff --git a/src/core/persistence/params.ts b/src/core/persistence/params.tsindex 6178d5772f..31b0e1a44d 100644--- a/src/core/persistence/params.ts+++ b/src/core/persistence/params.ts@@ -8,6 +8,26 @@ export const CAPTURE_EVENT_PARAMS: Record<string, ParamDef> = {kind: { type: 'string', description: 'Event kind.' },depth: { type: 'string', description: 'Event depth page to link.' },};+/**+ * #6524: the provenance the trusted local CLI stamps on its own captures+ * (`capture-cli`, `stdin` / `cli-positional`; a `--file` capture sends+ * `local_file` and the owner resolves its origin). `gbrain capture` has sent+ * these since #5622, and a running `gbrain serve` (IPC owner) or a thin client+ * reaches the op through dispatch, whose unknown-parameter check (#5970)+ * rejects every undeclared key on a write. Declared so dispatch admits them;+ * page-mutations.ts still replaces a remote caller's values with the+ * server-stamped `mcp:capture`, so the trust posture is unchanged. Full+ * surface only, like `content_origin`: the starter list keeps its size budget+ * (test/mcp-schema-budget.test.ts) and agents never set these.+ */+export const CAPTURE_CLI_PROVENANCE_PARAMS: Record<string, ParamDef> = {+ source_kind: { type: 'string', required: false, fullSurfaceOnly: true,+ description: 'Trusted local CLI provenance (capture-cli); a remote caller\'s value is replaced by the server-stamped mcp:capture.' },+ source_uri: { type: 'string', required: false, fullSurfaceOnly: true,+ description: 'Trusted local CLI provenance (stdin, cli-positional); a remote caller\'s value is replaced by the server-stamped mcp:capture.' },+ ingested_via: { type: 'string', required: false, fullSurfaceOnly: true,+ description: 'Trusted local CLI provenance (capture-cli); a remote caller\'s value is replaced by the server-stamped mcp:capture.' },+};import { WRITE_REQUEST_STATES, WRITE_HEALTH_REASONS, WRITE_HEALTH_ASSESSMENTS, WRITE_HEALTH_ACTIONS } from './types.ts';/** Leaf definitions: safe to import while the frozen verb registry is evaluating.diff --git a/test/capture-cli-params-contract-6524.test.ts b/test/capture-cli-params-contract-6524.test.tsnew file mode 100644index 0000000000..cb21d280a1--- /dev/null+++ b/test/capture-cli-params-contract-6524.test.ts@@ -0,0 +1,62 @@+/**+ * #6524: `gbrain capture` was dead on every brain with a running `gbrain+ * serve` and on every thin client. The CLI sends its provenance trio+ * (`source_kind`, `source_uri`, `ingested_via`; #5622) and dispatch rejects+ * every undeclared key on a write (#5970), so the two transports that go+ * through dispatch (resident-owner IPC, thin-client HTTP) refused with+ * "3 unknown parameters" while the direct-handler path kept working. This+ * pins the CLI's real parameter shapes against the op contract the server+ * validates with, so a key the CLI adds without declaring it fails here, not+ * at the user's terminal.+ */+import { describe, expect, test } from 'bun:test';+import { randomUUID } from 'node:crypto';+import { resolve } from 'node:path';+import { __testing } from '../src/commands/capture.ts';+import { operationsByName } from '../src/core/operations.ts';+import { findUnknownParams } from '../src/mcp/validate-params.ts';+import { filterOpsForSurface } from '../src/mcp/surface.ts';++const capture = operationsByName.capture!;+const content = 'A captured observation.';+const precondition = { request_id: randomUUID() };+const args = (argv: string[]) => __testing.parseArgs(argv) as Record<string, unknown>;++const shapes = {+ positional: __testing.captureParams(args(['hello', '--slug', 'inbox/example']), content, precondition, false),+ stdin: __testing.captureParams(args(['--stdin', '--type', 'event', '--who', 'alice-example', '--what', 'met', '--where', 'office', '--kind', 'meeting', '--depth', 'depth/example']), content, precondition, false),+ fileLocal: __testing.captureParams(args(['--file', 'notes/local.md']), content, precondition, false),+ fileThin: __testing.captureParams(args(['--file', 'notes/local.md']), content, precondition, true),+ positionalThin: __testing.captureParams(args(['hello']), content, precondition, true),+};++describe('#6524 the CLI capture parameter shapes are declared on the capture op', () => {+ for (const [name, params] of Object.entries(shapes)) {+ test(`${name}: dispatch finds no unknown parameter`, () => {+ expect(findUnknownParams(capture, params)).toEqual([]);+ });+ }++ test('a local caller sends its provenance; a thin client sends none of it', () => {+ expect(shapes.positional).toMatchObject({ content, ...precondition, slug: 'inbox/example', source_kind: 'capture-cli', source_uri: 'cli-positional', ingested_via: 'capture-cli' });+ expect(shapes.stdin).toMatchObject({ source_kind: 'capture-cli', source_uri: 'stdin', ingested_via: 'capture-cli', type: 'event', who: 'alice-example' });+ expect(shapes.fileLocal).toMatchObject({ source_kind: 'capture-cli', ingested_via: 'capture-cli', local_file: resolve('notes/local.md') });+ expect('source_uri' in shapes.fileLocal).toBe(false);+ for (const thin of [shapes.fileThin, shapes.positionalThin]) {+ expect(Object.keys(thin).filter(key => ['source_kind', 'source_uri', 'ingested_via', 'local_file'].includes(key))).toEqual([]);+ }+ });++ test('the provenance trio is a full-surface declaration and stays off the starter list', () => {+ for (const key of ['source_kind', 'source_uri', 'ingested_via']) {+ expect(capture.params[key]).toMatchObject({ type: 'string', required: false, fullSurfaceOnly: true });+ expect(capture.params[key]!.description).toContain('mcp:capture');+ }+ const starter = filterOpsForSurface([capture], 'starter')[0];+ expect(starter).toBeDefined();+ expect(Object.keys(starter!.params)).not.toContain('source_kind');+ expect(Object.keys(starter!.params)).not.toContain('source_uri');+ expect(Object.keys(starter!.params)).not.toContain('ingested_via');+ expect(Object.keys(filterOpsForSurface([capture], 'full')[0]!.params)).toEqual(expect.arrayContaining(['source_kind', 'source_uri', 'ingested_via']));+ });+});diff --git a/test/capture-dispatch-provenance-6524.test.ts b/test/capture-dispatch-provenance-6524.test.tsnew file mode 100644index 0000000000..37eab8011c--- /dev/null+++ b/test/capture-dispatch-provenance-6524.test.ts@@ -0,0 +1,76 @@+/**+ * #6524: `gbrain capture` has sent its provenance trio (`source_kind`,+ * `source_uri`, `ingested_via`) since #5622; since #5970 dispatch rejects any+ * undeclared key on a write. A CLI delegating to a running serve (IPC owner)+ * and every thin client reach capture through `dispatchToolCall`, so the+ * trio must be declared on the op. The literal below is the CLI's shape for+ * `gbrain capture "<text>" --slug <slug>` (the builder itself is pinned by+ * test/capture-cli-params-contract-6524.test.ts). Dispatch admits it; the+ * owner keeps a trusted local caller's values and replaces a remote caller's+ * with the server stamp, so declaring the keys lends no trust.+ *+ * On master both captures fail with "3 unknown parameters not declared in the+ * capture tool schema". Runs on PGLite; also on Postgres when DATABASE_URL is+ * set (testBackends).+ */+import { afterAll, beforeAll, describe, expect, test } from 'bun:test';+import { randomUUID } from 'node:crypto';+import type { BrainEngine } from '../src/core/engine.ts';+import { PGLiteEngine } from '../src/core/pglite-engine.ts';+import { disposePersistenceConsumer } from '../src/core/persistence/service.ts';+import { dispatchToolCall } from '../src/mcp/dispatch.ts';+import { isolatedPersistencePostgres } from './helpers/persistence-postgres.ts';+import { testBackends } from './helpers/test-backends.ts';++const backends = testBackends();+const engines: Array<{ backend: string; engine: BrainEngine }> = [];+let closePostgres: (() => Promise<void>) | undefined;++beforeAll(async () => {+ if (backends.includes('pglite')) {+ const engine = new PGLiteEngine();+ await engine.connect({}); await engine.initSchema();+ engines.push({ backend: 'pglite', engine });+ }+ if (backends.includes('postgres')) {+ const pg = await isolatedPersistencePostgres(process.env.DATABASE_URL!);+ engines.push({ backend: 'postgres', engine: pg.engine }); closePostgres = pg.close;+ }+ for (const { engine } of engines) await engine.setConfig('schema_pack', 'gbrain-base');+}, 120_000);++afterAll(async () => {+ for (const { engine } of engines) { await disposePersistenceConsumer(engine); await engine.disconnect(); }+ await closePostgres?.();+});++const cliShape = (slug: string, content: string) => ({+ content, request_id: randomUUID(), slug, source_kind: 'capture-cli', source_uri: 'cli-positional', ingested_via: 'capture-cli',+});+const parsed = (result: { content: Array<{ text: string }> }) => JSON.parse(result.content[0]!.text) as Record<string, unknown>;+const provenance = async (engine: BrainEngine, slug: string) => {+ const page = await engine.getPage(slug);+ return { source_kind: page?.source_kind, source_uri: page?.source_uri, ingested_via: page?.ingested_via };+};++describe('#6524 the CLI capture shape through dispatch', () => {+ for (const backend of backends) {+ const engineFor = () => engines.find(e => e.backend === backend)!.engine;++ test(`[${backend}] a trusted local caller (resident-owner IPC) is admitted and its provenance is stored`, async () => {+ const engine = engineFor();+ const slug = 'inbox/capture-cli-provenance-6524';+ const res = await dispatchToolCall(engine, 'capture', cliShape(slug, 'Captured from the CLI through a running serve.'), { remote: false, sourceId: 'default' });+ expect({ isError: res.isError ?? false, body: parsed(res) }).toMatchObject({ isError: false, body: { slug, channel: 'capture' } });+ expect(await provenance(engine, slug)).toEqual({ source_kind: 'capture-cli', source_uri: 'cli-positional', ingested_via: 'capture-cli' });+ });++ test(`[${backend}] a remote caller sending the same shape is admitted and its provenance is replaced by the server stamp`, async () => {+ const engine = engineFor();+ const slug = 'inbox/capture-remote-provenance-6524';+ const res = await dispatchToolCall(engine, 'capture', cliShape(slug, 'Submitted remotely with a claimed CLI provenance.'), { remote: true, transport: 'stdio', sourceId: 'default' });+ expect({ isError: res.isError ?? false, body: parsed(res) }).toMatchObject({ isError: false, body: { slug } });+ expect(await provenance(engine, slug)).toEqual({ source_kind: 'mcp:capture', source_uri: null, ingested_via: 'mcp:capture' });+ });+ }+});diff --git a/test/capture-live-transports-6524.test.ts b/test/capture-live-transports-6524.test.tsnew file mode 100644index 0000000000..df43e72a61--- /dev/null+++ b/test/capture-live-transports-6524.test.ts@@ -0,0 +1,116 @@+/**+ * #6524: `gbrain capture` was dead on every brain with a running `gbrain+ * serve` and on every thin client. Both transports reach the capture op+ * through `dispatchToolCall`, whose unknown-parameter check (#5970) rejects a+ * write carrying any undeclared key, and the CLI has sent its provenance trio+ * (`source_kind`, `source_uri`, `ingested_via`; #5622) since before that+ * check existed. The direct-handler path (no serve, or Postgres) bypassed+ * dispatch, which is why the breakage never reproduced locally.+ *+ * Both probes drive the real CLI subprocess:+ * - resident owner: a stdio `gbrain serve` holds the PGLite brain and the+ * CLI's capture is delegated to it over IPC; the stored row keeps the+ * trusted local provenance (`capture-cli` / `cli-positional`);+ * - thin client: a `gbrain serve --http` subprocess plus a thin-client+ * home whose CLI reaches it through `callRemoteTool`; the capture is+ * admitted and the owner stamps `mcp:capture` (remote provenance is+ * server-owned).+ * On the #5970..#6524 range both exit 1 with "3 unknown parameters".+ */+import { afterAll, beforeAll, expect, test } from 'bun:test';+import { spawn, type ChildProcess } from 'node:child_process';+import { mkdirSync, mkdtempSync, rmSync, writeFileSync } from 'node:fs';+import { createServer } from 'node:net';+import { tmpdir } from 'node:os';+import { join } from 'node:path';+import { Client } from '@modelcontextprotocol/sdk/client/index.js';+import { StdioClientTransport } from '@modelcontextprotocol/sdk/client/stdio.js';+import { runCli, type CliResult } from './helpers/cli-spawn.ts';++const CLI = join(import.meta.dir, '..', 'src', 'cli.ts');+const baseEnv = { GBRAIN_SKIP_STARTUP_HOOKS: '1', GBRAIN_UPDATE_CHECK: '0', GBRAIN_SWEEP: '0', GBRAIN_NON_INTERACTIVE: '1',+ GBRAIN_NO_BANNER: '1', NO_COLOR: '1', NODE_ENV: 'test', GBRAIN_SOURCE: undefined, GBRAIN_BRAIN_ID: undefined };++let home: string;++const gbrain = (cwd: string, args: string[]) => runCli(args, { home: cwd, cwd, env: baseEnv, timeoutMs: 90_000 });+const ok = (result: CliResult) => {+ expect({ exit: result.exitCode, failure: result.exitCode ? result.stdout + result.stderr : '' }).toEqual({ exit: 0, failure: '' });+ return JSON.parse(result.stdout) as Record<string, any>;+};+const provenance = (page: Record<string, any>) => ({ source_kind: page.source_kind, source_uri: page.source_uri, ingested_via: page.ingested_via });++async function freePort(): Promise<number> {+ return await new Promise((resolve, reject) => {+ const s = createServer();+ s.once('error', reject);+ s.listen(0, '127.0.0.1', () => {+ const a = s.address();+ s.close(() => resolve(typeof a === 'object' && a ? a.port : 0));+ });+ });+}++beforeAll(async () => {+ home = mkdtempSync(join(tmpdir(), 'gbrain-capture-6524-'));+ ok(await gbrain(home, ['init', '--pglite', '--no-embedding', '--non-interactive', '--json']));+}, 120_000);++afterAll(() => {+ rmSync(home, { recursive: true, force: true });+});++test('a capture delegated to a running stdio serve (resident PGLite owner) commits with the trusted CLI provenance', async () => {+ const env = { PATH: process.env.PATH ?? '/usr/bin:/bin', HOME: home, GBRAIN_HOME: home, GBRAIN_SKIP_STARTUP_HOOKS: '1',+ GBRAIN_UPDATE_CHECK: '0', GBRAIN_SWEEP: '0', NODE_ENV: 'test' };+ const client = new Client({ name: 'capture-6524-owner', version: '1' }, { capabilities: {} });+ const transport = new StdioClientTransport({ command: process.execPath, args: ['--no-env-file', CLI, 'serve'], cwd: home, env, stderr: 'pipe' });+ try {+ await client.connect(transport, { signal: AbortSignal.timeout(30_000) });+ const captured = ok(await gbrain(home, ['capture', 'Captured through the resident owner.', '--slug', 'inbox/owner-example-6524', '--json']));+ expect(captured).toMatchObject({ slug: 'inbox/owner-example-6524' });+ const page = ok(await gbrain(home, ['get', 'inbox/owner-example-6524', '--json']));+ expect(provenance(page)).toEqual({ source_kind: 'capture-cli', source_uri: 'cli-positional', ingested_via: 'capture-cli' });+ } finally {+ await client.close().catch(() => {});+ await transport.close().catch(() => {});+ }+}, 180_000);++test('a thin-client capture against a running `gbrain serve --http` commits with the server-stamped provenance', async () => {+ const reg = await gbrain(home, ['auth', 'register-client', 'capture-6524-thin', '--grant-types', 'client_credentials',+ '--scopes', 'read write', '--token-endpoint-auth-method', 'client_secret_post']);+ const clientId = /Client ID:\s+(\S+)/.exec(reg.stdout)?.[1];+ const clientSecret = /Client Secret:\s+(\S+)/.exec(reg.stdout)?.[1];+ if (!clientId || !clientSecret) throw new Error(`register-client yielded no credentials:\n${reg.stdout}\n${reg.stderr}`);+ const port = await freePort();+ const base = `http://127.0.0.1:${port}`;+ const serverEnv: Record<string, string> = { ...Object.fromEntries(Object.entries(process.env).filter((e): e is [string, string] => e[1] !== undefined)),+ HOME: home, GBRAIN_HOME: home, GBRAIN_SKIP_STARTUP_HOOKS: '1', GBRAIN_UPDATE_CHECK: '0', GBRAIN_SWEEP: '0', NODE_ENV: 'test' };+ for (const key of ['DATABASE_URL', 'GBRAIN_DATABASE_URL', 'GBRAIN_REMOTE_CLIENT_SECRET', 'GBRAIN_SOURCE', 'GBRAIN_BRAIN_ID']) delete serverEnv[key];+ const server: ChildProcess = spawn(process.execPath, ['--no-env-file', CLI, 'serve', '--http', '--bind', '127.0.0.1', '--port', String(port), '--public-url', base],+ { cwd: home, env: serverEnv, stdio: ['ignore', 'pipe', 'pipe'] });+ let serverErr = '';+ server.stderr?.on('data', (d: Buffer) => { serverErr += d.toString(); });+ const thinHome = mkdtempSync(join(tmpdir(), 'gbrain-capture-6524-thin-'));+ try {+ let ready = false;+ for (let i = 0; i < 120 && !ready; i++) {+ try { ready = (await fetch(`${base}/health`)).ok; } catch { /* not up yet */ }+ if (!ready) await Bun.sleep(500);+ }+ if (!ready) throw new Error(`serve --http did not become ready:\n${serverErr}`);+ mkdirSync(join(thinHome, '.gbrain'), { recursive: true });+ writeFileSync(join(thinHome, '.gbrain', 'config.json'), JSON.stringify({+ engine: 'postgres', remote_mcp: { issuer_url: base, mcp_url: `${base}/mcp`, oauth_client_id: clientId, oauth_client_secret: clientSecret },+ }));+ const captured = ok(await gbrain(thinHome, ['capture', 'Captured from a thin client.', '--slug', 'inbox/thin-example-6524', '--json']));+ expect(captured).toMatchObject({ slug: 'inbox/thin-example-6524' });+ const page = ok(await gbrain(home, ['get', 'inbox/thin-example-6524', '--json']));+ expect(provenance(page)).toEqual({ source_kind: 'mcp:capture', source_uri: null, ingested_via: 'mcp:capture' });+ } finally {+ server.kill('SIGTERM');+ await new Promise(resolve => { if (server.exitCode !== null) resolve(null); else server.once('exit', resolve); });+ rmSync(thinHome, { recursive: true, force: true });+ }+}, 180_000);diff --git a/test/postgres-unit-arms.txt b/test/postgres-unit-arms.txtindex bf09f798d8..915523467e 100644--- a/test/postgres-unit-arms.txt+++ b/test/postgres-unit-arms.txt@@ -16,6 +16,7 @@ test/alias-source-cascade-5094.test.tstest/attribution-backfill-history.test.tstest/behavior-change-notice.test.tstest/capture-consent-admission.test.ts+test/capture-dispatch-provenance-6524.test.tstest/chronicle-backfill-max-usd.test.tstest/colon-slug-windows-5032.test.tstest/company-brain-policy.test.ts