Skip to content

Garry's Opinionated OpenClaw/Hermes Agent Brain

TypeScript

test(lane-h): H1a keyless agent journey; fix caller-mistake fixes, keyless doctor WARNs, import --json, init enable hint

garrytanc3ee5adda6ec
diff --git a/src/cli/command-table.ts b/src/cli/command-table.ts
index c26824fb6a..430f48c649 100644
--- a/src/cli/command-table.ts
+++ b/src/cli/command-table.ts
@@ -245,7 +245,7 @@ export const CLI_COMMANDS: readonly CliCommandRecord[] = [ // Pre-connect: disp
// Post-connect: dispatched by dispatchConnectedCommand after connectEngine(), in master switch order.
{ name: 'mcp', phase: 'post-connect', thinClient: 'none', selfHelp: true, load: () => import('./commands/mcp.ts') },
- { name: 'import', phase: 'post-connect', thinClient: 'none', help: () => import('./help/import.ts'), load: () => import('./commands/import.ts') },
+ { name: 'import', phase: 'post-connect', thinClient: 'none', json: 'document', help: () => import('./help/import.ts'), load: () => import('./commands/import.ts') },
{ name: 'export', phase: 'post-connect', thinClient: 'refuse', selfHelp: true, load: () => import('./commands/export.ts') },
{ name: 'files', phase: 'post-connect', thinClient: 'refuse', load: () => import('./commands/files.ts') },
{ name: 'embed', phase: 'post-connect', thinClient: 'refuse', selfHelp: true, json: 'document', load: () => import('./commands/embed.ts') },
diff --git a/src/commands/doctor/check-fix.ts b/src/commands/doctor/check-fix.ts
index 7dfe66b219..b93853bc2d 100644
--- a/src/commands/doctor/check-fix.ts
+++ b/src/commands/doctor/check-fix.ts
@@ -51,6 +51,16 @@ export function agentFix(argv: string[], why: string, verifyCheck: string, extra
return { argv, consent: [], actor: 'agent', why, verify: doctorVerify(verifyCheck), requires_exclusive: false, ...extra };
}
+/**
+ * A low brain score's next step: the read-only remediation plan, which names
+ * the job and repair steps that raise each score component, their cost, and
+ * the highest score this brain can reach (a keyless brain's embed share stays 0).
+ */
+export function brainScorePlanFix(): Action {
+ return agentFix(['gbrain', 'doctor', '--remediation-plan', '--json'],
+ 'The plan lists which steps raise each score component, what they cost and the reachable maximum; it changes nothing.', 'brain_score');
+}
+
/**
* Information, not a problem: status `ok`, `severity: 'info'`. Use for a
* capability that is `disabled_by_choice` or `not_applicable` (keyless brain,
diff --git a/src/commands/doctor/checks/graph-health.ts b/src/commands/doctor/checks/graph-health.ts
index 40f8ae44a0..c00b35b40f 100644
--- a/src/commands/doctor/checks/graph-health.ts
+++ b/src/commands/doctor/checks/graph-health.ts
@@ -11,7 +11,7 @@ import { startHeartbeat } from '../../../core/progress.ts';
import { quarantineFilterFragment } from '../../../core/quarantine.ts';
import type { Check } from '../../doctor.ts';
import { connectedEngine, type DoctorContext, type DoctorEntry } from '../context.ts';
-import { checkError } from '../check-fix.ts';
+import { brainScorePlanFix, checkError } from '../check-fix.ts';
async function runGraphCoverage(ctx: DoctorContext): Promise<Check[]> {
const { progress } = ctx;
@@ -111,6 +111,7 @@ async function runGraphCoverage(ctx: DoctorContext): Promise<Check[]> {
name: 'brain_score',
status: health.brain_score >= 70 ? 'ok' : 'warn',
message: `Brain score ${health.brain_score}/100 (${parts.join(', ')})`,
+ ...(health.brain_score >= 70 ? {} : { fix: brainScorePlanFix() }),
});
} else {
checks.push({ name: 'brain_score', status: 'ok', message: `Brain score 100/100` });
diff --git a/src/commands/doctor/report-remote.ts b/src/commands/doctor/report-remote.ts
index 38fdca7866..9d646d10a4 100644
--- a/src/commands/doctor/report-remote.ts
+++ b/src/commands/doctor/report-remote.ts
@@ -64,7 +64,7 @@ import {
multiSourceDriftCheck,
multiSourceDriftNotVerified,
} from './schema-pack-checks.ts';
-import { checkError } from './check-fix.ts';
+import { brainScorePlanFix, checkError } from './check-fix.ts';
import type { RenderContext } from '../../core/agent-output.ts';
// Same alias the local doctor keeps for its own freshness checks; the alias
@@ -207,6 +207,7 @@ export async function doctorReportRemote(
name: 'brain_score',
status: score >= 70 ? 'ok' : score >= 50 ? 'warn' : 'fail',
message: `Brain score ${score}/100`,
+ ...(score >= 70 ? {} : { fix: brainScorePlanFix() }),
});
} catch (e) {
checks.push(checkError('brain_score', 'compute', e));
diff --git a/src/commands/doctor/skill-checks.ts b/src/commands/doctor/skill-checks.ts
index 81c4797707..cfeb33ddaa 100644
--- a/src/commands/doctor/skill-checks.ts
+++ b/src/commands/doctor/skill-checks.ts
@@ -283,10 +283,13 @@ export async function skillPreconditionsCheck(
};
const unmet: string[] = [];
+ let waitsForContent = true;
for (const skill of installed) {
const results = await checkPreconditions(skill.requires, ctx);
for (const r of results) {
- if (!r.met) unmet.push(`${skill.slug}: ${r.req.raw} — ${r.hint}`);
+ if (r.met) continue;
+ unmet.push(`${skill.slug}: ${r.req.raw} — ${r.hint}`);
+ if (!(r.req.kind === 'dir' || r.req.kind === 'pages' || (r.req.kind === 'source' && !r.req.arg))) waitsForContent = false;
}
}
if (unmet.length === 0) {
@@ -297,6 +300,13 @@ export async function skillPreconditionsCheck(
`${unmet.length} skill precondition(s) wait for content: the brain has no pages yet, so skills that need a corpus stay idle until the first import or sync.`,
'not_applicable', undefined, { unmet: unmet.slice(0, 8) });
}
+ // A skill whose corpus (a page directory, a page count) does not exist yet is idle, not broken:
+ // nothing to fix until the user brings that content, so this is information (E2 keyless/day-zero honesty).
+ if (waitsForContent) {
+ return infoCheck(name,
+ `${unmet.length} skill precondition(s) wait for content this brain does not hold yet; those skills stay idle until it is imported:\n ${unmet.slice(0, 8).join('\n ')}`,
+ 'not_applicable', undefined, { unmet });
+ }
return {
name,
status: 'warn',
diff --git a/src/commands/import.ts b/src/commands/import.ts
index f290b81808..3ba00f3cdd 100644
--- a/src/commands/import.ts
+++ b/src/commands/import.ts
@@ -1,3 +1,5 @@
+import { writeJsonDocument } from '../core/cli-force-exit.ts';
+import { opError } from '../core/ops/contract.ts';
import { hasSourceFilesystemLock, withSourceFilesystemLock, currentSourceFilesystemSignal } from '../core/minions/source-filesystem.ts';
import { readdirSync, lstatSync, existsSync, mkdirSync } from 'fs';
import { execFileSync } from 'child_process';
@@ -259,6 +261,21 @@ export async function runImport(
try {
assertEmbeddingEnabled(loadConfig());
} catch (e) {
+ // D2: under --json the refusal is the one document. The step the agent
+ // can take now is this import with --no-embed (pages stay keyword-
+ // searchable; vectors come later); enabling embeddings asks the user.
+ if (jsonOutput) {
+ throw opError('embedding_disabled', String(e instanceof Error ? e.message.split('\n')[0] : e),
+ 'Embeddings are off by choice on this brain, so import needs --no-embed; turning embeddings on needs the user\'s consent (gbrain doctor --only embeddings --json shows the command).', {
+ reason: 'disabled_by_choice',
+ why: 'This brain was set up keyword-only. Importing with --no-embed keeps every page keyword-searchable; `gbrain embed --stale` adds vectors once embeddings are enabled.',
+ fix: {
+ argv: ['gbrain', 'import', ...args.filter(a => a !== '--json' && a !== '--no-embed'), '--no-embed', '--json'],
+ consent: [], actor: 'agent', requires_exclusive: true,
+ why: 'Imports the same files without computing vectors, which needs no provider key.',
+ },
+ });
+ }
console.error(`\n${e instanceof Error ? e.message : e}`);
console.error('Tip: run `gbrain import <dir> --no-embed` to import without embedding now.');
throw new ImportAbortError('embedding disabled (deferred-setup sentinel)');
@@ -273,7 +290,7 @@ export async function runImport(
} catch (e) {
if (e instanceof EmbeddingCredentialError) {
if (jsonOutput) {
- console.log(JSON.stringify({ status: 'embedding_credentials_missing', diagnosis: e.diagnosis }));
+ await writeJsonDocument(JSON.stringify({ status: 'embedding_credentials_missing', diagnosis: e.diagnosis }));
} else {
console.error('');
console.error(e.userMessage);
@@ -1116,7 +1133,7 @@ export async function runImport(
// written only for git-repo dirs (see the gitHead gate below), so a caller
// importing a scratch directory has no other channel. Emit the per-file
// list so state can be gated per file.
- console.log(JSON.stringify({
+ await writeJsonDocument(JSON.stringify({
status: errors > 0 ? 'partial' : 'success', duration_s: parseFloat(totalTime),
imported, skipped, errors, chunks: chunksCreated,
...(resealSummary ? { resealed: resealSummary } : {}),
diff --git a/src/commands/init.ts b/src/commands/init.ts
index 7028c2f1c7..45fc0f273f 100644
--- a/src/commands/init.ts
+++ b/src/commands/init.ts
@@ -18,7 +18,8 @@ import type { BrainEngine } from '../core/engine.ts';
import { readPrimaryEmbeddingStores, readStoredEmbeddingIdentity } from '../core/stored-embedding-identity.ts';
import { deferInitJsonError, flushInitJsonResult, initJsonError, setInitJsonResult, writeDeferredInitJsonError } from './init-json.ts';
import { buildInitFirstRunNotices } from './init-first-run.ts';
-import { renderNotice, cliRenderContext } from '../core/agent-output.ts';
+import { renderNotice, cliRenderContext, shellQuote } from '../core/agent-output.ts';
+import { embeddingEnablement } from '../core/readiness.ts';
import { exitCodeForCode } from '../core/error-catalogue.ts';
import { promptLineStderr } from '../core/interaction.ts';
import type { SearchMode as SearchModeName } from '../core/search/mode.ts';
@@ -1091,7 +1092,7 @@ export async function initPGLite(opts: {
let resolvedModel: string | undefined;
if (opts.aiOpts?.noEmbedding) {
// D9 deferred-setup mode: skip preflight, no model/dim resolved.
- console.log(` --no-embedding: deferred setup — enable later with \`gbrain init --force --embedding-model voyage:voyage-4\` (\`config set embedding_model\` is refused by design)`);
+ console.log(deferredEmbeddingHint({ engine: 'pglite', database_path: dbPath, embedding_disabled: true }));
} else if (opts.aiOpts?.embedding_model) {
const { resolveSchemaEmbeddingDim } = await import('../core/embedding-dim-check.ts');
const pre = resolveSchemaEmbeddingDim({
@@ -1361,6 +1362,17 @@ export class InitPostgresFailure extends Error {
}
}
+/**
+ * The deferred-setup line init prints for `--no-embedding`: the same enable
+ * command readiness gives doctor, embed and MCP (A7 `embeddingEnablement`:
+ * resolved datastore, a provider that fits, pages and facts kept).
+ */
+function deferredEmbeddingHint(cfg: GBrainConfig): string {
+ const enable = embeddingEnablement(cfg);
+ const step = enable.argv ? shellQuote(enable.argv) : 'gbrain doctor --only embeddings --json';
+ return ` --no-embedding: deferred setup — enable later with \`${step}\` (\`config set embedding_model\` is refused by design)`;
+}
+
/** Exit-preserving wrapper — direct invocations keep their contract. */
async function initPostgres(opts: Parameters<typeof initPostgresCore>[0]) {
try {
@@ -1395,7 +1407,7 @@ export async function initPostgresCore(opts: {
let resolvedDim: number | undefined;
let resolvedModel: string | undefined;
if (opts.aiOpts?.noEmbedding) {
- console.log(` --no-embedding: deferred setup — enable later with \`gbrain init --force --embedding-model voyage:voyage-4\` (\`config set embedding_model\` is refused by design)`);
+ console.log(deferredEmbeddingHint({ engine: 'postgres', database_url: databaseUrl, embedding_disabled: true }));
} else if (opts.aiOpts?.embedding_model) {
const { resolveSchemaEmbeddingDim } = await import('../core/embedding-dim-check.ts');
const pre = resolveSchemaEmbeddingDim({
diff --git a/src/core/ops/op-fix.ts b/src/core/ops/op-fix.ts
index f700aa861b..806737a203 100644
--- a/src/core/ops/op-fix.ts
+++ b/src/core/ops/op-fix.ts
@@ -105,7 +105,7 @@ export function invalidParam(
tool: string,
param: string,
message: string,
- opts: { choices?: readonly string[]; example?: unknown; def?: ParamDef; legacy_error?: string } = {},
+ opts: { choices?: readonly string[]; example?: unknown; def?: ParamDef; legacy_error?: string; fix?: Action } = {},
): OperationError {
const example = opts.example ?? exampleValue(opts.def, opts.choices ?? opts.def?.enum);
const choices = opts.choices ?? opts.def?.enum;
@@ -115,8 +115,10 @@ export function invalidParam(
? `one of: ${choices.join(', ')}`
: `a ${opts.def?.type ?? 'value'}${opts.def?.description ? ` (${opts.def.description.replace(/\.$/, '')})` : ''}`;
const call = cli ? paramUse(ctx, param, example) : `${tool} {"${param}": ${JSON.stringify(example)}}`;
- return opError('invalid_params', message, `Pass ${name} as ${what}. Example: ${call}.`,
- opts.legacy_error ? { legacy_error: opts.legacy_error } : {});
+ return opError('invalid_params', message, `Pass ${name} as ${what}. Example: ${call}.`, {
+ ...(opts.legacy_error ? { legacy_error: opts.legacy_error } : {}),
+ ...(opts.fix ? { fix: opts.fix } : {}),
+ });
}
const SAFE_ID = /^[A-Za-z0-9][A-Za-z0-9_.:-]{0,127}$/;
diff --git a/src/mcp/dispatch.ts b/src/mcp/dispatch.ts
index 6a95e06f42..b10bd6cf1f 100644
--- a/src/mcp/dispatch.ts
+++ b/src/mcp/dispatch.ts
@@ -704,7 +704,7 @@ export async function dispatchToolCall(
logVerb(false);
// [c7] verb validation errors speak the protocol envelope (protocol_version);
// B3: every op's suggestion names the param's type, choices and an example.
- const invalid = schemaInvalidParams(op, validationFailure, { remote: opts.remote, transport: dispatchRenderContext(opts).transport === 'http' ? 'http' : 'stdio' });
+ const invalid = schemaInvalidParams(op, validationFailure, { remote: opts.remote, transport: dispatchRenderContext(opts).transport === 'http' ? 'http' : 'stdio' }, safeParams);
if (isVerb) invalid.protocolVersion = MEMORY_VERBS_VERSION;
return errorResult(invalid, opts, { op: name });
}
diff --git a/src/mcp/validate-params.ts b/src/mcp/validate-params.ts
index e846b80730..db9c8db5c8 100644
--- a/src/mcp/validate-params.ts
+++ b/src/mcp/validate-params.ts
@@ -18,6 +18,7 @@ import type { GBrainConfig } from '../core/config.ts';
import { suggestNearest } from '../core/levenshtein.ts';
import type { OperationError } from '../core/ops/contract.ts';
import { invalidParam } from '../core/ops/op-fix.ts';
+import type { Action } from '../core/agent-output.ts';
/** One validation failure: the message (never echoes the caller's value) and the param it names. */
export interface ParamValidationFailure { message: string; param: string }
@@ -57,15 +58,51 @@ export function validateParams(op: Operation, params: Record<string, unknown>):
/**
* B3: the `invalid_params` error for a schema failure — the param's type,
* description, valid choices and one example call on the caller's surface
- * (from the op's ParamDef), never the caller's raw value.
+ * (from the op's ParamDef), never the caller's raw value in `message`.
+ * Over MCP, a read op's wrong-typed or out-of-enum param also gets a `fix`:
+ * the same call with the caller's other arguments and a valid value for the
+ * param (H1a: a caller mistake returns a fix the agent can run).
*/
export function schemaInvalidParams(
op: Operation,
failure: ParamValidationFailure,
ctx: { remote?: boolean; transport?: 'stdio' | 'http' },
+ params?: Record<string, unknown>,
): OperationError {
+ const fix = params && ctx.remote !== false ? retryWithValidParam(op, failure, params) : undefined;
return invalidParam({ remote: ctx.remote ?? true, transport: ctx.transport }, op.cliHints?.name && ctx.remote === false ? op.cliHints.name : op.name,
- failure.param, failure.message, { def: op.params[failure.param] });
+ failure.param, failure.message, { def: op.params[failure.param], ...(fix ? { fix } : {}) });
+}
+
+/**
+ * The corrected call, or undefined when no safe one exists: never for a
+ * mutating op (an example value could change what gets written), a missing
+ * required param (only the caller knows its value), or a param whose valid
+ * value is not a closed choice, number or boolean. Arguments that are not
+ * short scalars are dropped; if a required one would be dropped, no fix.
+ */
+function retryWithValidParam(op: Operation, failure: ParamValidationFailure, params: Record<string, unknown>): Action | undefined {
+ if (op.mutating !== false) return undefined;
+ const def = op.params[failure.param];
+ if (!def || params[failure.param] === undefined || params[failure.param] === null) return undefined;
+ const value = def.enum?.length ? (def.default !== undefined && def.enum.includes(String(def.default)) ? def.default : def.enum[0])
+ : def.type === 'number' ? (typeof def.default === 'number' ? def.default : 10)
+ : def.type === 'boolean' ? (typeof def.default === 'boolean' ? def.default : true)
+ : undefined;
+ if (value === undefined) return undefined;
+ const args: Record<string, unknown> = {};
+ for (const [key, val] of Object.entries(params)) {
+ if (key === failure.param || !(key in op.params)) continue;
+ const scalar = typeof val === 'number' || typeof val === 'boolean' || (typeof val === 'string' && val.length <= 200);
+ if (scalar) args[key] = val;
+ else if (op.params[key]?.required) return undefined;
+ }
+ args[failure.param] = value;
+ return {
+ mcp: { tool: op.name, arguments: args },
+ consent: [], actor: 'agent', requires_exclusive: false,
+ why: `The call failed validation before it ran, so nothing changed. This is the same call with your other arguments kept and \`${failure.param}\` set to ${JSON.stringify(value)}.`,
+ };
}
/**
diff --git a/test/agent-journey.serial.test.ts b/test/agent-journey.serial.test.ts
new file mode 100644
index 0000000000..83db817ef9
--- /dev/null
+++ b/test/agent-journey.serial.test.ts
@@ -0,0 +1,324 @@
+/**
+ * Lane H1a (Tier 1): the deterministic keyless agent journey, end to end.
+ *
+ * An agent with no provider keys, no TTY, and stdin either closed
+ * (`</dev/null`) or an open pipe that never writes, drives the real CLI and
+ * real stdio MCP sessions under hard timeouts:
+ *
+ * init --pglite --no-embedding --json one document carrying the first-run decision bundle
+ * doctor --json day zero: 0 WARN/FAIL, health >= 90, capped_by
+ * import <dir> --no-embed --json 3 pages, one document
+ * doctor --remediate (no authorization) exit 3, consent payload, nothing mutated
+ * (also on a pending-migration brain: schema version unchanged)
+ * the user agrees → the fix argv verbatim → remediation runs, migrations apply after consent
+ * serve --surface verbs remember/recall, degraded notice as a separate prefixed
+ * block + _meta.gbrain_notices, caller mistake → one-block
+ * envelope whose fix runs; a second serve on the locked brain
+ * completes the handshake in status-only mode naming the owner
+ * serve --surface full search with the degraded notice, list_pages caller mistake → fix
+ * doctor --json health >= 90 with capped_by
+ *
+ * Machine timings (init, initialize, first remember, first recall) are printed
+ * and written to .context/agent-journey-timings.json for Lane I.
+ *
+ * Existing lane tests cover the pieces in isolation (cli-json-guard D2 init,
+ * doctor-day-zero E2, doctor-remediate-consent C1, observational-startup A4,
+ * mcp-notice-channels F3, serve-status-mode F4); this file proves they compose
+ * into one working journey through the real binary. Wire goldens:
+ * test/fixtures/agent-contract/v1/journey/ (transcripts in AGENT_OPERATOR_v1.md).
+ *
+ * Serial: real subprocesses and PGLite datastores in temp homes.
+ */
+import { afterAll, beforeAll, describe, expect, test } from 'bun:test';
+import { mkdirSync, mkdtempSync, rmSync, writeFileSync } from 'node:fs';
+import { tmpdir } from 'node:os';
+import { join } from 'node:path';
+import { PGLiteEngine } from '../src/core/pglite-engine.ts';
+import { LATEST_VERSION, hasPendingMigrations } from '../src/core/migrate.ts';
+import { withCoordinatedWrite } from '../src/core/persistence/context.ts';
+import { TEST_WRITE_ATTRIBUTION } from './helpers/write-attribution.ts';
+import { snapshotBrain, type BrainSnapshot } from './helpers/fresh-brain-snapshot.ts';
+import {
+ REPO, body, call, expectOneBlockError, gb, journeyGolden, mcp, noticeBlocks, oneDocument, NOTICE_PREFIX,
+ type McpSession, type StdinMode,
+} from './helpers/agent-journey.ts';
+
+const MARKER = 'quokka-journey-marker';
+const PAGES = 3;
+const timings: Record<string, number> = {};
+
+function brainPath(home: string): string { return join(home, '.gbrain', 'brain.pglite'); }
+
+async function withBrain<T>(home: string, fn: (engine: PGLiteEngine) => Promise<T>): Promise<T> {
+ const engine = new PGLiteEngine();
+ await engine.connect({ engine: 'pglite', database_path: brainPath(home) });
+ try { return await fn(engine); } finally { await engine.disconnect(); }
+}
+
+/** Brain state an unauthorized run must leave alone. The agent-contract event log (E11) and audit trail record the refusal by design. */
+async function brainState(home: string): Promise<BrainSnapshot> {
+ const snap = await snapshotBrain(home, brainPath(home));
+ for (const key of Object.keys(snap.files)) {
+ if (/(^|\/)\.gbrain\/(agent-contract|audit)(\/|$)/.test(key)) delete snap.files[key];
+ }
+ return snap;
+}
+
+function writeNotes(home: string): string {
+ const dir = join(home, 'notes');
+ mkdirSync(dir, { recursive: true });
+ for (let i = 1; i <= PAGES; i++) {
+ writeFileSync(join(dir, `journey-note-${i}.md`), `---\ntitle: Journey note ${i}\n---\n\n# Journey note ${i}\n\nThe ${MARKER} ${i} lives in note ${i}.\n`);
+ }
+ return dir;
+}
+
+/** A repairable finding a real legacy brain carries: a timeline row that exists only in the database. */
+async function seedRepairableFinding(home: string): Promise<void> {
+ await withBrain(home, engine => engine.transaction(tx => withCoordinatedWrite(tx, ['default'], () => tx.executeRaw(
+ `INSERT INTO timeline_entries(page_id,date,source,summary,detail)
+ SELECT id,'2026-07-01','legacy','A database-only event','' FROM pages WHERE source_id='default' AND slug='journey-note-1'`),
+ TEST_WRITE_ATTRIBUTION)));
+}
+
+interface DoctorReport { status: string; health_score: number; capped_by?: string[]; checks: Array<{ name: string; status: string; message: string; fix?: { argv?: string[]; next?: string }; fix_unavailable_reason?: string }> }
+
+function expectHealthy(report: DoctorReport, label: string): void {
+ expect(report.health_score, `${label}: health_score`).toBeGreaterThanOrEqual(90);
+ expect(report.capped_by, `${label}: capped_by names the keyless choice`).toEqual(['embeddings_disabled']);
+ const fails = report.checks.filter(c => c.status === 'fail').map(c => `${c.name}: ${c.message}`);
+ expect(fails, `${label}: no FAIL`).toEqual([]);
+ const unfixable = report.checks.filter(c => c.status === 'warn' && !c.fix?.argv).map(c => `${c.name}: ${c.message} (${c.fix_unavailable_reason})`);
+ expect(unfixable, `${label}: every WARN carries an executable fix`).toEqual([]);
+}
+
+for (const stdin of ['devnull', 'silent'] as StdinMode[]) {
+ describe(`H1a keyless CLI journey, stdin ${stdin === 'devnull' ? '</dev/null' : 'an open silent pipe'}`, () => {
+ let home = '';
+ const cli = (args: string[], timeoutMs = 120_000) => gb(home, args, { stdin, timeoutMs });
+
+ beforeAll(() => { home = mkdtempSync(join(tmpdir(), `gbrain-journey-${stdin}-`)); });
+ afterAll(() => { rmSync(home, { recursive: true, force: true }); });
+
+ test('init --pglite --no-embedding --json: one document with the first-run decision bundle', async () => {
+ const r = await cli(['init', '--pglite', '--no-embedding', '--json']);
+ expect(r.exitCode, r.stderr).toBe(0);
+ if (stdin === 'devnull') timings.init_ms = r.ms;
+ const doc = oneDocument(r, 'init --json');
+ expect(doc).toMatchObject({ status: 'success', engine: 'pglite', contract_version: 1 });
+ const bundles = (doc.notices as Array<Record<string, any>>).filter(n => n.code === 'first_run_decisions');
+ expect(bundles).toHaveLength(1);
+ const bundle = bundles[0]!;
+ expect(bundle).toMatchObject({ kind: 'ask', contract_version: 1 });
+ expect(bundle.user_message).toContain("Reply 'defaults'");
+ expect(bundle.decisions.map((d: { id: string }) => d.id)).toEqual(expect.arrayContaining(['search_mode', 'harness_wiring']));
+ for (const d of bundle.decisions) {
+ expect(d.options.map((o: { id: string }) => o.id), `${d.id}: default is an option`).toContain(d.default);
+ expect(d.default_reason, `${d.id}: default_reason`).toBeTruthy();
+ }
+ // No fabricated user fact: the brain holds no pages and no facts after init.
+ await withBrain(home, async engine => {
+ expect((await engine.executeRaw<{ n: number }>('SELECT count(*)::int AS n FROM pages'))[0]!.n).toBe(0);
+ expect((await engine.executeRaw<{ n: number }>('SELECT count(*)::int AS n FROM facts'))[0]!.n).toBe(0);
+ });
+ if (stdin === 'devnull') journeyGolden('init-first-run.json', doc, { home });
+ }, 150_000);
+
+ test('day-zero doctor --json: 0 WARN, 0 FAIL, health >= 90, capped_by', async () => {
+ const r = await cli(['doctor', '--json']);
+ expect(r.exitCode, r.stderr).toBe(0);
+ const report = oneDocument(r, 'doctor --json') as DoctorReport;
+ expect(report.checks.filter(c => c.status !== 'ok').map(c => `${c.status} ${c.name}: ${c.message}`)).toEqual([]);
+ expectHealthy(report, 'day zero');
+ }, 150_000);
+
+ test('day-zero doctor --remediate: nothing to do, nothing changed', async () => {
+ const before = await brainState(home);
+ const r = await cli(['doctor', '--remediate', '--json']);
+ expect(r.exitCode, r.stderr).toBe(0);
+ expect(oneDocument(r, 'doctor --remediate --json')).toMatchObject({ healthy: true, submitted: [], repairs_completed: 0 });
+ expect(await brainState(home)).toEqual(before);
+ }, 150_000);
+
+ test(`import ${PAGES} pages --no-embed --json: one document`, async () => {
+ const r = await cli(['import', writeNotes(home), '--no-embed', '--json']);
+ expect(r.exitCode, r.stderr).toBe(0);
+ expect(oneDocument(r, 'import --json')).toMatchObject({ status: 'success', imported: PAGES, errors: 0 });
+ }, 150_000);
+
+ test('doctor --remediate without authorization: exit 3, the consent payload, nothing mutated', async () => {
+ await seedRepairableFinding(home);
+ const before = await brainState(home);
+ const r = await cli(['doctor', '--remediate', '--include-repairs', '--json']);
+ expect(r.exitCode, r.stderr).toBe(3);
+ const payload = oneDocument(r, 'doctor --remediate --json (refused)');
+ expect(payload).toMatchObject({
+ status: 'confirmation_required', error: 'confirmation_required', code: 'confirmation_required',
+ effects: ['paid', 'destructive'], actor: 'agent', contract_version: 1,
+ });
+ expect(payload.fix.next).toBe('ask_user');
+ expect(payload.fix.argv.slice(0, 3)).toEqual(['gbrain', 'doctor', '--remediate']);
+ expect(payload.fix.argv).toEqual(expect.arrayContaining(['--yes', '--expect', payload.plan_hash]));
+ expect(payload.user_message).toBeTruthy();
+ expect(await brainState(home)).toEqual(before);
+
+ // Human output on a non-TTY: the [AGENT] block with a fenced [SHOW USER] relay, still nothing changed.
+ const human = await cli(['doctor', '--remediate', '--include-repairs']);
+ expect(human.exitCode).toBe(3);
+ expect(human.stdout).toContain('[AGENT]');
+ expect(human.stdout).toContain('[SHOW USER]');
+ expect(await brainState(home)).toEqual(before);
+ }, 200_000);
+
+ test('pending-migration brain: the refusal leaves the schema version unchanged; the approved fix migrates after consent', async () => {
+ const pending = String(LATEST_VERSION - 1);
+ await withBrain(home, engine => engine.setConfig('version', pending));
+ const r = await cli(['doctor', '--remediate', '--include-repairs', '--json']);
+ expect(r.exitCode, r.stderr).toBe(3);
+ const payload = oneDocument(r, 'doctor --remediate --json (pending migration)');
+ expect(payload.code).toBe('confirmation_required');
+ await withBrain(home, async engine => {
+ expect(await engine.getConfig('version')).toBe(pending);
+ expect(await hasPendingMigrations(engine)).toBe(true);
+ });
+
+ // The user agreed: the agent runs fix.argv exactly as given.
+ const fixArgv = payload.fix.argv as string[];
+ expect(fixArgv[0]).toBe('gbrain');
+ const approved = await cli(fixArgv.slice(1), 240_000);
+ expect(approved.exitCode, approved.stderr.slice(-3000)).toBe(0);
+ const result = oneDocument(approved, 'approved doctor --remediate');
+ expect(result.repairs_completed).toBe(1);
+ await withBrain(home, async engine => {
+ expect(await engine.getConfig('version')).toBe(String(LATEST_VERSION));
+ });
+ const verify = await cli(['doctor', '--only', 'timeline_history', '--json']);
+ expect(verify.exitCode, verify.stderr).toBe(0);
+ const check = (oneDocument(verify, 'doctor --only timeline_history').checks as DoctorReport['checks']).find(c => c.name === 'timeline_history');
+ expect(check?.status).toBe('ok');
+ }, 300_000);
+
+ test('after import and remediation: doctor --json health >= 90 with capped_by; every WARN has a fix', async () => {
+ const r = await cli(['doctor', '--json']);
+ expect(r.exitCode, r.stderr).toBe(0);
+ expectHealthy(oneDocument(r, 'doctor --json (after import)') as DoctorReport, 'after import');
+ }, 150_000);
+ });
+}
+
+describe('H1a keyless MCP journey (stdio)', () => {
+ let home = '';
+ const open: McpSession[] = [];
+
+ beforeAll(async () => {
+ home = mkdtempSync(join(tmpdir(), 'gbrain-journey-mcp-'));
+ expect((await gb(home, ['init', '--pglite', '--no-embedding', '--json'], { timeoutMs: 120_000 })).exitCode).toBe(0);
+ expect((await gb(home, ['import', writeNotes(home), '--no-embed', '--json'], { timeoutMs: 120_000 })).exitCode).toBe(0);
+ }, 300_000);
+
+ afterAll(async () => {
+ for (const s of open) await s.close();
+ rmSync(home, { recursive: true, force: true });
+ try {
+ mkdirSync(join(REPO, '.context'), { recursive: true });
+ writeFileSync(join(REPO, '.context', 'agent-journey-timings.json'), `${JSON.stringify({ recorded_at: new Date().toISOString(), ...timings }, null, 2)}\n`);
+ } catch { /* timings are informational */ }
+ console.log(`[agent-journey] machine timings (ms): ${JSON.stringify(timings)}`);
+ });
+
+ test('surface verbs: remember/recall, the degraded notice block, a caller mistake with a runnable fix, status-only second serve', async () => {
+ const verbs = await mcp(home, ['--surface', 'verbs']);
+ open.push(verbs);
+ timings.initialize_ms = verbs.initMs;
+ const tools = (await verbs.client.listTools()).tools.map(t => t.name);
+ expect(tools).toEqual(expect.arrayContaining(['remember', 'recall', 'forget']));
+ expect(tools).not.toContain('get_health');
+ expect(verbs.client.getInstructions()).toContain('recall');
+
+ let t0 = performance.now();
+ const remembered = await call(verbs, 'remember', { fact: `${MARKER} is the install-check fact`, provenance: 'install-check' });
+ timings.first_remember_ms = Math.round(performance.now() - t0);
+ expect(remembered.isError, JSON.stringify(remembered).slice(0, 1000)).toBeFalsy();
+
+ t0 = performance.now();
+ const recalled = await call(verbs, 'recall', { query: MARKER });
+ timings.first_recall_ms = Math.round(performance.now() - t0);
+ expect(recalled.isError).toBeFalsy();
+ const text0 = recalled.content[0].text;
+ expect(text0.startsWith(NOTICE_PREFIX)).toBe(false);
+ const result = body(recalled);
+ expect(JSON.stringify(result)).toContain(MARKER);
+ expect(result.results.length).toBe(PAGES);
+ // The degraded notice is its own prefixed block (the model sees it) and mirrored in _meta.
+ const blocks = noticeBlocks(recalled);
+ expect(blocks).toHaveLength(1);
+ expect(blocks[0]!.split('\n')[0]).toBe('[gbrain notice degraded_recall kind=degraded]');
+ expect(blocks[0]).toContain('never as "the brain has nothing on this"');
+ expect(recalled._meta?.gbrain_notices?.map((n: { code: string }) => n.code)).toEqual(['degraded_recall']);
+ journeyGolden('recall-degraded.json', recalled, { home });
+
+ // Caller mistake: one block, an envelope with a fix the agent runs as given.
+ const mistake = await call(verbs, 'recall', { query: MARKER, limit: 'abc' });
+ const env = expectOneBlockError(mistake, 'recall limit:"abc"');
+ expect(env).toMatchObject({ error: 'invalid_params', code: 'invalid_params', class: 'caller', retryable: false });
+ expect(env.fix.next).toBe('run');
+ expect(env.fix.mcp).toEqual({ tool: 'recall', arguments: { query: MARKER, limit: 10 } });
+ expect(env.suggestion).toContain('recall');
+ journeyGolden('caller-mistake.json', mistake, { home });
+ const fixed = await call(verbs, env.fix.mcp.tool, env.fix.mcp.arguments);
+ expect(fixed.isError).toBeFalsy();
+ expect(JSON.stringify(body(fixed))).toContain(MARKER);
+
+ // F4: a second serve on the locked brain completes the handshake with gbrain_status naming the owner.
+ const second = await mcp(home, []);
+ open.push(second);
+ expect(second.client.getInstructions()).toContain('STATUS-ONLY MODE');
+ expect((await second.client.listTools()).tools.map(t => t.name)).toEqual(['gbrain_status']);
+ const statusResult = await call(second, 'gbrain_status');
+ const status = body(statusResult);
+ expect(status).toMatchObject({ status: 'unavailable', reason: 'lock_held' });
+ expect(status.lock_owner).toMatchObject({ pid: verbs.pid, transport: 'stdio' });
+ expect(status.why).toContain(`PID ${verbs.pid}`);
+ expect(status.fix.next).toBe('tell_user_to_run');
+ expect(status.user_message).toBeTruthy();
+ journeyGolden('status-only-lock-held.json', statusResult, { home, pids: [verbs.pid] });
+ const refused = await call(second, 'recall', { query: MARKER });
+ expect(expectOneBlockError(refused, 'recall on a status-only serve').code).toBe('serve_status_only');
+ await second.close();
+ await verbs.close();
+ }, 240_000);
+
+ test('surface full: search carries the degraded notice; a list_pages caller mistake carries a fix that runs', async () => {
+ const full = await mcp(home, ['--surface', 'full']);
+ open.push(full);
+ const tools = (await full.client.listTools()).tools.map(t => t.name);
+ expect(tools).toEqual(expect.arrayContaining(['search', 'query', 'list_pages', 'get_page', 'recall']));
+ const found = await call(full, 'search', { query: MARKER });
+ expect(found.isError).toBeFalsy();
+ expect(Array.isArray(body(found))).toBe(true);
+ expect(JSON.stringify(body(found))).toContain(MARKER);
+ expect(noticeBlocks(found).map(b => b.split('\n')[0])).toEqual(['[gbrain notice degraded_recall kind=degraded]']);
+ expect(found._meta?.gbrain_notices?.[0]?.code).toBe('degraded_recall');
+
+ const mistake = await call(full, 'list_pages', { sort: 'bogus', limit: 2 });
+ const env = expectOneBlockError(mistake, 'list_pages sort:"bogus"');
+ expect(env.code).toBe('invalid_params');
+ expect(env.fix).toMatchObject({ next: 'run', mcp: { tool: 'list_pages', arguments: { limit: 2 } } });
+ const listed = await call(full, env.fix.mcp.tool, env.fix.mcp.arguments);
+ expect(listed.isError).toBeFalsy();
+
+ // A missing required param names the param; there is no value to invent, so no fix.
+ const missing = expectOneBlockError(await call(full, 'get_page', {}), 'get_page {}');
+ expect(missing.code).toBe('invalid_params');
+ expect(missing.message).toContain('slug');
+ await full.close();
+ }, 240_000);
+
+ test('the brain stays healthy after the MCP session: health >= 90 with capped_by', async () => {
+ const r = await gb(home, ['doctor', '--json'], { timeoutMs: 120_000 });
+ expect(r.exitCode).toBe(0);
+ expectHealthy(oneDocument(r, 'doctor --json (after MCP)') as DoctorReport, 'after MCP');
+ expect(timings.initialize_ms).toBeLessThan(30_000);
+ expect(timings.first_recall_ms).toBeLessThan(30_000);
+ }, 150_000);
+});
diff --git a/test/cli-contract.serial.test.ts b/test/cli-contract.serial.test.ts
index 9c22ae3e9a..c4481809f3 100644
--- a/test/cli-contract.serial.test.ts
+++ b/test/cli-contract.serial.test.ts
@@ -117,6 +117,8 @@ const JSON_ROWS: Record<string, JsonRow> = {
ok: ['eval', 'gate', '--qrels', QRELS, '--embedder', 'deterministic', '--threshold-recall-at-k', '0', '--threshold-first-relevant-hit', '0', '--threshold-expected-top1', '0', '--json'],
fail: ['eval', 'gate', '--qrels', QRELS, '--embedder', 'deterministic', '--json'], failOnBrain: true,
},
+ // Lane H journey: import declares json (one document; a keyless brain's refusal is an embedding_disabled envelope).
+ import: { ok: ['import', join(brainHome, 'loose'), '--no-embed', '--json'], fail: ['import', join(brainHome, 'loose'), '--json'], failOnBrain: true },
'apply-migrations': { ok: ['apply-migrations', '--dry-run', '--json'], fail: ['apply-migrations', '--json', '--migration', '9.9.9'], failOnBrain: true },
};
@@ -151,6 +153,8 @@ describe('D5 json contract: one success and one failure per json-declared comman
writeFileSync(join(repo, 'example.md'), '---\ntitle: Example\n---\nHello world\n');
const git = (args: string[]) => Bun.spawnSync(['git', '-c', '[email protected]', '-c', 'user.name=fixture', ...args], { cwd: repo });
git(['init', '-q']); git(['add', '.']); git(['commit', '-qm', 'init']);
+ mkdirSync(join(brainHome, 'loose'));
+ writeFileSync(join(brainHome, 'loose', 'loose-page.md'), '---\ntitle: Loose\n---\nA page outside any source repo\n');
const add = await runCli(['sources', 'add', 'notes', '--path', repo], { home: brainHome, cwd: brainHome, timeoutMs: 60_000 });
if (add.exitCode !== 0) throw new Error(`fixture sources add failed: ${add.stderr}`);
}, 240_000);
diff --git a/test/fixtures/agent-contract/v1/journey/caller-mistake.json b/test/fixtures/agent-contract/v1/journey/caller-mistake.json
new file mode 100644
index 0000000000..b569e206fc
--- /dev/null
+++ b/test/fixtures/agent-contract/v1/journey/caller-mistake.json
@@ -0,0 +1,9 @@
+{
+ "content": [
+ {
+ "type": "text",
+ "text": "{\n \"error\": \"invalid_params\",\n \"code\": \"invalid_params\",\n \"message\": \"Parameter \\\"limit\\\" must be a number\",\n \"suggestion\": \"Pass `limit` as a number (Per-arm cap: max fact rows AND max search results. Default 50, cap 100). Example: recall {\\\"limit\\\": 10}. Next: recall {\\\"query\\\":\\\"quokka-journey-marker\\\",\\\"limit\\\":10}\",\n \"docs\": \"{{DOCS_BASE}}/docs/guides/error-codes.md#invalid_params\",\n \"protocol_version\": 1,\n \"fix\": {\n \"mcp\": {\n \"tool\": \"recall\",\n \"arguments\": {\n \"query\": \"quokka-journey-marker\",\n \"limit\": 10\n }\n },\n \"consent\": [],\n \"actor\": \"agent\",\n \"why\": \"The call failed validation before it ran, so nothing changed. This is the same call with your other arguments kept and `limit` set to 10.\",\n \"requires_exclusive\": false\n },\n \"docs_cmd\": [\n \"gbrain\",\n \"errors\",\n \"invalid_params\"\n ],\n \"class\": \"caller\",\n \"retryable\": false,\n \"contract_version\": 1\n}"
+ }
+ ],
+ "isError": true
+}
diff --git a/test/fixtures/agent-contract/v1/journey/init-first-run.json b/test/fixtures/agent-contract/v1/journey/init-first-run.json
new file mode 100644
index 0000000000..066181767a
--- /dev/null
+++ b/test/fixtures/agent-contract/v1/journey/init-first-run.json
@@ -0,0 +1,96 @@
+{
+ "status": "success",
+ "engine": "pglite",
+ "path": "{{HOME}}/.gbrain/brain.pglite",
+ "pages": 0,
+ "embedding_check": {
+ "ok": true,
+ "skipped": "no_embedding"
+ },
+ "content": {
+ "version": 1,
+ "brain_id": "{{UUID}}",
+ "source_id": "default",
+ "source_incarnation": "{{UUID}}",
+ "root": "{{HOME}}/.gbrain/content/{{UUID}}/default",
+ "repository_kind": "content_directory",
+ "backup": "not_verified",
+ "status": "ready",
+ "stage": "complete",
+ "pending_actions": [
+ "Optional: initialize Git explicitly; configure an off-host backup separately."
+ ],
+ "owned_root": true,
+ "fresh_root_activation": true,
+ "root_identity": "{{ROOT_IDENTITY}}"
+ },
+ "notices": [
+ {
+ "code": "first_run_decisions",
+ "kind": "ask",
+ "why": "The brain is ready. These settings were applied with defaults or need the user's choice; none blocks using the brain.",
+ "user_message": "gbrain is installed. Reply 'defaults' to keep the recommended settings (search_mode: conservative; harness_wiring: skip), or tell me what to change.",
+ "decisions": [
+ {
+ "id": "search_mode",
+ "question": "Which search mode should this brain use? Per-query search payload cost at 10K queries/month (Haiku 4.5 / Sonnet 4.6 / Opus 4.7): conservative $40 / $120 / $200, balanced $100 / $300 / $500, tokenmax $200 / $600 / $1,000 per month.",
+ "options": [
+ {
+ "id": "conservative",
+ "label": "conservative (applied)",
+ "argv": [
+ "gbrain",
+ "config",
+ "set",
+ "search.mode",
+ "conservative"
+ ]
+ },
+ {
+ "id": "balanced",
+ "label": "balanced",
+ "argv": [
+ "gbrain",
+ "config",
+ "set",
+ "search.mode",
+ "balanced"
+ ]
+ },
+ {
+ "id": "tokenmax",
+ "label": "tokenmax",
+ "argv": [
+ "gbrain",
+ "config",
+ "set",
+ "search.mode",
+ "tokenmax"
+ ]
+ }
+ ],
+ "default": "conservative",
+ "default_reason": "No expansion-capable API key (Anthropic/OpenAI/Google) — start with a tight result budget; semantic result caching is temporarily disabled."
+ },
+ {
+ "id": "harness_wiring",
+ "question": "Which agent app should get gbrain memory? The install guide has a one-line command for each.",
+ "options": [
+ {
+ "id": "wire",
+ "label": "Register `<absolute path to gbrain> serve --surface verbs` as a stdio MCP server in your agent host; the install section lists the exact command per harness (Claude Code, Codex, Grok Build, opencode, OpenClaw)."
+ },
+ {
+ "id": "skip",
+ "label": "Do not register gbrain with an agent harness now."
+ }
+ ],
+ "default": "skip",
+ "default_reason": "No agent harness was detected."
+ }
+ ],
+ "contract_version": 1
+ }
+ ],
+ "contract_version": 1
+}
diff --git a/test/fixtures/agent-contract/v1/journey/recall-degraded.json b/test/fixtures/agent-contract/v1/journey/recall-degraded.json
new file mode 100644
index 0000000000..287e855970
--- /dev/null
+++ b/test/fixtures/agent-contract/v1/journey/recall-degraded.json
@@ -0,0 +1,22 @@
+{
+ "_meta": {
+ "gbrain_notices": [
+ {
+ "code": "degraded_recall",
+ "kind": "degraded",
+ "why": "Recall was degraded (keyword_only_no_embedding_provider): semantic (vector) search did not run, so matches phrased differently from the query can be missing. Treat a thin or empty result as \"not found with a degraded search\", never as \"the brain has nothing on this\". This brain was set up keyword-only by the user's choice; mention it only if the user asks why something was not found.",
+ "contract_version": 1
+ }
+ ]
+ },
+ "content": [
+ {
+ "type": "text",
+ "text": "{\n \"facts\": [\n {\n \"id\": 1,\n \"fact\": \"quokka-journey-marker is the install-check fact\",\n \"kind\": \"fact\",\n \"entity_slug\": null,\n \"source_id\": \"default\",\n \"visibility\": \"world\",\n \"notability\": \"medium\",\n \"valid_from\": \"{{TIME}}\",\n \"valid_until\": null,\n \"expired_at\": null,\n \"superseded_by\": null,\n \"consolidated_at\": null,\n \"consolidated_into\": null,\n \"source\": \"install-check\",\n \"source_session\": null,\n \"context\": null,\n \"confidence\": 1,\n \"created_at\": \"{{TIME}}\",\n \"fact_id\": \"1\",\n \"provenance\": \"install-check\"\n }\n ],\n \"total\": 1,\n \"protocol_version\": 1,\n \"results\": [\n {\n \"slug\": \"journey-note-3\",\n \"title\": \"Journey note 3\",\n \"chunk\": \"# Journey note 3\\n\\nThe quokka-journey-marker 3 lives in note 3.\",\n \"evidence\": \"keyword_exact\",\n \"create_safety\": \"probable\",\n \"provenance\": \"journey-note-3\"\n },\n {\n \"slug\": \"journey-note-2\",\n \"title\": \"Journey note 2\",\n \"chunk\": \"# Journey note 2\\n\\nThe quokka-journey-marker 2 lives in note 2.\",\n \"evidence\": \"keyword_exact\",\n \"create_safety\": \"probable\",\n \"provenance\": \"journey-note-2\"\n },\n {\n \"slug\": \"journey-note-1\",\n \"title\": \"Journey note 1\",\n \"chunk\": \"# Journey note 1\\n\\nThe quokka-journey-marker 1 lives in note 1.\",\n \"evidence\": \"keyword_exact\",\n \"create_safety\": \"probable\",\n \"provenance\": \"journey-note-1\"\n }\n ],\n \"search_degraded\": \"keyword_only_no_embedding_provider\"\n}"
+ },
+ {
+ "type": "text",
+ "text": "[gbrain notice degraded_recall kind=degraded]\nwhy: Recall was degraded (keyword_only_no_embedding_provider): semantic (vector) search did not run, so matches phrased differently from the query can be missing. Treat a thin or empty result as \"not found with a degraded search\", never as \"the brain has nothing on this\". This brain was set up keyword-only by the user's choice; mention it only if the user asks why something was not found."
+ }
+ ]
+}
diff --git a/test/fixtures/agent-contract/v1/journey/status-only-lock-held.json b/test/fixtures/agent-contract/v1/journey/status-only-lock-held.json
new file mode 100644
index 0000000000..da59f76602
--- /dev/null
+++ b/test/fixtures/agent-contract/v1/journey/status-only-lock-held.json
@@ -0,0 +1,8 @@
+{
+ "content": [
+ {
+ "type": "text",
+ "text": "{\n \"status\": \"unavailable\",\n \"reason\": \"lock_held\",\n \"why\": \"This brain ({{HOME}}/.gbrain/brain.pglite) is open in another `gbrain serve` (PID {{PID}}), usually started by another agent session, so this server cannot open it.\",\n \"brain_path\": \"{{HOME}}/.gbrain/brain.pglite\",\n \"config_path\": \"{{HOME}}/.gbrain/config.json\",\n \"lock_owner\": {\n \"pid\": \"{{PID}}\",\n \"transport\": \"stdio\",\n \"serve\": true\n },\n \"fix\": {\n \"mcp\": {\n \"tool\": \"gbrain_status\",\n \"arguments\": {}\n },\n \"consent\": [],\n \"actor\": \"user\",\n \"why\": \"Close the session that owns the brain (another `gbrain serve` (PID {{PID}}), usually started by another agent session); then call gbrain_status again and this server opens the brain in place (re-checked at most every 5 s). If your client does not refresh its tool list after recovery, restart this MCP server.\",\n \"user_message\": \"Your gbrain brain is already open in another gbrain serve (PID {{PID}}), usually started by another agent session, so this session can't use memory right now. Close that session and I'll reconnect, or I can set up one shared gbrain server so both sessions work at once. Which do you prefer?\",\n \"requires_exclusive\": false\n },\n \"user_message\": \"Your gbrain brain is already open in another gbrain serve (PID {{PID}}), usually started by another agent session, so this session can't use memory right now. Close that session and I'll reconnect, or I can set up one shared gbrain server so both sessions work at once. Which do you prefer?\",\n \"decisions\": [\n {\n \"id\": \"lock_recovery\",\n \"question\": \"Two agent sessions want the same brain. Close the other session, or share one HTTP server?\",\n \"options\": [\n {\n \"id\": \"close_owner\",\n \"label\": \"Close another gbrain serve (PID {{PID}}), usually started by another agent session; this server recovers on the next gbrain_status call.\"\n },\n {\n \"id\": \"share_http\",\n \"label\": \"Run one shared `gbrain serve --http` and connect every harness to it (writes harness config, mints tokens); the full plan is share_http_plan.\",\n \"argv\": [\n \"kill\",\n \"{{PID}}\"\n ]\n }\n ],\n \"default\": \"close_owner\",\n \"default_reason\": \"Nothing is installed or reconfigured; the brain comes back as soon as the other session ends.\"\n }\n ],\n \"share_http_plan\": {\n \"argv\": [\n \"kill\",\n \"{{PID}}\"\n ],\n \"command\": \"kill {{PID}}\",\n \"consent\": [],\n \"actor\": \"user\",\n \"why\": \"Stop another `gbrain serve` (PID {{PID}}), usually started by another agent session first (or quit that session); the shared server needs the brain's single-writer lock.\",\n \"requires_exclusive\": false,\n \"then\": {\n \"argv\": [\n \"gbrain\",\n \"serve\",\n \"--http\"\n ],\n \"command\": \"gbrain serve --http\",\n \"consent\": [\n \"persistent_install\"\n ],\n \"actor\": \"user\",\n \"why\": \"Run ONE shared HTTP server for every agent session on this machine (keep it running, e.g. under autopilot or a terminal).\",\n \"requires_exclusive\": true,\n \"then\": {\n \"argv\": [\n \"gbrain\",\n \"bootstrap\",\n \"harness\",\n \"--harness\",\n \"all\",\n \"--yes\"\n ],\n \"command\": \"gbrain bootstrap harness --harness all --yes\",\n \"consent\": [\n \"persistent_install\",\n \"credentials\"\n ],\n \"actor\": \"user\",\n \"why\": \"Mints one bearer token per detected harness through the running HTTP server and rewrites each harness MCP entry to it (each stdio entry keeps working until its harness is rewired).\",\n \"user_message\": \"I can connect your agent apps to the shared gbrain server so every session uses memory at once. That stores an access token in each app's config and pre-approves gbrain's tools. OK?\",\n \"verify\": {\n \"argv\": [\n \"gbrain\",\n \"doctor\",\n \"--only\",\n \"harness_wiring\",\n \"--json\"\n ]\n },\n \"docs\": \"{{DOCS_BASE}}/docs/guides/remote-mcp.md\",\n \"requires_exclusive\": false\n }\n }\n },\n \"checked_at\": \"{{TIME}}\",\n \"contract_version\": 1\n}"
+ }
+ ]
+}
diff --git a/test/helpers/agent-journey.ts b/test/helpers/agent-journey.ts
new file mode 100644
index 0000000000..d08624e07b
--- /dev/null
+++ b/test/helpers/agent-journey.ts
@@ -0,0 +1,201 @@
+/**
+ * Shared harness for the Lane H agent journeys (docs/designs/AGENT_OPERATOR_WAVE.md
+ * "Lane H"): the real CLI as a subprocess and real stdio MCP sessions against a
+ * keyless PGLite brain in a hermetic HOME, the way an agent harness drives gbrain.
+ *
+ * - `gb()` runs `bun --no-env-file run src/cli.ts …` with stdin either closed
+ * (`</dev/null`) or an open pipe that never writes (a harness that forgot to
+ * close stdin), under a hard SIGKILL timeout, and times the run.
+ * - `mcp()` opens a real `gbrain serve` over stdio with the MCP SDK client.
+ * - `journeyGolden()` freezes a normalised wire value under
+ * test/fixtures/agent-contract/v1/journey/ (paths, pids, ids and times become
+ * placeholders; `next` is never stored, like the A0 goldens). The protocol
+ * page's journey transcripts are generated from these files
+ * (scripts/build-agent-protocol.ts). Regenerate: GBRAIN_TEST_UPDATE_GOLDENS=1.
+ */
+import { expect } from 'bun:test';
+import { mkdirSync, readFileSync, 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 { keylessBrainEnv } from './provider-env.ts';
+
+export const REPO = join(import.meta.dir, '..', '..');
+const CLI = join(REPO, 'src', 'cli.ts');
+export const JOURNEY_GOLDENS = join(REPO, 'test', 'fixtures', 'agent-contract', 'v1', 'journey');
+
+export type StdinMode = 'devnull' | 'silent';
+
+/**
+ * Process-scoped agent markers (src/core/interaction.ts) and harness config
+ * homes: harness detection reads them, so a test runner inside an agent or
+ * with a real harness config must not leak them into the journey.
+ */
+const AMBIENT_HARNESS = ['CLAUDECODE', 'CLAUDE_CODE_ENTRYPOINT', 'CODEX_SANDBOX', 'CODEX_CI', 'OPENCODE', 'OPENCODE_PID',
+ 'CODEX_HOME', 'CLAUDE_CONFIG_DIR', 'XDG_CONFIG_HOME', 'XDG_DATA_HOME'];
+
+/** Hermetic keyless env: no provider keys, no database URLs, no agent markers or harness config homes, no ambient GBRAIN_* routing (brain, source, surface…). */
+export function journeyEnv(home: string, extra: Record<string, string | undefined> = {}): Record<string, string> {
+ const env = keylessBrainEnv(process.env, home);
+ for (const key of Object.keys(env)) {
+ if (key.startsWith('GBRAIN_') || key === 'DATABASE_URL' || key === 'LLMS_REPO_BASE' || AMBIENT_HARNESS.includes(key)) delete env[key];
+ }
+ env.HOME = home;
+ env.GBRAIN_HOME = home;
+ env.GBRAIN_SKIP_STARTUP_HOOKS = '1';
+ for (const [k, v] of Object.entries(extra)) {
+ if (v === undefined) delete env[k];
+ else env[k] = v;
+ }
+ return env;
+}
+
+export interface GbResult { exitCode: number; stdout: string; stderr: string; ms: number; killed: boolean }
+
+/** One CLI invocation as a non-TTY agent shell runs it. Fails the test if the hard timeout had to kill it. */
+export async function gb(home: string, args: string[], opts: { stdin?: StdinMode; cwd?: string; timeoutMs?: number; env?: Record<string, string | undefined> } = {}): Promise<GbResult> {
+ const t0 = performance.now();
+ const proc = Bun.spawn(['bun', '--no-env-file', 'run', CLI, ...args], {
+ cwd: opts.cwd ?? home,
+ env: journeyEnv(home, opts.env),
+ stdin: opts.stdin === 'silent' ? 'pipe' : Bun.file('/dev/null'),
+ stdout: 'pipe',
+ stderr: 'pipe',
+ });
+ let killed = false;
+ const killer = setTimeout(() => { killed = true; try { proc.kill('SIGKILL'); } catch { /* gone */ } }, opts.timeoutMs ?? 90_000);
+ try {
+ const [stdout, stderr, exitCode] = await Promise.all([new Response(proc.stdout).text(), new Response(proc.stderr).text(), proc.exited]);
+ const res = { exitCode, stdout, stderr, ms: Math.round(performance.now() - t0), killed };
+ expect(killed, `gbrain ${args.join(' ')} hung (stdin ${opts.stdin ?? 'devnull'}) and was killed:\n${stderr.slice(-2000)}`).toBe(false);
+ return res;
+ } finally {
+ clearTimeout(killer);
+ if (opts.stdin === 'silent') try { (proc.stdin as { end?: () => void }).end?.(); } catch { /* closed */ }
+ }
+}
+
+/** stdout of a `--json` invocation must be exactly one JSON document. */
+export function oneDocument(r: GbResult, label: string): Record<string, any> {
+ try {
+ const doc = JSON.parse(r.stdout);
+ expect(doc !== null && typeof doc === 'object', `${label}: --json stdout is not an object`).toBe(true);
+ return doc;
+ } catch (e) {
+ throw new Error(`${label}: --json stdout is not one JSON document (exit ${r.exitCode}): ${String(e)}\nstdout: ${r.stdout.slice(0, 1500)}\nstderr: ${r.stderr.slice(-1500)}`);
+ }
+}
+
+export interface McpSession {
+ client: Client;
+ pid: number;
+ initMs: number;
+ stderr: () => string;
+ close: () => Promise<void>;
+}
+
+/** A real `gbrain serve` on stdio, initialised (handshake done) with the SDK client. */
+export async function mcp(home: string, serveArgs: string[] = [], opts: { cwd?: string; env?: Record<string, string | undefined> } = {}): Promise<McpSession> {
+ const transport = new StdioClientTransport({
+ command: 'bun', args: ['--no-env-file', 'run', CLI, 'serve', ...serveArgs],
+ cwd: opts.cwd ?? home, env: journeyEnv(home, opts.env), stderr: 'pipe',
+ });
+ let stderr = '';
+ transport.stderr?.on('data', (d: Buffer) => { stderr += d.toString(); });
+ const client = new Client({ name: 'agent-journey', version: '1.0.0' }, { capabilities: {} });
+ const t0 = performance.now();
+ await client.connect(transport);
+ const initMs = Math.round(performance.now() - t0);
+ return {
+ client, pid: transport.pid ?? -1, initMs, stderr: () => stderr,
+ close: async () => { try { await client.close(); } catch { /* best-effort */ } },
+ };
+}
+
+export interface ToolResult { content: Array<{ type: string; text: string }>; isError?: boolean; _meta?: Record<string, any> }
+
+export async function call(s: McpSession, name: string, args: Record<string, unknown> = {}): Promise<ToolResult> {
+ return await s.client.callTool({ name, arguments: args }) as unknown as ToolResult;
+}
+
+/** content[0] parsed: the result body, or the error envelope of an isError result. */
+export function body(r: ToolResult): any {
+ return JSON.parse(r.content[0].text);
+}
+
+export const NOTICE_PREFIX = '[gbrain notice ';
+
+/** The prefixed notice blocks after content[0]. */
+export function noticeBlocks(r: ToolResult): string[] {
+ return r.content.slice(1).map(c => c.text).filter(t => t.startsWith(NOTICE_PREFIX));
+}
+
+/** Error results are exactly one content block holding the v1 envelope (A6). */
+export function expectOneBlockError(r: ToolResult, label: string): any {
+ expect(r.isError, `${label}: isError`).toBe(true);
+ expect(r.content.length, `${label}: an error result is one content block`).toBe(1);
+ const env = body(r);
+ expect(env.contract_version, `${label}: contract_version`).toBe(1);
+ expect(typeof env.code, `${label}: code`).toBe('string');
+ expect(typeof env.suggestion, `${label}: suggestion`).toBe('string');
+ return env;
+}
+
+export async function waitFor(pred: () => Promise<boolean> | boolean, ms = 30_000): Promise<boolean> {
+ const end = Date.now() + ms;
+ while (Date.now() < end) {
+ if (await pred()) return true;
+ await new Promise(r => setTimeout(r, 500));
+ }
+ return false;
+}
+
+// ── journey goldens ────────────────────────────────────────────────────────
+
+const UUID = /[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}/g;
+const ISO = /\d{4}-\d{2}-\d{2}[T ]\d{2}:\d{2}:\d{2}(?:\.\d+)?(?:Z|[+-]\d{2}(?::?\d{2})?)?/g;
+const DOCS = /https:\/\/github\.com\/garrytan\/gbrain\/blob\/[^/\s"]+/g;
+const VOLATILE_KEYS = new Set(['duration_s', 'root_identity', 'plan_hash', 'doctor_run_id']);
+
+export interface GoldenVars { home: string; pids?: number[] }
+
+function normaliseString(s: string, v: GoldenVars): string {
+ let out = s.split(v.home).join('{{HOME}}').replace(DOCS, '{{DOCS_BASE}}').replace(UUID, '{{UUID}}').replace(ISO, '{{TIME}}')
+ .replace(/ph_[0-9a-f]{24}/g, '{{PLAN_HASH}}');
+ for (const pid of v.pids ?? []) out = out.replace(new RegExp(`\\b${pid}\\b`, 'g'), '{{PID}}');
+ return out.replace(/^next: [a-z_]+$/m, 'next: {{next}}');
+}
+
+/** Paths, pids, ids, times and plan hashes become placeholders; `next` is stripped (computed at render time). */
+export function normaliseWire(value: unknown, v: GoldenVars): unknown {
+ if (Array.isArray(value)) return value.map(x => normaliseWire(x, v));
+ if (value && typeof value === 'object') {
+ const out: Record<string, unknown> = {};
+ for (const [k, x] of Object.entries(value as Record<string, unknown>)) {
+ if (k === 'next') continue;
+ if (VOLATILE_KEYS.has(k)) { out[k] = `{{${k.toUpperCase()}}}`; continue; }
+ if ((k === 'pid' || k === 'lock_owner_pid') && typeof x === 'number' && (v.pids ?? []).includes(x)) { out[k] = '{{PID}}'; continue; }
+ out[k] = normaliseWire(x, v);
+ }
+ return out;
+ }
+ if (typeof value === 'string') {
+ const t = value.trimStart();
+ if (t.startsWith('{') || t.startsWith('[')) {
+ try { return JSON.stringify(normaliseWire(JSON.parse(value), v), null, 2); } catch { /* prose */ }
+ }
+ return normaliseString(value, v);
+ }
+ return value;
+}
+
+/** Compare (or, with GBRAIN_TEST_UPDATE_GOLDENS=1, rewrite) one journey golden. */
+export function journeyGolden(name: string, actual: unknown, vars: GoldenVars): void {
+ const path = join(JOURNEY_GOLDENS, name);
+ const text = `${JSON.stringify(normaliseWire(actual, vars), null, 2)}\n`;
+ if (process.env.GBRAIN_TEST_UPDATE_GOLDENS === '1') {
+ mkdirSync(JOURNEY_GOLDENS, { recursive: true });
+ writeFileSync(path, text);
+ }
+ expect(text, `journey golden ${name} drifted; if the change is intended, regenerate with GBRAIN_TEST_UPDATE_GOLDENS=1 and run bun run build:agent-protocol`).toBe(readFileSync(path, 'utf8'));
+}
diff --git a/test/readiness-advice-lint.test.ts b/test/readiness-advice-lint.test.ts
index 9c9d2c81a6..9ed1047999 100644
--- a/test/readiness-advice-lint.test.ts
+++ b/test/readiness-advice-lint.test.ts
@@ -21,7 +21,7 @@ const EXEMPT = new Set(['src/core/readiness.ts', 'src/core/cli-flag-registry.gen
/** Shrink-only baseline: file → allowed hit count, with the owner that removes it. */
const ALLOWLIST: Record<string, { count: number; reason: string }> = {
'src/commands/doctor/checks/embedding-health.ts': { count: 1, reason: 'Lane E1: doctor fixes become readiness Actions' },
- 'src/commands/init.ts': { count: 3, reason: 'Lane E/G5: init deferred-setup hint renders embeddingEnablement' },
+ 'src/commands/init.ts': { count: 2, reason: 'Lane E/G5: init deferred-setup hint renders embeddingEnablement' },
'src/commands/models.ts': { count: 1, reason: 'Lane E: models dims hint' },
'src/commands/reindex-code.ts': { count: 2, reason: 'Lane E: reindex-code embedding hint' },
'src/commands/reinit-pglite.ts': { count: 2, reason: 'usage examples of reinit-pglite\'s own --embedding-model flag' },