Garry's Opinionated OpenClaw/Hermes Agent Brain
TypeScript
test(lane-h): H4 Postgres parity of the agent journey and upgrade fixtures; caller mistakes on the persistence CLI lane exit 2; stdio DB-access fixes name the user
garrytan2a3dbc578a7d
diff --git a/scripts/e2e-test-map.ts b/scripts/e2e-test-map.tsindex 5ff5ec0905..520662cdea 100644--- a/scripts/e2e-test-map.ts+++ b/scripts/e2e-test-map.ts@@ -291,7 +291,7 @@ export const E2E_TEST_MAP: Record<string, string[]> = {"src/core/lease-schema.ts": ["test/e2e/db-lock-acquisition-token.test.ts"],// O-CEO-13 wave-8 write contract gate: receipts, replay, edit_page, publication reauthorization."src/core/persistence/page-edit.ts": ["test/e2e/write-contract-conformance.test.ts"],- "src/core/persistence/write-wait.ts": ["test/e2e/write-contract-conformance.test.ts"],+ "src/core/persistence/write-wait.ts": ["test/e2e/write-contract-conformance.test.ts", "test/e2e/agent-journey-postgres.test.ts"],"src/core/ops/page-edit.ts": ["test/e2e/write-contract-conformance.test.ts"],// Foundations 1 write attribution: actor settings and BEFORE ROW triggers, direct and through PgBouncer."src/core/persistence/attribution.ts": ["test/e2e/write-attribution-postgres.test.ts"],@@ -509,13 +509,27 @@ export const E2E_TEST_MAP: Record<string, string[]> = {"src/core/persistence/memory-mutations.ts": ["test/e2e/withdrawal-followup-writes-postgres.test.ts"],"src/core/persistence/coordinator.ts": ["test/e2e/withdrawal-followup-writes-postgres.test.ts"],"src/core/facts/meta-hook.ts": ["test/e2e/capture-dedup-postgres.test.ts", "test/e2e/hot-memory-invalidation-postgres.test.ts", "test/e2e/facts-context-injection-postgres.test.ts", "test/e2e/serve-http-meta.test.ts"],- "src/mcp/dispatch.ts": ["test/e2e/hot-memory-invalidation-postgres.test.ts", "test/e2e/write-contract-conformance.test.ts"],+ "src/mcp/dispatch.ts": ["test/e2e/hot-memory-invalidation-postgres.test.ts", "test/e2e/write-contract-conformance.test.ts", "test/e2e/agent-journey-postgres.test.ts"],// Foundations 1 F4b: PGLite-only planner-stats accounting; Postgres must gain no object, doctor/repair read pg_stat_user_tables."src/core/planner-stats.ts": ["test/e2e/planner-stats-postgres.test.ts"],"src/core/planner-stats-schema.ts": ["test/e2e/planner-stats-postgres.test.ts", "test/e2e/schema-drift.test.ts", "test/e2e/schema-catalog-golden.test.ts"],"src/core/schema-migrations/v193-f4-planner-stats.ts": ["test/e2e/planner-stats-postgres.test.ts", "test/e2e/schema-drift.test.ts", "test/e2e/schema-catalog-golden.test.ts"],"src/commands/doctor/checks/planner-stats.ts": ["test/e2e/planner-stats-postgres.test.ts"],"src/core/repair/planner-stats.ts": ["test/e2e/planner-stats-postgres.test.ts"],+ // Agent operator wave H4: Postgres parity of the keyless agent journey (init --json, day-zero doctor,+ // doctor --remediate consent on a pending-migration brain, stdio MCP notices/errors/readiness, degraded serve).+ "src/core/agent-output.ts": ["test/e2e/agent-journey-postgres.test.ts"],+ "src/core/readiness.ts": ["test/e2e/agent-journey-postgres.test.ts"],+ "src/core/consent.ts": ["test/e2e/agent-journey-postgres.test.ts"],+ "src/core/consent-cli.ts": ["test/e2e/agent-journey-postgres.test.ts"],+ "src/core/interop-notices.ts": ["test/e2e/agent-journey-postgres.test.ts"],+ "src/core/degraded-engine.ts": ["test/e2e/agent-journey-postgres.test.ts"],+ "src/core/agent-contract-log.ts": ["test/e2e/agent-journey-postgres.test.ts"],+ "src/mcp/server.ts": ["test/e2e/agent-journey-postgres.test.ts"],+ "src/mcp/capabilities.ts": ["test/e2e/agent-journey-postgres.test.ts"],+ "src/mcp/validate-params.ts": ["test/e2e/agent-journey-postgres.test.ts"],+ "src/commands/init.ts": ["test/e2e/agent-journey-postgres.test.ts"],+ "src/commands/serve-status.ts": ["test/e2e/agent-journey-postgres.test.ts"],// Schema source of truth: any change must pass the cross-engine drift gate."src/schema.sql": ["test/e2e/schema-drift.test.ts", "test/e2e/schema-catalog-golden.test.ts"],"src/core/pglite-schema.ts": ["test/e2e/schema-drift.test.ts", "test/e2e/schema-catalog-golden.test.ts"],@@ -578,7 +592,7 @@ export const E2E_TEST_MAP: Record<string, string[]> = {"src/commands/autopilot-probes.ts": ["test/e2e/autopilot-linux-lifecycle.serial.test.ts", "test/e2e/worker-readiness-cli.test.ts"],"src/commands/doctor.ts": ["test/e2e/doctor-progress.test.ts", "test/e2e/doctor-json-golden.test.ts"],// Doctor check modules peeled from doctor.ts feed the same e2e surface.- "src/commands/doctor/**": ["test/e2e/doctor-progress.test.ts", "test/e2e/recovery-layer.test.ts", "test/e2e/fix-wave-3-integration.test.ts", "test/e2e/doctor-json-golden.test.ts"],+ "src/commands/doctor/**": ["test/e2e/doctor-progress.test.ts", "test/e2e/recovery-layer.test.ts", "test/e2e/fix-wave-3-integration.test.ts", "test/e2e/doctor-json-golden.test.ts", "test/e2e/agent-journey-postgres.test.ts"],// Knowledge graph layer feeds graph-quality."src/core/link-extraction.ts": ["test/e2e/graph-quality.test.ts", "test/e2e/attendance-retrieval-postgres.test.ts"],"src/core/attendance-repair.ts": ["test/e2e/attendance-repair-postgres.test.ts"],diff --git a/scripts/e2e-weights.json b/scripts/e2e-weights.jsonindex 164df4a99d..db9cc5e34b 100644--- a/scripts/e2e-weights.json+++ b/scripts/e2e-weights.json@@ -1,4 +1,5 @@{+ "test/e2e/agent-journey-postgres.test.ts": 18000,"test/e2e/anomalies-pglite.test.ts": 2180,"test/e2e/auth-permissions.test.ts": 1810,"test/e2e/auth-takes-holders-pglite.test.ts": 1070,diff --git a/scripts/serial-weights.json b/scripts/serial-weights.jsonindex 6dc82df579..92cea29a04 100644--- a/scripts/serial-weights.json+++ b/scripts/serial-weights.json@@ -2,6 +2,7 @@"test/admin-embed-spawn.serial.test.ts": 55,"test/advisor-backup-coverage.serial.test.ts": 2,"test/agent-install-backup.serial.test.ts": 114,+ "test/agent-journey-upgrade.serial.test.ts": 70,"test/agent-register-guards.serial.test.ts": 22,"test/agent-scheduler-contract.serial.test.ts": 39,"test/agent-voice-cors.serial.test.ts": 1,diff --git a/scripts/ubicloud/weights.json b/scripts/ubicloud/weights.jsonindex 07082f8935..0e3fe19a7a 100644--- a/scripts/ubicloud/weights.json+++ b/scripts/ubicloud/weights.json@@ -1,4 +1,5 @@{+ "e2e:test/e2e/agent-journey-postgres.test.ts": 18000,"e2e:test/e2e/anomalies-pglite.test.ts": 2886,"e2e:test/e2e/attendance-repair-postgres.test.ts": 21285,"e2e:test/e2e/attendance-retrieval-postgres.test.ts": 27079,@@ -274,6 +275,7 @@"serial:test/agent-install-backup.serial.test.ts": 81187,"serial:test/agent-install-follow-setup.serial.test.ts": 44197,"serial:test/agent-install-shared-skills.serial.test.ts": 2732,+ "serial:test/agent-journey-upgrade.serial.test.ts": 70000,"serial:test/agent-register-guards.serial.test.ts": 11667,"serial:test/agent-scheduler-contract.serial.test.ts": 25493,"serial:test/agent-voice-cors.serial.test.ts": 1530,diff --git a/src/core/agent-output.ts b/src/core/agent-output.tsindex 5cb2fcf279..89f4cc5f1d 100644--- a/src/core/agent-output.ts+++ b/src/core/agent-output.ts@@ -633,7 +633,7 @@ function dbParts(e: unknown, ctx: AgentErrorContext): EnvelopeParts | undefinederror: 'unavailable', code: 'unavailable', reason: 'schema_missing', message: d.message,suggestion: 'Run gbrain apply-migrations on the brain host, then retry.',fix: {- argv: ['gbrain', 'apply-migrations', '--yes'], consent: [], actor: ctx.transport === 'cli' ? 'agent' : 'host_admin',+ argv: ['gbrain', 'apply-migrations', '--yes'], consent: [], actor: 'agent',why: 'The code expects a table or column this brain does not have yet.', requires_exclusive: true,verify: { argv: ['gbrain', 'doctor', '--json'] },},@@ -644,7 +644,7 @@ function dbParts(e: unknown, ctx: AgentErrorContext): EnvelopeParts | undefinederror: verb ? 'unavailable' : 'database_error', code: verb ? 'unavailable' : 'database_error', reason: d.reason,message: d.message, suggestion: `${formatDbAccessMarker(d)}. ${d.remediation} Run: gbrain db-repair`,fix: {- argv: ['gbrain', 'db-repair'], consent: [], actor: ctx.transport === 'cli' ? 'agent' : 'host_admin',+ argv: ['gbrain', 'db-repair'], consent: [], actor: 'agent',why: 'db-repair diagnoses the database connection without changing anything.', requires_exclusive: false,},...(verb ? { detail: d.reason, protocol_version: 1 as const } : {}),diff --git a/src/core/persistence/write-wait.ts b/src/core/persistence/write-wait.tsindex 7e1e7ac6bc..ddb37c066c 100644--- a/src/core/persistence/write-wait.ts+++ b/src/core/persistence/write-wait.ts@@ -6,7 +6,8 @@*/import { loadConfig, type GBrainConfig } from '../config.ts';import { getCliOptions } from '../cli-options.ts';-import { PENDING_WRITE_EXIT_CODE } from '../exit-codes.ts';+import { PENDING_WRITE_EXIT_CODE, USAGE_EXIT_CODE } from '../exit-codes.ts';+import { exitCodeForCode } from '../error-catalogue.ts';import { OperationError } from '../ops/contract.ts';import { admittedPendingReceipt, type WriteReceipt } from './types.ts';@@ -95,12 +96,13 @@ export function pendingReceiptOf(error: unknown): WriteReceipt | null {/*** The one CLI exit verdict for a failed write (O-DX-1/O-ENG-1): an admitted- * pending receipt exits PENDING_WRITE_EXIT_CODE (0 with the opt-in); every- * other error, including a pre-admission `unavailable`, exits 1.+ * pending receipt exits PENDING_WRITE_EXIT_CODE (0 with the opt-in); a caller+ * mistake (`invalid_params`) exits 2 per the A3 exit table; every other error,+ * including a pre-admission `unavailable`, exits 1.*/export function writeErrorExitCode(error: unknown, acceptPending: boolean): number {- if (!pendingReceiptOf(error)) return 1;- return acceptPending ? 0 : PENDING_WRITE_EXIT_CODE;+ if (pendingReceiptOf(error)) return acceptPending ? 0 : PENDING_WRITE_EXIT_CODE;+ return error instanceof OperationError && exitCodeForCode(error.code) === USAGE_EXIT_CODE ? USAGE_EXIT_CODE : 1;}/** The copy-paste poll command for a pending receipt. */diff --git a/test/agent-journey-upgrade.serial.test.ts b/test/agent-journey-upgrade.serial.test.tsnew file mode 100644index 0000000000..0171aa4549--- /dev/null+++ b/test/agent-journey-upgrade.serial.test.ts@@ -0,0 +1,483 @@+/**+ * Agent operator wave H4: upgrade fixtures (docs/designs/AGENT_OPERATOR_WAVE.md,+ * Lane H). What a v0.60.37.0 install already had keeps working after the+ * upgrade, with the outputs, authorization and recovery it relied on:+ *+ * (1) existing scripts: every `--json` document an old script parsed still+ * parses with every key path, exit code and `error` value it had+ * (frozen capture: test/fixtures/agent-contract/v0.60.37-json-documents.json),+ * except the documented renumbers; legacy advice keys stay put.+ * (2) scheduled jobs: cron/autopilot invocations, non-TTY, keep running; the+ * only flip is the one the behavior table lists (`doctor --remediate`).+ * (3) harness configs: a pre-surface Claude Code registration, a Codex+ * config.toml registration and a bare-`gbrain` registration answer+ * initialize + tools/list + recall, and `doctor --only harness_wiring`+ * reports each (the bare one with the rewire fix).+ * (4) an old thin client (the frozen v0.60.37 parser in+ * test/fixtures/agent-contract/frozen-thin-client-v0.60.37.ts, over the+ * same SDK transport it used) against a real new `serve --http`.+ * (5) queued jobs from before the upgrade carry no submit-time authorization+ * and run under the configured budget (spec A4).+ *+ * Spec row → test (existing coverage this file does not duplicate):+ * legacy `error` values and v1 fields on the goldens, both skew directions → test/thin-client-contract-skew.test.ts+ * exit-3 enumeration and the published exit table → test/exit-codes.test.ts+ * budget stop 3 → 11 (`embed --stale`, `dream --drain`) → test/embed.serial.test.ts, test/embed-exit-code-3037.serial.test.ts,+ * test/dream-drain-failure-summary.serial.test.ts+ * consent table: every gated command non-TTY exits 3 and mutates nothing → test/consent-table.serial.test.ts (C9)+ * absolute `serve --surface verbs` Claude registration smoke, live owner → test/doctor-harness-smoke.serial.test.ts+ * #5157 pre-cutover jobs (no submission authority) need review first → test/minions-legacy-journey.test.ts,+ * test/e2e/minions-legacy-journey-postgres.test.ts+ * Postgres parity of the H1 journey → test/e2e/agent-journey-postgres.test.ts+ * (1) real CLI documents, renumbered exits, legacy keys → this file, "(1)"+ * (2) cron/autopilot non-TTY → this file, "(2)"+ * (3) pre-surface, Codex and bare-binary registrations → this file, "(3)"+ * (4) frozen old client against a live new serve --http → this file, "(4)"+ * (5) pre-upgrade queued paid job under the configured cap → this file, "(5)"+ *+ * Keyless PGLite in hermetic HOME = GBRAIN_HOME; real subprocess CLI+ * (`bun --no-env-file src/cli.ts`), real MCP sessions, hard timeouts.+ * Row (5) points the embedding provider at a local stub (no network, no key).+ *+ * Serial: subprocess CLIs and servers over temp PGLite brains.+ */+import { afterAll, beforeAll, describe, expect, test } from 'bun:test';+import { spawn, type ChildProcess } from 'node:child_process';+import { chmodSync, mkdirSync, readFileSync, rmSync, writeFileSync } from 'node:fs';+import { delimiter, join } from 'node:path';+import { Client } from '@modelcontextprotocol/sdk/client/index.js';+import { StdioClientTransport } from '@modelcontextprotocol/sdk/client/stdio.js';+import { StreamableHTTPClientTransport } from '@modelcontextprotocol/sdk/client/streamableHttp.js';+import { makeDoctorHome, runGbrain, type DoctorHome, type GbrainRun } from './helpers/doctor-json-golden.ts';+import { PROVIDER_ENV_KEYS } from './helpers/provider-env.ts';+import { oldReadError, oldUnpack } from './fixtures/agent-contract/frozen-thin-client-v0.60.37.ts';+import { extractToolErrorDetail } from '../src/core/mcp-client.ts';+import { PGLiteEngine } from '../src/core/pglite-engine.ts';+import { MinionQueue } from '../src/core/minions/queue.ts';++const REPO = join(import.meta.dir, '..');+const CLI = join(REPO, 'src', 'cli.ts');+const MARKER = 'zelkova-upgrade-fixture';+const FROZEN = JSON.parse(readFileSync(join(import.meta.dir, 'fixtures', 'agent-contract', 'v0.60.37-json-documents.json'), 'utf8')) as {+ commands: Record<string, { exit: number; keys?: string[]; error?: string; json?: false }>;+};++const homes: DoctorHome[] = [];+afterAll(() => { for (const h of homes) h.cleanup(); });++/** A hermetic home with a keyless PGLite brain and three imported notes (the frozen capture's fixture). */+async function upgradedBrain(prefix: string, initArgs: string[] = ['init', '--pglite', '--no-embedding'], env: Record<string, string | undefined> = {}): Promise<DoctorHome> {+ const h = makeDoctorHome(prefix);+ homes.push(h);+ rmSync(h.skillsDir, { recursive: true, force: true });+ const init = await run(h, initArgs, env);+ expect(init.exitCode, init.stderr).toBe(0);+ const notes = join(h.home, 'notes');+ mkdirSync(notes, { recursive: true });+ for (const n of ['alpha', 'beta', 'gamma']) {+ writeFileSync(join(notes, `${n}.md`), `---\ntitle: ${n} note\n---\n\n# ${n} note\n\nThe ${MARKER} ${n} fact lives here.\n`);+ }+ const imported = await run(h, ['import', notes, '--no-embed'], env);+ expect(imported.exitCode, imported.stderr).toBe(0);+ return h;+}++/** The hermetic CLI env of test/helpers/doctor-json-golden.ts (no network preload when `net` is set). */+function childEnv(h: DoctorHome, extra: Record<string, string | undefined> = {}): Record<string, string> {+ const env: Record<string, string> = {};+ for (const [k, v] of Object.entries(process.env)) if (v !== undefined) env[k] = v;+ for (const k of PROVIDER_ENV_KEYS) delete env[k];+ for (const k of ['DATABASE_URL', 'GBRAIN_DATABASE_URL', 'GBRAIN_REMOTE_CLIENT_SECRET', 'GBRAIN_PGLITE_SNAPSHOT', 'GBRAIN_SKILLS_DIR', 'GBRAIN_SOURCE',+ 'GBRAIN_SERVE_FAIL_FAST', 'CLAUDECODE', 'CLAUDE_CODE_ENTRYPOINT', 'CODEX_SANDBOX', 'CODEX_CI', 'CODEX_HOME', 'OPENCODE', 'OPENCODE_PID', 'XDG_CONFIG_HOME']) delete env[k];+ Object.assign(env, {+ HOME: h.home, GBRAIN_HOME: h.home, GBRAIN_AUDIT_DIR: join(h.home, 'audit'), GBRAIN_SKIP_STARTUP_HOOKS: '1', NO_COLOR: '1',+ PATH: [join(h.home, 'bin'), '/usr/bin', '/bin'].join(delimiter),+ });+ for (const [k, v] of Object.entries(extra)) {+ if (v === undefined) delete env[k];+ else env[k] = v;+ }+ return env;+}++function run(h: DoctorHome, args: string[], env: Record<string, string | undefined> = {}, timeoutMs = 120_000): Promise<GbrainRun> {+ return runGbrain(h, args, env, timeoutMs);+}++/** A CLI run with network allowed (row 5 talks to the local provider stub). */+async function runNet(h: DoctorHome, args: string[], env: Record<string, string | undefined>, timeoutMs = 120_000) {+ const proc = Bun.spawn([process.execPath, '--no-env-file', CLI, ...args], { cwd: h.work, env: childEnv(h, env), stdin: 'ignore', stdout: 'pipe', stderr: 'pipe' });+ const killer = setTimeout(() => proc.kill(9), timeoutMs);+ try {+ const [stdout, stderr, exitCode] = await Promise.all([new Response(proc.stdout).text(), new Response(proc.stderr).text(), proc.exited]);+ return { stdout, stderr, exitCode };+ } finally {+ clearTimeout(killer);+ }+}++function keyPaths(v: unknown, prefix: string, out: Set<string>): Set<string> {+ if (Array.isArray(v)) { for (const el of v) keyPaths(el, `${prefix}[]`, out); return out; }+ if (v && typeof v === 'object') for (const [k, x] of Object.entries(v)) { out.add(`${prefix}.${k}`); keyPaths(x, `${prefix}.${k}`, out); }+ return out;+}++function splitArgs(command: string): string[] {+ const i = command.indexOf(' {');+ return i < 0 ? command.split(' ') : [...command.slice(0, i).split(' '), command.slice(i + 1)];+}++/** Rows of docs/guides/exit-codes.md "Changed in this release" this file proves on the real CLI. */+const RENUMBERED: Record<string, { now: number; docRow: string }> = {+ 'sources remove default --json': { now: 2, docRow: '`gbrain sources remove default` / `gbrain sources archive default`' },+};++describe('(1) existing scripts after the upgrade', () => {+ let h: DoctorHome;+ beforeAll(async () => { h = await upgradedBrain('upgrade-scripts'); }, 180_000);++ test('every --json document a v0.60.37 script parsed: same exit, same error value, every key path still there', async () => {+ const problems: string[] = [];+ for (const [command, old] of Object.entries(FROZEN.commands)) {+ const r = await run(h, splitArgs(command), { GBRAIN_NON_INTERACTIVE: '1' });+ const expectedExit = RENUMBERED[command]?.now ?? old.exit;+ if (r.exitCode !== expectedExit) problems.push(`${command}: exit ${r.exitCode}, a v0.60.37 script expects ${expectedExit}`);+ if (r.json === null) { problems.push(`${command}: stdout is no longer one JSON document: ${r.stdout.slice(0, 200)}`); continue; }+ const now = keyPaths(r.json, '$', new Set());+ const missing = (old.keys ?? []).filter(k => !now.has(k));+ if (missing.length) problems.push(`${command}: lost key paths ${missing.join(', ')}`);+ if (old.error !== undefined && (r.json as { error?: unknown }).error !== old.error) {+ problems.push(`${command}: error ${(r.json as { error?: unknown }).error} (was ${old.error})`);+ }+ }+ expect(problems).toEqual([]);+ }, 300_000);++ test('the renumbered exits are the documented ones, on every lane that reaches them', async () => {+ const changed = readFileSync(join(REPO, 'docs', 'guides', 'exit-codes.md'), 'utf8').split('## Changed in this release')[1] ?? '';+ for (const { now, docRow } of Object.values(RENUMBERED)) expect(changed).toContain(`| ${docRow} | 3 | ${now} |`);+ expect(changed).toContain('| `gbrain call` invalid parameters | 1 | 2 |');++ // Managed sources run through the persistence lane; its caller mistakes exit 2 like every other CLI lane.+ for (const args of [['sources', 'remove', 'default'], ['sources', 'archive', 'default'], ['sources', 'remove', 'default', '--json']]) {+ const r = await run(h, args, { GBRAIN_NON_INTERACTIVE: '1' });+ expect(r.exitCode, `${args.join(' ')}: ${r.stderr}`).toBe(2);+ expect(r.stderr).toContain('Error [invalid_params]');+ }+ const call = await run(h, ['call', 'get_page', '{}'], { GBRAIN_NON_INTERACTIVE: '1' });+ expect(call.exitCode).toBe(2);+ expect(call.json).toMatchObject({ error: 'invalid_params', code: 'invalid_params', contract_version: 1 });+ const notFound = await run(h, ['call', 'get_page', JSON.stringify({ slug: 'no-such-page' })], { GBRAIN_NON_INTERACTIVE: '1' });+ expect(notFound.exitCode).toBe(1);+ }, 180_000);++ test('legacy advice keys stay where old scripts read them, next to the v1 fields', async () => {+ const backup = await run(h, ['backup', 'status', '--json']);+ const assets = (backup.json as { assets: Array<Record<string, unknown>> }).assets;+ expect(assets.length).toBeGreaterThan(0);+ for (const asset of assets) expect('fix_argv' in asset).toBe(true);+ const err = (await run(h, ['call', 'get_page', JSON.stringify({ slug: 'no-such-page' })])).json as Record<string, any>;+ expect(err).toMatchObject({ error: 'page_not_found', code: 'page_not_found' });+ expect(typeof err.suggestion).toBe('string');+ expect(err.fix?.argv).toEqual(['gbrain', 'get', 'no-such-page', '--include-deleted']);+ }, 120_000);+});++describe('(2) scheduled jobs: cron and autopilot invocations, non-TTY', () => {+ let h: DoctorHome;+ beforeAll(async () => { h = await upgradedBrain('upgrade-cron'); }, 180_000);++ test('the one listed flip: doctor --remediate with runnable work now stops for consent (exit 3, nothing submitted)', async () => {+ const table = readFileSync(join(REPO, 'docs', 'protocol', 'AGENT_OPERATOR_v1.md'), 'utf8').split('## Behavior changes for scripts and agents')[1] ?? '';+ expect(table).toContain('| `gbrain doctor --remediate` without a terminal | ran paid and mutating work');+ const r = await run(h, ['doctor', '--remediate', '--target-score', '30', '--json']);+ expect(r.exitCode, r.stdout + r.stderr).toBe(3);+ expect(r.json).toMatchObject({ code: 'confirmation_required', fix: { next: 'ask_user' } });+ const stats = (await run(h, ['jobs', 'stats', '--json'])).json as { by_status: Record<string, number> };+ expect(stats.by_status.waiting ?? 0).toBe(0);+ }, 180_000);++ const CRON: Array<{ args: string[]; json?: true }> = [+ { args: ['dream', '--json'], json: true },+ { args: ['jobs', 'submit', 'autopilot-cycle', '--follow'] },+ { args: ['extract', 'all'] },+ { args: ['embed', '--stale', '--json'], json: true },+ { args: ['jobs', 'work'] },+ { args: ['doctor', '--json'], json: true },+ ];+ for (const row of CRON) {+ test(`gbrain ${row.args.join(' ')} still runs unattended (exit 0, no consent stop)`, async () => {+ const r = await run(h, row.args, {}, 180_000);+ expect(r.exitCode, `${r.stdout.slice(-1500)}\n${r.stderr.slice(-1500)}`).toBe(0);+ expect(r.stdout).not.toContain('confirmation_required');+ expect(r.stderr).not.toContain('[SHOW USER]');+ if (row.json) expect(r.json).not.toBeNull();+ }, 200_000);+ }++ test('dream --json is still the CycleReport a cron log parses', async () => {+ const report = (await run(h, ['dream', '--json'], {}, 180_000)).json as Record<string, unknown>;+ expect(report).toMatchObject({ schema_version: '1' });+ expect(Array.isArray(report.phases)).toBe(true);+ expect(typeof report.status).toBe('string');+ }, 200_000);++});++interface McpSession { client: Client; close: () => Promise<void> }++async function stdioSession(command: string, args: string[], env: Record<string, string>, cwd: string): Promise<McpSession> {+ const transport = new StdioClientTransport({ command, args, env, cwd, stderr: 'pipe' });+ const client = new Client({ name: 'registered-harness', version: '1.0.0' }, { capabilities: {} });+ await client.connect(transport, { timeout: 60_000 });+ return { client, close: () => client.close() };+}++function body(res: unknown): unknown {+ return JSON.parse((res as { content: Array<{ text: string }> }).content[0].text);+}++describe('(3) harness configs registered before the upgrade', () => {+ let h: DoctorHome;+ beforeAll(async () => {+ h = await upgradedBrain('upgrade-harness');+ writeFileSync(join(h.home, 'bin', 'gbrain'), `#!/bin/sh\nexec "${process.execPath}" --no-env-file "${CLI}" "$@"\n`);+ chmodSync(join(h.home, 'bin', 'gbrain'), 0o755);+ }, 180_000);++ const clear = () => {+ rmSync(join(h.home, '.claude.json'), { force: true });+ rmSync(join(h.home, '.codex'), { recursive: true, force: true });+ };++ async function registeredRecall(command: string, args: string[], regEnv: Record<string, string>) {+ const s = await stdioSession(command, args, { ...childEnv(h), ...regEnv }, h.work);+ try {+ const tools = (await s.client.listTools()).tools.map(t => t.name);+ expect(tools).toContain('recall');+ expect(tools).not.toContain('gbrain_status');+ const res = await s.client.callTool({ name: 'recall', arguments: { query: MARKER } }) as { isError?: boolean };+ expect(res.isError).toBeFalsy();+ expect(JSON.stringify(body(res))).toContain(MARKER);+ return tools;+ } finally {+ await s.close();+ }+ }++ function harnessCheck(r: GbrainRun): Record<string, any> {+ const check = (r.json as { checks?: Array<Record<string, any>> } | null)?.checks?.find(c => c.name === 'harness_wiring');+ if (!check) throw new Error(`no harness_wiring check: ${r.stdout.slice(0, 500)} ${r.stderr.slice(0, 500)}`);+ return check;+ }++ test('a pre-surface Claude Code registration (`serve`, no --surface) keeps the full catalog and recalls', async () => {+ clear();+ const regEnv = { GBRAIN_HOME: h.home, GBRAIN_SKIP_STARTUP_HOOKS: '1' };+ writeFileSync(join(h.home, '.claude.json'), JSON.stringify({ mcpServers: { gbrain: { type: 'stdio', command: process.execPath, args: ['--no-env-file', CLI, 'serve'], env: regEnv } } }));+ const tools = await registeredRecall(process.execPath, ['--no-env-file', CLI, 'serve'], regEnv);+ expect(tools).toContain('search');+ const check = harnessCheck(await run(h, ['doctor', '--only', 'harness_wiring', '--json']));+ expect(check).toMatchObject({ status: 'ok', details: { harness: 'claude-code', reason: 'wired_running', smoke: 'smoke_passed' } });+ }, 120_000);++ test('a Codex config.toml registration keeps working and doctor reports it', async () => {+ clear();+ mkdirSync(join(h.home, '.codex'), { recursive: true });+ writeFileSync(join(h.home, '.codex', 'config.toml'), [+ 'model = "gpt-example"', '', '[mcp_servers.gbrain]', `command = ${JSON.stringify(process.execPath)}`,+ `args = ${JSON.stringify(['--no-env-file', CLI, 'serve', '--surface', 'verbs'])}`,+ `env = { GBRAIN_HOME = ${JSON.stringify(h.home)}, GBRAIN_SKIP_STARTUP_HOOKS = "1" }`, '',+ ].join('\n'));+ await registeredRecall(process.execPath, ['--no-env-file', CLI, 'serve', '--surface', 'verbs'], { GBRAIN_HOME: h.home, GBRAIN_SKIP_STARTUP_HOOKS: '1' });+ const check = harnessCheck(await run(h, ['doctor', '--only', 'harness_wiring', '--json']));+ expect(check, JSON.stringify(check)).toMatchObject({ status: 'ok', details: { harness: 'codex', reason: 'wired_running', smoke: 'smoke_passed' } });+ }, 120_000);++ test('a bare `gbrain serve` registration still answers on a PATH that has gbrain; doctor flags it with the rewire fix', async () => {+ clear();+ writeFileSync(join(h.home, '.claude.json'), JSON.stringify({ mcpServers: { gbrain: { command: 'gbrain', args: ['serve'] } } }));+ await registeredRecall('gbrain', ['serve'], {});+ const check = harnessCheck(await run(h, ['doctor', '--only', 'harness_wiring', '--json']));+ expect(check).toMatchObject({ status: 'warn', details: { harness: 'claude-code', reason: 'bare_binary' } });+ expect(check.fix?.argv?.[0] ?? check.fix_unavailable_reason, JSON.stringify(check)).toBeTruthy();+ }, 120_000);+});++describe('(4) an old thin client against a real new serve --http', () => {+ let h: DoctorHome;+ let server: ChildProcess | null = null;+ let rw = '';+ let ro = '';+ const PORT = 44000 + Math.floor(Math.random() * 2000);+ const URL_ = `http://127.0.0.1:${PORT}/mcp`;++ beforeAll(async () => {+ h = await upgradedBrain('upgrade-thin-client');+ const token = async (name: string, scopes: string) => {+ const r = await run(h, ['auth', 'create', name, '--scopes', scopes]);+ expect(r.exitCode, r.stderr).toBe(0);+ return (r.stdout.match(/gbrain_[a-f0-9]{64}/) ?? [''])[0];+ };+ rw = await token('old-thin-client', 'read,write');+ ro = await token('old-thin-reader', 'read');+ expect(rw && ro).toBeTruthy();+ server = spawn(process.execPath, ['--no-env-file', CLI, 'serve', '--http', '--bind', '127.0.0.1', '--port', String(PORT)],+ { cwd: h.work, env: childEnv(h), stdio: ['ignore', 'ignore', 'ignore'] });+ const end = Date.now() + 60_000;+ while (Date.now() < end) {+ if ((await fetch(`http://127.0.0.1:${PORT}/health`).catch(() => null))?.ok) return;+ await Bun.sleep(500);+ }+ throw new Error('serve --http never became healthy');+ }, 180_000);++ afterAll(async () => {+ if (!server) return;+ server.kill('SIGTERM');+ await new Promise(r => server!.once('exit', r));+ });++ /** The old client's wire: SDK Client + StreamableHTTP with the bearer it minted. */+ async function oldClient(token: string): Promise<Client> {+ const client = new Client({ name: 'gbrain-thin-client', version: '0.60.37.0' }, { capabilities: {} });+ await client.connect(new StreamableHTTPClientTransport(new URL(URL_), { requestInit: { headers: { Authorization: `Bearer ${token}` } } }));+ return client;+ }++ test('success bodies: the old content[0]-only parse still gets the result, notice blocks or not', async () => {+ const c = await oldClient(rw);+ try {+ const res = await c.callTool({ name: 'search', arguments: { query: MARKER } }) as { content: Array<{ type: string; text: string }> };+ expect(res.content.length).toBeGreaterThan(1);+ const rows = oldUnpack(res) as Array<{ slug: string }>;+ expect(Array.isArray(rows)).toBe(true);+ expect(rows.map(r => r.slug).sort()).toEqual(['alpha', 'beta', 'gamma']);+ } finally {+ await c.close();+ }+ }, 60_000);++ test('error results: one block, and the old join-all parse reads the v0.60.37 error value and a suggestion', async () => {+ const c = await oldClient(rw);+ const reader = await oldClient(ro);+ try {+ const cases: Array<[Client, string, Record<string, unknown>, string]> = [+ [c, 'get_page', {}, 'invalid_params'],+ [c, 'get_page', { slug: 'no-such-page' }, 'page_not_found'],+ [c, 'no_such_tool', {}, 'unknown_operation'],+ [reader, 'put_page', { slug: 'notes/x', content: 'x' }, 'insufficient_scope'],+ ];+ for (const [client, name, args, oldCode] of cases) {+ const res = await client.callTool({ name, arguments: args }) as { isError?: boolean; content: Array<{ text: string }> };+ expect(res.isError, name).toBe(true);+ expect(res.content).toHaveLength(1);+ const old = oldReadError(res);+ expect(old.code, name).toBe(oldCode);+ expect(typeof old.suggestion, name).toBe('string');+ }+ const unknown = await c.callTool({ name: 'no_such_tool', arguments: {} }) as { content: Array<{ text: string }> };+ expect(extractToolErrorDetail(unknown.content[0].text)).toMatchObject({ code: 'unknown_operation', canonical_code: 'unknown_tool' });+ const denied = JSON.parse((await reader.callTool({ name: 'remember', arguments: { fact: 'x' } }) as { content: Array<{ text: string }> }).content[0].text);+ expect(denied).toMatchObject({ error: 'insufficient_scope', code: 'insufficient_scope', your_scopes: ['read'] });+ expect(denied.fix?.argv?.slice(0, 3)).toEqual(['gbrain', 'auth', 'rescope-token']);+ } finally {+ await c.close();+ await reader.close();+ }+ }, 60_000);+});++describe('(5) jobs queued before the upgrade run under the configured budget', () => {+ let h: DoctorHome;+ let provider: ReturnType<typeof Bun.serve>;+ let embeddingCalls = 0;+ let env: Record<string, string>;++ beforeAll(async () => {+ provider = Bun.serve({+ hostname: '127.0.0.1', port: 0, async fetch(request) {+ if (request.method === 'GET') return Response.json({ data: [{ id: 'text-embedding-3-small' }] });+ const payload = await request.json() as { input: string | string[] };+ const input = Array.isArray(payload.input) ? payload.input : [payload.input];+ embeddingCalls += 1;+ return Response.json({+ object: 'list', model: 'text-embedding-3-small',+ data: input.map((_, index) => ({ object: 'embedding', index, embedding: Array.from({ length: 1536 }, (_, i) => (i === index % 1536 ? 1 : 0)) })),+ usage: { prompt_tokens: 8 * input.length, total_tokens: 8 * input.length },+ });+ },+ });+ env = { OPENAI_API_KEY: 'synthetic-upgrade-fixture', OPENAI_BASE_URL: `http://127.0.0.1:${provider.port}/v1` };+ h = makeDoctorHome('upgrade-queued-jobs');+ homes.push(h);+ rmSync(h.skillsDir, { recursive: true, force: true });+ const init = await runNet(h, ['init', '--pglite', '--embedding-model', 'openai:text-embedding-3-small', '--embedding-dimensions', '1536', '--non-interactive'], env);+ expect(init.exitCode, init.stderr).toBe(0);+ const notes = join(h.home, 'notes');+ mkdirSync(notes, { recursive: true });+ for (const n of ['alpha', 'beta', 'gamma']) writeFileSync(join(notes, `${n}.md`), `---\ntitle: ${n} note\n---\n\n# ${n} note\n\nThe ${MARKER} ${n} fact lives here.\n`);+ const imported = await runNet(h, ['import', notes, '--no-embed'], env);+ expect(imported.exitCode, imported.stderr).toBe(0);+ }, 180_000);++ afterAll(() => { provider?.stop(true); });++ /**+ * The waiting row a v0.60.37 `gbrain jobs submit embed-backfill --follow` admitted on PGLite (its only queue+ * path there) and left behind when the process died before the inline claim: name and params only, no+ * submit-time authorization on it.+ */+ async function queuePreUpgradeRow(): Promise<number> {+ const engine = new PGLiteEngine();+ await engine.connect({ engine: 'pglite', database_path: join(h.home, '.gbrain', 'brain.pglite') });+ try {+ const job = await new MinionQueue(engine).add('embed-backfill', { sourceId: 'default' }, { queue: 'default' }, { allowPgliteInlineWorker: true });+ const [row] = await engine.executeRaw<{ data: Record<string, unknown> }>('SELECT data FROM minion_jobs WHERE id = $1', [job.id]);+ expect(row.data).toEqual({ sourceId: 'default' });+ return job.id;+ } finally {+ await engine.disconnect();+ }+ }++ async function jobRow(id: number): Promise<{ status: string; result: Record<string, any>; error_text: string | null }> {+ const engine = new PGLiteEngine();+ await engine.connect({ engine: 'pglite', database_path: join(h.home, '.gbrain', 'brain.pglite') });+ try {+ const [row] = await engine.executeRaw<{ status: string; result: Record<string, any>; error_text: string | null }>('SELECT status, result, error_text FROM minion_jobs WHERE id = $1', [id]);+ return row;+ } finally {+ await engine.disconnect();+ }+ }++ test('a configured cap below the work stops every provider call at the cap; the job is not refused for consent', async () => {+ expect((await runNet(h, ['config', 'set', 'embed.backfill_max_usd', '0.00000001'], env)).exitCode).toBe(0);+ const id = await queuePreUpgradeRow();+ const before = embeddingCalls;+ const worker = await runNet(h, ['jobs', 'work'], env, 180_000);+ expect(worker.exitCode, worker.stderr.slice(-2000)).toBe(0);+ expect(worker.stdout + worker.stderr).not.toContain('confirmation_required');+ expect(worker.stderr).toContain('embed-backfill:default: projected cost');+ expect(embeddingCalls).toBe(before);+ const row = await jobRow(id);+ expect(row.status, `${row.error_text}\n${worker.stderr.slice(-2000)}`).not.toBe('completed');+ expect(row.error_text).toContain('embed-backfill: incomplete');+ const cancelled = await runNet(h, ['jobs', 'cancel', String(id)], env);+ expect(cancelled.exitCode, cancelled.stderr).toBe(0);+ }, 240_000);++ test('a configured cap that covers the work runs it to completion', async () => {+ expect((await runNet(h, ['config', 'set', 'embed.backfill_max_usd', '1'], env)).exitCode).toBe(0);+ const id = await queuePreUpgradeRow();+ const worker = await runNet(h, ['jobs', 'work'], env, 180_000);+ expect(worker.exitCode, worker.stderr.slice(-2000)).toBe(0);+ const row = await jobRow(id);+ expect(row.status).toBe('completed');+ expect(row.result.status).toBe('success');+ expect(row.result.embedded).toBeGreaterThan(0);+ expect(row.result.spentUsd).toBeLessThanOrEqual(1);+ expect(embeddingCalls).toBeGreaterThan(0);+ }, 240_000);+});diff --git a/test/e2e/agent-journey-postgres.test.ts b/test/e2e/agent-journey-postgres.test.tsnew file mode 100644index 0000000000..6802d24931--- /dev/null+++ b/test/e2e/agent-journey-postgres.test.ts@@ -0,0 +1,353 @@+/**+ * Agent operator wave H4: Postgres parity for the DB-backed asserts of the H1+ * keyless journey (docs/designs/AGENT_OPERATOR_WAVE.md, Lane H).+ *+ * Each describe gets its own scratch database on the DATABASE_URL server+ * (`gbrain_test_agent_journey_<uuid>`, dropped afterwards) and a hermetic+ * HOME = GBRAIN_HOME from test/helpers/doctor-json-golden.ts (provider keys+ * removed, `fetch` refused by the no-network preload, non-TTY, stdin closed).+ * Every step is the real CLI (`bun --no-env-file src/cli.ts …`) or a real+ * stdio MCP session through @modelcontextprotocol/sdk, with hard timeouts.+ *+ * Journey on Postgres + pgvector, keyless:+ * init --url --no-embedding --json (one document, the decision bundle)+ * → day-zero doctor --json: zero warn/fail, health ≥ 90, capped_by+ * → import 3 pages+ * → doctor --remediate without authorization on a pending-migration+ * fixture: exit 3, confirmation_required (ask_user), nothing submitted,+ * no page changed, schema version unchanged (observational startup)+ * → stdio serve on `verbs` and `full`: handshake with the full catalog (no+ * status-only tool: that mode is PGLite-lock specific), the degraded+ * recall notice as a separate `[gbrain notice ` block + _meta.gbrain_notices+ * with content[0] still the bare result, caller mistakes as one isError+ * block (invalid_params: class, docs_cmd and an example call; a missing+ * page: a runnable `fix` with the MCP re-invocation), the stdio wire value+ * for an unknown tool unchanged from v0.60.37, readiness on+ * gbrain://capabilities+ * → doctor: agent_contract (E11) warns about the refused unattended run with+ * the preapproval fix; with that engine-independent log set aside, health+ * ≥ 90 with capped_by.+ * Postgres readiness (F4 keeps the existing degraded-serve path for Postgres):+ * a serve whose database does not exist yet completes the handshake, every+ * tool call returns one classified isError block with a fix, and once the+ * database exists (`gbrain init`, the fix) the same session recovers and+ * recalls without a restart.+ *+ * Tier 1 (no API keys). Skips without DATABASE_URL.+ * Run: DATABASE_URL=... bun test test/e2e/agent-journey-postgres.test.ts+ */+import { afterAll, describe, expect, test } from 'bun:test';+import { randomUUID } from 'node:crypto';+import { mkdirSync, renameSync, rmSync, writeFileSync } from 'node:fs';+import { join } from 'node:path';+import { Client } from '@modelcontextprotocol/sdk/client/index.js';+import { StdioClientTransport } from '@modelcontextprotocol/sdk/client/stdio.js';+import postgres from '#postgres';+import { assertSafeE2eDatabaseUrl } from '../helpers/db-guard.ts';+import { makeDoctorHome, networkAttempts, runGbrain, type DoctorHome, type GbrainRun } from '../helpers/doctor-json-golden.ts';+import { PROVIDER_ENV_KEYS } from '../helpers/provider-env.ts';++const DATABASE_URL = process.env.DATABASE_URL;+const describeE2E = DATABASE_URL ? describe : describe.skip;+if (!DATABASE_URL) console.log('Skipping E2E agent journey on Postgres (DATABASE_URL not set)');++const CLI = join(import.meta.dir, '..', '..', 'src', 'cli.ts');+const PRELOAD = join(import.meta.dir, '..', 'helpers', 'no-network-preload.ts');+const MARKER = 'zelkova-pg-journey-7k2';+const NOTICE_PREFIX = '[gbrain notice ';++const homes: DoctorHome[] = [];+const drops: Array<() => Promise<void>> = [];+afterAll(async () => {+ for (const drop of drops) await drop();+ for (const h of homes) h.cleanup();+});++function admin() {+ return postgres(DATABASE_URL!, { max: 1, prepare: false });+}++/** A scratch database name on the DATABASE_URL server; `create` false leaves it absent. */+async function scratchDatabase(create = true): Promise<{ name: string; url: string; sql: ReturnType<typeof postgres> }> {+ assertSafeE2eDatabaseUrl(DATABASE_URL!);+ const name = `gbrain_test_agent_journey_${randomUUID().replaceAll('-', '')}`;+ const sql = admin();+ if (create) await sql.unsafe(`CREATE DATABASE ${name}`);+ const url = new URL(DATABASE_URL!);+ url.pathname = `/${name}`;+ drops.push(async () => {+ try { await sql.unsafe(`DROP DATABASE IF EXISTS ${name} WITH (FORCE)`); } finally { await sql.end(); }+ });+ return { name, url: url.toString(), sql };+}++async function brainQuery<T>(url: string, fn: (sql: ReturnType<typeof postgres>) => Promise<T>): Promise<T> {+ const sql = postgres(url, { max: 1, prepare: false });+ try { return await fn(sql); } finally { await sql.end(); }+}++function doc(run: GbrainRun): Record<string, any> {+ if (run.json === null || typeof run.json !== 'object') {+ throw new Error(`gbrain ${run.args.join(' ')} (exit ${run.exitCode}) did not print one JSON document.\nstdout: ${run.stdout.slice(0, 2000)}\nstderr: ${run.stderr.slice(0, 2000)}`);+ }+ return run.json as Record<string, any>;+}++function notOk(report: Record<string, any>): string[] {+ return (report.checks as Array<{ name: string; status: string; message: string }>)+ .filter(c => c.status !== 'ok').map(c => `${c.name} ${c.status}: ${c.message}`);+}++/** The hermetic child env runGbrain uses, for the MCP serve child. */+function serveEnv(h: DoctorHome): Record<string, string> {+ const env: Record<string, string> = {};+ for (const [k, v] of Object.entries(process.env)) if (v !== undefined) env[k] = v;+ for (const k of PROVIDER_ENV_KEYS) delete env[k];+ for (const k of ['DATABASE_URL', 'GBRAIN_DATABASE_URL', 'GBRAIN_REMOTE_CLIENT_SECRET', 'GBRAIN_PGLITE_SNAPSHOT', 'GBRAIN_SKILLS_DIR', 'GBRAIN_SOURCE',+ 'GBRAIN_SERVE_FAIL_FAST', 'GBRAIN_SERVE_DEGRADED', 'CLAUDECODE', 'CLAUDE_CODE_ENTRYPOINT', 'CODEX_SANDBOX', 'CODEX_CI', 'CODEX_HOME', 'OPENCODE', 'OPENCODE_PID']) delete env[k];+ Object.assign(env, {+ HOME: h.home, GBRAIN_HOME: h.home, GBRAIN_AUDIT_DIR: join(h.home, 'audit'), GBRAIN_SKIP_STARTUP_HOOKS: '1',+ GBRAIN_TEST_NET_LOG: h.netLog, NO_COLOR: '1', GBRAIN_NO_RETRY_CONNECT: '1',+ });+ return env;+}++interface Session { client: Client; stderr: () => string; initializeMs: number }++async function openServe(h: DoctorHome, surface: string): Promise<Session> {+ const transport = new StdioClientTransport({+ command: process.execPath, args: ['--no-env-file', '--preload', PRELOAD, CLI, 'serve', '--surface', surface],+ cwd: h.work, env: serveEnv(h), stderr: 'pipe',+ });+ let stderr = '';+ transport.stderr?.on('data', (d: Buffer) => { stderr += d.toString(); });+ const client = new Client({ name: 'agent-journey-postgres', version: '1.0.0' }, { capabilities: {} });+ const started = Date.now();+ await client.connect(transport, { timeout: 60_000 });+ return { client, stderr: () => stderr, initializeMs: Date.now() - started };+}++type ToolResult = { content: Array<{ type: string; text: string }>; isError?: boolean; _meta?: Record<string, unknown> };++async function call(s: Session, name: string, args: Record<string, unknown>): Promise<ToolResult> {+ return await s.client.callTool({ name, arguments: args }, undefined, { timeout: 60_000 }) as ToolResult;+}++function expectOneBlockError(res: ToolResult, label: string): Record<string, any> {+ expect(res.isError, `${label}: ${JSON.stringify(res).slice(0, 800)}`).toBe(true);+ expect(res.content).toHaveLength(1);+ const env = JSON.parse(res.content[0].text) as Record<string, any>;+ expect(typeof env.error).toBe('string');+ expect(typeof env.code).toBe('string');+ expect(env.contract_version).toBe(1);+ return env;+}++function expectDegradedNotice(res: ToolResult, label: string): void {+ expect(res.isError, label).toBeFalsy();+ expect(res.content[0].text.startsWith(NOTICE_PREFIX), `${label}: content[0] must stay the bare result`).toBe(false);+ const blocks = res.content.slice(1).filter(c => c.text.startsWith(NOTICE_PREFIX));+ expect(blocks.some(b => b.text.startsWith(`${NOTICE_PREFIX}degraded_recall kind=degraded]`)), `${label}: ${JSON.stringify(res.content.map(c => c.text.slice(0, 80)))}`).toBe(true);+ const meta = (res._meta?.gbrain_notices ?? []) as Array<{ code: string; kind: string; contract_version: number }>;+ expect(meta.some(n => n.code === 'degraded_recall' && n.kind === 'degraded' && n.contract_version === 1)).toBe(true);+}++describeE2E('H4: keyless agent journey on Postgres', () => {+ let h: DoctorHome;+ let db: { name: string; url: string };+ const timings: Record<string, number> = {};++ test('init --url --no-embedding --json prints one document with the decision bundle', async () => {+ db = await scratchDatabase();+ h = makeDoctorHome('agent-journey-pg');+ homes.push(h);+ // A first install has no skills workspace in HOME (test/doctor-day-zero.serial.test.ts does the same).+ rmSync(h.skillsDir, { recursive: true, force: true });+ const started = Date.now();+ const init = await runGbrain(h, ['init', '--non-interactive', '--url', db.url, '--no-embedding', '--json'], {}, 120_000);+ timings.init_ms = Date.now() - started;+ expect(init.exitCode, init.stderr).toBe(0);+ const out = doc(init);+ expect(out).toMatchObject({ status: 'success', engine: 'postgres', contract_version: 1 });+ const bundle = (out.notices as Array<Record<string, any>>).find(n => n.code === 'first_run_decisions');+ expect(bundle).toMatchObject({ kind: 'ask', contract_version: 1 });+ expect((bundle!.decisions as Array<{ id: string }>).map(d => d.id)).toContain('search_mode');+ }, 180_000);++ test('day-zero doctor --json: no warn or fail, health ≥ 90, capped_by names the keyless cap', async () => {+ const run = await runGbrain(h, ['doctor', '--json']);+ const report = doc(run);+ expect(report.engine).toBe('postgres');+ expect(notOk(report)).toEqual([]);+ expect(report.health_score).toBeGreaterThanOrEqual(90);+ expect(report.capped_by).toContain('embeddings_disabled');+ expect(networkAttempts(h)).toEqual([]);+ }, 180_000);++ test('import 3 pages', async () => {+ const notes = join(h.home, 'notes');+ mkdirSync(notes, { recursive: true });+ for (const n of ['alpha', 'beta', 'gamma']) {+ writeFileSync(join(notes, `${n}.md`), `---\ntitle: ${n} note\n---\n\n# ${n} note\n\nThe ${MARKER} ${n} fact lives here.\n`);+ }+ const run = await runGbrain(h, ['import', notes, '--no-embed']);+ expect(run.exitCode, run.stderr).toBe(0);+ expect(run.stdout).toContain('3 pages imported');+ const [{ n }] = await brainQuery(db.url, sql => sql`SELECT count(*)::int AS n FROM pages`);+ expect(n).toBe(3);+ }, 120_000);++ test('doctor --remediate without authorization on a pending-migration brain: exit 3, nothing runs, schema version unchanged', async () => {+ const latest = await brainQuery(db.url, sql => sql`SELECT value FROM config WHERE key = 'version'`);+ const pending = String(Number(latest[0].value) - 3);+ await brainQuery(db.url, sql => sql`UPDATE config SET value = ${pending} WHERE key = 'version'`);+ const snapshot = () => brainQuery(db.url, async sql => JSON.stringify({+ pages: await sql`SELECT slug, content_hash, updated_at::text AS u FROM pages ORDER BY slug`,+ links: await sql`SELECT count(*)::int AS n FROM links`,+ timeline: await sql`SELECT count(*)::int AS n FROM timeline_entries`,+ jobs: await sql`SELECT count(*)::int AS n FROM minion_jobs`,+ version: await sql`SELECT value FROM config WHERE key = 'version'`,+ }));+ const before = await snapshot();+ // The keyless ceiling caps the default target 90; a reachable target makes the extract step runnable.+ const run = await runGbrain(h, ['doctor', '--remediate', '--target-score', '30', '--json'], { GBRAIN_NON_INTERACTIVE: '1' });+ expect(run.exitCode, `${run.stdout}\n${run.stderr}`).toBe(3);+ const payload = doc(run);+ expect(payload).toMatchObject({ status: 'confirmation_required', error: 'confirmation_required', code: 'confirmation_required', actor: 'agent', contract_version: 1 });+ expect(payload.effects).toContain('paid');+ expect(payload.fix.next).toBe('ask_user');+ expect(payload.fix.argv).toContain('--yes');+ expect(typeof payload.user_message).toBe('string');+ expect(await snapshot()).toBe(before);+ expect((await brainQuery(db.url, sql => sql`SELECT value FROM config WHERE key = 'version'`))[0].value).toBe(pending);++ // What the refusal asked about is real: the plan has a runnable step at that target.+ // (`--remediation-plan` is not observational: its normal startup applies the pending migrations.)+ const plan = doc(await runGbrain(h, ['doctor', '--remediation-plan', '--target-score', '30', '--json']));+ expect(plan.target_unreachable).toBe(false);+ expect((plan.plan as Array<{ id: string }>).map(step => step.id)).toContain('extract.stale');++ // Doctor's normal (non-observational) startup leaves the schema current.+ const migrated = await runGbrain(h, ['doctor', '--json']);+ expect(migrated.exitCode, migrated.stderr).toBe(0);+ expect((await brainQuery(db.url, sql => sql`SELECT value FROM config WHERE key = 'version'`))[0].value).toBe(latest[0].value);+ }, 240_000);++ for (const surface of ['verbs', 'full'] as const) {+ test(`stdio serve --surface ${surface}: handshake, degraded notice channel, one-block caller mistake with fix, readiness`, async () => {+ const s = await openServe(h, surface);+ try {+ timings[`initialize_${surface}_ms`] = s.initializeMs;+ expect(s.client.getServerVersion()?.name).toBeTruthy();+ const instructions = s.client.getInstructions() ?? '';+ expect(instructions).toContain(NOTICE_PREFIX.trim());+ const tools = (await s.client.listTools()).tools.map(t => t.name);+ expect(tools).toContain('recall');+ expect(tools).not.toContain('gbrain_status');+ if (surface === 'verbs') expect(tools).not.toContain('search');+ else expect(tools).toContain('search');++ const op = surface === 'verbs' ? 'recall' : 'search';+ const started = Date.now();+ const found = await call(s, op, { query: MARKER });+ timings[`first_${op}_${surface}_ms`] = Date.now() - started;+ expectDegradedNotice(found, `${surface} ${op}`);+ const body = JSON.parse(found.content[0].text);+ expect(JSON.stringify(body)).toContain(MARKER);+ if (op === 'search') expect(Array.isArray(body)).toBe(true);+ const again = await call(s, op, { query: MARKER });+ expect(again.content.some(c => c.text.startsWith(`${NOTICE_PREFIX}degraded_recall`)), 'stdio delivers the degraded notice once per session').toBe(false);++ const mistake = expectOneBlockError(await call(s, op, { query: 5 }), `${surface} ${op} with a non-string query`);+ expect(mistake).toMatchObject({ code: 'invalid_params', class: 'caller', retryable: false, docs_cmd: ['gbrain', 'errors', 'invalid_params'] });+ expect(mistake.suggestion).toContain(`Example: ${op} {"query": `);++ if (surface === 'full') {+ const missing = expectOneBlockError(await call(s, 'get_page', { slug: 'h4-no-such-page' }), 'get_page on a missing slug');+ expect(missing.code).toBe('page_not_found');+ expect(missing.fix).toMatchObject({ next: 'run', actor: 'agent', consent: [], mcp: { tool: 'get_page', arguments: { slug: 'h4-no-such-page', include_deleted: true } } });+ const followed = await call(s, missing.fix.mcp.tool, missing.fix.mcp.arguments);+ expect(expectOneBlockError(followed, 'the fix, followed').code).toBe('page_not_found');+ }++ // stdio keeps the v0.60.37 wire value for an unknown tool (HTTP's frozen value is unknown_operation).+ const unknown = expectOneBlockError(await call(s, 'no_such_tool_h4', {}), 'unknown tool');+ expect(unknown.error).toBe('unknown_tool');+ expect(unknown.code).toBe('unknown_tool');++ const caps = await s.client.readResource({ uri: 'gbrain://capabilities' });+ const capabilities = JSON.parse((caps.contents[0] as { text: string }).text) as Record<string, any>;+ expect(Array.isArray(capabilities.readiness)).toBe(true);+ const embeddings = (capabilities.readiness as Array<Record<string, any>>).find(r => /embed/.test(String(r.capability ?? r.id ?? r.name)));+ expect(embeddings, JSON.stringify(capabilities.readiness)).toBeDefined();+ } finally {+ await s.client.close();+ }+ expect(networkAttempts(h)).toEqual([]);+ }, 180_000);+ }++ test('after the journey: E11 recorded the refusal; health ≥ 90 with capped_by; timings recorded', async () => {+ const report = doc(await runGbrain(h, ['doctor', '--json']));+ const contract = (report.checks as Array<Record<string, any>>).find(c => c.name === 'agent_contract')!;+ expect(contract.status).toBe('warn');+ expect(contract.message).toContain('doctor --remediate×1');+ expect(contract.fix).toMatchObject({ actor: 'user', consent: ['paid'] });+ expect(contract.fix.argv.slice(0, 3)).toEqual(['gbrain', 'config', 'set']);+ // The E11 log is a GBRAIN_HOME file (engine-independent) and keeps that deliberate refusal as a warn for 7 days;+ // the brain's own health is scored with it set aside.+ const events = join(h.home, '.gbrain', 'agent-contract', 'events.jsonl');+ renameSync(events, `${events}.journey`);+ try {+ const brain = doc(await runGbrain(h, ['doctor', '--json']));+ expect(brain.health_score, notOk(brain).join('\n')).toBeGreaterThanOrEqual(90);+ expect(brain.capped_by).toContain('embeddings_disabled');+ } finally {+ renameSync(`${events}.journey`, events);+ }+ for (const key of ['init_ms', 'initialize_verbs_ms', 'initialize_full_ms']) expect(timings[key]).toBeGreaterThan(0);+ console.log(`[agent-journey-postgres] timings ${JSON.stringify(timings)}`);+ }, 180_000);+});++describeE2E('H4: Postgres serve readiness keeps the degraded-serve path', () => {+ test('a database that does not exist yet: handshake, classified one-block errors with a fix, recovery in place after init', async () => {+ const db = await scratchDatabase(false);+ const h = makeDoctorHome('agent-journey-pg-degraded');+ homes.push(h);+ mkdirSync(join(h.home, '.gbrain'), { recursive: true });+ writeFileSync(join(h.home, '.gbrain', 'config.json'), JSON.stringify({ engine: 'postgres', database_url: db.url, embedding_disabled: true }));++ const s = await openServe(h, 'verbs');+ try {+ const tools = (await s.client.listTools()).tools.map(t => t.name);+ expect(tools).toContain('recall');+ expect(tools).not.toContain('gbrain_status');+ const down = expectOneBlockError(await call(s, 'recall', { query: MARKER }), 'recall on a missing database');+ expect(down).toMatchObject({ error: 'unavailable', code: 'unavailable', reason: 'db_missing', protocol_version: 1 });+ // A1 surface rule: a CLI-only fix over stdio is the user's to run on this machine (host_admin is HTTP's actor).+ expect(down.fix).toMatchObject({ argv: ['gbrain', 'db-repair'], actor: 'user', next: 'tell_user_to_run' });+ expect(JSON.stringify(down)).not.toContain(db.url);++ await db.sql.unsafe(`CREATE DATABASE ${db.name}`);+ const init = await runGbrain(h, ['init', '--non-interactive', '--url', db.url, '--no-embedding']);+ expect(init.exitCode, init.stderr).toBe(0);+ const remembered = await (async () => {+ const end = Date.now() + 60_000;+ let last: ToolResult | null = null;+ while (Date.now() < end) {+ last = await call(s, 'remember', { fact: `${MARKER} survives a database outage`, provenance: 'agent-journey-postgres' });+ if (!last.isError) return last;+ await Bun.sleep(1_000);+ }+ throw new Error(`the degraded serve never recovered: ${JSON.stringify(last).slice(0, 800)}\n${s.stderr().slice(-2000)}`);+ })();+ expect(remembered.isError).toBeFalsy();+ const recalled = await call(s, 'recall', { query: MARKER });+ expect(recalled.isError).toBeFalsy();+ expect(recalled.content[0].text).toContain(MARKER);+ } finally {+ await s.client.close();+ }+ }, 240_000);+});diff --git a/test/fixtures/agent-contract/v0.60.37-json-documents.json b/test/fixtures/agent-contract/v0.60.37-json-documents.jsonnew file mode 100644index 0000000000..2957943a2f--- /dev/null+++ b/test/fixtures/agent-contract/v0.60.37-json-documents.json@@ -0,0 +1,247 @@+{+ "_provenance": "Captured from gbrain v0.60.37.0 (master 109b9921, the release before the agent operator wave) by running each command non-interactively in the hermetic env of test/agent-journey-upgrade.serial.test.ts (keyless PGLite brain: init --pglite --no-embedding, three imported notes). keys: every JSON key path the old document had (\"$\" root, \"[]\" array elements; doctor and dream to depth 2, the rest to depth 3). exit: the old exit code. error: the old top-level error value. Never edit by hand: a script written against v0.60.37.0 reads these; the new release may only add.",+ "commands": {+ "doctor --json": {+ "exit": 0,+ "keys": [+ "$.brain_checks_score",+ "$.category_scores",+ "$.category_scores.brain",+ "$.category_scores.meta",+ "$.category_scores.ops",+ "$.category_scores.skill",+ "$.checks",+ "$.checks[].category",+ "$.checks[].details",+ "$.checks[].message",+ "$.checks[].name",+ "$.checks[].status",+ "$.db_url_source",+ "$.engine",+ "$.health_score",+ "$.schema_version",+ "$.status",+ "$.top_issues",+ "$.top_issues[].fix",+ "$.top_issues[].name",+ "$.top_issues[].status",+ "$.top_issues[].tier"+ ]+ },+ "backup status --json": {+ "exit": 1,+ "keys": [+ "$.assets",+ "$.assets[].detail",+ "$.assets[].fix_argv",+ "$.assets[].id",+ "$.assets[].kind",+ "$.assets[].state",+ "$.checked_at",+ "$.computed_by",+ "$.gbrain_version",+ "$.interval_days",+ "$.overall",+ "$.recovery",+ "$.recovery.pages_at_risk",+ "$.recovery.recoverable_repos",+ "$.recovery.statement",+ "$.recovery_scope",+ "$.remote_check_at",+ "$.schema_version",+ "$.totals",+ "$.totals.assets",+ "$.totals.configured_repos",+ "$.totals.failing",+ "$.totals.no_remote",+ "$.totals.pages_at_risk",+ "$.totals.recoverable_repos",+ "$.totals.unpushed"+ ]+ },+ "jobs stats --json": {+ "exit": 0,+ "keys": [+ "$.by_status",+ "$.by_type",+ "$.divergent",+ "$.queue",+ "$.queue_health",+ "$.queue_health.active",+ "$.queue_health.stalled",+ "$.queue_health.waiting",+ "$.ttl_cancelled_24h",+ "$.wedge",+ "$.wedge.active_healthy",+ "$.wedge.last_completed_at",+ "$.wedge.minutes_since_completion",+ "$.wedge.queue",+ "$.wedge.waiting"+ ]+ },+ "sources list --json": {+ "exit": 0,+ "keys": [+ "$.sources",+ "$.sources[].federated",+ "$.sources[].id",+ "$.sources[].last_sync_at",+ "$.sources[].local_path",+ "$.sources[].mirror_read_only",+ "$.sources[].name",+ "$.sources[].page_count"+ ]+ },+ "search zelkova-upgrade-fixture --json": {+ "exit": 0,+ "keys": [+ "$[].base_score",+ "$[].chunk_id",+ "$[].chunk_index",+ "$[].chunk_source",+ "$[].chunk_text",+ "$[].create_safety",+ "$[].effective_date",+ "$[].effective_date_source",+ "$[].evidence",+ "$[].id",+ "$[].keyword_hit",+ "$[].page_id",+ "$[].score",+ "$[].slug",+ "$[].source_id",+ "$[].stale",+ "$[].title",+ "$[].type"+ ]+ },+ "autopilot --status --json": {+ "exit": 0,+ "keys": [+ "$.disabled_reason",+ "$.heartbeat_age_seconds",+ "$.install_target",+ "$.installed",+ "$.job",+ "$.job.cron_marker",+ "$.job.install_id_path",+ "$.job.installed_definition",+ "$.job.kind",+ "$.job.launchd_label",+ "$.job.log_path",+ "$.job.needs_reinstall",+ "$.job.shared_job_of_other_brain",+ "$.job.start_script",+ "$.job.suffix",+ "$.job.systemd_unit",+ "$.job.wrapper_path",+ "$.last_log",+ "$.paused_reason",+ "$.stale_after_seconds",+ "$.state"+ ]+ },+ "google status --json": {+ "exit": 1,+ "keys": [+ "$.accounts",+ "$.client_on_file",+ "$.linked_sources",+ "$.ok",+ "$.status"+ ]+ },+ "features --json": {+ "exit": 0,+ "keys": [+ "$.brain_score",+ "$.recommendations",+ "$.recommendations[].auto_fixable",+ "$.recommendations[].command",+ "$.recommendations[].id",+ "$.recommendations[].pitch",+ "$.recommendations[].priority",+ "$.recommendations[].title",+ "$.scan_ts",+ "$.version"+ ]+ },+ "dream --json": {+ "exit": 0,+ "keys": [+ "$.brain_dir",+ "$.duration_ms",+ "$.phases",+ "$.phases[].details",+ "$.phases[].duration_ms",+ "$.phases[].pages_recomputed",+ "$.phases[].phase",+ "$.phases[].status",+ "$.phases[].summary",+ "$.schema_version",+ "$.status",+ "$.timestamp",+ "$.totals",+ "$.totals.backlinks_added",+ "$.totals.consolidate_takes_written",+ "$.totals.edges_ambiguous",+ "$.totals.edges_resolved",+ "$.totals.facts_consolidated",+ "$.totals.lint_fixes",+ "$.totals.orphans_found",+ "$.totals.pages_embedded",+ "$.totals.pages_emotional_weight_recomputed",+ "$.totals.pages_extracted",+ "$.totals.pages_synced",+ "$.totals.patterns_written",+ "$.totals.phantoms_ambiguous",+ "$.totals.phantoms_redirected",+ "$.totals.phantoms_skipped_drift",+ "$.totals.purged_pages_count",+ "$.totals.purged_sources_count",+ "$.totals.synth_pages_written",+ "$.totals.transcripts_processed"+ ]+ },+ "call get_page {\"slug\":\"no-such-page\"}": {+ "exit": 1,+ "keys": [+ "$.error",+ "$.message",+ "$.suggestion"+ ],+ "error": "page_not_found"+ },+ "call search {\"query\":\"zelkova-upgrade-fixture\"}": {+ "exit": 0,+ "keys": [+ "$[].base_score",+ "$[].chunk_id",+ "$[].chunk_index",+ "$[].chunk_source",+ "$[].chunk_text",+ "$[].create_safety",+ "$[].effective_date",+ "$[].effective_date_source",+ "$[].evidence",+ "$[].id",+ "$[].keyword_hit",+ "$[].page_id",+ "$[].score",+ "$[].slug",+ "$[].source_id",+ "$[].stale",+ "$[].title",+ "$[].type"+ ]+ },+ "sources remove default --json": {+ "exit": 1,+ "keys": [+ "$.error",+ "$.message"+ ],+ "error": "invalid_params"+ }+ }+}