Skip to content

Garry's Opinionated OpenClaw/Hermes Agent Brain

TypeScript

bootstrap status: detect and adopt a Codex project-scoped MCP connection (#4082)

garrytan3ca6c869a5d7
diff --git a/scripts/module-size-limits.tsv b/scripts/module-size-limits.tsv
index 94840ca45d..5d6fe78be7 100644
--- a/scripts/module-size-limits.tsv
+++ b/scripts/module-size-limits.tsv
@@ -28,7 +28,7 @@ src/core/minions/queue.ts 2528 ratchet grown #4078 + megawave probe-liveness unl
src/commands/init.ts 1878 ratchet +2 fix wave 9 lane F #5253: leaving deferred setup also clears the DB-plane embedding_disabled row (both init branches); grown v0.46.x keyless capability notices; grown db-availability loop: initPostgresCore typed-failure extraction + --prefer-postgres ladder hook + pgvector rethrow fix; +1 at megawave/wave-k merge; +master-merge true-up; wave-k: merge; #3753 --force re-init engine-preservation guard; +1 wave-k merge-union brace (--prefer-postgres close); +10 ambient-writeback WP8: runWritebackNudge consent ask in both engine epilogues (logic lives in core/onboard/writeback-nudge.ts); +4: v0.48.2 reranker readiness at init + test seam; +1: v0.48.2 provider normalization; +3: v0.48.2 review fixes; master integration: +2: preserve typed PGLite busy errors in schema-only init; shared-skills integration on company-ingestion base; retired provider integration removed; retain stored-vector identity on re-init; -14: first-run bundle + quickstart registration helpers live in init-first-run.ts (writeback/skills asks folded into the bundle); +5 agent operator follow-up Item 2: --surface flag (value flag, parse, help line, module-level registration surface, type import) for the printed harness registration; +2 fix wave lane B3: both engine paths stamp a database init created as a fresh install for the behavior_changes notice (core/behavior-change-notice.ts)
src/commands/integrations.ts 1739 ratchet grown v0.46.26.0 megawave (#4039 connector compat) + 1 nosemgrep dataflow annotation (path-traversal audit); wave-k: exported heartbeatPath seam (#3900)
src/core/minions/handlers/subagent.ts 1925 ratchet merged: master v131 settle rework + dream-wave C5 peel + C6 accounting + C7 lease heartbeats/lost-lease aborts + C9 oneshot dispatch + adversarial fix batches; grown by #4078 subagent-loop capability fix; +6 lines (reasoning-item replay: adaptContentBlocksToChatBlocks handles 'reasoning' blocks); +3 wave G #4514: Anthropic-via-OpenRouter allowed on the subagent loop; +36 lines (code review, same PR): isPromptTooLongError walks a bounded .cause chain so it still matches post-normalizeAIError() wrapping, plus extractPromptTooLongDetail so the dead-lettered job's error carries the matched provider detail instead of the generic normalizeAIError() wrapper text; master integration: harness support: boundary wiring to shared grants, isolated setup, withdrawal and delegated guards; #5105: +13 call-site wiring to shared tool-write-identity helper across fresh and replay dispatch; +7 fix wave 9 lane B #4921: ai.chat.per_turn_timeout_ms read once and passed to the oneshot and gateway-loop paths (resolver lives in minions/handler-timeouts.ts)
-src/commands/bootstrap.ts 2134 ratchet grandfathered at merge (grew past the 1500 cap on master); raised for #4066 HOME_WORKSPACE_GUARD_EXEMPT (status/uninstall/harness); +5 for the harnessDetect test seam (bulk lives in core/bootstrap/harness.ts); +23 for the contract subcommand dispatcher glue (#4105 absorb — bulk lives in core/bootstrap/contract.ts); +codex hooks-consent gate + mcp+hooks receipt registration + uninstall arm; +42 ambient-writeback WP8: interview-time SURFACE_MULTIUSER audience apply (pre-init ordering) + applyDeclaredAudienceFromInterview; +3 #4897 harness usage clause documenting --source ID semantics; +5 #5878: --refresh-skills dispatch and usage lines (logic in core/bootstrap/harness-skills.ts); +11 #5488: SUBCOMMAND_HELP harness entry (gate on --help / -h / help) — CLI help line, cannot move; +11 #4618 seat: --seat/--no-seat help lines and the runHooks parse (parse + notes live in core/bootstrap/hooks.ts parseSeatFlags)
+src/commands/bootstrap.ts 2141 ratchet grandfathered at merge (grew past the 1500 cap on master); raised for #4066 HOME_WORKSPACE_GUARD_EXEMPT (status/uninstall/harness); +5 for the harnessDetect test seam (bulk lives in core/bootstrap/harness.ts); +23 for the contract subcommand dispatcher glue (#4105 absorb — bulk lives in core/bootstrap/contract.ts); +codex hooks-consent gate + mcp+hooks receipt registration + uninstall arm; +42 ambient-writeback WP8: interview-time SURFACE_MULTIUSER audience apply (pre-init ordering) + applyDeclaredAudienceFromInterview; +3 #4897 harness usage clause documenting --source ID semantics; +5 #5878: --refresh-skills dispatch and usage lines (logic in core/bootstrap/harness-skills.ts); +11 #5488: SUBCOMMAND_HELP harness entry (gate on --help / -h / help) — CLI help line, cannot move; +11 #4618 seat: --seat/--no-seat help lines and the runHooks parse (parse + notes live in core/bootstrap/hooks.ts parseSeatFlags); +7 #4082: --adopt dispatch in runHooks and its two help lines (adoption logic lives in core/bootstrap/adopt-connection.ts + adopted-connections.ts)
src/core/minions/worker.ts 1774 ratchet grandfathered at merge (grew past the 1500 cap on master, #4170); grown v0.46.11.0 five-issue wave; security: durable queued authority and confined filesystem dispatch; typed readiness, configuration-blocked lifecycle and bounded release; post-validation readiness publication and confirmed isolated-execution stop evidence; latch typed lock-renewal faults before generic retry; +9 Lane D: JobDeferredError routing (deferJob helper); +1 spend authorization: runWithJobSpend import (both handler seams call it in place of the bare handler)
src/commands/sources.ts 2059 ratchet +5 PR #5955 / fix wave 14 P2.7: sources set-strategy dispatch and help row, the strategy field of sources list --json (body in sources-strategy.ts); +5 #5988: sources status/retry-held help rows describe Git holds (help lines cannot move); +2 #5988: sources status <id> filter and Git held files (view in persistence/connector-status.ts); +5 F0: sources refresh dispatch and help rows (command body in sources-refresh.ts, protocol in persistence/worktree-refresh.ts); +6 fix wave 5 #5409: mirror-readonly/mirror-writable dispatch, help rows and the list --json mirror_read_only field (body in sources-mirror.ts); grown v0.46.22.0 phone wave: github source kind (#4104); +129 v0.47 gmail-loops: google source-kind flags + vault preflight + duplicate-account warn + access-mode validation; +8 set-path dispatch + help rows (#4739 — command body peeled to sources-set-path.ts); +29 #4698 adoption: --calendar-id flag + duplicate-account warn scoped to overlapping services; #5105: trusted writer administration route; company handlers and receipt status wiring; parsing stays in dedicated modules; canonical reconciliation: +5 engine-free sibling-command dispatch and help row, implementation remains in source-reconcile.ts; +4 fix wave 3 lane A: sources status connector recovery state and run counts (view lives in persistence/connector-status.ts); +3 fix wave 4 lane B: sources retry-held dispatch and help row (command body in sources-retry-held.ts) and the connector first-sync note on add; bodies in source-delete.ts and sources-set-path.ts); +4 #5984: sources status shows the managed sync backlog (logic in persistence/sync-drain.ts); v0.60.48.0 merge: #5984 growth re-summed over v0.60.47.0 (2031 measured); +11 W-B4: sources shared-skills dispatch, its --help guard and help rows, and the shared_skills field/lines in sources status (body in sources-shared-skills.ts, view in shared-skills/source-opt-out.ts); +4 #6188: uncommitted legacy fence-repair notices in sources status (logic in fence-repair/uncommitted.ts); +7 #6317: data_moving/movement_state on sources status and its human line (reader in persistence/sync-movement.ts), writer movement help row
src/core/link-extraction.ts 2358 ratchet grown v0.46.26.0 megawave: link-aware timeline split + delimiter-outside-links (#3957 #4062 #3737); +37 wave-k #3908 reimpl: isCrossSourceLinksEnabled config ladder; +10 wave #4277: parseTimelineEntries skips generated backlink receipts; +17 #4855: latin-fold in normalizeBasename + dir-hint step tries both slug grammars; +17: #4855 Latin stroke-letter fold; +5: #4873 ./-relative markdown links kept as live references; +34 wave review: `../y.md` sibling links resolve on the DB path + folded bare-wikilink grammar (#4873 class); +62 #4977: role-prior suppression in machine-list sections (rolePriorSuppressedRanges, EntityRef.index); +3 composed with #4985 (variation-selector strip) in the same wave; +4 #4995: markdown-link anchor strip + lowercase-candidate rationale comments; +6 pre-landing review: #4977 suppression on code-stripped content + truthful watermark/section-list comments; T2: source-qualified inference and atomic origin-scoped derived links; canonical attendance evidence, source-qualified orientation, strict attendee resolution, and relocated filesystem link scanner (command export preserved); +4: pack-owned fallback and ambiguous attendee guards Display-label attendance exclusion, indexed evidence membership, and bounded strict resolver caching; attendance-boundary review.; complete attendance resolution and fence-safe evidence traversal; frontmatter discovery, canonical basename admission and code-aware attendance comment masking; exclude inline HTML comment spans from admitted attendance ranges; +17 write-path wave: same-name rule for entity fuzzy matches + rename-alias fallback in makeResolver; +1 #5567: materialized marker ends bullet detail; +30 #5749: unique global-basename step before fuzzy and live keyword resolution (ResolveOptions, watermark note); #5765: bold **Attendees:** label accepted + LINK_EXTRACTOR_VERSION_TS bump note; +10 eval-wave N9-2/N9-3/N12-7: pack frontmatter mappings inherit FRONTMATTER_LINK_MAP direction, page-type-bound pack attended follows canonical attendance, LINK_EXTRACTOR_VERSION_TS bump note; +1 #5623: normalizeBasename collapses hyphen runs like slugifySegment (extractor watermark note); +11 #5562: parseTimelineEntries accepts dated ### headings (FS-extractor parity); +3 eval-wave N12-6: Participants accepted as attendance evidence + LINK_EXTRACTOR_VERSION_TS bump note; +22 P5 wanted pages: AuthoredRef on body link candidates; -33 lowered: P5 moved machine-section ranges to core/machine-sections.ts and stated relation types to core/line-grammar.ts; +7 P5: ExtractPageLinksOptions interface + wikilinkAuthoredRef helper (keeps extractPageLinks under the function-size limit); +32 P5: per-edge verb attachment (attachedVerb, VERB_RULES) + joined-as works_at + extractor watermark note; P5 x temporal-edges merge: verb attachment reads the verb at the link's own position in the window (excerptAnchor) and the within-page dedup (now dedupeCandidates) drops a mention of a target the page also links with a typed edge; links joined only by commas/conjunctions share the verb before the first (coordinated); board roles (BOARD_RE, BOARD_AFTER_RE) resolve to invested_in for an investor page and advises otherwise, never works_at; +1 fix wave 11 #6191: imports targetTakesVerb (role-verb target guard lives in link-target-roles.ts); v0.60.105.0 merge: #5984 Phase 5 link preparation (+6) re-summed over wave 11 at 2211; +109 Q2 Track C: stable verb-rule ids, traceLinkType/explainLinkType (reasons for every typing decision), per-occurrence typer hoisted out of extractPageLinks (makeTypeFor); unit logic lives in core/link-typing-units.ts; +25 Q2 Track C: typing-unit verb rules and vetoes in attachedVerb/traceLinkType, validity stints in explainLinkType; +4 U3: board-seat rule split out of INVESTED_RE (same verb and precedence) and investor-prior/link offsets passed to unit vetoes; +11 U2: locateLink shared by attachedVerb and the U2 post-pass in traceLinkType; -11 lowered: Q2 verdict reverted U2 (locateLink and the post-pass)
diff --git a/src/commands/bootstrap.ts b/src/commands/bootstrap.ts
index 01e09a82fc..5ea8157267 100644
--- a/src/commands/bootstrap.ts
+++ b/src/commands/bootstrap.ts
@@ -203,9 +203,10 @@ const SUBCOMMAND_HELP: Record<string, string> = {
' under your own account), verify the privacy bit via the API, push.',
hooks:
'gbrain bootstrap hooks [--harness claude-code|codex|opencode] [--repair] [--no-hooks] [--gbrain-bin <path>]\n' +
- ' [--seat <label> | --no-seat] [--surface verbs|starter|full]\n' +
+ ' [--seat <label> | --no-seat] [--surface verbs|starter|full] [--adopt [--name <server>]]\n' +
' Register MCP (--surface full unless given; a replaced entry keeps its surface) (+ per-turn hooks on Claude Code, ON by default; --no-hooks opts out).\n' +
- ' --seat credits captured sessions to this agent seat (kept on re-install; --no-seat clears it; --seat off records none).',
+ ' --seat credits captured sessions to this agent seat (kept on re-install; --no-seat clears it; --seat off records none).\n' +
+ ' --adopt (Codex): record the project .codex/config.toml server you manage yourself as the wire evidence after a passing verify; writes no config.',
verify:
'gbrain bootstrap verify [--json]\n' +
' The whole install contract (round-trip, graph floor, magic moment, scans, hooks smoke). Exit 0 or not done.',
@@ -1100,6 +1101,12 @@ async function runHooks(
return 1;
}
const sourceId = state.manifest.source_id;
+ if (rest.includes('--adopt')) {
+ const { adoptConnection } = await import('../core/bootstrap/adopt-connection.ts');
+ const adopted = adoptConnection(ws, home, harness, flagValue(rest, '--name') ?? undefined);
+ for (const line of adopted.lines) (adopted.code === 0 ? console.log : console.error)(line);
+ return adopted.code;
+ }
// WP8: the interview's declared audience becomes the machine-local
// brain.audience declaration (file mirror; the classifier and the harness
diff --git a/src/core/bootstrap/adopt-connection.ts b/src/core/bootstrap/adopt-connection.ts
new file mode 100644
index 0000000000..efdd170880
--- /dev/null
+++ b/src/core/bootstrap/adopt-connection.ts
@@ -0,0 +1,66 @@
+/**
+ * `gbrain bootstrap hooks --adopt --harness codex [--name <server>]` (#4082):
+ * record an operator-managed Codex project connection as the wire phase's
+ * evidence instead of registering a user-global `codex mcp add` entry it does
+ * not need. Adoption needs proof the connection works, and the proof is the
+ * install contract: the newest `gbrain bootstrap verify` run must have passed
+ * and must be newer than the project config it vouches for. Nothing is written
+ * to `.codex/config.toml`, no receipt registration is fabricated, and the
+ * recorded fingerprint carries no header values or tokens.
+ */
+import { statSync } from 'node:fs';
+import { join } from 'node:path';
+type Harness = 'claude-code' | 'codex' | 'opencode';
+import { listVerifyRuns } from './status.ts';
+import {
+ CODEX_PROJECT_CONFIG,
+ DEFAULT_CODEX_SERVER_NAME,
+ adoptedConnectionsPath,
+ detectCodexProjectServer,
+ recordAdoptedConnection,
+} from './adopted-connections.ts';
+
+export interface AdoptConnectionResult { code: number; lines: string[] }
+
+export function adoptConnection(ws: string, gbrainHomeDir: string, harness: Harness, name = DEFAULT_CODEX_SERVER_NAME): AdoptConnectionResult {
+ if (harness !== 'codex') {
+ return { code: 2, lines: [`--adopt applies to a Codex project config (${CODEX_PROJECT_CONFIG}); ${harness} registrations are bootstrap-owned — run \`gbrain bootstrap hooks --harness ${harness}\` without --adopt`] };
+ }
+ let detected: ReturnType<typeof detectCodexProjectServer>;
+ try {
+ detected = detectCodexProjectServer(ws, name);
+ } catch (error) {
+ return { code: 1, lines: [`${CODEX_PROJECT_CONFIG} does not parse: ${error instanceof Error ? error.message : String(error)} — fix the file, then re-run`] };
+ }
+ if (!detected) {
+ return { code: 1, lines: [`nothing to adopt: ${CODEX_PROJECT_CONFIG} does not define mcp_servers.${name} in this workspace (pass --name <server> for another table, or run \`gbrain bootstrap hooks --harness codex\` for a bootstrap-owned registration)`] };
+ }
+ const verify = listVerifyRuns(gbrainHomeDir)[0] ?? null;
+ if (!verify || !verify.ok) {
+ return { code: 1, lines: [verify
+ ? `the newest \`gbrain bootstrap verify\` run (${verify.ts}) failed: ${verify.checks_failed.join(', ')} — fix it and re-run verify before adopting`
+ : 'no `gbrain bootstrap verify` run on record — adoption needs a passing verify as evidence; run it from this workspace first'] };
+ }
+ const configMtime = statSync(join(ws, CODEX_PROJECT_CONFIG)).mtime.toISOString();
+ if (configMtime > verify.ts) {
+ return { code: 1, lines: [`${CODEX_PROJECT_CONFIG} changed at ${configMtime}, after the newest passing verify (${verify.ts}) — re-run \`gbrain bootstrap verify\`, then adopt`] };
+ }
+ recordAdoptedConnection(gbrainHomeDir, {
+ harness: 'codex',
+ scope: 'project',
+ workspace: ws,
+ name,
+ transport: detected.transport,
+ target: detected.target,
+ fingerprint: detected.fingerprint,
+ adopted_at: new Date().toISOString(),
+ evidence: { verify_ts: verify.ts },
+ });
+ return {
+ code: 0,
+ lines: [
+ `adopted codex project connection mcp_servers.${name} (${detected.transport} ${detected.target}) — evidence: verify ${verify.ts}`,
+ `recorded in ${adoptedConnectionsPath(gbrainHomeDir)} (fingerprint ${detected.fingerprint.slice(0, 12)}…; no tokens stored); \`gbrain bootstrap status\` now reports the wire phase done`,
+ ],
+ };
+}
diff --git a/src/core/bootstrap/adopted-connections.ts b/src/core/bootstrap/adopted-connections.ts
new file mode 100644
index 0000000000..ce790eb055
--- /dev/null
+++ b/src/core/bootstrap/adopted-connections.ts
@@ -0,0 +1,135 @@
+/**
+ * Adopted harness connections (#4082): a Codex project-scoped MCP server the
+ * operator manages in `<workspace>/.codex/config.toml` (streamable HTTP with
+ * OAuth, logged in with `codex mcp login`) is not a bootstrap-owned
+ * registration, so `bootstrap status` used to report the wire phase pending
+ * and send the operator to a user-global `codex mcp add` it did not need.
+ *
+ * Three states, kept apart on purpose:
+ * - `detected`: the project config defines the server; nothing proves it works → `partial`;
+ * - `adopted`: `gbrain bootstrap wire --adopt --harness codex` recorded it after a
+ * passing `bootstrap verify`, with a redacted fingerprint → `done`;
+ * - `drifted`: the recorded fingerprint no longer matches the effective config
+ * (URL, header names, or the table is gone) → `partial`, re-adopt.
+ *
+ * The evidence lives in its own versioned sidecar beside the install receipt
+ * (`<gbrain-home>/bootstrap/adopted-connections.json`), never inside the
+ * receipt: uninstall tears down what bootstrap wrote, and this config is not
+ * that. The fingerprint is sha256 over the canonical JSON of the server's type,
+ * URL and header *names* (the shape `src/core/setup/claude-code.ts` uses for its
+ * MCP entries); header values and tokens are never stored or printed. Readable
+ * offline: no engine, no Codex binary.
+ */
+import { createHash } from 'node:crypto';
+import { existsSync, mkdirSync, readFileSync } from 'node:fs';
+import { join } from 'node:path';
+import { atomicWriteTextFile } from './atomic-write.ts';
+
+export const ADOPTED_CONNECTIONS_VERSION = 1;
+export const CODEX_PROJECT_CONFIG = join('.codex', 'config.toml');
+export const DEFAULT_CODEX_SERVER_NAME = 'gbrain';
+
+export interface DetectedCodexProjectServer {
+ harness: 'codex';
+ scope: 'project';
+ name: string;
+ transport: 'streamable_http' | 'stdio';
+ /** The URL for an HTTP server, the command for stdio; never a header value. */
+ target: string;
+ header_names: string[];
+ fingerprint: string;
+}
+
+export interface AdoptedConnection {
+ harness: 'codex';
+ scope: 'project';
+ workspace: string;
+ name: string;
+ transport: DetectedCodexProjectServer['transport'];
+ target: string;
+ fingerprint: string;
+ adopted_at: string;
+ /** What proved the connection: the passing verify run it was adopted after. */
+ evidence: { verify_ts: string };
+}
+
+export interface AdoptedConnectionsFile { version: typeof ADOPTED_CONNECTIONS_VERSION; connections: AdoptedConnection[] }
+
+export type AdoptedConnectionState =
+ | { state: 'adopted'; connection: AdoptedConnection; detected: DetectedCodexProjectServer }
+ | { state: 'drifted'; connection: AdoptedConnection; detected: DetectedCodexProjectServer | null; why: string }
+ | { state: 'detected'; detected: DetectedCodexProjectServer }
+ | { state: 'none' };
+
+const canonical = (v: unknown): unknown => Array.isArray(v) ? v.map(canonical)
+ : v && typeof v === 'object' ? Object.fromEntries(Object.keys(v as object).sort().map(k => [k, canonical((v as Record<string, unknown>)[k])])) : v;
+/** sha256 over canonical JSON of what identifies the connection; header values are excluded by construction. */
+export const connectionFingerprint = (parts: { type: string; target: string; header_names: string[] }): string =>
+ createHash('sha256').update(JSON.stringify(canonical(parts))).digest('hex');
+
+export function adoptedConnectionsPath(gbrainHomeDir: string): string {
+ return join(gbrainHomeDir, 'bootstrap', 'adopted-connections.json');
+}
+
+/**
+ * The effective `[mcp_servers.<name>]` table of the project config, or null
+ * when the file or the table is absent. Throws when the file does not parse:
+ * a broken config is a finding, not "no server".
+ */
+export function detectCodexProjectServer(ws: string, name = DEFAULT_CODEX_SERVER_NAME): DetectedCodexProjectServer | null {
+ const path = join(ws, CODEX_PROJECT_CONFIG);
+ if (!existsSync(path)) return null;
+ const parsed = (Bun as unknown as { TOML: { parse(t: string): unknown } }).TOML.parse(readFileSync(path, 'utf8'));
+ const servers = parsed && typeof parsed === 'object' ? (parsed as Record<string, unknown>).mcp_servers : undefined;
+ const server = servers && typeof servers === 'object' ? (servers as Record<string, unknown>)[name] : undefined;
+ if (!server || typeof server !== 'object') return null;
+ const table = server as Record<string, unknown>;
+ const headers = table.http_headers && typeof table.http_headers === 'object' ? Object.keys(table.http_headers as object).sort() : [];
+ if (typeof table.url === 'string' && table.url) {
+ return { harness: 'codex', scope: 'project', name, transport: 'streamable_http', target: table.url, header_names: headers,
+ fingerprint: connectionFingerprint({ type: 'codex:streamable_http', target: table.url, header_names: headers }) };
+ }
+ if (typeof table.command === 'string' && table.command) {
+ const command = [table.command, ...(Array.isArray(table.args) ? table.args.map(String) : [])].join(' ');
+ return { harness: 'codex', scope: 'project', name, transport: 'stdio', target: command, header_names: [],
+ fingerprint: connectionFingerprint({ type: 'codex:stdio', target: command, header_names: [] }) };
+ }
+ return null;
+}
+
+export function readAdoptedConnections(gbrainHomeDir: string): AdoptedConnectionsFile {
+ const path = adoptedConnectionsPath(gbrainHomeDir);
+ if (!existsSync(path)) return { version: ADOPTED_CONNECTIONS_VERSION, connections: [] };
+ try {
+ const parsed = JSON.parse(readFileSync(path, 'utf8')) as Partial<AdoptedConnectionsFile>;
+ if (parsed.version !== ADOPTED_CONNECTIONS_VERSION || !Array.isArray(parsed.connections)) return { version: ADOPTED_CONNECTIONS_VERSION, connections: [] };
+ return { version: ADOPTED_CONNECTIONS_VERSION, connections: parsed.connections.filter(entry => entry && typeof entry.fingerprint === 'string' && typeof entry.workspace === 'string') };
+ } catch { return { version: ADOPTED_CONNECTIONS_VERSION, connections: [] }; }
+}
+
+/** Record (or replace, per workspace + harness + name) one adopted connection. */
+export function recordAdoptedConnection(gbrainHomeDir: string, connection: AdoptedConnection): AdoptedConnectionsFile {
+ const current = readAdoptedConnections(gbrainHomeDir);
+ const connections = [...current.connections.filter(entry => !(entry.workspace === connection.workspace && entry.harness === connection.harness && entry.name === connection.name)), connection];
+ const next: AdoptedConnectionsFile = { version: ADOPTED_CONNECTIONS_VERSION, connections };
+ mkdirSync(join(gbrainHomeDir, 'bootstrap'), { recursive: true });
+ atomicWriteTextFile(adoptedConnectionsPath(gbrainHomeDir), `${JSON.stringify(next, null, 2)}\n`);
+ return next;
+}
+
+/** The workspace's Codex connection state from the sidecar and the effective project config. */
+export function adoptedConnectionState(ws: string, gbrainHomeDir: string, name = DEFAULT_CODEX_SERVER_NAME): AdoptedConnectionState {
+ const connection = readAdoptedConnections(gbrainHomeDir).connections.find(entry => entry.workspace === ws && entry.harness === 'codex' && entry.name === name) ?? null;
+ let detected: DetectedCodexProjectServer | null;
+ try { detected = detectCodexProjectServer(ws, name); }
+ catch (error) {
+ const why = `${CODEX_PROJECT_CONFIG} does not parse: ${error instanceof Error ? error.message : String(error)}`;
+ return connection ? { state: 'drifted', connection, detected: null, why } : { state: 'none' };
+ }
+ if (!connection) return detected ? { state: 'detected', detected } : { state: 'none' };
+ if (!detected) return { state: 'drifted', connection, detected: null, why: `${CODEX_PROJECT_CONFIG} no longer defines mcp_servers.${name}` };
+ if (detected.fingerprint !== connection.fingerprint) {
+ return { state: 'drifted', connection, detected, why: `mcp_servers.${name} changed since adoption (${connection.transport} ${connection.target} → ${detected.transport} ${detected.target})` };
+ }
+ return { state: 'adopted', connection, detected };
+}
diff --git a/src/core/bootstrap/status.ts b/src/core/bootstrap/status.ts
index f330621366..a959aa78a8 100644
--- a/src/core/bootstrap/status.ts
+++ b/src/core/bootstrap/status.ts
@@ -35,6 +35,7 @@ import { binaryOnPath, detectExecutionEnvironment, type ExecutionEnvironment } f
import { resolveGbrainHome } from '../gbrain-home.ts';
import { githubOwnerRepoString, isProxyBlocked403 } from '../repo-visibility.ts';
+import { CODEX_PROJECT_CONFIG, adoptedConnectionState } from './adopted-connections.ts';
import { BOOTSTRAP_TEMPLATES } from './assets.ts';
import {
readManifest,
@@ -268,7 +269,8 @@ export const PHASES: PhaseSpec[] = [
'gbrain bootstrap hooks --harness <claude-code|codex|opencode> — MCP scope consent applies on ' +
'Claude Code and opencode (recorded during the interview, pre-confirm; opencode defaults to ' +
'user-global — the sharing-safe choice, since it spawns project-config servers with no trust gate); ' +
- 'Codex registrations are always user-global (no scope flag)',
+ 'Codex registrations are always user-global (no scope flag); a project-scoped .codex/config.toml server ' +
+ 'you manage yourself is adopted, never rewritten: `gbrain bootstrap hooks --adopt --harness codex` after a passing verify',
detect: (ws, ctx) => {
const regs = ctx.receipt?.registrations ?? [];
if (regs.length > 0) {
@@ -288,6 +290,24 @@ export const PHASES: PhaseSpec[] = [
};
}
if (hooksInstalled(ws)) return { state: 'done', detail: 'hooks present in .claude/settings.local.json' };
+ // Operator-managed Codex project config (#4082): `.codex/config.toml`
+ // in the workspace, logged in with `codex mcp login`. Detected is
+ // PARTIAL (nothing proves it reaches the brain); adopted after a
+ // passing verify is DONE; a fingerprint drift is PARTIAL again.
+ const adopted = adoptedConnectionState(ws, ctx.gbrainHomeDir);
+ if (adopted.state === 'adopted') {
+ return { state: 'done', detail: `codex (project, adopted ${adopted.connection.adopted_at}): ${CODEX_PROJECT_CONFIG} mcp_servers.${adopted.connection.name}` };
+ }
+ if (adopted.state === 'drifted') {
+ return { state: 'partial', detail: `codex (project) adopted connection drifted — ${adopted.why}; re-run \`gbrain bootstrap verify\` then \`gbrain bootstrap hooks --adopt --harness codex\`` };
+ }
+ if (adopted.state === 'detected') {
+ return {
+ state: 'partial',
+ detail: `codex (project) detected, not verified: ${CODEX_PROJECT_CONFIG} defines mcp_servers.${adopted.detected.name} (${adopted.detected.transport}) — ` +
+ 'run `gbrain bootstrap verify`, then `gbrain bootstrap hooks --adopt --harness codex` to adopt it (no user-global `codex mcp add` needed)',
+ };
+ }
return { state: 'pending' };
},
},
diff --git a/test/bootstrap-adopted-connection.serial.test.ts b/test/bootstrap-adopted-connection.serial.test.ts
new file mode 100644
index 0000000000..3d53b61f89
--- /dev/null
+++ b/test/bootstrap-adopted-connection.serial.test.ts
@@ -0,0 +1,224 @@
+/**
+ * #4082 — bootstrap status must tell an operator-managed Codex PROJECT
+ * connection (`<ws>/.codex/config.toml`, streamable HTTP + `codex mcp login`)
+ * apart from "nothing wired": detected is PARTIAL, adopted after a passing
+ * verify is DONE, a drifted fingerprint is PARTIAL again. The evidence lives in
+ * a versioned sidecar beside the receipt and never carries header values.
+ *
+ * Serial: the dispatcher resolves the gbrain home from GBRAIN_HOME.
+ */
+import { describe, test, expect, beforeEach, afterAll, beforeAll } from 'bun:test';
+import { mkdirSync, mkdtempSync, readFileSync, rmSync, utimesSync, writeFileSync } from 'node:fs';
+import { tmpdir } from 'node:os';
+import { join } from 'node:path';
+
+import { runBootstrap } from '../src/commands/bootstrap.ts';
+import { writeManifest } from '../src/core/bootstrap/format.ts';
+import { statusReport } from '../src/core/bootstrap/status.ts';
+import {
+ ADOPTED_CONNECTIONS_VERSION,
+ adoptedConnectionState,
+ adoptedConnectionsPath,
+ detectCodexProjectServer,
+ readAdoptedConnections,
+} from '../src/core/bootstrap/adopted-connections.ts';
+import { adoptConnection } from '../src/core/bootstrap/adopt-connection.ts';
+
+let tmpParent: string;
+let home: string;
+let ws: string;
+let prevHome: string | undefined;
+
+const HTTP_SERVER = (url: string, token: string) =>
+ `[mcp_servers.gbrain]\nurl = "${url}"\nhttp_headers = { Authorization = "Bearer ${token}" }\n`;
+
+function writeProjectConfig(text: string, mtime?: Date): void {
+ mkdirSync(join(ws, '.codex'), { recursive: true });
+ const path = join(ws, '.codex', 'config.toml');
+ writeFileSync(path, text);
+ if (mtime) utimesSync(path, mtime, mtime);
+}
+
+function writeVerifyRun(ts: string, ok: boolean): void {
+ mkdirSync(join(home, 'bootstrap'), { recursive: true });
+ writeFileSync(
+ join(home, 'bootstrap', `verify-${ts.replace(/[:.]/g, '-')}.json`),
+ JSON.stringify({ ts, ok, checks: ok ? [] : [{ id: 'roundtrip', ok: false, detail: 'x' }] }),
+ );
+}
+
+async function wirePhase() {
+ const report = await statusReport(ws, { gbrainHomeDir: home });
+ return report.phases.find((p) => p.id === 'wire')!;
+}
+
+async function capture<T>(fn: () => Promise<T>): Promise<{ result: T; out: string; err: string }> {
+ const origLog = console.log;
+ const origErr = console.error;
+ let out = '';
+ let err = '';
+ console.log = (...args: unknown[]) => { out += args.map(String).join(' ') + '\n'; };
+ console.error = (...args: unknown[]) => { err += args.map(String).join(' ') + '\n'; };
+ try {
+ return { result: await fn(), out, err };
+ } finally {
+ console.log = origLog;
+ console.error = origErr;
+ }
+}
+
+beforeAll(() => {
+ prevHome = process.env.GBRAIN_HOME;
+});
+
+beforeEach(() => {
+ tmpParent = mkdtempSync(join(tmpdir(), 'gb-adopt-'));
+ home = join(tmpParent, '.gbrain');
+ mkdirSync(home, { recursive: true });
+ ws = mkdtempSync(join(tmpdir(), 'gb-adopt-ws-'));
+ process.env.GBRAIN_HOME = tmpParent;
+});
+
+afterAll(() => {
+ if (prevHome === undefined) delete process.env.GBRAIN_HOME;
+ else process.env.GBRAIN_HOME = prevHome;
+ rmSync(tmpParent, { recursive: true, force: true });
+ rmSync(ws, { recursive: true, force: true });
+});
+
+describe('bootstrap status wire phase with a Codex project config (#4082)', () => {
+ test('a project-local streamable-HTTP server is DETECTED (partial), not pending, and the hint adopts instead of re-registering', async () => {
+ writeProjectConfig(HTTP_SERVER('https://brain.example.test/mcp', 'secret-token-value'));
+ const wire = await wirePhase();
+ expect(wire.state).toBe('partial');
+ expect(wire.detail).toContain('.codex/config.toml defines mcp_servers.gbrain (streamable_http)');
+ expect(wire.detail).toContain('gbrain bootstrap hooks --adopt --harness codex');
+ expect(wire.detail).toContain('no user-global `codex mcp add` needed');
+ expect(wire.detail).not.toContain('secret-token-value');
+ expect(wire.resume_hint).toContain('project-scoped .codex/config.toml server');
+ });
+
+ test('no project config → still pending (the receipt/hook detectors are untouched)', async () => {
+ expect((await wirePhase()).state).toBe('pending');
+ });
+});
+
+describe('detectCodexProjectServer + fingerprint', () => {
+ test('fingerprint covers transport, URL and header NAMES; a rotated token leaves it unchanged, a new URL changes it', () => {
+ writeProjectConfig(HTTP_SERVER('https://brain.example.test/mcp', 'token-a'));
+ const a = detectCodexProjectServer(ws)!;
+ writeProjectConfig(HTTP_SERVER('https://brain.example.test/mcp', 'token-b'));
+ const b = detectCodexProjectServer(ws)!;
+ writeProjectConfig(HTTP_SERVER('https://other.example.test/mcp', 'token-a'));
+ const c = detectCodexProjectServer(ws)!;
+ expect(a).toEqual({
+ harness: 'codex', scope: 'project', name: 'gbrain', transport: 'streamable_http',
+ target: 'https://brain.example.test/mcp', header_names: ['Authorization'], fingerprint: a.fingerprint,
+ });
+ expect(a.fingerprint).toMatch(/^[0-9a-f]{64}$/);
+ expect(b.fingerprint).toBe(a.fingerprint);
+ expect(c.fingerprint).not.toBe(a.fingerprint);
+ expect(JSON.stringify(a)).not.toContain('token-a');
+ });
+
+ test('stdio tables, another table name, a missing file and a broken file', () => {
+ expect(detectCodexProjectServer(ws)).toBeNull();
+ writeProjectConfig('[mcp_servers.other]\ncommand = "gbrain"\nargs = ["serve", "--source", "ws"]\n');
+ expect(detectCodexProjectServer(ws)).toBeNull();
+ expect(detectCodexProjectServer(ws, 'other')).toMatchObject({ transport: 'stdio', target: 'gbrain serve --source ws', header_names: [] });
+ writeProjectConfig('[mcp_servers.gbrain\nurl = "https://x"\n');
+ expect(() => detectCodexProjectServer(ws)).toThrow();
+ expect(adoptedConnectionState(ws, home)).toEqual({ state: 'none' });
+ });
+});
+
+describe('adoptConnection evidence gate', () => {
+ const URL = 'https://brain.example.test/mcp';
+
+ test('refuses without a passing verify, and when the config changed after the verify', () => {
+ writeProjectConfig(HTTP_SERVER(URL, 't'), new Date('2026-01-02T00:00:00Z'));
+ const none = adoptConnection(ws, home, 'codex');
+ expect(none.code).toBe(1);
+ expect(none.lines[0]).toContain('no `gbrain bootstrap verify` run on record');
+
+ writeVerifyRun('2026-01-03T00:00:00.000Z', false);
+ const failed = adoptConnection(ws, home, 'codex');
+ expect(failed.code).toBe(1);
+ expect(failed.lines[0]).toContain('failed: roundtrip');
+
+ writeVerifyRun('2026-01-04T00:00:00.000Z', true);
+ writeProjectConfig(HTTP_SERVER(URL, 't'), new Date('2026-01-05T00:00:00Z'));
+ const stale = adoptConnection(ws, home, 'codex');
+ expect(stale.code).toBe(1);
+ expect(stale.lines[0]).toContain('after the newest passing verify');
+ expect(readAdoptedConnections(home).connections).toEqual([]);
+ });
+
+ test('refuses a non-Codex harness and a missing table', () => {
+ writeVerifyRun('2026-01-04T00:00:00.000Z', true);
+ expect(adoptConnection(ws, home, 'claude-code').code).toBe(2);
+ const missing = adoptConnection(ws, home, 'codex');
+ expect(missing.code).toBe(1);
+ expect(missing.lines[0]).toContain('nothing to adopt');
+ });
+
+ test('adopts after a passing verify → wire done; a URL change drifts → partial; the sidecar is versioned and token-free', async () => {
+ writeProjectConfig(HTTP_SERVER(URL, 'secret-token-value'), new Date('2026-01-02T00:00:00Z'));
+ writeVerifyRun('2026-01-04T00:00:00.000Z', true);
+ const adopted = adoptConnection(ws, home, 'codex');
+ expect(adopted.code).toBe(0);
+ expect(adopted.lines.join('\n')).toContain('no tokens stored');
+
+ const raw = readFileSync(adoptedConnectionsPath(home), 'utf8');
+ expect(raw).not.toContain('secret-token-value');
+ const file = JSON.parse(raw);
+ expect(file.version).toBe(ADOPTED_CONNECTIONS_VERSION);
+ expect(file.connections).toHaveLength(1);
+ expect(file.connections[0]).toMatchObject({ harness: 'codex', scope: 'project', workspace: ws, name: 'gbrain', transport: 'streamable_http', target: URL, evidence: { verify_ts: '2026-01-04T00:00:00.000Z' } });
+
+ const done = await wirePhase();
+ expect(done.state).toBe('done');
+ expect(done.detail).toContain('codex (project, adopted');
+
+ writeProjectConfig(HTTP_SERVER('https://moved.example.test/mcp', 'secret-token-value'), new Date('2026-01-02T00:00:00Z'));
+ const drifted = await wirePhase();
+ expect(drifted.state).toBe('partial');
+ expect(drifted.detail).toContain('adopted connection drifted');
+ expect(drifted.detail).toContain('https://moved.example.test/mcp');
+
+ // A token rotation alone is not drift.
+ writeProjectConfig(HTTP_SERVER(URL, 'rotated-token'), new Date('2026-01-02T00:00:00Z'));
+ expect((await wirePhase()).state).toBe('done');
+
+ // Re-adopting the moved config replaces the row instead of appending.
+ writeProjectConfig(HTTP_SERVER('https://moved.example.test/mcp', 't'), new Date('2026-01-02T00:00:00Z'));
+ expect(adoptConnection(ws, home, 'codex').code).toBe(0);
+ expect(readAdoptedConnections(home).connections).toHaveLength(1);
+ expect(readAdoptedConnections(home).connections[0].target).toBe('https://moved.example.test/mcp');
+
+ rmSync(join(ws, '.codex'), { recursive: true });
+ const gone = await wirePhase();
+ expect(gone.state).toBe('partial');
+ expect(gone.detail).toContain('no longer defines mcp_servers.gbrain');
+ });
+});
+
+describe('gbrain bootstrap hooks --adopt (dispatcher)', () => {
+ test('records the project connection without touching .codex/config.toml; refuses non-Codex', async () => {
+ writeManifest(ws, { format_version: 1, initialized: true, agent_name: 'Testy', created_by: 'test', created_at: new Date().toISOString(), source_id: 'workspace' });
+ const toml = HTTP_SERVER('https://brain.example.test/mcp', 'tok');
+ writeProjectConfig(toml, new Date('2026-01-02T00:00:00Z'));
+ writeVerifyRun('2026-01-04T00:00:00.000Z', true);
+
+ const wrong = await capture(() => runBootstrap(['hooks', '--workspace', ws, '--harness', 'claude-code', '--adopt']));
+ expect(wrong.result).toBe(2);
+ expect(wrong.err).toContain('--adopt applies to a Codex project config');
+
+ const ok = await capture(() => runBootstrap(['hooks', '--workspace', ws, '--harness', 'codex', '--adopt']));
+ expect(ok.result).toBe(0);
+ expect(ok.out).toContain('adopted codex project connection mcp_servers.gbrain');
+ expect(readFileSync(join(ws, '.codex', 'config.toml'), 'utf8')).toBe(toml);
+ expect(readAdoptedConnections(home).connections).toHaveLength(1);
+ expect((await wirePhase()).state).toBe('done');
+ });
+});