diff --git a/plugins/genie/.codex-plugin/plugin.json b/plugins/genie/.codex-plugin/plugin.json index e119b49f3..776b20040 100644 --- a/plugins/genie/.codex-plugin/plugin.json +++ b/plugins/genie/.codex-plugin/plugin.json @@ -12,14 +12,13 @@ "keywords": ["workflow", "orchestration", "codex", "skills", "agents"], "skills": "./skills/", "hooks": "./hooks/codex-hooks.json", - "mcpServers": "./.mcp.json", "interface": { "displayName": "Genie", "shortDescription": "Plan, execute, review, and ship with Genie", "longDescription": "First-class Genie workflows for Codex, including shared skills, lifecycle hooks, and MCP task state. Genie CLI setup can install optional role agents.", "developerName": "Namastex Labs", "category": "Developer Tools", - "capabilities": ["Skills", "Hooks", "MCP"], + "capabilities": ["Skills", "Hooks"], "websiteURL": "https://github.com/automagik-dev/genie", "defaultPrompt": [ "Use $genie:wish to turn this request into an executable plan.", diff --git a/plugins/genie/.mcp.json b/plugins/genie/.mcp.json deleted file mode 100644 index c05ea4edf..000000000 --- a/plugins/genie/.mcp.json +++ /dev/null @@ -1,7 +0,0 @@ -{ - "genie": { - "command": "node", - "args": ["./scripts/mcp-launcher.cjs"], - "cwd": "." - } -} diff --git a/scripts/build-binary.sh b/scripts/build-binary.sh index aaef4eeb0..0036738d6 100755 --- a/scripts/build-binary.sh +++ b/scripts/build-binary.sh @@ -128,7 +128,6 @@ for required in \ ".agents/plugins/marketplace.json" \ ".claude-plugin/marketplace.json" \ "plugins/genie/.codex-plugin/plugin.json" \ - "plugins/genie/.mcp.json" \ "plugins/genie/scripts/mcp-launcher.cjs" \ "plugins/genie/.claude-plugin/plugin.json" \ "plugins/genie/hooks/hooks.json" \ diff --git a/scripts/codex-plugin-only-smoke.ts b/scripts/codex-plugin-only-smoke.ts index ca9be4cd4..7dc77a5d4 100644 --- a/scripts/codex-plugin-only-smoke.ts +++ b/scripts/codex-plugin-only-smoke.ts @@ -188,18 +188,22 @@ function isRecord(value: unknown): value is Record { function assertInstalledPluginMcpShape(iso: IsolatedHome, version: string): void { const root = join(iso.codexHome, 'plugins', 'cache', 'automagik', 'genie', version); - const config: unknown = JSON.parse(readFileSync(join(root, '.mcp.json'), 'utf8')); - const configRecord = isRecord(config) ? config : {}; - const wrapped = configRecord.mcp_servers; - const servers = isRecord(wrapped) ? wrapped : configRecord; - const genie = servers.genie; - const command = isRecord(genie) ? genie.command : undefined; - const args = isRecord(genie) ? genie.args : undefined; - const cwd = isRecord(genie) ? genie.cwd : undefined; - if (command !== 'node' || !Array.isArray(args) || args[0] !== './scripts/mcp-launcher.cjs' || cwd !== '.') { - fail(`installed plugin MCP entry shape is wrong: ${JSON.stringify(genie)}`); + // Group A removed the Codex plugin MCP route: the installed manifest declares no + // mcpServers and no MCP capability, and ships no `.mcp.json`. Codex MCP now comes + // ONLY from the marker-owned project route reconciled by `genie init` (asserted + // separately as the project `.mcp.json`/`.codex/config.toml`). + const manifest: unknown = JSON.parse(readFileSync(join(root, '.codex-plugin', 'plugin.json'), 'utf8')); + const manifestRecord = isRecord(manifest) ? manifest : {}; + if ('mcpServers' in manifestRecord) { + fail('installed Codex plugin manifest must not declare mcpServers (plugin MCP route removed)'); } - if (!existsSync(join(root, 'scripts', 'mcp-launcher.cjs'))) fail('installed plugin MCP launcher is missing'); + const iface = isRecord(manifestRecord.interface) ? manifestRecord.interface : {}; + if (Array.isArray(iface.capabilities) && iface.capabilities.includes('MCP')) { + fail('installed Codex plugin must not advertise the MCP capability (plugin MCP route removed)'); + } + if (existsSync(join(root, '.mcp.json'))) fail('installed Codex plugin must not ship a .mcp.json route file'); + // The plugin-local launcher stays — Claude drives it via its own inline manifest entry. + if (!existsSync(join(root, 'scripts', 'mcp-launcher.cjs'))) fail('plugin MCP launcher (Claude) is missing'); } function assertSessionStartHook(iso: IsolatedHome, version: string): void { diff --git a/scripts/fresh-install-smoke.test.ts b/scripts/fresh-install-smoke.test.ts index e979bc79f..650dd10bb 100644 --- a/scripts/fresh-install-smoke.test.ts +++ b/scripts/fresh-install-smoke.test.ts @@ -291,7 +291,7 @@ describe('fresh-install-smoke', () => { } }); - test('rejects unsupported camelCase plugin MCP config before source/cache packaging passes', () => { + test('rejects any plugin .mcp.json route file (the Codex plugin MCP route was removed)', () => { const root = mkdtempSync(join(tmpdir(), 'genie-plugin-mcp-schema-fixture-')); try { const pluginRoot = join(root, 'plugin'); @@ -300,10 +300,12 @@ describe('fresh-install-smoke', () => { dereference: false, verbatimSymlinks: true, }); + // A resurrected plugin `.mcp.json` (in any shape) must fail the smoke: the + // Codex plugin no longer provides an MCP route, so shipping one is a defect. writeFileSync( join(pluginRoot, '.mcp.json'), JSON.stringify({ - mcpServers: { + mcp_servers: { genie: { command: 'node', args: ['./scripts/mcp-launcher.cjs'], cwd: '.' }, }, }), @@ -311,7 +313,7 @@ describe('fresh-install-smoke', () => { const result = runSmoke(['--skills-dir', join(REPO_ROOT, 'skills'), '--plugin-root', pluginRoot]); expect(result.code).not.toBe(0); - expect(result.stderr).toContain('must not use unsupported camelCase mcpServers'); + expect(result.stderr).toContain('must not ship a .mcp.json route file'); } finally { rmSync(root, { recursive: true, force: true }); } diff --git a/scripts/fresh-install-smoke.ts b/scripts/fresh-install-smoke.ts index 04c475d03..c9fdc9b11 100644 --- a/scripts/fresh-install-smoke.ts +++ b/scripts/fresh-install-smoke.ts @@ -440,39 +440,28 @@ function checkStarterPrompts(manifest: Record, names: string[]) } function checkPluginMcpLayout(pluginRoot: string, manifest: Record): void { - if (manifest.mcpServers !== './.mcp.json') { - fail('Codex plugin manifest mcpServers must point to ./.mcp.json'); - } - const configPath = join(pluginRoot, '.mcp.json'); - if (!existsSync(configPath)) fail(`Codex plugin MCP config missing: ${configPath}`); - const config = JSON.parse(readFileSync(configPath, 'utf8')) as Record; - if ('mcpServers' in config) fail('Codex plugin .mcp.json must not use unsupported camelCase mcpServers'); - const wrapped = config.mcp_servers; - const serverMap = - typeof wrapped === 'object' && wrapped !== null && !Array.isArray(wrapped) - ? (wrapped as Record) - : config; - const rawEntry = serverMap.genie; - const entry = - typeof rawEntry === 'object' && rawEntry !== null && !Array.isArray(rawEntry) - ? (rawEntry as { command?: unknown; args?: unknown; cwd?: unknown }) + // Group A removed the Codex plugin MCP route: the manifest declares no mcpServers + // and no MCP capability, and the payload ships no `.mcp.json`. Codex MCP is + // provided ONLY by the marker-owned project route reconciled by `genie init`. + if ('mcpServers' in manifest) fail('Codex plugin manifest must not declare mcpServers (plugin MCP route removed)'); + const iface = manifest.interface; + const capabilities = + typeof iface === 'object' && iface !== null && !Array.isArray(iface) + ? (iface as { capabilities?: unknown }).capabilities : undefined; - if ( - entry?.command !== 'node' || - !Array.isArray(entry.args) || - entry.args.length !== 1 || - entry.args[0] !== './scripts/mcp-launcher.cjs' || - entry.cwd !== '.' - ) { - fail('Codex plugin MCP entry must run node ./scripts/mcp-launcher.cjs with cwd "."'); + if (Array.isArray(capabilities) && capabilities.includes('MCP')) { + fail('Codex plugin must not advertise the MCP capability (plugin MCP route removed)'); } - const launcher = resolve(pluginRoot, entry.args[0]); + if (existsSync(join(pluginRoot, '.mcp.json'))) fail('Codex plugin must not ship a .mcp.json route file'); + // The plugin-local launcher persists — Claude drives it via its own inline + // ${CLAUDE_PLUGIN_ROOT}-anchored manifest entry (checked in checkClaudePluginMcpLayout). + const launcher = resolve(pluginRoot, 'scripts', 'mcp-launcher.cjs'); if (!isWithin(resolve(pluginRoot), launcher)) fail('Codex MCP launcher escapes the plugin root'); if (!existsSync(launcher) || !lstatSync(launcher).isFile() || lstatSync(launcher).isSymbolicLink()) { - fail(`Codex MCP launcher must be a physical plugin-local file: ${launcher}`); + fail(`plugin-local MCP launcher must be a physical file: ${launcher}`); } if (!isWithin(realpathSync(pluginRoot), realpathSync(launcher))) { - fail('Codex MCP launcher resolves outside the plugin root'); + fail('plugin-local MCP launcher resolves outside the plugin root'); } } diff --git a/src/lib/codex-mcp-health-session.test.ts b/src/lib/codex-mcp-health-session.test.ts index 5b02dff03..4026b125e 100644 --- a/src/lib/codex-mcp-health-session.test.ts +++ b/src/lib/codex-mcp-health-session.test.ts @@ -68,6 +68,27 @@ describe('runBoundedCodexMcpSession', () => { expect(result.detail).toContain('read-only genie_wish_status did not return a non-error result'); }); + test('accepts a fail-closed typed "no project context" wish_status (throwaway non-project cwd)', () => { + // The probe cwd is not a project, so the fail-closed server returns a typed + // error rather than an empty board — that IS the read-only health signal. + for (const kind of ['project-context-unavailable', 'project-database-unavailable', 'unsupported-project-layout']) { + const stdout = `${[ + { jsonrpc: '2.0', id: 1, result: { protocolVersion: '2024-11-05', serverInfo: { name: 'genie' } } }, + { jsonrpc: '2.0', id: 2, result: { tools: REQUIRED_GENIE_MCP_TOOLS.map((name) => ({ name })) } }, + { + jsonrpc: '2.0', + id: 3, + result: { isError: true, structuredContent: { error: kind, detail: kind } }, + }, + ] + .map((reply) => JSON.stringify(reply)) + .join('\n')}\n`; + const result = runBoundedCodexMcpSession({ ...base, spawn: fakeSpawn({ stdout }) }); + expect(result.ok).toBe(true); + expect(result.wishStatusReadOnly).toBe(true); + } + }); + test('rejects a session whose tools/list reply never arrived', () => { const stdout = `${JSON.stringify({ jsonrpc: '2.0', id: 1, result: { protocolVersion: '2024-11-05' } })}\n`; const result = runBoundedCodexMcpSession({ ...base, spawn: fakeSpawn({ stdout }) }); diff --git a/src/lib/codex-mcp-health-session.ts b/src/lib/codex-mcp-health-session.ts index 5407b3d49..2c32670f1 100644 --- a/src/lib/codex-mcp-health-session.ts +++ b/src/lib/codex-mcp-health-session.ts @@ -11,15 +11,31 @@ * bounds the whole session. * * The server opens `.genie/genie.db` READ-ONLY and only writes to stdout, so the - * probe never mutates disk. Callers still hand it an isolated throwaway `cwd` so - * a missing db degrades to an empty board (never creating -wal/-shm siblings in - * real home/state trees). runtime-integrations proves the zero-mutation - * guarantee with a digest-around-session test. + * probe never mutates disk. Callers still hand it an isolated throwaway `cwd` + * that is not a project: the fail-closed server returns a typed "no project + * context" wish_status there rather than fabricating an empty board (never + * creating -wal/-shm siblings in real home/state trees), and this probe treats + * that typed refusal as read-only-healthy. runtime-integrations proves the + * zero-mutation guarantee with a digest-around-session test. */ export const MCP_HEALTH_PROTOCOL_VERSION = '2024-11-05'; export const DEFAULT_HEALTH_SESSION_TIMEOUT_MS = 10_000; +/** + * The fail-closed project-context error kinds the read-only `genie mcp` server + * returns (structuredContent `{ error, detail }`, `isError: true`) instead of a + * fabricated empty board when the cwd is not a resolvable project. Source of + * truth: `ProjectContextKind` in `src/lib/v5/genie-db.ts`. The health probe runs + * in a throwaway non-project cwd, so one of these is the EXPECTED wish_status + * outcome and proves the read-only path works — it is not a failure. + */ +const NO_PROJECT_CONTEXT_ERROR_KINDS = new Set([ + 'project-context-unavailable', + 'project-database-unavailable', + 'unsupported-project-layout', +]); + /** The five read-only Genie tools every healthy plugin launcher must expose. */ export const REQUIRED_GENIE_MCP_TOOLS = [ 'genie_board', @@ -138,6 +154,22 @@ function replyError(reply: JsonRpcReply | undefined, label: string): string | nu return null; } +/** + * A read-only wish_status is healthy when it either returns a non-error board + * (`isError === false`) OR a well-formed fail-closed "no project context" typed + * error. The health probe deliberately runs in a throwaway non-project cwd where + * the latter is expected: the server correctly refuses to serve an empty board + * without mutating disk. Any other `isError: true` (an unrecognized/real tool + * failure) is still rejected. + */ +function wishStatusIsReadOnlyHealthy(result: { isError?: unknown; structuredContent?: unknown }): boolean { + if (result.isError === false) return true; + if (result.isError !== true) return false; + const structured = result.structuredContent; + const kind = structured && typeof structured === 'object' ? (structured as { error?: unknown }).error : undefined; + return typeof kind === 'string' && NO_PROJECT_CONTEXT_ERROR_KINDS.has(kind); +} + function listedToolNames(reply: JsonRpcReply): string[] { const result = reply.result as { tools?: unknown }; if (!Array.isArray(result.tools)) return []; @@ -199,8 +231,8 @@ export function runBoundedCodexMcpSession(options: BoundedCodexMcpSessionOptions const callReply = byId.get(3); const callError = replyError(callReply, 'genie_wish_status'); if (callError !== null) return { ok: false, detail: callError }; - const callResult = (callReply as JsonRpcReply).result as { isError?: unknown }; - if (callResult.isError !== false) { + const callResult = (callReply as JsonRpcReply).result as { isError?: unknown; structuredContent?: unknown }; + if (!wishStatusIsReadOnlyHealthy(callResult)) { return { ok: false, detail: 'read-only genie_wish_status did not return a non-error result' }; } diff --git a/src/lib/codex-project-mcp.test.ts b/src/lib/codex-project-mcp.test.ts index 47aac626a..15a7c9a57 100644 --- a/src/lib/codex-project-mcp.test.ts +++ b/src/lib/codex-project-mcp.test.ts @@ -16,6 +16,7 @@ import { tmpdir } from 'node:os'; import { dirname, join } from 'node:path'; import { type CodexPluginProbe, + genieFacadeMcpEntry, genieMcpEntry, inspectCodexPluginMcpUsability, inspectCodexProjectMcp, @@ -76,7 +77,16 @@ function seedActivePlugin(version = '1.2.3'): { const manifestPath = join(pluginRoot, '.codex-plugin', 'plugin.json'); const manifest = JSON.parse(readFileSync(manifestPath, 'utf8')) as Record; manifest.version = version; + // Group A removed the Codex plugin MCP route from the SHIPPED payload, so the + // fixture reconstructs a hypothetical plugin-with-MCP layout to keep exercising + // the fail-closed usability guard (launcher/node/binary). The removal itself is + // proven separately against the real source plugin. + manifest.mcpServers = './.mcp.json'; writeFileSync(manifestPath, `${JSON.stringify(manifest, null, 2)}\n`); + writeFileSync( + join(pluginRoot, '.mcp.json'), + `${JSON.stringify({ mcp_servers: { genie: { command: 'node', args: ['./scripts/mcp-launcher.cjs'], cwd: '.' } } }, null, 2)}\n`, + ); const genieHome = join(root, 'genie-home'); const binary = join(genieHome, 'bin', process.platform === 'win32' ? 'genie.exe' : 'genie'); const nodePath = join(root, 'controlled-bin', 'node'); @@ -122,6 +132,71 @@ describe('project MCP executable entry', () => { }); }); +describe('genieFacadeMcpEntry (marker-owned Codex route)', () => { + test('is the stable /bin/genie facade with args ["mcp"] and no cwd override', () => { + expect(genieFacadeMcpEntry('/home/u/.genie', 'linux')).toEqual({ + command: '/home/u/.genie/bin/genie', + args: ['mcp'], + }); + // No effective cwd override is part of the entry (source omits it entirely). + expect(genieFacadeMcpEntry('/home/u/.genie', 'linux')).not.toHaveProperty('cwd'); + }); + + test('uses genie.exe on win32 and is independent of the running executable', () => { + expect(genieFacadeMcpEntry('C:/Users/u/.genie', 'win32')).toEqual({ + command: 'C:/Users/u/.genie/bin/genie.exe', + args: ['mcp'], + }); + // A relocated GENIE_HOME yields a different facade — the command is not the cache/execPath. + expect(genieFacadeMcpEntry('/relocated/home', 'linux').command).toBe('/relocated/home/bin/genie'); + }); +}); + +describe('Codex plugin MCP route removal (Group A)', () => { + test('the shipped Codex plugin manifest declares NO mcpServers and NO MCP capability', () => { + const manifest = JSON.parse( + readFileSync(join(import.meta.dir, '..', '..', 'plugins', 'genie', '.codex-plugin', 'plugin.json'), 'utf8'), + ) as { mcpServers?: unknown; interface?: { capabilities?: unknown } }; + expect(manifest.mcpServers).toBeUndefined(); + expect(manifest.interface?.capabilities).not.toContain('MCP'); + }); + + test('the shipped Codex plugin payload ships no .mcp.json route file', () => { + expect(existsSync(join(import.meta.dir, '..', '..', 'plugins', 'genie', '.mcp.json'))).toBe(false); + }); + + test('a real (unaltered) plugin copy is never a usable MCP provider — the guard fails closed', () => { + const pluginRoot = join(root, 'real-plugin'); + cpSync(join(import.meta.dir, '..', '..', 'plugins', 'genie'), pluginRoot, { + recursive: true, + dereference: false, + verbatimSymlinks: true, + }); + const manifest = JSON.parse(readFileSync(join(pluginRoot, '.codex-plugin', 'plugin.json'), 'utf8')) as { + version: string; + }; + const result = inspectCodexPluginMcpUsability({ + pluginRoot, + expectedPluginName: 'genie', + expectedVersion: manifest.version, + genieHome: join(root, 'genie-home'), + resolveCommand: () => join(root, 'node'), + }); + expect(result.usable).toBe(false); + // It fails at the manifest indirection because the route was removed. + expect(result.detail).toContain('mcpServers'); + }); + + // Claude's separate inline launcher contract MUST remain intact. + test("Claude's plugin manifest still declares its own inline mcpServers launcher", () => { + const claude = JSON.parse( + readFileSync(join(import.meta.dir, '..', '..', 'plugins', 'genie', '.claude-plugin', 'plugin.json'), 'utf8'), + ) as { mcpServers?: { genie?: { command?: string; args?: string[] } } }; + expect(claude.mcpServers?.genie?.command).toBe('node'); + expect(claude.mcpServers?.genie?.args?.[0]).toContain('mcp-launcher.cjs'); + }); +}); + describe('resolveGitWorktreeRoot', () => { test('resolves root, nested directory, and linked worktree to their own working-tree roots', () => { const repo = join(root, 'repo'); diff --git a/src/lib/codex-project-mcp.ts b/src/lib/codex-project-mcp.ts index 50a58eb8f..87056a812 100644 --- a/src/lib/codex-project-mcp.ts +++ b/src/lib/codex-project-mcp.ts @@ -120,7 +120,23 @@ export interface RegisterProjectMcpOptions { /** Reuse a caller's one-shot probe so a launch with N worktrees queries Codex once. */ pluginProbe?: CodexPluginProbe; probeDeps?: CodexPluginProbeDeps; + /** Command written to the Claude/Warp JSON configs (`.mcp.json`, `.warp/.mcp.json`). */ entry?: McpServerEntry; + /** + * Dedicated command for the marker-owned Codex `.codex/config.toml` route. + * Defaults to {@link RegisterProjectMcpOptions.entry}. Trusted `genie init` + * passes the stable {@link genieFacadeMcpEntry} facade here so the Codex marker + * uses the version-independent `/bin/genie` command even while + * Claude/Warp keep the running-executable entry. + */ + codexEntry?: McpServerEntry; + /** + * Reconcile the marker-owned Codex route INDEPENDENT of plugin/delivery state + * (trusted `genie init`). A route name is not proof of ownership, so an + * unmanaged same-key route is still preserved and reported rather than + * overwritten. + */ + forceCodexFallback?: boolean; } export interface GitProjectRoots { @@ -620,6 +636,22 @@ export function genieMcpEntry(command?: string, argv = process.argv): McpServerE return { command: executable, args: script ? [script, 'mcp'] : ['mcp'] }; } +/** + * The stable marker-owned Codex route command: the canonical absolute + * `/bin/genie` facade with `args = ["mcp"]` and NO effective cwd + * override. Unlike {@link genieMcpEntry} (which records the running executable + * for Claude/Warp), this facade path is deliberately version- and + * plugin-independent: it survives plugin updates and symlinked invocation, and + * is rewritten only by trusted `genie init` after an explicit GENIE_HOME + * relocation. It never resolves to a versioned plugin-cache path. + */ +export function genieFacadeMcpEntry( + genieHome: string = resolveGenieHome(), + platform: NodeJS.Platform = process.platform, +): McpServerEntry { + return { command: join(genieHome, 'bin', platform === 'win32' ? 'genie.exe' : 'genie'), args: ['mcp'] }; +} + function isJsonObject(value: unknown): value is JsonObject { return typeof value === 'object' && value !== null && !Array.isArray(value); } @@ -973,14 +1005,18 @@ export function reconcileCodexProjectMcp( */ export function registerProjectMcpConfigs(root: string, options: RegisterProjectMcpOptions = {}): McpConfigResult[] { const entry = options.entry ?? genieMcpEntry(); - const plugin = options.pluginProbe ?? probeCodexGeniePlugin(options.probeDeps); + const codexEntry = options.codexEntry ?? entry; const preparedJson = [join(root, '.mcp.json'), join(root, '.warp', '.mcp.json')].map((path) => prepareJsonMcpConfig(path, entry), ); - // Explicit init must leave a discoverable route even before the Codex CLI is - // installed. The marker-owned fallback is lifecycle-owned and can later be - // removed atomically when a usable plugin is proven. - const preparedCodex = prepareCodexFallback(join(root, '.codex', 'config.toml'), entry, !isUsableCodexPlugin(plugin)); + // Trusted init reconciles the marker-owned Codex route independent of plugin + // state (`forceCodexFallback`) — the `||` short-circuits so a forced call never + // spends a Codex query. Otherwise the marker is retained only when no usable + // plugin is proven. Either way an unowned same-key route is preserved. + const required = + options.forceCodexFallback === true || + !isUsableCodexPlugin(options.pluginProbe ?? probeCodexGeniePlugin(options.probeDeps)); + const preparedCodex = prepareCodexFallback(join(root, '.codex', 'config.toml'), codexEntry, required); if (!preparedCodex.ok) { throw new Error(`Cannot reconcile Codex project MCP at ${preparedCodex.path}: ${preparedCodex.detail}`); diff --git a/src/lib/runtime-integrations.test.ts b/src/lib/runtime-integrations.test.ts index 4de067e85..a2f4ded0d 100644 --- a/src/lib/runtime-integrations.test.ts +++ b/src/lib/runtime-integrations.test.ts @@ -2577,7 +2577,6 @@ describe('proveCodexPluginHealth reject-before-retirement matrix (R4)', () => { const rejectCases: Array<[string, Partial]> = [ ['a disabled plugin', { enabled: false }], ['a wrong-version plugin', { version: '0.0.0' }], - ['an unusable launcher', { usable: false }], ['an ambiguous active root', { activePluginRoot: undefined }], ['an errored snapshot', { status: 'error' }], ]; @@ -2589,6 +2588,18 @@ describe('proveCodexPluginHealth reject-before-retirement matrix (R4)', () => { }); } + test('accepts a snapshot with no Codex MCP route (usable:false) — plugin MCP is Claude-only now', () => { + // Group A removed the plugin's Codex MCP route, so a post-A snapshot reports + // usable:false. Plugin health is decoupled from Codex-MCP-route usability: a + // proven active root + verified payload + a working launcher session is + // healthy. The launcher (retained for Claude) is exercised by runSession. + const opts = healthyOpts(); + opts.snapshot = { ...opts.snapshot, usable: false, usabilityDetail: 'plugin ships no Codex MCP route' }; + const proof = proveCodexPluginHealth(opts); + expect(proof.version).toBe(1); + expect(proof.mcp.wishStatusReadOnly).toBe(true); + }); + test('rejects payload identity drift (verifyCodexPayload throws)', () => { const opts = healthyOpts(); opts.verifyCodexPayload = () => { diff --git a/src/lib/runtime-integrations.ts b/src/lib/runtime-integrations.ts index 171414d35..7b1bf3476 100644 --- a/src/lib/runtime-integrations.ts +++ b/src/lib/runtime-integrations.ts @@ -3010,10 +3010,18 @@ function bindActiveRootToCanonicalCache(activePluginRoot: string, codexHome: str /** * Reject health BEFORE any retirement unless the single snapshot is exactly one - * enabled target-version plugin with a usable launcher, a canonically-verified - * installed payload and exact inventory, and a bounded MCP session that - * completes initialize / tools-list (all five tools) / read-only wish_status. - * Returns a frozen {@link CodexHealthProof} whose payload feeds retirement. + * enabled target-version plugin with a proven active cache root, a + * canonically-verified installed payload and exact inventory, and a bounded MCP + * session that completes initialize / tools-list (all five tools) / read-only + * wish_status. Returns a frozen {@link CodexHealthProof} whose payload feeds + * retirement. + * + * Plugin health is deliberately DECOUPLED from Codex-MCP-route usability + * (`snapshot.usable`). The plugin no longer registers a Codex MCP route — that + * path is the marker-owned project `.codex/config.toml` reconciled by `genie + * init`. A healthy plugin provides skills + hooks + the retained Claude + * `mcp-launcher.cjs`; the launcher's ability to spawn and speak MCP is proven by + * the bounded session below, not by a plugin-declared MCP registration. */ export function proveCodexPluginHealth(options: ProveCodexPluginHealthOptions): CodexHealthProof { const { snapshot } = options; @@ -3028,7 +3036,9 @@ export function proveCodexPluginHealth(options: ProveCodexPluginHealthOptions): if (snapshot.activePluginRoot === undefined) { rejectHealth(`active plugin root was not proven by the snapshot: ${snapshot.usabilityDetail ?? snapshot.detail}`); } - if (snapshot.usable !== true) rejectHealth(snapshot.usabilityDetail ?? 'plugin MCP launcher is not usable'); + // NOTE: `snapshot.usable` (Codex-MCP-route usability) is intentionally NOT a + // health gate. The plugin ships no Codex MCP route; the launcher's health is + // proven by the bounded MCP session below. const activePluginRoot = snapshot.activePluginRoot; // Bind the consumed tree to the canonical cache BEFORE any digesting or MCP @@ -3046,7 +3056,10 @@ export function proveCodexPluginHealth(options: ProveCodexPluginHealthOptions): // A7: the session runs through the snapshot's own proven launcher (derived // from the single activePluginRoot, not a re-read), in an isolated throwaway - // cwd so a missing db degrades to an empty board without touching real state. + // cwd that is not a project. The fail-closed MCP server there returns a typed + // "no project context" result rather than a fabricated empty board; the health + // session accepts that as read-only-healthy — the launcher spawning and + // speaking MCP IS the signal, an absent board there is expected. const runSession = options.runSession ?? runBoundedCodexMcpSession; const sessionCwd = mkdtempSync(join(tmpdir(), 'genie-mcp-health-')); let session: McpSessionResult; diff --git a/src/lib/v5/genie-db.ts b/src/lib/v5/genie-db.ts index e584be243..0dc2096c0 100644 --- a/src/lib/v5/genie-db.ts +++ b/src/lib/v5/genie-db.ts @@ -14,9 +14,9 @@ */ import type { Database } from 'bun:sqlite'; -import { execSync } from 'node:child_process'; -import { existsSync } from 'node:fs'; -import { dirname, join } from 'node:path'; +import { execFileSync, execSync } from 'node:child_process'; +import { existsSync, lstatSync } from 'node:fs'; +import { dirname, join, normalize } from 'node:path'; import { openSqlite } from './sqlite-open.js'; // Concurrency + typed-error primitives now live in sqlite-open.ts (shared with @@ -76,6 +76,154 @@ export function resolveDbPath(cwd?: string): string { return join(resolveRepoRoot(cwd), '.genie', 'genie.db'); } +// ============================================================================ +// Fail-closed project context (Group A: no outer/cache-root empty-board masquerade) +// ============================================================================ + +/** + * The typed states a project surface resolves BEFORE any MCP tool can serialize + * an empty board. A non-`ok` kind MUST surface as a structured error, never a + * healthy-looking empty projection. Bare/submodule/external-git-dir layouts are + * `unsupported-project-layout`; they never fall outward or to a plugin cache. + */ +export type ProjectContextKind = + | 'ok' + | 'project-context-unavailable' + | 'project-database-unavailable' + | 'unsupported-project-layout'; + +export interface ProjectContextOk { + kind: 'ok'; + /** The child's observable `process.cwd()`; Genie NEVER chdir's away from it. */ + effectiveLaunchCwd: string; + /** Nearest containing worktree root; a linked worktree stays linked here. */ + worktreeConfigRoot: string; + /** Absolute `git rev-parse --git-common-dir` (the MAIN repo's `.git` for a linked worktree). */ + gitCommonDir: string; + /** `dirname(gitCommonDir)` — the repo that owns the shared genie.db. */ + genieStorageRoot: string; + /** The ONLY database candidate: `/.genie/genie.db`. */ + dbPath: string; +} + +export interface ProjectContextError { + kind: Exclude; + /** The observable launch CWD is always known, even on failure. */ + effectiveLaunchCwd: string; + detail: string; + /** Best-effort roots when they are resolvable (e.g. database-unavailable). */ + worktreeConfigRoot?: string; + gitCommonDir?: string; + genieStorageRoot?: string; + dbPath?: string; +} + +export type ProjectContext = ProjectContextOk | ProjectContextError; + +/** Trimmed stdout of a bounded, no-shell `git` invocation, or `null` on failure. */ +function runGit(cwd: string, args: string[]): string | null { + try { + return execFileSync('git', args, { + cwd, + encoding: 'utf-8', + stdio: ['pipe', 'pipe', 'pipe'], + timeout: 5_000, + }).trim(); + } catch { + return null; + } +} + +/** A linked worktree's git dir lives under `/worktrees/`. */ +function isLinkedWorktree(gitDir: string, gitCommonDir: string): boolean { + return normalize(dirname(gitDir)) === normalize(join(gitCommonDir, 'worktrees')); +} + +/** A `.git` FILE at a non-linked worktree root marks an external/separate git dir. */ +function dotGitIsFile(worktreeRoot: string): boolean { + try { + return lstatSync(join(worktreeRoot, '.git')).isFile(); + } catch { + return false; + } +} + +/** + * Resolve the four-value production path model for `cwd` WITHOUT ever changing + * the process CWD or considering a plugin cache. Git discovery stops at the + * nearest enclosing worktree, so a nested initialized repository resolves to its + * OWN storage root and a nested repo without a Genie database fails at that + * boundary rather than walking outward to an outer database. + * + * Bare repositories, submodules, and external/separate-Git-dir layouts return + * `unsupported-project-layout` BEFORE any database lookup. A resolvable layout + * whose `/.genie/genie.db` is absent returns + * `project-database-unavailable` — never an empty board. + */ +export function resolveProjectContext(cwd: string = process.cwd()): ProjectContext { + const effectiveLaunchCwd = cwd; + // Bare vs not-a-repo: `--is-bare-repository` succeeds inside a git dir even + // where `--show-toplevel` would abort, so it cleanly separates the two. + const isBare = runGit(cwd, ['rev-parse', '--is-bare-repository']); + if (isBare === null) { + return { kind: 'project-context-unavailable', effectiveLaunchCwd, detail: `no Git worktree contains ${cwd}` }; + } + if (isBare === 'true') { + return { + kind: 'unsupported-project-layout', + effectiveLaunchCwd, + detail: 'bare Git repositories are not a supported Genie project layout', + }; + } + // A non-empty superproject working tree means cwd is inside a submodule. + const superproject = runGit(cwd, ['rev-parse', '--path-format=absolute', '--show-superproject-working-tree']); + if (superproject) { + return { + kind: 'unsupported-project-layout', + effectiveLaunchCwd, + detail: 'Git submodules are not a supported Genie project layout', + }; + } + const raw = runGit(cwd, ['rev-parse', '--path-format=absolute', '--show-toplevel', '--git-common-dir', '--git-dir']); + const [topRaw, commonRaw, gitDirRaw] = (raw ?? '').split('\n').map((line) => line.trim()); + if (!topRaw || !commonRaw || !gitDirRaw) { + return { + kind: 'project-context-unavailable', + effectiveLaunchCwd, + detail: `unable to resolve Git roots for ${cwd}`, + }; + } + const worktreeConfigRoot = normalizeGitPath(topRaw); + const gitCommonDir = normalizeGitPath(commonRaw); + const gitDir = normalizeGitPath(gitDirRaw); + // A non-linked worktree whose `.git` is a FILE points its common dir outside + // the project (`git init --separate-git-dir`); `dirname(gitCommonDir)` would + // then be an unrelated directory, so refuse it explicitly. + if (!isLinkedWorktree(gitDir, gitCommonDir) && dotGitIsFile(worktreeConfigRoot)) { + return { + kind: 'unsupported-project-layout', + effectiveLaunchCwd, + worktreeConfigRoot, + gitCommonDir, + detail: 'external/separate Git directory layouts are not a supported Genie project layout', + }; + } + const genieStorageRoot = normalizeGitPath(dirname(gitCommonDir)); + const dbPath = join(genieStorageRoot, '.genie', 'genie.db'); + if (!existsSync(dbPath)) { + return { + kind: 'project-database-unavailable', + effectiveLaunchCwd, + worktreeConfigRoot, + gitCommonDir, + genieStorageRoot, + dbPath, + detail: `no Genie database at ${dbPath}; run \`genie init\` in ${genieStorageRoot}`, + }; + } + return { kind: 'ok', effectiveLaunchCwd, worktreeConfigRoot, gitCommonDir, genieStorageRoot, dbPath }; +} + // ============================================================================ // Open / init // ============================================================================ diff --git a/src/lib/v5/mcp-server.ts b/src/lib/v5/mcp-server.ts index de364814a..25cdb3318 100644 --- a/src/lib/v5/mcp-server.ts +++ b/src/lib/v5/mcp-server.ts @@ -20,6 +20,7 @@ import type { Database } from 'bun:sqlite'; import { createInterface } from 'node:readline'; +import type { ProjectContext } from './genie-db.js'; import type { McpTool, ToolContext } from './mcp-tools.js'; // ============================================================================ @@ -93,6 +94,14 @@ export interface McpServerConfig { * statically imports `bun:sqlite` / `mcp-tools`. */ openReadonlyDb: (cwd: string) => Database | null; + /** + * OPT-IN fail-closed resolver (net-new). When provided, the loop resolves the + * project context once per `tools/call` and, on any non-`ok` kind, returns a + * typed structured error (`{ error, detail }`, `isError: true`) instead of + * dispatching the tool against an outer/cache-root empty board. Consumers that + * omit it (e.g. `genie ui-bridge`) keep the legacy cwd-based degrade-to-empty. + */ + resolveContext?: (cwd: string) => ProjectContext; /** Build the `initialize` reply from the client's declared params. */ initialize: (params: Record | undefined) => InitializeOutcome; /** @@ -114,12 +123,27 @@ export interface McpServerConfig { */ export async function runMcpServerLoop(config: McpServerConfig): Promise { const cwd = process.cwd(); + // Resolve the fail-closed context up front when a resolver is injected; only an + // `ok` context may hold a read handle. Without a resolver, keep the legacy open. + const initialContext = config.resolveContext?.(cwd); + const openHandle = (context: ProjectContext | undefined): Database | null => + context === undefined ? config.openReadonlyDb(cwd) : context.kind === 'ok' ? config.openReadonlyDb(cwd) : null; // Single source of truth for the read handle: the per-call reopen below writes // back to ctx.db, and close() reads ctx.db — so a mid-session reopen is always // the one that gets closed (no stale/leaked handle). - const ctx: ToolContext = { db: config.openReadonlyDb(cwd), cwd }; + const ctx: ToolContext = { db: openHandle(initialContext), cwd, context: initialContext }; const toolByName = new Map(config.tools.map((t) => [t.name, t] as const)); + /** + * Serialize a non-`ok` project context as a stable structured MCP error. This + * is the ONE place the read-only server refuses to serve an empty board when + * repository context or the genie.db is missing/unsupported. + */ + function failClosed(id: number | string | null, context: ProjectContext): void { + const payload = { error: context.kind, detail: (context as { detail?: string }).detail ?? context.kind }; + ok(id, { content: [{ type: 'text', text: JSON.stringify(payload) }], structuredContent: payload, isError: true }); + } + function handleToolsCall(id: number | string | null, params: Record | undefined): void { const name = typeof params?.name === 'string' ? params.name : ''; const args = (params?.arguments as Record | undefined) ?? {}; @@ -132,6 +156,22 @@ export async function runMcpServerLoop(config: McpServerConfig): Promise { }); return; } + // Fail-closed gate (opt-in). Re-resolve ONLY while not yet `ok` so a db/context + // created mid-session (e.g. a fresh `genie init`) is picked up without spending + // git probes on every call once the context is settled. Any non-`ok` state + // becomes a typed error rather than an outer/cache-root empty board. + if (config.resolveContext) { + const context = ctx.context?.kind === 'ok' ? ctx.context : config.resolveContext(cwd); + ctx.context = context; + if (context.kind !== 'ok') { + if (ctx.db) { + ctx.db.close(); + ctx.db = null; + } + failClosed(id, context); + return; + } + } // The db may have been absent when the server started (null handle → empty // board). Re-attempt the read-only open per call so a db created mid-session // (e.g. a fresh `genie init` or a bridge write) is picked up instead of diff --git a/src/lib/v5/mcp-tools.test.ts b/src/lib/v5/mcp-tools.test.ts new file mode 100644 index 000000000..75c5a133d --- /dev/null +++ b/src/lib/v5/mcp-tools.test.ts @@ -0,0 +1,240 @@ +/** + * mcp-tools — the fail-closed project-context resolver (Group A) and the + * read-only tool projections it guards. + * + * The resolver is re-exported from mcp-tools.ts on purpose: `genie mcp` pulls it + * through the SAME lazy dynamic import that loads the tool registry, so the read + * server can refuse to serialize an outer/cache-root empty board without dragging + * the readonly bun:sqlite open into the eager genie.ts import graph. + * + * Every fixture is a real git repo in a tmpdir (per repo convention) so the four + * production values — effectiveLaunchCwd, worktreeConfigRoot, absolute + * gitCommonDir, and genieStorageRoot = dirname(gitCommonDir) — are exercised + * against actual `git rev-parse` behavior, not mocks. + */ + +import { afterEach, beforeEach, describe, expect, test } from 'bun:test'; +import { execFileSync } from 'node:child_process'; +import { existsSync, mkdirSync, mkdtempSync, realpathSync, rmSync } from 'node:fs'; +import { tmpdir } from 'node:os'; +import { basename, dirname, join } from 'node:path'; +import { openDb } from './genie-db.js'; +import { MCP_TOOLS, openReadonlyDb, resolveProjectContext } from './mcp-tools.js'; +import { createBoard, createTask } from './task-state.js'; + +let base: string; + +function git(cwd: string, ...args: string[]): void { + execFileSync('git', args, { + cwd, + stdio: 'ignore', + env: { + ...process.env, + GIT_AUTHOR_NAME: 'Test', + GIT_AUTHOR_EMAIL: 'test@example.com', + GIT_COMMITTER_NAME: 'Test', + GIT_COMMITTER_EMAIL: 'test@example.com', + }, + }); +} + +/** Real git repo with one commit at `dir` (created if absent). */ +function initRepo(dir: string): string { + mkdirSync(dir, { recursive: true }); + git(dir, 'init', '-b', 'main'); + git(dir, 'commit', '--allow-empty', '-m', 'init'); + return dir; +} + +/** Create a real, seeded genie.db under `/.genie/genie.db`. */ +function seedDb(storageRoot: string): void { + const db = openDb({ cwd: storageRoot }); + const board = createBoard(db, 'repo'); + createTask(db, { title: 'seed', boardId: board.id, wish: 'w', group: 'g' }); + // Fold pending WAL frames into the main db and close before any reader opens, + // so readonly consumers aren't racing an open WAL writer under cross-file + // test contention (would otherwise surface as "database is locked"). + db.exec('PRAGMA wal_checkpoint(TRUNCATE)'); + db.close(); +} + +/** + * Canonicalize by realpath-ing the nearest EXISTING ancestor and re-appending + * the (possibly absent) tail — so macOS /private symlinks never cause false + * diffs, and an intentionally-absent db path still compares cleanly. + */ +function canon(p: string): string { + let existing = p; + const tail: string[] = []; + while (!existsSync(existing) && dirname(existing) !== existing) { + tail.unshift(basename(existing)); + existing = dirname(existing); + } + return tail.length > 0 ? join(realpathSync(existing), ...tail) : realpathSync(existing); +} + +function samePath(actual: string | undefined, expected: string): void { + expect(actual).toBeDefined(); + expect(canon(actual as string)).toBe(canon(expected)); +} + +beforeEach(() => { + base = mkdtempSync(join(tmpdir(), 'genie-ctx-')); +}); + +afterEach(() => { + rmSync(base, { recursive: true, force: true }); +}); + +// ============================================================================ +// resolveProjectContext — the four-value model + typed fail-closed states +// ============================================================================ + +describe('resolveProjectContext: supported layouts', () => { + test('repository root with a genie.db resolves all four values and never changes launch cwd', () => { + const repo = initRepo(join(base, 'repo')); + seedDb(repo); + const ctx = resolveProjectContext(repo); + expect(ctx.kind).toBe('ok'); + if (ctx.kind !== 'ok') throw new Error('expected ok'); + samePath(ctx.effectiveLaunchCwd, repo); // launch cwd is the input, unchanged + samePath(ctx.worktreeConfigRoot, repo); + samePath(ctx.gitCommonDir, join(repo, '.git')); + samePath(ctx.genieStorageRoot, repo); + samePath(ctx.dbPath, join(repo, '.genie', 'genie.db')); + // genieStorageRoot is exactly dirname(gitCommonDir). + samePath(dirname(ctx.gitCommonDir), ctx.genieStorageRoot); + }); + + test('an ordinary nested subdirectory resolves to the same storage root, not the subdir', () => { + const repo = initRepo(join(base, 'repo')); + seedDb(repo); + const deep = join(repo, 'src', 'deep'); + mkdirSync(deep, { recursive: true }); + const ctx = resolveProjectContext(deep); + expect(ctx.kind).toBe('ok'); + if (ctx.kind !== 'ok') throw new Error('expected ok'); + samePath(ctx.effectiveLaunchCwd, deep); // cwd stays the subdir + samePath(ctx.genieStorageRoot, repo); // but storage is the repo root + samePath(ctx.dbPath, join(repo, '.genie', 'genie.db')); + }); + + test('an initialized nested repository uses its OWN storage root, never the outer db', () => { + const outer = initRepo(join(base, 'outer')); + seedDb(outer); + const nested = initRepo(join(outer, 'vendor', 'nested')); + seedDb(nested); + const ctx = resolveProjectContext(nested); + expect(ctx.kind).toBe('ok'); + if (ctx.kind !== 'ok') throw new Error('expected ok'); + samePath(ctx.genieStorageRoot, nested); + samePath(ctx.dbPath, join(nested, '.genie', 'genie.db')); + expect(canon(ctx.dbPath)).not.toBe(canon(join(outer, '.genie', 'genie.db'))); + }); + + test('a linked worktree keeps config under the linked root but the db under the main common root', () => { + const main = initRepo(join(base, 'main')); + seedDb(main); // db lives ONLY at the main common root + const linked = join(base, 'linked'); + git(main, 'worktree', 'add', '-b', 'wt', linked); + const ctx = resolveProjectContext(linked); + expect(ctx.kind).toBe('ok'); + if (ctx.kind !== 'ok') throw new Error('expected ok'); + samePath(ctx.worktreeConfigRoot, linked); // config stays in the linked worktree + samePath(ctx.gitCommonDir, join(main, '.git')); // common dir is the MAIN repo's .git + samePath(ctx.genieStorageRoot, main); // dirname(gitCommonDir) == main + samePath(ctx.dbPath, join(main, '.genie', 'genie.db')); // sentinel read from the main db + // Neither the main-worktree cwd nor a cache is substituted as launch context. + samePath(ctx.effectiveLaunchCwd, linked); + }); +}); + +describe('resolveProjectContext: fail-closed states', () => { + test('a non-git directory is project-context-unavailable (never falls outward)', () => { + const plain = join(base, 'plain'); + mkdirSync(plain, { recursive: true }); + const ctx = resolveProjectContext(plain); + expect(ctx.kind).toBe('project-context-unavailable'); + samePath(ctx.effectiveLaunchCwd, plain); + }); + + test('a git repo with no genie.db is project-database-unavailable and names the exact candidate', () => { + const repo = initRepo(join(base, 'repo')); + const ctx = resolveProjectContext(repo); + expect(ctx.kind).toBe('project-database-unavailable'); + if (ctx.kind === 'ok') throw new Error('expected error'); + samePath(ctx.genieStorageRoot as string, repo); + samePath(ctx.dbPath as string, join(repo, '.genie', 'genie.db')); + expect(ctx.detail).toContain('.genie/genie.db'); + }); + + test('an uninitialized nested repository fails at its own boundary, never reading the outer db', () => { + const outer = initRepo(join(base, 'outer')); + seedDb(outer); // outer HAS a db — the nested boundary must not fall through to it + const nested = initRepo(join(outer, 'nested')); // no db here + const ctx = resolveProjectContext(nested); + expect(ctx.kind).toBe('project-database-unavailable'); + if (ctx.kind === 'ok') throw new Error('expected error'); + samePath(ctx.dbPath as string, join(nested, '.genie', 'genie.db')); + expect(canon(ctx.dbPath as string)).not.toBe(canon(join(outer, '.genie', 'genie.db'))); + }); + + test('a bare repository is unsupported-project-layout before any db lookup', () => { + const bare = join(base, 'bare.git'); + git(base, 'init', '--bare', bare); + const ctx = resolveProjectContext(bare); + expect(ctx.kind).toBe('unsupported-project-layout'); + expect(ctx.dbPath).toBeUndefined(); + }); + + test('a submodule working tree is unsupported-project-layout', () => { + const sub = initRepo(join(base, 'subrepo')); + const superRepo = initRepo(join(base, 'super')); + execFileSync('git', ['-c', 'protocol.file.allow=always', 'submodule', 'add', sub, 'mysub'], { + cwd: superRepo, + stdio: 'ignore', + env: { + ...process.env, + GIT_AUTHOR_NAME: 'T', + GIT_AUTHOR_EMAIL: 't@e.com', + GIT_COMMITTER_NAME: 'T', + GIT_COMMITTER_EMAIL: 't@e.com', + }, + }); + seedDb(superRepo); // even with an outer db present, the submodule must not use it + const ctx = resolveProjectContext(join(superRepo, 'mysub')); + expect(ctx.kind).toBe('unsupported-project-layout'); + expect(ctx.dbPath).toBeUndefined(); + }); + + test('an external/separate-git-dir layout is unsupported-project-layout', () => { + const work = join(base, 'work'); + const external = join(base, 'external-gitdir'); + mkdirSync(work, { recursive: true }); + git(base, 'init', `--separate-git-dir=${external}`, work); + const ctx = resolveProjectContext(work); + expect(ctx.kind).toBe('unsupported-project-layout'); + expect(ctx.dbPath).toBeUndefined(); + }); +}); + +// ============================================================================ +// The read tools serve real state when the context is ok +// ============================================================================ + +describe('tools serve real state under an ok context', () => { + test('genie_board reflects the seeded db opened from the resolved storage root', () => { + const repo = initRepo(join(base, 'repo')); + seedDb(repo); + const ctx = resolveProjectContext(repo); + if (ctx.kind !== 'ok') throw new Error('expected ok'); + const db = openReadonlyDb(ctx.effectiveLaunchCwd); + expect(db).not.toBeNull(); + const board = MCP_TOOLS.find((t) => t.name === 'genie_board'); + const payload = board?.handler({ db, cwd: ctx.effectiveLaunchCwd, context: ctx }, {}) as { + counts: { total: number }; + }; + expect(payload.counts.total).toBe(1); + db?.close(); + }); +}); diff --git a/src/lib/v5/mcp-tools.ts b/src/lib/v5/mcp-tools.ts index e41745a12..aaea19b56 100644 --- a/src/lib/v5/mcp-tools.ts +++ b/src/lib/v5/mcp-tools.ts @@ -15,7 +15,13 @@ import { Database } from 'bun:sqlite'; import { execFileSync } from 'node:child_process'; -import { resolveDbPath } from './genie-db.js'; +import { type ProjectContext, resolveDbPath } from './genie-db.js'; +import { BUSY_TIMEOUT_MS } from './sqlite-open.js'; + +// Re-exported so `genie mcp` (mcp.ts) pulls the fail-closed context resolver in +// the SAME lazy dynamic import that already loads the tool registry — keeping +// the readonly bun:sqlite open out of the eager genie.ts import graph. +export { type ProjectContext, resolveProjectContext } from './genie-db.js'; import { type TaskFilter, type TaskRow, @@ -36,10 +42,19 @@ import { * file does not exist (readonly open of a missing file throws) so callers can * degrade to an empty board instead of crashing the server. The handle is the * caller's to close. + * + * The read-only connection is given the SAME `busy_timeout` as the shared write + * primitive (see sqlite-open.ts): under concurrent access a straggling WAL + * writer must be waited out, not surfaced as an instant `-32603 "database is + * locked"`. `busy_timeout` is valid on a readonly connection and does not + * mutate the file. An absent-db open still throws before the pragma runs, so the + * degrade-to-`null` contract is preserved. */ export function openReadonlyDb(cwd?: string): Database | null { try { - return new Database(resolveDbPath(cwd), { readonly: true }); + const db = new Database(resolveDbPath(cwd), { readonly: true }); + db.exec(`PRAGMA busy_timeout = ${BUSY_TIMEOUT_MS}`); + return db; } catch { return null; } @@ -145,6 +160,13 @@ export interface ToolContext { db: Database | null; /** Working directory for git branch resolution. Defaults to `process.cwd()`. */ cwd: string; + /** + * The fail-closed project context resolved by the server loop when a resolver + * is injected. When its `kind` is not `ok`, the loop returns a typed error for + * every tool call instead of an empty board (see mcp-server.ts). Absent for + * consumers (e.g. ui-bridge) that do not opt into fail-closed resolution. + */ + context?: ProjectContext; } export interface McpTool { diff --git a/src/term-commands/init.test.ts b/src/term-commands/init.test.ts index 7d452a345..f36e57c43 100644 --- a/src/term-commands/init.test.ts +++ b/src/term-commands/init.test.ts @@ -293,138 +293,81 @@ describe('Codex MCP fallback merge', () => { }); // ============================================================================ -// Verified-current fallback gate — B's observation facade (Group D, D5) +// Marker-owned Codex route — plugin- and delivery-independent (Group A) // ============================================================================ -import { - type CanonicalFact, - type CodexActivationSnapshot, - type FamilyWitness, - type IntentFact, - type PhysicalCacheFact, - type QueryFact, - type RefreshIntent, - parseReleaseVersion, -} from '../lib/codex-activation.js'; -import { isCodexVerifiedCurrent } from './init.js'; - -const IT_T = '5.260712.1'; -const IT_OLD = '5.260711.9'; -const IT_NEWER = '5.260713.4'; -const IT_DIGEST = 'a'.repeat(64); - -function itVer(s: string) { - const parsed = parseReleaseVersion(s); - if (!parsed) throw new Error(`bad version ${s}`); - return parsed; -} -function itFamily(): FamilyWitness { - return { status: 'present', digest: 'f'.repeat(64), identity: '10:300' }; -} -function itCanonical(): CanonicalFact { - return { status: 'ok', version: itVer(IT_T), digest: IT_DIGEST, identity: '10:100' }; -} -function itReg(version = IT_T): QueryFact { - return { status: 'ok', registration: { present: true, enabled: true, version: itVer(version) } }; -} -function itCache(digest = IT_DIGEST): PhysicalCacheFact { - return { kind: 'present', digest, identity: '10:200' }; -} -function itIntentTargetCurrent(): IntentFact { - const intent: RefreshIntent = { - schemaVersion: 1, - refreshIntentId: '1'.repeat(32), - operationId: '2'.repeat(32), - fromPluginVersion: IT_OLD, - targetVersion: IT_T, - direction: 'upgrade', - priorEnabled: true, - canonicalPayloadSha256: IT_DIGEST, - phase: 'planned', - commandKind: 'codex-plugin-add', - lastFailure: '', - receiptId: null, - }; - return { status: 'valid', intent, contentSha256: 'd'.repeat(64) }; -} -function itSnapshot(over: Partial = {}): CodexActivationSnapshot { - return { - canonical: itCanonical(), - query: itReg(), - cache: itCache(), - receipt: { status: 'absent' }, - delivery: { status: 'absent' }, - intent: { status: 'absent' }, - receiptConsumed: false, - observationWitness: { before: itFamily(), after: itFamily() }, - observedAt: '2026-07-12T00:00:00.000Z', - ...over, - }; -} -function gate(snapshot: CodexActivationSnapshot, observed: string[] = []): boolean { - return isCodexVerifiedCurrent({ - resolveCodexCommand: () => '/fake/codex', - observeCodexActivation: ({ command }) => { - observed.push(command ?? 'null'); - return snapshot; - }, +/** Run `genie init` with an isolated GENIE_HOME and no Codex CLI on PATH. */ +function runInitWithHome(cwd: string, genieHome: string): { code: number; stderr: string } { + const res = Bun.spawnSync([process.execPath, CLI, 'init'], { + cwd, + stdout: 'pipe', + stderr: 'pipe', + // No Codex CLI on PATH: init must STILL write the marker (plugin-independent). + env: { ...process.env, PATH: '/usr/bin:/bin', GENIE_HOME: genieHome }, }); + return { code: res.exitCode, stderr: res.stderr.toString() }; } -describe('init verified-current fallback gate', () => { - test('a fresh `current` observation is the ONLY state that reconciles (true)', () => { - expect(gate(itSnapshot())).toBe(true); - }); - - test('state matrix: pending / broken / indeterminate / recovery all retain fallback (false)', () => { - // activation-pending (N < T) - expect(gate(itSnapshot({ query: itReg(IT_OLD), cache: itCache('b'.repeat(64)) }))).toBe(false); - // query-failed (broken/indeterminate) - expect(gate(itSnapshot({ query: { status: 'failed', detail: 'timed out' } }))).toBe(false); - // registration-absent (activation required) - expect( - gate(itSnapshot({ query: { status: 'ok', registration: { present: false } }, cache: { kind: 'absent' } })), - ).toBe(false); - // cache-missing - expect(gate(itSnapshot({ cache: { kind: 'absent' } }))).toBe(false); - // installed-newer (implicit downgrade refused) - expect(gate(itSnapshot({ query: itReg(IT_NEWER) }))).toBe(false); - }); - - test('a current-LOOKING but payload-mismatched snapshot is NOT fresh authority (false)', () => { - // same version string, divergent cache digest → payload-mismatch, never current. - expect(gate(itSnapshot({ cache: itCache('c'.repeat(64)) }))).toBe(false); +describe('init marker-owned Codex route', () => { + test('writes the stable /bin/genie facade with args ["mcp"] and no cwd override', () => { + initGitRepo(dir); + const home = join(dir, 'home-a'); + expect(runInitWithHome(dir, home).code).toBe(0); + const toml = readFileSync(join(dir, '.codex', 'config.toml'), 'utf8'); + expect(toml).toContain('# BEGIN GENIE MCP FALLBACK'); + // The marker command is the canonical stable facade, never a versioned cache path. + expect(toml).toContain(`mcp_servers.genie.command = "${join(home, 'bin', 'genie')}"`); + expect(toml).toContain('mcp_servers.genie.args = ["mcp"]'); + // No effective cwd override is written. + expect(toml).not.toContain('cwd'); }); - test('a current-version snapshot with an unresolved refresh intent is a recovery state, not current (false)', () => { - // intent-target-current dominates the ordinary `current` row: retain fallback. - expect(gate(itSnapshot({ intent: itIntentTargetCurrent() }))).toBe(false); + test('is created even with no Codex CLI present (plugin- and delivery-independent)', () => { + initGitRepo(dir); + // Default runInit already strips codex from PATH; the marker must still exist. + expect(runInit(dir).code).toBe(0); + expect(existsSync(join(dir, '.codex', 'config.toml'))).toBe(true); + expect(readFileSync(join(dir, '.codex', 'config.toml'), 'utf8')).toContain('mcp_servers.genie'); }); - test('the observation is taken with the freshly resolved codex command (no stale authority)', () => { - const observed: string[] = []; - gate(itSnapshot(), observed); - expect(observed).toEqual(['/fake/codex']); + test('an explicit GENIE_HOME relocation is reconciled to the new facade by init', () => { + initGitRepo(dir); + const homeA = join(dir, 'home-a'); + const homeB = join(dir, 'home-b'); + expect(runInitWithHome(dir, homeA).code).toBe(0); + expect(runInitWithHome(dir, homeB).code).toBe(0); + const toml = readFileSync(join(dir, '.codex', 'config.toml'), 'utf8'); + expect(toml).toContain(`mcp_servers.genie.command = "${join(homeB, 'bin', 'genie')}"`); + expect(toml).not.toContain(join(homeA, 'bin', 'genie')); + // Exactly one owned marker block — reconciliation never duplicates. + expect(toml.match(/BEGIN GENIE MCP FALLBACK/g)).toHaveLength(1); }); - test('an absent codex CLI observes with a null command and never reconciles', () => { - const observed: string[] = []; - const result = isCodexVerifiedCurrent({ - resolveCodexCommand: () => null, - observeCodexActivation: ({ command }) => { - observed.push(command === null ? 'null' : command); - return itSnapshot({ query: { status: 'failed', detail: 'codex CLI not found' } }); - }, - }); - expect(result).toBe(false); - expect(observed).toEqual(['null']); + test('an unowned same-key Codex route is preserved byte-for-byte and reported, never overwritten', () => { + initGitRepo(dir); + const codexPath = join(dir, '.codex', 'config.toml'); + mkdirSync(join(dir, '.codex'), { recursive: true }); + const personal = '[mcp_servers.genie]\ncommand = "/my/own/genie"\nargs = ["mcp"]\n'; + writeFileSync(codexPath, personal); + const { code, stderr } = runInitWithHome(dir, join(dir, 'home-a')); + expect(code).toBe(1); + expect(stderr.toLowerCase()).toMatch(/unverified|preserved/); + // The user file is untouched, and no scaffold leaked past the collision. + expect(readFileSync(codexPath, 'utf8')).toBe(personal); + expect(existsSync(join(dir, '.genie', 'INDEX.md'))).toBe(false); }); - test('init.ts never mints an assertion/permit and never touches the lifecycle lease', () => { + test('init.ts never mints an assertion/permit and never touches the lifecycle lease or delivery', () => { const source = readFileSync(join(import.meta.dir, 'init.ts'), 'utf8'); - expect(source.includes('acquireLifecycleLease')).toBe(false); - expect(source.includes('requestRetirementAssertion')).toBe(false); - expect(source.includes('authorizeCodexActivation')).toBe(false); - expect(source.includes('executeCodexActivation')).toBe(false); + for (const forbidden of [ + 'acquireLifecycleLease', + 'requestRetirementAssertion', + 'authorizeCodexActivation', + 'executeCodexActivation', + 'observeCodexActivation', + 'beginActivation', + ]) { + expect(source.includes(forbidden)).toBe(false); + } }); }); diff --git a/src/term-commands/init.ts b/src/term-commands/init.ts index 6d8c80023..341c0d1d7 100644 --- a/src/term-commands/init.ts +++ b/src/term-commands/init.ts @@ -14,16 +14,11 @@ import { existsSync, mkdirSync, readFileSync, writeFileSync } from 'node:fs'; import { dirname, join } from 'node:path'; import type { Command } from 'commander'; -// Group D consumes B's stable observation/reporting facade — never A's internals -// directly — to gate init's project-fallback reconciliation on a fresh -// `verified-current` observation. -import { classifyCodexActivation, observeCodexActivation } from '../lib/codex-activation-executor.js'; -import type { CodexActivationSnapshot } from '../lib/codex-activation.js'; import { type ArtifactAction, - type CodexPluginProbe, type McpConfigResult, type RegisterProjectMcpOptions, + genieFacadeMcpEntry, mergeCodexMcpFallback, registerProjectMcpConfigs, removeCodexMcpFallback, @@ -143,69 +138,6 @@ export function registerMcpConfigs(root: string, options: RegisterProjectMcpOpti return registerProjectMcpConfigs(root, options); } -// ============================================================================ -// Verified-current fallback gate (Group D, D5) -// ============================================================================ - -/** Test/observation seams for the read-only, permit-free verified-current gate. */ -export interface InitCodexObservationDeps { - /** Injected activation observer (defaults to B's facade over the resolved codex CLI). */ - observeCodexActivation?: (options: { command: string | null }) => CodexActivationSnapshot; - /** Resolve the codex executable (defaults to `Bun.which('codex')`, null on failure). */ - resolveCodexCommand?: () => string | null; -} - -function defaultResolveCodexCommand(): string | null { - try { - return Bun.which('codex'); - } catch { - return null; - } -} - -/** - * Decide whether init may reconcile the project fallback (trust the plugin, - * remove the marker-owned `.codex/config.toml` route). ONLY a fresh, unambiguous - * `verified-current` activation observation grants that — the classifier's - * `current` state, which requires the installed cache digest to equal the - * canonical payload with no unresolved refresh intent. Pending, broken, - * indeterminate, and current-LOOKING recovery states (e.g. `intent-target-current`) - * all return false so the fallback is retained. This is a pure, read-only - * observation: it never mints an assertion/permit, runs a plugin/cache mutator, - * or touches the lifecycle lease. It never treats a prior/current-looking - * snapshot as fresh authority — the observation is taken here, now. - */ -export function isCodexVerifiedCurrent(deps: InitCodexObservationDeps = {}): boolean { - const resolveCommand = deps.resolveCodexCommand ?? defaultResolveCodexCommand; - const observe = deps.observeCodexActivation ?? ((options) => observeCodexActivation(options)); - const snapshot = observe({ command: resolveCommand() }); - return classifyCodexActivation(snapshot).kind === 'current'; -} - -/** - * Project the verified-current verdict onto the codex-fallback decision - * `registerProjectMcpConfigs` consumes: a verified-current observation is the - * only usable-plugin signal (removes the fallback); everything else keeps - * `isUsableCodexPlugin` false so the marker-owned fallback is retained. - */ -function verifiedCurrentProbe(verifiedCurrent: boolean): CodexPluginProbe { - return verifiedCurrent - ? { - cliAvailable: true, - status: 'ok', - installed: true, - enabled: true, - usable: true, - detail: 'activation observer: verified-current (plugin trusted, project fallback removed)', - } - : { - cliAvailable: false, - status: 'unavailable', - installed: false, - detail: 'activation observer: not verified-current; project fallback retained', - }; -} - // ============================================================================ // Reporting // ============================================================================ @@ -253,21 +185,21 @@ interface InitOptions { json?: boolean; } -function handleInit(opts: InitOptions, deps: InitCodexObservationDeps = {}): void { +function handleInit(opts: InitOptions): void { run(() => { const root = resolveGitRoot(process.cwd()); if (!root) throw new NotAGitRepoError(); - // Init reconciles the Codex project fallback ONLY when a fresh observation is - // exactly `verified-current`; pending/broken/indeterminate/recovery states - // retain the fallback and make zero plugin/cache mutation. The observation is - // read-only and never mints an assertion/permit or acquires the lease. - const verifiedCurrent = isCodexVerifiedCurrent(deps); - - // MCP config is planned and schema-checked before any scaffold mutation. - // A wrong-shaped existing JSON file therefore fails without leaving a new - // INDEX or gitignore rules behind. - const mcp = registerMcpConfigs(root, { pluginProbe: verifiedCurrentProbe(verifiedCurrent) }); + // Trusted init ALWAYS reconciles one intact marker-owned Codex route using the + // stable `/bin/genie` facade with no effective cwd override — + // independent of plugin and delivery state, and never touching delivery, + // journal, plugin-enabled, agent, or cache state. A route name is not proof of + // ownership, so an unmanaged same-key route is preserved and reported. + // + // MCP config is planned and schema-checked before any scaffold mutation, so a + // wrong-shaped existing JSON file fails without leaving a new INDEX or + // gitignore rules behind. + const mcp = registerMcpConfigs(root, { codexEntry: genieFacadeMcpEntry(), forceCodexFallback: true }); const index = scaffoldIndex(root); const gitignore = scaffoldGitignore(root); const result: InitResult = { root, index, gitignore: gitignore.action, rulesAdded: gitignore.added, mcp }; diff --git a/src/term-commands/mcp.test.ts b/src/term-commands/mcp.test.ts index 3329f56f7..680cbc295 100644 --- a/src/term-commands/mcp.test.ts +++ b/src/term-commands/mcp.test.ts @@ -118,6 +118,10 @@ function seed(cwd: string): { taskId: string } { const t = createTask(db, { title: 'seed task', boardId: board.id, wish: 'genie-mcp', group: 'g2' }); createTask(db, { title: 'other', boardId: board.id }); createWishGroups(db, 'genie-mcp', [{ name: 'g1' }, { name: 'g2', dependsOn: ['g1'] }]); + // Fold pending WAL frames into the main db before the reader subprocess opens, + // so the readonly `genie mcp` server isn't racing an open WAL writer under + // cross-file test contention ("database is locked"). + db.exec('PRAGMA wal_checkpoint(TRUNCATE)'); db.close(); return { taskId: t.id }; } @@ -284,6 +288,7 @@ describe('mcp tools/call', () => { Date.now(), taskId, ); + db.exec('PRAGMA wal_checkpoint(TRUNCATE)'); db.close(); const responses = await driveMcp(repo, [ INIT, @@ -325,6 +330,7 @@ describe('mcp runtime-layer backward compatibility', () => { db.query( "UPDATE tasks SET blocked_by='x', blocked_reason='r', heartbeat_at=1, agent_kind='codex', lane='Idea' WHERE id=?", ).run(taskId); + db.exec('PRAGMA wal_checkpoint(TRUNCATE)'); db.close(); const responses = await driveMcp(repo, [ @@ -369,22 +375,51 @@ describe('mcp runtime-layer backward compatibility', () => { }); // ============================================================================ -// Absent-db degrade +// Fail-closed: a missing genie.db is a typed error, never an empty board // ============================================================================ -describe('mcp absent-db degrade', () => { - test('genie_board degrades to an empty board when genie.db is absent', async () => { - // Fresh repo, never seeded → no .genie/genie.db. Readonly open throws → null. +describe('mcp missing-database fail-closed', () => { + test('genie_board on a git repo with no genie.db returns project-database-unavailable, not empty success', async () => { + // Fresh git repo, never seeded → no .genie/genie.db. The old behavior served + // a healthy-looking empty board (the masquerade); Group A returns a typed error. const responses = await driveMcp(repo, [ INIT, INITIALIZED, { jsonrpc: '2.0', id: 12, method: 'tools/call', params: { name: 'genie_board', arguments: {} } }, ]); const res = responses.find((r) => r.id === 12); - expect(res?.result?.isError).toBe(false); - const payload = toolPayload<{ board: null; counts: { total: number }; tasks: unknown[] }>(res!); - expect(payload.counts.total).toBe(0); - expect(payload.tasks).toEqual([]); + expect(res?.result?.isError).toBe(true); + const payload = toolPayload<{ error: string; detail: string }>(res!); + expect(payload.error).toBe('project-database-unavailable'); + // The error names the exact storage-root DB candidate, never a cache path. + expect(payload.detail).toContain('.genie/genie.db'); + expect(payload).not.toHaveProperty('counts'); + expect(payload).not.toHaveProperty('tasks'); + }); + + test('every read tool fails closed identically when the database is absent', async () => { + const calls = [ + { id: 13, name: 'genie_board', arguments: {} }, + { id: 14, name: 'genie_wish_status', arguments: { wish: 'x' } }, + { id: 15, name: 'genie_worktree_context', arguments: { branch: 'main' } }, + { id: 16, name: 'genie_task', arguments: { id: 't_1' } }, + { id: 17, name: 'genie_active', arguments: {} }, + ]; + const responses = await driveMcp(repo, [ + INIT, + INITIALIZED, + ...calls.map((c) => ({ + jsonrpc: '2.0', + id: c.id, + method: 'tools/call', + params: { name: c.name, arguments: c.arguments }, + })), + ]); + for (const c of calls) { + const res = responses.find((r) => r.id === c.id); + expect(res?.result?.isError).toBe(true); + expect(toolPayload<{ error: string }>(res!).error).toBe('project-database-unavailable'); + } }); test('reopens a db created AFTER the server started (no stale empty board)', async () => { @@ -476,6 +511,7 @@ describe('mcp worktree branch resolution', () => { createWishGroups(db, 'genie', [{ name: 'mcp' }]); createTask(db, { title: 'b', boardId: board.id, wish: 'genie-mcp', group: 'g1' }); createWishGroups(db, 'genie-mcp', [{ name: 'g1' }]); + db.exec('PRAGMA wal_checkpoint(TRUNCATE)'); db.close(); const res = await driveMcp(repo, [ INIT, diff --git a/src/term-commands/mcp.ts b/src/term-commands/mcp.ts index aa363e9c6..cb9dbd1ef 100644 --- a/src/term-commands/mcp.ts +++ b/src/term-commands/mcp.ts @@ -37,11 +37,14 @@ const PROTOCOL_VERSION = '2024-11-05'; */ export async function runMcpServer(): Promise { // Lazy: the read-only bun:sqlite open + tools load here, not at genie startup. - const { MCP_TOOLS, openReadonlyDb } = await import('../lib/v5/mcp-tools.js'); + const { MCP_TOOLS, openReadonlyDb, resolveProjectContext } = await import('../lib/v5/mcp-tools.js'); const { runMcpServerLoop } = await import('../lib/v5/mcp-server.js'); await runMcpServerLoop({ tools: MCP_TOOLS, openReadonlyDb, + // Fail-closed: missing repository context / genie.db / unsupported layouts + // surface as a typed MCP error instead of a healthy-looking empty board. + resolveContext: resolveProjectContext, // Fixed reply that ignores the client's declared version — read-only `genie // mcp` does NOT negotiate. Key order pinned for byte-identical output. initialize: () => ({ diff --git a/tests/integration/codex-project-route-migration.test.ts b/tests/integration/codex-project-route-migration.test.ts new file mode 100644 index 000000000..6a1084f3b --- /dev/null +++ b/tests/integration/codex-project-route-migration.test.ts @@ -0,0 +1,173 @@ +/** + * Two-repository Codex project-route migration (Group A, D7 + acceptance). + * + * After the global plugin MCP route disappears (the Codex plugin ships none), + * an untouched repository has an EXPLICITLY ABSENT project route and NO fallback: + * `genie mcp` launched there fails closed with `project-database-unavailable` + * rather than serving an outer/cache-root empty board or another repo's state. + * The single reconciliation command is `cd && genie init`, which creates + * only that repo's marker-owned route. Afterward each repo returns ONLY its own + * unique seeded sentinel. + */ + +import { afterEach, beforeEach, describe, expect, test } from 'bun:test'; +import { execFileSync } from 'node:child_process'; +import { existsSync, mkdirSync, mkdtempSync, readFileSync, rmSync } from 'node:fs'; +import { tmpdir } from 'node:os'; +import { join } from 'node:path'; +import { openDb } from '../../src/lib/v5/genie-db.js'; +import { createBoard, createTask, createWishGroups } from '../../src/lib/v5/task-state.js'; + +const GENIE = join(import.meta.dir, '..', '..', 'src', 'genie.ts'); + +let base: string; +let genieHome: string; + +function git(cwd: string, ...args: string[]): void { + execFileSync('git', args, { + cwd, + stdio: 'ignore', + env: { + ...process.env, + GIT_AUTHOR_NAME: 'T', + GIT_AUTHOR_EMAIL: 't@e.com', + GIT_COMMITTER_NAME: 'T', + GIT_COMMITTER_EMAIL: 't@e.com', + }, + }); +} + +function initRepo(name: string): string { + const dir = join(base, name); + mkdirSync(dir, { recursive: true }); + git(dir, 'init', '-b', 'main'); + git(dir, 'commit', '--allow-empty', '-m', 'init'); + return dir; +} + +function runInit(cwd: string): { code: number; stderr: string } { + const res = Bun.spawnSync([process.execPath, GENIE, 'init'], { + cwd, + stdout: 'pipe', + stderr: 'pipe', + // No Codex CLI on PATH + isolated GENIE_HOME: the marker route is plugin-independent. + env: { ...process.env, PATH: '/usr/bin:/bin', GENIE_HOME: genieHome }, + }); + return { code: res.exitCode, stderr: res.stderr.toString() }; +} + +/** Seed a repo's db with a UNIQUE sentinel wish so cross-repo bleed is detectable. */ +function seedSentinel(repo: string, sentinel: string): void { + const db = openDb({ cwd: repo }); + const board = createBoard(db, 'repo'); + createTask(db, { title: `task-${sentinel}`, boardId: board.id, wish: sentinel, group: 'g' }); + createWishGroups(db, sentinel, [{ name: 'g' }]); + // Fold pending WAL frames into the main db and close before any reader (the + // `genie mcp` subprocess) opens, so the readonly reader isn't racing an open + // WAL writer under cross-file contention ("database is locked"). + db.exec('PRAGMA wal_checkpoint(TRUNCATE)'); + db.close(); +} + +interface RpcResponse { + id: number | string | null; + result?: { content?: Array<{ text: string }>; isError?: boolean }; +} + +async function driveBoard(cwd: string): Promise<{ isError: boolean; payload: Record }> { + const proc = Bun.spawn(['bun', GENIE, 'mcp'], { + cwd, + stdin: 'pipe', + stdout: 'pipe', + stderr: 'pipe', + env: { ...process.env, NO_COLOR: '1', GENIE_TEST_SKIP_PGSERVE: '1' }, + }); + const requests = [ + { + jsonrpc: '2.0', + id: 1, + method: 'initialize', + params: { protocolVersion: '2024-11-05', capabilities: {}, clientInfo: { name: 't', version: '0' } }, + }, + { jsonrpc: '2.0', method: 'notifications/initialized' }, + { jsonrpc: '2.0', id: 2, method: 'tools/call', params: { name: 'genie_board', arguments: {} } }, + ]; + proc.stdin.write(`${requests.map((r) => JSON.stringify(r)).join('\n')}\n`); + await proc.stdin.end(); + const stdout = await new Response(proc.stdout).text(); + await proc.exited; + const responses = stdout + .split('\n') + .filter((l) => l.trim().length > 0) + .map((l) => JSON.parse(l) as RpcResponse); + const res = responses.find((r) => r.id === 2); + if (!res?.result) throw new Error(`no tools/call result: ${stdout}`); + return { isError: res.result.isError === true, payload: JSON.parse(res.result.content?.[0]?.text ?? '{}') }; +} + +const markerPath = (repo: string) => join(repo, '.codex', 'config.toml'); + +beforeEach(() => { + base = mkdtempSync(join(tmpdir(), 'genie-migrate-')); + genieHome = join(base, 'genie-home'); +}); + +afterEach(() => { + rmSync(base, { recursive: true, force: true }); +}); + +describe('two-repo Codex project-route migration', () => { + test('reconciled A serves only A; untouched B fails closed; `cd B && genie init` reconciles only B', async () => { + const repoA = initRepo('repoA'); + const repoB = initRepo('repoB'); + + // --- A: reconcile the marker-owned route and seed A's unique sentinel. --- + expect(runInit(repoA).code).toBe(0); + const tomlA = readFileSync(markerPath(repoA), 'utf8'); + expect(tomlA).toContain('# BEGIN GENIE MCP FALLBACK'); + expect(tomlA).toContain(`${join(genieHome, 'bin', 'genie')}`); // stable facade, not a cache path + expect(existsSync(join(repoA, '.mcp.json'))).toBe(true); // Claude/Warp route from init + seedSentinel(repoA, 'alpha-sentinel'); + + const aBoard = await driveBoard(repoA); + expect(aBoard.isError).toBe(false); + expect((aBoard.payload.tasks as Array<{ wish: string }>).some((t) => t.wish === 'alpha-sentinel')).toBe(true); + + // --- B untouched: no project route, no fallback, fails closed (no A bleed). --- + expect(existsSync(markerPath(repoB))).toBe(false); // explicitly absent project route + expect(existsSync(join(repoB, '.mcp.json'))).toBe(false); + const bBefore = await driveBoard(repoB); + expect(bBefore.isError).toBe(true); + expect(bBefore.payload.error).toBe('project-database-unavailable'); + // Critically: B never returns A's sentinel nor a healthy empty board. + expect(JSON.stringify(bBefore.payload)).not.toContain('alpha-sentinel'); + expect(bBefore.payload).not.toHaveProperty('counts'); + + // --- `cd B && genie init` reconciles ONLY B; A is untouched. --- + expect(runInit(repoB).code).toBe(0); + expect(existsSync(markerPath(repoB))).toBe(true); + expect(readFileSync(markerPath(repoB), 'utf8')).toContain(`${join(genieHome, 'bin', 'genie')}`); + seedSentinel(repoB, 'bravo-sentinel'); + + const bAfter = await driveBoard(repoB); + expect(bAfter.isError).toBe(false); + const bWishes = (bAfter.payload.tasks as Array<{ wish: string }>).map((t) => t.wish); + expect(bWishes).toContain('bravo-sentinel'); + expect(bWishes).not.toContain('alpha-sentinel'); // B returns ONLY B's sentinel + + // A still serves only A after B's reconciliation. + const aAgain = await driveBoard(repoA); + const aWishes = (aAgain.payload.tasks as Array<{ wish: string }>).map((t) => t.wish); + expect(aWishes).toContain('alpha-sentinel'); + expect(aWishes).not.toContain('bravo-sentinel'); + }); + + test('an untouched repo with no genie.db never serializes a healthy empty board', async () => { + const repo = initRepo('lonely'); + // No init, no db. The read server must refuse rather than masquerade as empty. + const board = await driveBoard(repo); + expect(board.isError).toBe(true); + expect(board.payload.error).toBe('project-database-unavailable'); + expect(board.payload.detail).toContain('genie init'); + }); +});