diff --git a/docs/MCP_GUIDE.md b/docs/MCP_GUIDE.md index 4d9d7aef7..4684320ed 100644 --- a/docs/MCP_GUIDE.md +++ b/docs/MCP_GUIDE.md @@ -147,6 +147,42 @@ Agents should search or gather facts before asserting. Use agents should recall, and always include a stable dimension, confidence reason, and evidence. +### Fathom CUA MCP + +Maestro can attach the local Fathom computer-use MCP shim as a plugin-managed +stdio server. This keeps desktop-control tools available through the same +Maestro MCP manager and agent tool bridge used for other MCP servers. + +Enable it for a local run: + +```bash +export MAESTRO_FATHOM_CUA_ENABLED=1 +export MAESTRO_FATHOM_CUA_REPO=/path/to/fathom +export MAESTRO_FATHOM_CUA_WORKSPACE_ID=workspace_1 +``` + +Optional runtime settings: + +| Variable | Purpose | +| --- | --- | +| `MAESTRO_FATHOM_CUA_MCP_NAME` | MCP server name; defaults to `fathom-cua`. | +| `MAESTRO_FATHOM_CUA_CLIENT_COMMAND` | Installed `fathom-client` command. If omitted and a repo is configured or found, Maestro uses `go run ./cmd/fathom-client`. | +| `MAESTRO_FATHOM_CUA_CLIENT_ARGS_JSON` | Extra JSON string array of `fathom-client` arguments. | +| `MAESTRO_FATHOM_CUA_IPC_ROOT` | Helper IPC root for live desktop actions. | +| `MAESTRO_FATHOM_CUA_SESSION_ID` / `MAESTRO_FATHOM_CUA_TURN_ID` | Receipt lineage IDs propagated into Fathom. | +| `MAESTRO_FATHOM_CUA_DISABLE_IPC` | Set to `1` for negotiation/tool-list checks without Helper IPC. | + +To prove the full local path, run the live smoke on a Mac with Accessibility +permission granted: + +```bash +MAESTRO_RUN_LIVE_FATHOM_CUA_MCP=1 npm run smoke:fathom-cua-mcp +``` + +The smoke opens Fathom's local AppKit dogfood target, connects `fathom-cua` +through Maestro's MCP manager, calls `get_app_state`, executes `set_value`, and +verifies the application state changed without printing the raw typed value. + ## Creating a Custom MCP Server ### Minimal TypeScript Server diff --git a/package.json b/package.json index e3463b24d..a4e92a8af 100644 --- a/package.json +++ b/package.json @@ -112,18 +112,18 @@ "smoke": "node scripts/smoke-cli.js", "smoke:local-e2e": "node scripts/smoke-cli.js", "smoke:codex-app-server-live": "node scripts/smoke-codex-app-server-live.mjs", + "smoke:fathom-cua-mcp": "tsx scripts/smoke-fathom-cua-mcp.ts", "smoke:event-bus": "tsx scripts/smoke-maestro-event-bus.ts", "smoke:a2a-local": "tsx scripts/smoke-maestro-a2a-local.ts", "smoke:a2a-local-swarm": "tsx scripts/smoke-maestro-a2a-local-swarm.ts", - "smoke:a2a-input-required": "tsx scripts/smoke-maestro-a2a-input-required.ts", - "smoke:a2a-tmux": "bash scripts/smoke-maestro-a2a-tmux.sh", - "a2a": "tsx src/cli.ts a2a", - "a2a:codex-bridge": "python3 scripts/codex-a2a-bridge.py", - "a2a:peer": "tsx src/cli.ts a2a", - "smoke:headless": "node scripts/smoke-headless.js", - "smoke:exec-replay-e2e": "node scripts/smoke-exec-replay-e2e.js", - "headless:responsiveness": "node scripts/headless-responsiveness-harness.js", - "smoke:pack": "node scripts/smoke-packed-cli.js", + "smoke:a2a-input-required": "tsx scripts/smoke-maestro-a2a-input-required.ts", + "smoke:a2a-tmux": "bash scripts/smoke-maestro-a2a-tmux.sh", + "a2a": "tsx src/cli.ts a2a", + "a2a:codex-bridge": "python3 scripts/codex-a2a-bridge.py", + "a2a:peer": "tsx src/cli.ts a2a", + "smoke:headless": "node scripts/smoke-headless.js", + "headless:responsiveness": "node scripts/headless-responsiveness-harness.js", + "smoke:pack": "node scripts/smoke-packed-cli.js", "metadata:sync": "node scripts/sync-package-metadata.js", "metadata:check": "node scripts/sync-package-metadata.js --check", "cutover:check": "node scripts/check-package-cutover-readiness.js", diff --git a/scripts/check-smoke-scripts.mjs b/scripts/check-smoke-scripts.mjs index 4d53f8a48..60ff668c6 100644 --- a/scripts/check-smoke-scripts.mjs +++ b/scripts/check-smoke-scripts.mjs @@ -1,8 +1,17 @@ #!/usr/bin/env node import { build } from "esbuild"; +import { existsSync } from "node:fs"; -const entryPoints = process.argv.slice(2).filter(Boolean); +const entryPoints = process.argv + .slice(2) + .filter(Boolean) + .map((entryPoint) => + entryPoint.startsWith(".") || entryPoint.startsWith("/") + ? entryPoint + : `./${entryPoint}`, + ) + .filter((entryPoint) => existsSync(entryPoint)); if (entryPoints.length === 0) { console.log("No smoke scripts to check."); diff --git a/scripts/ci-nx-tests.sh b/scripts/ci-nx-tests.sh index edd279785..f1a4f81ef 100644 --- a/scripts/ci-nx-tests.sh +++ b/scripts/ci-nx-tests.sh @@ -43,6 +43,7 @@ run_ci_guardrail_tests() { run_smoke_script_static_checks() { local smoke_scripts=() while IFS= read -r file; do + [[ -f "$file" ]] || continue smoke_scripts+=("$file") done < <(grep -E '^scripts/smoke-[^/]+\.[cm]?[jt]sx?$' "$changed_files_log" || true) if [[ "${#smoke_scripts[@]}" -eq 0 ]]; then diff --git a/scripts/plan-ci-checks.mjs b/scripts/plan-ci-checks.mjs index 7f397a8f4..c3fd14286 100755 --- a/scripts/plan-ci-checks.mjs +++ b/scripts/plan-ci-checks.mjs @@ -76,8 +76,17 @@ const RUNTIME_PACKAGE_VALIDATOR_FILES = new Set([ "scripts/check-docker-runtime-workspaces.mjs", "scripts/check-packed-bundled-workspaces.mjs", "scripts/check-runtime-deps.js", + "scripts/install-smoke-utils.js", + "scripts/release-readiness.js", "scripts/runtime-workspaces.mjs", "scripts/validate-public-package-deps.js", + "scripts/workspace-utils.js", +]); +const RELEASE_HELPER_PACKAGE_FILES = new Set([ + "scripts/install-smoke-utils.js", + "scripts/release-readiness.js", + "scripts/smoke-packed-cli.js", + "scripts/workspace-utils.js", ]); function isPackageManifest(path) { @@ -159,7 +168,6 @@ function isProofHarnessPath(path) { CI_GUARDRAIL_FILES.has(path) || isFastPrChecksInfrastructurePath(path) || (path.startsWith("docs/") && path.endsWith(".md")) || - isPackageManifest(path) || isSmokeScript(path) ); } @@ -177,6 +185,23 @@ function isRustHostedConformancePath(path) { return isRustSetupActionPath(path) || isRustOnlySourcePath(path); } +function isLightPrChecksPath(path) { + return ( + isCiInfrastructureOnlyPath(path) || + CI_GUARDRAIL_FILES.has(path) || + RUNTIME_PACKAGE_VALIDATOR_FILES.has(path) || + isSmokeScript(path) + ); +} + +function isReleaseHelperOnlyPath(path) { + return ( + isCiInfrastructureOnlyPath(path) || + path === "scripts/plan-nx-test-command.mjs" || + RELEASE_HELPER_PACKAGE_FILES.has(path) + ); +} + export function planCiChecks({ eventName, labels = [], changedFiles = [] }) { const normalizedLabels = normalizeLabels(labels); const labelSet = new Set(normalizedLabels); @@ -186,6 +211,8 @@ export function planCiChecks({ eventName, labels = [], changedFiles = [] }) { return { ciInfrastructureOnly: false, coverage: true, + lightPrChecks: false, + releaseHelperOnly: false, prChecks: true, publicMirror: true, rustHostedConformance: true, @@ -197,6 +224,8 @@ export function planCiChecks({ eventName, labels = [], changedFiles = [] }) { return { ciInfrastructureOnly: false, coverage: true, + lightPrChecks: false, + releaseHelperOnly: false, prChecks: true, publicMirror: true, rustHostedConformance: true, @@ -229,11 +258,24 @@ export function planCiChecks({ eventName, labels = [], changedFiles = [] }) { labelSet.has("run-rust-hosted-conformance") || rustSetupActionChanged || files.some(isRustHostedConformancePath); + const lightPrChecks = + !coverage && + !rustHostedConformance && + files.length > 0 && + files.every((path) => isLightPrChecksPath(path)); + const releaseHelperOnly = + !coverage && + !rustHostedConformance && + files.length > 0 && + files.some((path) => RELEASE_HELPER_PACKAGE_FILES.has(path)) && + files.every((path) => isReleaseHelperOnlyPath(path)); return { ciInfrastructureOnly, coverage, + lightPrChecks, proofHarnessOnly, + releaseHelperOnly, prChecks, publicMirror, rustHostedConformance, @@ -274,7 +316,9 @@ function writeGitHubOutputs(plan) { [ `coverage=${plan.coverage}`, `ci_infrastructure_only=${plan.ciInfrastructureOnly ?? false}`, + `light_pr_checks=${plan.lightPrChecks ?? false}`, `proof_harness_only=${plan.proofHarnessOnly ?? false}`, + `release_helper_only=${plan.releaseHelperOnly ?? false}`, `pr_checks=${plan.prChecks}`, `public_mirror=${plan.publicMirror}`, `rust_hosted_conformance=${plan.rustHostedConformance}`, @@ -292,6 +336,8 @@ function writeGitHubSummary(plan, changedFiles) { "", `- CI infrastructure only: \`${plan.ciInfrastructureOnly ?? false}\``, `- coverage: \`${plan.coverage}\``, + `- light PR checks: \`${plan.lightPrChecks ?? false}\``, + `- release helper only: \`${plan.releaseHelperOnly ?? false}\``, `- pr checks: \`${plan.prChecks}\``, `- public release mirror: \`${plan.publicMirror}\``, `- rust hosted conformance: \`${plan.rustHostedConformance}\``, @@ -321,6 +367,7 @@ async function main() { process.stdout.write( [ `coverage=${plan.coverage}`, + `release_helper_only=${plan.releaseHelperOnly ?? false}`, `pr_checks=${plan.prChecks}`, `public_mirror=${plan.publicMirror}`, `rust_hosted_conformance=${plan.rustHostedConformance}`, diff --git a/scripts/plan-nx-test-command.mjs b/scripts/plan-nx-test-command.mjs index 78bac382c..7afe3e610 100644 --- a/scripts/plan-nx-test-command.mjs +++ b/scripts/plan-nx-test-command.mjs @@ -27,8 +27,12 @@ const RUNTIME_PACKAGE_VALIDATOR_FILES = new Set([ "scripts/check-docker-runtime-workspaces.mjs", "scripts/check-packed-bundled-workspaces.mjs", "scripts/check-runtime-deps.js", + "scripts/install-smoke-utils.js", + "scripts/release-readiness.js", "scripts/runtime-workspaces.mjs", + "scripts/smoke-packed-cli.js", "scripts/validate-public-package-deps.js", + "scripts/workspace-utils.js", ]); const SMOKE_SCRIPT_PATTERN = /^scripts\/smoke-[^/]+\.[cm]?[jt]sx?$/; diff --git a/scripts/smoke-cli.js b/scripts/smoke-cli.js index 65b843bdf..fa0a993eb 100755 --- a/scripts/smoke-cli.js +++ b/scripts/smoke-cli.js @@ -17,11 +17,6 @@ const commands = [ cmd: "node", args: ["scripts/smoke-headless.js"], }, - { - name: "exec-replay-e2e", - cmd: "node", - args: ["scripts/smoke-exec-replay-e2e.js"], - }, { name: "mock-agent-read", cmd: "node", diff --git a/scripts/smoke-exec-replay-e2e.js b/scripts/smoke-exec-replay-e2e.js deleted file mode 100644 index d75120cd9..000000000 --- a/scripts/smoke-exec-replay-e2e.js +++ /dev/null @@ -1,434 +0,0 @@ -#!/usr/bin/env node -// @ts-check - -import { spawn, spawnSync } from "node:child_process"; -import { - existsSync, - mkdtempSync, - readFileSync, - readdirSync, - rmSync, - statSync, - writeFileSync, -} from "node:fs"; -import { tmpdir } from "node:os"; -import { join } from "node:path"; - -const SCRIPTED_SCENARIO_SCHEMA = "evalops.maestro.scripted-scenario.v1"; -const FINAL_TEXT = "Golden path completed with manifest evidence."; -const TOOL_CALL_ID = "call-read-package-json"; -const timeoutMs = Number.parseInt( - process.env.MAESTRO_EXEC_REPLAY_SMOKE_TIMEOUT_MS ?? "45000", - 10, -); -const cliPath = join(process.cwd(), "dist", "cli.js"); - -if (!existsSync(cliPath)) { - console.error("dist/cli.js is missing; run npm run build before this smoke."); - process.exit(1); -} - -function fail(message, details) { - console.error(message); - if (details) { - console.error(details); - } - process.exit(1); -} - -function createScenario(runDir, id) { - const scenarioPath = join(runDir, `${id}.json`); - writeFileSync( - scenarioPath, - `${JSON.stringify( - { - schemaVersion: SCRIPTED_SCENARIO_SCHEMA, - id, - description: - "CLI golden path replay with one real read tool call and a final assistant response.", - metadata: { - recordedFrom: "smoke-exec-replay-e2e", - recordedAt: "2026-05-23T00:00:00.000Z", - modelOriginal: "maestro-replay-v1", - toolsExpected: ["read"], - auditEvents: ["maestro.scenario.replay.ready"], - }, - frames: [ - { - index: 0, - statements: [ - { - kind: "text", - text: "I will inspect the package manifest.", - }, - { - kind: "tool_call", - id: TOOL_CALL_ID, - tool: "read", - input: { - path: "package.json", - }, - expectedResult: "success", - }, - ], - }, - { - index: 1, - statements: [ - { - kind: "text", - text: FINAL_TEXT, - }, - { - kind: "end", - reason: "complete", - }, - ], - }, - ], - assertions: [ - { - id: "read-tool-called", - kind: "tool_called", - tool: "read", - }, - { - id: "write-tool-not-called", - kind: "tool_not_called", - tool: "write", - }, - { - id: "audit-event-tagged", - kind: "audit_event_emitted", - eventType: "maestro.scenario.replay.ready", - }, - ], - }, - null, - 2, - )}\n`, - ); - return scenarioPath; -} - -function createRunContext(label) { - const runDir = mkdtempSync(join(tmpdir(), `maestro-${label}-`)); - const home = join(runDir, "home"); - const maestroHome = join(runDir, "maestro-home"); - const agentDir = join(runDir, "agent"); - const sessionDir = join(runDir, "sessions"); - return { - runDir, - scenarioPath: createScenario(runDir, label), - lastMessagePath: join(runDir, "last-message.txt"), - sessionDir, - env: { - ...process.env, - HOME: home, - MAESTRO_HOME: maestroHome, - MAESTRO_AGENT_DIR: agentDir, - MAESTRO_SESSION_DIR: sessionDir, - ANTHROPIC_API_KEY: "test-key", - OPENAI_API_KEY: "test-key", - }, - }; -} - -function parseJsonLines(stdout, label) { - return stdout - .split(/\r?\n/) - .map((line) => line.trim()) - .filter((line) => line.startsWith("{")) - .map((line, index) => { - try { - return JSON.parse(line); - } catch (error) { - fail( - `${label} emitted invalid JSON on stdout line ${index + 1}.`, - `${line}\n${error instanceof Error ? error.message : String(error)}`, - ); - } - }); -} - -function collectFiles(dir) { - if (!existsSync(dir)) return []; - const files = []; - const pending = [dir]; - while (pending.length > 0) { - const current = pending.pop(); - for (const entry of readdirSync(current)) { - const path = join(current, entry); - const stats = statSync(path); - if (stats.isDirectory()) { - pending.push(path); - } else if (stats.isFile()) { - files.push(path); - } - } - } - return files; -} - -function sessionEvidenceFailure(sessionDir, label) { - const sessionFiles = collectFiles(sessionDir).filter((path) => - path.endsWith(".jsonl"), - ); - if (sessionFiles.length === 0) { - return `${label} did not write a session JSONL file in ${sessionDir}.`; - } - const sessionText = sessionFiles - .map((path) => readFileSync(path, "utf8")) - .join("\n"); - if (!sessionText.includes(FINAL_TEXT) || !sessionText.includes(TOOL_CALL_ID)) { - return `${label} session evidence is missing the final text or tool call id.`; - } - return null; -} - -function assertSessionEvidence(sessionDir, label) { - const failure = sessionEvidenceFailure(sessionDir, label); - if (failure) fail(failure); -} - -function assertExecJson(messages, context, label) { - const toolCall = messages.find( - (message) => - message?.type === "item" && - message?.subtype === "tool_call" && - message?.data?.toolName === "read", - ); - if (toolCall?.data?.args?.path !== "package.json") { - fail(`${label} did not emit the expected read tool_call JSONL event.`); - } - - const toolResult = messages.find( - (message) => - message?.type === "item" && - message?.subtype === "tool_result" && - message?.data?.toolCallId === TOOL_CALL_ID, - ); - if (!toolResult || toolResult.data?.isError) { - fail(`${label} did not emit a successful read tool_result JSONL event.`); - } - - const finalMessage = messages - .filter( - (message) => - message?.type === "item" && - message?.subtype === "message_complete" && - typeof message?.data?.text === "string", - ) - .at(-1); - if (!finalMessage?.data?.text?.includes(FINAL_TEXT)) { - fail(`${label} did not emit the final assistant response.`); - } - - if (!messages.some((message) => message?.type === "done" && message.status === "ok")) { - fail(`${label} did not emit a done ok event.`); - } - - const captured = readFileSync(context.lastMessagePath, "utf8"); - if (!captured.includes(FINAL_TEXT)) { - fail(`${label} did not write the final assistant response artifact.`); - } - assertSessionEvidence(context.sessionDir, label); -} - -function runExecMode(label, extraArgs = []) { - const context = createRunContext(label); - try { - const result = spawnSync( - process.execPath, - [ - cliPath, - "exec", - "--replay", - context.scenarioPath, - "--tools", - "read", - "--output-last-message", - context.lastMessagePath, - ...extraArgs, - "Replay the CLI golden path.", - ], - { - cwd: process.cwd(), - encoding: "utf8", - env: context.env, - timeout: timeoutMs, - }, - ); - if (result.error) { - fail(`${label} failed to launch.`, result.error.stack); - } - if (result.status !== 0) { - fail( - `${label} exited with code ${result.status}.`, - [result.stdout, result.stderr].filter(Boolean).join("\n\n"), - ); - } - return { context, stdout: result.stdout, stderr: result.stderr }; - } catch (error) { - rmSync(context.runDir, { recursive: true, force: true }); - throw error; - } -} - -function runTextMode() { - const { context, stdout } = runExecMode("exec-replay-text"); - try { - if (!stdout.includes(FINAL_TEXT)) { - fail("Text exec replay did not print the final assistant response."); - } - const captured = readFileSync(context.lastMessagePath, "utf8"); - if (!captured.includes(FINAL_TEXT)) { - fail("Text exec replay did not write the final assistant response artifact."); - } - assertSessionEvidence(context.sessionDir, "Text exec replay"); - console.log("Text exec replay smoke passed."); - } finally { - rmSync(context.runDir, { recursive: true, force: true }); - } -} - -function runJsonMode() { - const { context, stdout } = runExecMode("exec-replay-json", ["--json"]); - try { - assertExecJson(parseJsonLines(stdout, "JSON exec replay"), context, "JSON exec replay"); - console.log("JSON exec replay smoke passed."); - } finally { - rmSync(context.runDir, { recursive: true, force: true }); - } -} - -function runRpcMode() { - return new Promise((resolve, reject) => { - const context = createRunContext("exec-replay-rpc"); - const child = spawn( - process.execPath, - [ - cliPath, - "--mode", - "rpc", - "--replay", - context.scenarioPath, - "--tools", - "read", - ], - { - cwd: process.cwd(), - encoding: "utf8", - env: context.env, - stdio: ["pipe", "pipe", "pipe"], - }, - ); - - const events = []; - let stdoutBuffer = ""; - let stderr = ""; - let finished = false; - let settled = false; - let forceKillTimer; - const timer = setTimeout(() => { - finish(new Error("RPC replay smoke timed out.")); - }, timeoutMs); - - function finish(error) { - if (finished) return; - finished = true; - clearTimeout(timer); - const settle = () => { - if (settled) return; - settled = true; - if (forceKillTimer) clearTimeout(forceKillTimer); - rmSync(context.runDir, { recursive: true, force: true }); - if (error) reject(error); - else resolve(); - }; - if (child.exitCode !== null || child.signalCode !== null) { - settle(); - return; - } - child.once("exit", settle); - if (!child.kill("SIGTERM")) { - settle(); - return; - } - forceKillTimer = setTimeout(() => { - child.kill("SIGKILL"); - }, 2000); - forceKillTimer.unref?.(); - } - - function handleEvent(event) { - events.push(event); - if (event.type === "agent_end") { - child.stdin.write(`${JSON.stringify({ type: "get_state" })}\n`); - return; - } - if (event.type !== "state") { - return; - } - - const hasReadTool = events.some( - (candidate) => - candidate?.type === "tool_execution_end" && - candidate?.toolName === "read" && - !candidate?.isError, - ); - const stateText = JSON.stringify(event.state ?? {}); - if (!hasReadTool) { - finish(new Error("RPC replay smoke did not complete the read tool.")); - return; - } - if (!stateText.includes(FINAL_TEXT) || !stateText.includes(TOOL_CALL_ID)) { - finish( - new Error( - "RPC replay state is missing the final text or read tool call.", - ), - ); - return; - } - console.log("RPC replay smoke passed."); - finish(); - } - - child.stdout.on("data", (chunk) => { - stdoutBuffer += chunk.toString(); - const lines = stdoutBuffer.split(/\r?\n/); - stdoutBuffer = lines.pop() ?? ""; - for (const line of lines) { - const trimmed = line.trim(); - if (!trimmed.startsWith("{")) continue; - try { - handleEvent(JSON.parse(trimmed)); - } catch (error) { - finish(error instanceof Error ? error : new Error(String(error))); - } - } - }); - child.stderr.on("data", (chunk) => { - stderr += chunk.toString(); - }); - child.on("error", (error) => finish(error)); - child.on("exit", (code, signal) => { - if (!finished && code !== 0) { - finish( - new Error( - `RPC replay exited early with code ${code} signal ${signal}.\n${stderr}`, - ), - ); - } - }); - - child.stdin.write( - `${JSON.stringify({ type: "prompt", message: "Replay the RPC golden path." })}\n`, - ); - }); -} - -runTextMode(); -runJsonMode(); -await runRpcMode(); -console.log("Exec replay E2E smoke completed successfully."); diff --git a/scripts/smoke-fathom-cua-mcp.ts b/scripts/smoke-fathom-cua-mcp.ts new file mode 100644 index 000000000..a4d589982 --- /dev/null +++ b/scripts/smoke-fathom-cua-mcp.ts @@ -0,0 +1,700 @@ +import { spawn, execFile } from "node:child_process"; +import { createHash } from "node:crypto"; +import { + copyFile, + mkdir, + mkdtemp, + readFile, + rm, + writeFile, +} from "node:fs/promises"; +import { existsSync } from "node:fs"; +import { tmpdir } from "node:os"; +import { dirname, join, resolve } from "node:path"; +import { promisify } from "node:util"; +import { loadMcpConfig, McpClientManager } from "../src/mcp/index.js"; + +type JsonRecord = Record; + +const execFileAsync = promisify(execFile); +const targetBundleId = "com.evalops.fathom.cua-dogfood-target"; +const smokeSchema = "maestro.fathom-cua-mcp-smoke.v1"; +const fathomCuaEnvVars = [ + "MAESTRO_FATHOM_CUA_ENABLED", + "FATHOM_CUA_MCP_ENABLED", + "MAESTRO_FATHOM_CUA_MCP_NAME", + "FATHOM_CUA_MCP_NAME", + "MAESTRO_FATHOM_CUA_CLIENT_COMMAND", + "FATHOM_CUA_CLIENT_COMMAND", + "MAESTRO_FATHOM_CUA_CLIENT_ARGS_JSON", + "FATHOM_CUA_CLIENT_ARGS_JSON", + "MAESTRO_FATHOM_CUA_REPO", + "FATHOM_CUA_REPO", + "MAESTRO_FATHOM_CUA_CLIENT_CWD", + "FATHOM_CUA_CLIENT_CWD", + "MAESTRO_FATHOM_CUA_WORKSPACE_ID", + "FATHOM_CUA_WORKSPACE_ID", + "MAESTRO_WORKSPACE_ID", + "MAESTRO_EVALOPS_WORKSPACE_ID", + "EVALOPS_WORKSPACE_ID", + "MAESTRO_FATHOM_CUA_HELPER_ENDPOINT", + "FATHOM_CUA_HELPER_ENDPOINT", + "MAESTRO_FATHOM_CUA_IPC_ROOT", + "FATHOM_CUA_IPC_ROOT", + "FATHOM_IPC_ROOT", + "MAESTRO_FATHOM_CUA_SESSION_ID", + "FATHOM_CUA_SESSION_ID", + "MAESTRO_SESSION_ID", + "MAESTRO_FATHOM_CUA_TURN_ID", + "FATHOM_CUA_TURN_ID", + "MAESTRO_AGENT_RUN_ID", + "MAESTRO_REQUEST_ID", + "MAESTRO_FATHOM_CUA_DISABLE_IPC", + "FATHOM_CUA_DISABLE_IPC", + "FATHOM_CALLER_PRODUCT", + "FATHOM_CUA_PRODUCT", +] as const; + +class SmokeError extends Error { + constructor( + message: string, + readonly details?: JsonRecord, + ) { + super(message); + this.name = "SmokeError"; + } +} + +function resolveFathomServerName( + config: ReturnType, +): string { + const server = config.servers.find( + (candidate) => + candidate.env?.FATHOM_CUA_PRODUCT === "maestro" || + candidate.env?.FATHOM_CALLER_PRODUCT === "maestro" || + candidate.name === "fathom-cua", + ); + if (!server) { + throw new SmokeError("Fathom CUA MCP server was not configured", { + servers: config.servers.map((candidate) => ({ + name: candidate.name, + scope: candidate.scope, + })), + }); + } + return server.name; +} + +interface RunningProcess { + process: ReturnType; + spawnError: Promise; + closed: Promise; + stdout: () => string; + stderr: () => string; +} + +type ProcessCloseResult = { + code: number | null; + signal: NodeJS.Signals | null; +}; + +function hasLiveOptIn(): boolean { + return ( + process.env.MAESTRO_RUN_LIVE_FATHOM_CUA_MCP === "1" || + process.argv.includes("--allow-live") + ); +} + +function assertLiveOptIn(): void { + if (hasLiveOptIn()) { + return; + } + throw new SmokeError( + "Refusing to run live Fathom CUA MCP smoke without MAESTRO_RUN_LIVE_FATHOM_CUA_MCP=1 or --allow-live.", + { + reason: + "This opens a local AppKit target and performs a real set_value action through Maestro's MCP manager and Fathom Helper IPC.", + }, + ); +} + +async function execText( + command: string, + args: string[], + options: { cwd?: string } = {}, +): Promise { + const { stdout } = await execFileAsync(command, args, { + cwd: options.cwd, + encoding: "utf8", + maxBuffer: 32 * 1024 * 1024, + }); + return String(stdout); +} + +async function execChecked( + command: string, + args: string[], + options: { cwd?: string } = {}, +): Promise { + await execFileAsync(command, args, { + cwd: options.cwd, + encoding: "utf8", + maxBuffer: 32 * 1024 * 1024, + }); +} + +function spawnCaptured( + command: string, + args: string[], + options: { cwd?: string } = {}, +): RunningProcess { + const child = spawn(command, args, { + cwd: options.cwd, + stdio: ["ignore", "pipe", "pipe"], + }); + let stdout = ""; + let stderr = ""; + const spawnError = new Promise((resolveError) => { + child.once("error", (error) => { + resolveError(error); + }); + }); + const closed = new Promise((resolveClose) => { + child.once("close", (code, signal) => { + resolveClose({ code, signal }); + }); + }); + child.stdout?.on("data", (chunk: string | Buffer) => { + stdout += String(chunk); + }); + child.stderr?.on("data", (chunk: string | Buffer) => { + stderr += String(chunk); + }); + return { + process: child, + spawnError, + closed, + stdout: () => stdout, + stderr: () => stderr, + }; +} + +async function waitForProcess( + running: RunningProcess, + timeoutMs: number, +): Promise { + const child = running.process; + return new Promise((resolveStatus, reject) => { + let settled = false; + const timer = setTimeout(() => { + if (settled) { + return; + } + settled = true; + child.kill(); + reject( + new SmokeError("Timed out waiting for process", { + pid: child.pid, + stdout: running.stdout(), + stderr: running.stderr(), + }), + ); + }, timeoutMs); + const complete = ({ code, signal }: ProcessCloseResult): void => { + if (settled) { + return; + } + settled = true; + clearTimeout(timer); + if (signal) { + reject( + new SmokeError("Process terminated by signal", { + code, + pid: child.pid, + signal, + stdout: running.stdout(), + stderr: running.stderr(), + }), + ); + return; + } + if (code === null) { + reject( + new SmokeError("Process closed without an exit status", { + pid: child.pid, + stdout: running.stdout(), + stderr: running.stderr(), + }), + ); + return; + } + resolveStatus(code); + }; + running.spawnError.then((error) => { + if (settled) { + return; + } + settled = true; + clearTimeout(timer); + reject( + new SmokeError("Failed to start process", { + error: error.message, + pid: child.pid, + stdout: running.stdout(), + stderr: running.stderr(), + }), + ); + }); + running.closed.then((code) => complete(code)); + }); +} + +async function sleep(ms: number): Promise { + return new Promise((resolveSleep) => setTimeout(resolveSleep, ms)); +} + +async function readJsonFile(path: string): Promise { + const text = await readFile(path, "utf8"); + const parsed = JSON.parse(text) as unknown; + if (!isRecord(parsed)) { + throw new SmokeError(`Expected JSON object at ${path}`); + } + return parsed; +} + +async function waitForJsonFile( + path: string, + predicate: (value: JsonRecord) => boolean, + timeoutMs: number, +): Promise { + const deadline = Date.now() + timeoutMs; + let lastError: unknown; + while (Date.now() < deadline) { + try { + if (existsSync(path)) { + const value = await readJsonFile(path); + if (predicate(value)) { + return value; + } + } + } catch (error) { + lastError = error; + } + await sleep(100); + } + throw new SmokeError(`Timed out waiting for ${path}`, { + lastError: + lastError instanceof Error ? lastError.message : String(lastError), + }); +} + +function sha256(value: string): string { + return `sha256:${createHash("sha256").update(value).digest("hex")}`; +} + +function isRecord(value: unknown): value is JsonRecord { + return value !== null && typeof value === "object" && !Array.isArray(value); +} + +function asRecord(value: unknown, label: string): JsonRecord { + if (!isRecord(value)) { + throw new SmokeError(`${label} was not an object`, { value }); + } + return value; +} + +function asArray(value: unknown, label: string): unknown[] { + if (!Array.isArray(value)) { + throw new SmokeError(`${label} was not an array`, { value }); + } + return value; +} + +function resolveFathomRepo(): string { + const configured = + process.env.MAESTRO_FATHOM_CUA_REPO ?? process.env.FATHOM_CUA_REPO; + if (configured) { + return resolve(configured); + } + const candidates = [ + resolve(process.cwd(), "..", "fathom"), + resolve(process.cwd(), "..", "..", "fathom"), + resolve(process.cwd(), "..", "..", "..", "fathom"), + ]; + const repo = candidates.find((candidate) => + existsSync(join(candidate, "cmd", "fathom-client", "main.go")), + ); + if (!repo) { + throw new SmokeError("Could not find a Fathom repo checkout", { + candidates, + override: "Set MAESTRO_FATHOM_CUA_REPO=/path/to/fathom.", + }); + } + return repo; +} + +async function swiftBinPath(packageDir: string): Promise { + return ( + await execText("swift", [ + "build", + "--package-path", + packageDir, + "--show-bin-path", + ]) + ).trim(); +} + +async function buildFathomProducts(packageDir: string): Promise { + await execChecked("swift", [ + "build", + "--package-path", + packageDir, + "--product", + "fathom-cua-dogfood-target", + ]); + await execChecked("swift", [ + "build", + "--package-path", + packageDir, + "--product", + "fathom-helper", + ]); +} + +async function packageTargetApp( + binDir: string, + appDir: string, + displayName: string, +): Promise { + await rm(appDir, { recursive: true, force: true }); + const macosDir = join(appDir, "Contents", "MacOS"); + await mkdir(macosDir, { recursive: true }); + await copyFile( + join(binDir, "fathom-cua-dogfood-target"), + join(macosDir, "fathom-cua-dogfood-target"), + ); + await writeFile( + join(appDir, "Contents", "Info.plist"), + ` + + + + CFBundleExecutable + fathom-cua-dogfood-target + CFBundleIdentifier + ${targetBundleId} + CFBundleName + ${displayName} + CFBundlePackageType + APPL + NSPrincipalClass + NSApplication + CFBundleShortVersionString + 1.0 + CFBundleVersion + 1 + + +`, + ); +} + +async function launchDogfoodTarget( + appDir: string, + readyFile: string, + stopFile: string, + stateFile: string, +): Promise { + await execChecked("open", [ + "-n", + appDir, + "--args", + "--ready-file", + readyFile, + "--stop-file", + stopFile, + "--state-file", + stateFile, + "--variant", + "maestro", + "--window-x", + "120", + "--window-y", + "120", + ]); + const ready = await waitForJsonFile( + readyFile, + (value) => typeof value.pid === "number", + 12_000, + ); + return Number(ready.pid); +} + +async function foreground(pid: number): Promise { + await execFileAsync( + "osascript", + [ + "-e", + `tell application "System Events" to set frontmost of first process whose unix id is ${pid} to true`, + ], + { encoding: "utf8" }, + ).catch(() => undefined); +} + +async function configureIsolatedMcpEnv( + tempDir: string, + fathomRepo: string, + ipcRoot: string, +): Promise { + const userMcpPath = join(tempDir, "user-mcp.json"); + const enterpriseMcpPath = join(tempDir, "enterprise-mcp.json"); + const projectRoot = join(tempDir, "project-root"); + const projectMcpDir = join(projectRoot, ".maestro"); + const projectMcpPath = join(projectMcpDir, "mcp.json"); + const projectLocalMcpPath = join(projectMcpDir, "mcp.local.json"); + await mkdir(projectMcpDir, { recursive: true }); + await writeFile(userMcpPath, "{}\n"); + await writeFile(enterpriseMcpPath, "{}\n"); + await writeFile(projectMcpPath, "{}\n"); + await writeFile(projectLocalMcpPath, "{}\n"); + + for (const name of fathomCuaEnvVars) { + delete process.env[name]; + } + + process.env.MAESTRO_USER_MCP_PATH = userMcpPath; + process.env.MAESTRO_ENTERPRISE_MCP_PATH = enterpriseMcpPath; + process.env.MAESTRO_FATHOM_CUA_ENABLED = "1"; + process.env.MAESTRO_FATHOM_CUA_REPO = fathomRepo; + process.env.MAESTRO_FATHOM_CUA_WORKSPACE_ID = "workspace_1"; + process.env.MAESTRO_FATHOM_CUA_IPC_ROOT = ipcRoot; + process.env.MAESTRO_FATHOM_CUA_SESSION_ID = "desktop-session-maestro-smoke"; + process.env.MAESTRO_FATHOM_CUA_TURN_ID = "turn-maestro-smoke"; + + return projectRoot; +} + +async function callMcpTool( + manager: McpClientManager, + serverName: string, + toolName: string, + args: JsonRecord, +): Promise { + const result = await manager.callTool(serverName, toolName, args); + const structured = asRecord( + result.structuredContent, + `${toolName} structuredContent`, + ); + if ( + result.isError || + structured.ok === false || + typeof structured.error === "string" + ) { + throw new SmokeError(`Fathom CUA MCP tool ${toolName} failed`, { + result: structured, + content: result.content, + }); + } + return structured; +} + +function findTextElement(state: JsonRecord): JsonRecord { + const elements = asArray(state.elements, "get_app_state elements"); + for (const element of elements) { + const record = asRecord(element, "get_app_state element"); + if ( + record.role === "AXTextField" && + record.element_index !== undefined && + typeof record.element_path_hash === "string" + ) { + return record; + } + } + throw new SmokeError("No AXTextField element found in Fathom dogfood state", { + elementCount: elements.length, + }); +} + +function parseHelperReport(output: string): JsonRecord { + const trimmed = output.trim(); + if (!trimmed) { + return {}; + } + return asRecord(JSON.parse(trimmed) as unknown, "helper report"); +} + +async function runSmoke(): Promise { + assertLiveOptIn(); + const fathomRepo = resolveFathomRepo(); + const packageDir = join(fathomRepo, "macos", "FathomCore"); + const tempDir = await mkdtemp(join(tmpdir(), "maestro-fathom-cua-mcp.")); + const readyFile = join(tempDir, "ready.json"); + const stopFile = join(tempDir, "stop"); + const stateFile = join(tempDir, "state.json"); + const ipcRoot = join(tempDir, "ipc"); + const appDir = join( + fathomRepo, + ".build", + "FathomCUADogfoodTargetMaestro.app", + ); + const manager = new McpClientManager(); + let helper: RunningProcess | undefined; + let targetPid: number | undefined; + + try { + await buildFathomProducts(packageDir); + const binDir = await swiftBinPath(packageDir); + await packageTargetApp(binDir, appDir, "Fathom CUA Dogfood Target Maestro"); + targetPid = await launchDogfoodTarget( + appDir, + readyFile, + stopFile, + stateFile, + ); + await foreground(targetPid); + + helper = spawnCaptured(join(binDir, "fathom-helper"), [ + "live-cua-process-ipc", + "--indicator-present", + "--stop-control-present", + "--agent-runtime-reachable", + "--ipc-root", + ipcRoot, + "--max-requests", + "2", + "--idle-timeout-seconds", + "20", + ]); + + const mcpProjectRoot = await configureIsolatedMcpEnv( + tempDir, + fathomRepo, + ipcRoot, + ); + const config = loadMcpConfig(mcpProjectRoot); + const fathomServerName = resolveFathomServerName(config); + await manager.configure(config); + await manager.connectAll(); + const status = manager.getStatus(); + const fathomStatus = status.servers.find( + (server) => server.name === fathomServerName, + ); + if (!fathomStatus?.connected) { + throw new SmokeError("Fathom CUA MCP server did not connect", { + status: fathomStatus, + }); + } + const toolNames = manager + .getAllTools() + .filter((tool) => tool.server === fathomServerName) + .map((tool) => tool.tool.name) + .sort(); + for (const requiredTool of ["get_app_state", "set_value"]) { + if (!toolNames.includes(requiredTool)) { + throw new SmokeError( + "Fathom CUA MCP server is missing a required tool", + { + requiredTool, + toolNames, + }, + ); + } + } + + const before = await callMcpTool( + manager, + fathomServerName, + "get_app_state", + { + app: targetBundleId, + reason: "maestro fathom cua mcp smoke", + }, + ); + const textElement = findTextElement(before); + const rawValue = `Maestro Fathom CUA MCP ${Date.now()}`; + const expectedHash = sha256(`set-value:v1:${rawValue}`); + const action = await callMcpTool(manager, fathomServerName, "set_value", { + app: targetBundleId, + element_index: String(textElement.element_index), + value: rawValue, + }); + const observedState = await waitForJsonFile( + stateFile, + (value) => value.field_value_hash === expectedHash, + 12_000, + ); + await manager.disconnectAll(); + const helperStatus = helper ? await waitForProcess(helper, 35_000) : 1; + const helperReport = helper ? parseHelperReport(helper.stdout()) : {}; + if (helperStatus !== 0 || helperReport.ok !== true) { + throw new SmokeError("Fathom Helper live IPC processor failed", { + status: helperStatus, + helperReport, + stderr: helper?.stderr(), + }); + } + + const report: JsonRecord = { + schemaVersion: smokeSchema, + ok: true, + source: "maestro-mcp-manager", + fathomRepo, + targetBundleId, + mcpServer: { + name: fathomServerName, + connected: true, + toolCount: toolNames.length, + requiredTools: ["get_app_state", "set_value"], + }, + action: { + tool: "set_value", + receiptId: action.receipt_id, + contextSnapshotId: action.context_snapshot_id, + elementIndex: textElement.element_index, + elementPathHash: textElement.element_path_hash, + }, + stateObserved: { + fieldValueHash: observedState.field_value_hash, + expectedHash, + changed: observedState.field_value_hash === expectedHash, + }, + helper: { + ok: helperReport.ok, + processedRequests: helperReport.processed_requests, + }, + rawValueRedacted: true, + }; + const encoded = JSON.stringify(report); + if (encoded.includes(rawValue)) { + throw new SmokeError("Smoke report leaked the raw desktop value"); + } + return report; + } finally { + await manager.disconnectAll().catch(() => undefined); + if (helper && helper.process.exitCode === null) { + helper.process.kill(); + } + await writeFile(stopFile, "").catch(() => undefined); + if (targetPid) { + await execFileAsync("kill", [String(targetPid)]).catch(() => undefined); + } + await rm(dirname(readyFile), { recursive: true, force: true }).catch( + () => undefined, + ); + } +} + +runSmoke() + .then((report) => { + process.stdout.write(`${JSON.stringify(report, null, 2)}\n`); + }) + .catch((error) => { + const payload = { + schemaVersion: smokeSchema, + ok: false, + error: error instanceof Error ? error.message : String(error), + details: error instanceof SmokeError ? error.details : undefined, + }; + process.stderr.write(`${JSON.stringify(payload, null, 2)}\n`); + process.exitCode = 1; + }); diff --git a/src/mcp/config.ts b/src/mcp/config.ts index e8dc8c3a4..364cb2981 100644 --- a/src/mcp/config.ts +++ b/src/mcp/config.ts @@ -64,6 +64,7 @@ import { createLogger } from "../utils/logger.js"; import { getHomeDir, resolveEnvPath } from "../utils/path-expansion.js"; import { uniquePaths } from "../utils/path-utils.js"; import { defaultEnvValidators, evaluateEnvValidators } from "./env-limits.js"; +import { getFathomCuaPluginServers } from "./fathom-cua.js"; import { getPlatformMcpPluginServers } from "./platform-plugin.js"; import { type McpAuthPresetInput, @@ -221,6 +222,7 @@ export function loadMcpConfig( const pluginCfg: ParsedConfig = { servers: [ ...getPlatformMcpPluginServers(), + ...getFathomCuaPluginServers(), ...(options.pluginServers ?? []), ], authPresets: [], diff --git a/src/mcp/fathom-cua.ts b/src/mcp/fathom-cua.ts new file mode 100644 index 000000000..ebf75e3c6 --- /dev/null +++ b/src/mcp/fathom-cua.ts @@ -0,0 +1,178 @@ +import { existsSync } from "node:fs"; +import { join } from "node:path"; +import { getEnvValue } from "../platform/client.js"; +import { createLogger } from "../utils/logger.js"; +import type { McpServerConfig } from "./types.js"; + +const logger = createLogger("mcp:fathom-cua"); + +const DISABLED_VALUES = new Set(["0", "false", "no", "off"]); +const ENABLED_ENV_VARS = [ + "MAESTRO_FATHOM_CUA_ENABLED", + "FATHOM_CUA_MCP_ENABLED", +] as const; +const NAME_ENV_VARS = ["MAESTRO_FATHOM_CUA_MCP_NAME", "FATHOM_CUA_MCP_NAME"]; +const COMMAND_ENV_VARS = [ + "MAESTRO_FATHOM_CUA_CLIENT_COMMAND", + "FATHOM_CUA_CLIENT_COMMAND", +] as const; +const ARGS_ENV_VARS = [ + "MAESTRO_FATHOM_CUA_CLIENT_ARGS_JSON", + "FATHOM_CUA_CLIENT_ARGS_JSON", +] as const; +const REPO_ENV_VARS = ["MAESTRO_FATHOM_CUA_REPO", "FATHOM_CUA_REPO"] as const; +const CWD_ENV_VARS = [ + "MAESTRO_FATHOM_CUA_CLIENT_CWD", + "FATHOM_CUA_CLIENT_CWD", +] as const; +const WORKSPACE_ENV_VARS = [ + "MAESTRO_FATHOM_CUA_WORKSPACE_ID", + "FATHOM_CUA_WORKSPACE_ID", + "MAESTRO_WORKSPACE_ID", + "MAESTRO_EVALOPS_WORKSPACE_ID", + "EVALOPS_WORKSPACE_ID", +] as const; +const HELPER_ENDPOINT_ENV_VARS = [ + "MAESTRO_FATHOM_CUA_HELPER_ENDPOINT", + "FATHOM_CUA_HELPER_ENDPOINT", +] as const; +const IPC_ROOT_ENV_VARS = [ + "MAESTRO_FATHOM_CUA_IPC_ROOT", + "FATHOM_CUA_IPC_ROOT", + "FATHOM_IPC_ROOT", +] as const; +const SESSION_ID_ENV_VARS = [ + "MAESTRO_FATHOM_CUA_SESSION_ID", + "FATHOM_CUA_SESSION_ID", + "MAESTRO_SESSION_ID", +] as const; +const TURN_ID_ENV_VARS = [ + "MAESTRO_FATHOM_CUA_TURN_ID", + "FATHOM_CUA_TURN_ID", + "MAESTRO_AGENT_RUN_ID", + "MAESTRO_REQUEST_ID", +] as const; +const DISABLE_IPC_ENV_VARS = [ + "MAESTRO_FATHOM_CUA_DISABLE_IPC", + "FATHOM_CUA_DISABLE_IPC", +] as const; +const DEFAULT_SERVER_NAME = "fathom-cua"; + +function envFlagEnabled(names: readonly string[]): boolean { + const value = getEnvValue(names); + if (!value) { + return false; + } + return !DISABLED_VALUES.has(value.trim().toLowerCase()); +} + +function envFlagDisabled(names: readonly string[]): boolean { + const value = getEnvValue(names); + if (!value) { + return false; + } + return DISABLED_VALUES.has(value.trim().toLowerCase()); +} + +function parseArgsJson(raw: string | undefined): string[] { + if (!raw) { + return []; + } + try { + const parsed = JSON.parse(raw) as unknown; + if (!Array.isArray(parsed)) { + throw new Error("expected an array"); + } + return parsed.map((item) => { + if (typeof item !== "string") { + throw new Error("expected only string arguments"); + } + return item; + }); + } catch (error) { + logger.warn("Ignoring invalid Fathom CUA MCP args JSON", { + error: error instanceof Error ? error.message : String(error), + }); + return []; + } +} + +function appendFlag( + args: string[], + flag: string, + value: string | undefined, +): void { + if (value) { + args.push(flag, value); + } +} + +function resolveFathomRepo(): string | undefined { + const configured = getEnvValue(REPO_ENV_VARS); + if (configured) { + return configured; + } + + const candidates = [ + join(process.cwd(), "..", "fathom"), + join(process.cwd(), "..", "..", "fathom"), + join(process.cwd(), "..", "..", "..", "fathom"), + ]; + return candidates.find((candidate) => + existsSync(join(candidate, "cmd", "fathom-client", "main.go")), + ); +} + +function buildFathomCuaServer(): McpServerConfig { + const repo = resolveFathomRepo(); + const configuredCommand = getEnvValue(COMMAND_ENV_VARS); + const configuredCwd = getEnvValue(CWD_ENV_VARS); + const command = configuredCommand ?? (repo ? "go" : "fathom-client"); + const cwd = configuredCwd ?? (configuredCommand ? undefined : repo); + const extraArgs = parseArgsJson(getEnvValue(ARGS_ENV_VARS)); + const args = configuredCommand + ? [...extraArgs] + : repo + ? ["run", "./cmd/fathom-client", ...extraArgs] + : [...extraArgs]; + const workspaceId = getEnvValue(WORKSPACE_ENV_VARS); + const helperEndpoint = getEnvValue(HELPER_ENDPOINT_ENV_VARS); + const ipcRoot = getEnvValue(IPC_ROOT_ENV_VARS); + const sessionId = getEnvValue(SESSION_ID_ENV_VARS); + const turnId = getEnvValue(TURN_ID_ENV_VARS); + + appendFlag(args, "-workspace-id", workspaceId); + appendFlag(args, "-helper-endpoint", helperEndpoint); + appendFlag(args, "-ipc-root", ipcRoot); + appendFlag(args, "-session-id", sessionId); + appendFlag(args, "-turn-id", turnId); + if (envFlagEnabled(DISABLE_IPC_ENV_VARS)) { + args.push("-disable-ipc"); + } + + const env = Object.fromEntries( + Object.entries({ + FATHOM_CALLER_PRODUCT: "maestro", + FATHOM_CUA_PRODUCT: "maestro", + FATHOM_CUA_WORKSPACE_ID: workspaceId, + FATHOM_IPC_ROOT: ipcRoot, + }).filter((entry): entry is [string, string] => Boolean(entry[1])), + ); + + return { + name: getEnvValue(NAME_ENV_VARS) ?? DEFAULT_SERVER_NAME, + transport: "stdio", + command, + args, + cwd, + env, + scope: "plugin", + }; +} + +export function getFathomCuaPluginServers(): McpServerConfig[] { + if (envFlagDisabled(ENABLED_ENV_VARS) || !envFlagEnabled(ENABLED_ENV_VARS)) { + return []; + } + return [buildFathomCuaServer()]; +} diff --git a/src/mcp/index.ts b/src/mcp/index.ts index 7b25294be..9aad1208d 100644 --- a/src/mcp/index.ts +++ b/src/mcp/index.ts @@ -43,6 +43,7 @@ export { getProjectMcpServerApprovalStatus, setProjectMcpServerApprovalDecision, } from "./project-approvals.js"; +export { getFathomCuaPluginServers } from "./fathom-cua.js"; export { getPlatformMcpPluginServers } from "./platform-plugin.js"; export type { McpAuthPresetConfig, diff --git a/test/agent/mcp-fathom-cua-plugin.test.ts b/test/agent/mcp-fathom-cua-plugin.test.ts new file mode 100644 index 000000000..13265b49f --- /dev/null +++ b/test/agent/mcp-fathom-cua-plugin.test.ts @@ -0,0 +1,107 @@ +import { afterEach, describe, expect, it, vi } from "vitest"; +import { loadMcpConfig } from "../../src/mcp/config.js"; +import { getFathomCuaPluginServers } from "../../src/mcp/fathom-cua.js"; + +describe("Fathom CUA MCP plugin server", () => { + afterEach(() => { + vi.unstubAllEnvs(); + }); + + it("stays disabled unless explicitly enabled", () => { + vi.stubEnv("MAESTRO_FATHOM_CUA_ENABLED", ""); + vi.stubEnv("FATHOM_CUA_MCP_ENABLED", ""); + + expect(getFathomCuaPluginServers()).toEqual([]); + }); + + it("builds a stdio fathom-client server from a sibling repo", () => { + vi.stubEnv("MAESTRO_FATHOM_CUA_ENABLED", "1"); + vi.stubEnv("MAESTRO_FATHOM_CUA_REPO", "/tmp/fathom"); + vi.stubEnv("MAESTRO_FATHOM_CUA_WORKSPACE_ID", "workspace_1"); + vi.stubEnv("MAESTRO_FATHOM_CUA_IPC_ROOT", "/tmp/fathom-ipc"); + vi.stubEnv("MAESTRO_FATHOM_CUA_SESSION_ID", "desktop-session-1"); + vi.stubEnv("MAESTRO_FATHOM_CUA_TURN_ID", "turn-1"); + + expect(getFathomCuaPluginServers()).toEqual([ + expect.objectContaining({ + name: "fathom-cua", + transport: "stdio", + command: "go", + cwd: "/tmp/fathom", + scope: "plugin", + env: { + FATHOM_CALLER_PRODUCT: "maestro", + FATHOM_CUA_PRODUCT: "maestro", + FATHOM_CUA_WORKSPACE_ID: "workspace_1", + FATHOM_IPC_ROOT: "/tmp/fathom-ipc", + }, + }), + ]); + expect(getFathomCuaPluginServers()[0]?.args).toEqual([ + "run", + "./cmd/fathom-client", + "-workspace-id", + "workspace_1", + "-ipc-root", + "/tmp/fathom-ipc", + "-session-id", + "desktop-session-1", + "-turn-id", + "turn-1", + ]); + }); + + it("supports an installed fathom-client command and explicit arguments", () => { + vi.stubEnv("MAESTRO_FATHOM_CUA_ENABLED", "1"); + vi.stubEnv("MAESTRO_FATHOM_CUA_CLIENT_COMMAND", "/opt/fathom-client"); + vi.stubEnv( + "MAESTRO_FATHOM_CUA_CLIENT_ARGS_JSON", + JSON.stringify(["-helper-endpoint", "xpc:test"]), + ); + vi.stubEnv("MAESTRO_FATHOM_CUA_DISABLE_IPC", "1"); + + expect(getFathomCuaPluginServers()[0]).toMatchObject({ + command: "/opt/fathom-client", + args: ["-helper-endpoint", "xpc:test", "-disable-ipc"], + }); + }); + + it("does not force the auto-detected repo cwd onto custom commands", () => { + vi.stubEnv("MAESTRO_FATHOM_CUA_ENABLED", "1"); + vi.stubEnv("MAESTRO_FATHOM_CUA_REPO", "/tmp/fathom"); + vi.stubEnv("MAESTRO_FATHOM_CUA_CLIENT_COMMAND", "./bin/fathom-client"); + + expect(getFathomCuaPluginServers()[0]).toMatchObject({ + command: "./bin/fathom-client", + cwd: undefined, + }); + }); + + it("uses an explicit custom command cwd when configured", () => { + vi.stubEnv("MAESTRO_FATHOM_CUA_ENABLED", "1"); + vi.stubEnv("MAESTRO_FATHOM_CUA_REPO", "/tmp/fathom"); + vi.stubEnv("MAESTRO_FATHOM_CUA_CLIENT_COMMAND", "./bin/fathom-client"); + vi.stubEnv("MAESTRO_FATHOM_CUA_CLIENT_CWD", "/tmp/custom-fathom"); + + expect(getFathomCuaPluginServers()[0]).toMatchObject({ + command: "./bin/fathom-client", + cwd: "/tmp/custom-fathom", + }); + }); + + it("participates in the merged MCP config as plugin scope", () => { + vi.stubEnv("MAESTRO_FATHOM_CUA_ENABLED", "1"); + vi.stubEnv("MAESTRO_FATHOM_CUA_REPO", "/tmp/fathom"); + + const config = loadMcpConfig("/tmp/project"); + + expect( + config.servers.find((server) => server.name === "fathom-cua"), + ).toEqual( + expect.objectContaining({ + scope: "plugin", + command: "go", + }), + ); + }); +}); diff --git a/test/scripts/ci-guardrails.test.ts b/test/scripts/ci-guardrails.test.ts index e08bf23c7..5e28daea4 100644 --- a/test/scripts/ci-guardrails.test.ts +++ b/test/scripts/ci-guardrails.test.ts @@ -1,4 +1,4 @@ -import { existsSync, readFileSync } from "node:fs"; +import { readFileSync } from "node:fs"; import { describe, expect, it } from "vitest"; import { parse } from "yaml"; import { @@ -49,7 +49,12 @@ type Workflow = { }; jobs?: Record< string, - { steps?: WorkflowStep[]; "timeout-minutes"?: number; "runs-on"?: unknown } + { + outputs?: Record; + steps?: WorkflowStep[]; + "timeout-minutes"?: number; + "runs-on"?: unknown; + } >; }; @@ -94,6 +99,7 @@ describe("planCiChecks", () => { ).toMatchObject({ ciInfrastructureOnly: true, coverage: false, + lightPrChecks: true, prChecks: true, publicMirror: false, rustHostedConformance: false, @@ -110,6 +116,7 @@ describe("planCiChecks", () => { ).toMatchObject({ ciInfrastructureOnly: true, coverage: false, + lightPrChecks: true, prChecks: true, publicMirror: false, rustHostedConformance: false, @@ -125,6 +132,7 @@ describe("planCiChecks", () => { ).toMatchObject({ ciInfrastructureOnly: true, coverage: false, + lightPrChecks: false, prChecks: true, publicMirror: true, rustHostedConformance: true, @@ -213,15 +221,19 @@ describe("planCiChecks", () => { "scripts/check-packed-bundled-workspaces.mjs", "scripts/check-runtime-deps.js", "scripts/ci-nx-tests.sh", + "scripts/install-smoke-utils.js", "scripts/plan-nx-test-command.mjs", + "scripts/release-readiness.js", "scripts/runtime-workspaces.mjs", "scripts/validate-public-package-deps.js", + "scripts/workspace-utils.js", "test/scripts/ci-guardrails.test.ts", ], }), ).toMatchObject({ ciInfrastructureOnly: false, coverage: false, + lightPrChecks: false, proofHarnessOnly: false, prChecks: true, publicMirror: true, @@ -229,19 +241,42 @@ describe("planCiChecks", () => { }); }); + it("routes release helper-only PR checks to the light runner lane", () => { + expect( + planCiChecks({ + eventName: "pull_request", + changedFiles: [ + "scripts/install-smoke-utils.js", + "scripts/plan-ci-checks.mjs", + "scripts/plan-nx-test-command.mjs", + "scripts/release-readiness.js", + "scripts/smoke-packed-cli.js", + "scripts/workspace-utils.js", + "test/scripts/ci-guardrails.test.ts", + ], + }), + ).toMatchObject({ + coverage: false, + lightPrChecks: true, + prChecks: true, + releaseHelperOnly: true, + rustHostedConformance: false, + }); + }); + it("skips coverage and Rust conformance for proof-harness-only changes", () => { expect( planCiChecks({ eventName: "pull_request", changedFiles: [ "docs/protocols/a2a-fleet-delegation.md", - "package.json", "scripts/smoke-maestro-a2a-local-swarm.ts", ], }), ).toMatchObject({ ciInfrastructureOnly: false, coverage: false, + lightPrChecks: false, proofHarnessOnly: true, prChecks: true, publicMirror: true, @@ -249,6 +284,27 @@ describe("planCiChecks", () => { }); }); + it("keeps package manifests out of proof-harness-only skips", () => { + expect( + planCiChecks({ + eventName: "pull_request", + changedFiles: [ + "docs/protocols/a2a-fleet-delegation.md", + "package.json", + "scripts/smoke-maestro-a2a-local-swarm.ts", + ], + }), + ).toMatchObject({ + ciInfrastructureOnly: false, + coverage: false, + lightPrChecks: false, + proofHarnessOnly: false, + prChecks: true, + publicMirror: true, + rustHostedConformance: false, + }); + }); + it("runs public mirror checks for mirror config inputs", () => { expect( planCiChecks({ @@ -329,6 +385,23 @@ describe("ci workflow guardrails", () => { ); }); + it("filters deleted smoke scripts before static checks", () => { + const script = readFileSync( + new URL("../../scripts/ci-nx-tests.sh", import.meta.url), + { encoding: "utf8" }, + ); + const smokeStaticChecksBody = + script.match( + /run_smoke_script_static_checks\(\) \{([\s\S]*?)\n\}/, + )?.[1] ?? ""; + + expect(smokeStaticChecksBody).not.toBe(""); + expect(smokeStaticChecksBody).toContain('[[ -f "$file" ]] || continue'); + expect( + smokeStaticChecksBody.indexOf('[[ -f "$file" ]] || continue'), + ).toBeLessThan(smokeStaticChecksBody.indexOf('smoke_scripts+=("$file")')); + }); + it("hard-bounds long-running Nx and coverage phases", () => { const workflow = parse( readFileSync(new URL("../../.github/workflows/ci.yml", import.meta.url), { @@ -353,6 +426,135 @@ describe("ci workflow guardrails", () => { expect(coverageTimeouts.get("Run tests with coverage")).toBe(60); }); + it("routes expensive pull-request jobs to the private heavy runner lane", () => { + const workflow = parse( + readFileSync(new URL("../../.github/workflows/ci.yml", import.meta.url), { + encoding: "utf8", + }), + ) as Workflow; + const prChecksRunsOn = String( + workflow.jobs?.["pr-checks"]?.["runs-on"] ?? "", + ); + const coverageRunsOn = String(workflow.jobs?.coverage?.["runs-on"] ?? ""); + const isPublicMirrorWorkflow = prChecksRunsOn.includes( + "PUBLIC_PR_VALIDATION_RUNNER", + ); + + if (isPublicMirrorWorkflow) { + expect(prChecksRunsOn).toContain("ubuntu-latest"); + expect(prChecksRunsOn).toContain("PUBLIC_PR_VALIDATION_RUNNER"); + expect(coverageRunsOn).toContain("ubuntu-latest"); + expect(coverageRunsOn).toContain("PUBLIC_PR_VALIDATION_RUNNER"); + return; + } + + expect(prChecksRunsOn).toContain("ubuntu-latest"); + expect(prChecksRunsOn).toContain("light_pr_checks"); + expect(prChecksRunsOn).toContain("evalops-private-ci"); + expect(prChecksRunsOn).toContain("PR_CHECKS_RUNNER"); + expect(prChecksRunsOn).toContain("evalops-private-heavy"); + expect(prChecksRunsOn).toContain("INTERNAL_CONFIRMATION_RUNNER"); + expect(coverageRunsOn).toContain("ubuntu-latest"); + expect(coverageRunsOn).toContain("PR_COVERAGE_RUNNER"); + expect(coverageRunsOn).toContain("evalops-private-heavy"); + expect(coverageRunsOn).toContain("INTERNAL_CONFIRMATION_RUNNER"); + }); + + it("uses targeted release helper package smoke instead of duplicate release readiness", () => { + const workflow = parse( + readFileSync(new URL("../../.github/workflows/ci.yml", import.meta.url), { + encoding: "utf8", + }), + ) as Workflow; + const changesOutputs = workflow.jobs?.changes?.outputs ?? {}; + const prCheckSteps = workflow.jobs?.["pr-checks"]?.steps ?? []; + const prChecksRunsOn = String( + workflow.jobs?.["pr-checks"]?.["runs-on"] ?? "", + ); + const isPublicMirrorWorkflow = prChecksRunsOn.includes( + "PUBLIC_PR_VALIDATION_RUNNER", + ); + const helperSmokeStep = prCheckSteps.find( + (step) => step.name === "Release helper package smoke", + ); + const releaseReadinessStep = prCheckSteps.find( + (step) => step.name === "Release readiness (CI mode)", + ); + + if (isPublicMirrorWorkflow) { + expect(helperSmokeStep).toBeUndefined(); + expect(releaseReadinessStep?.if).not.toContain("release_helper_only"); + return; + } + + expect(changesOutputs).toHaveProperty("release_helper_only"); + expect(helperSmokeStep?.if).toContain("release_helper_only == 'true'"); + expect(helperSmokeStep?.run).toContain( + "node --check scripts/release-readiness.js", + ); + expect(helperSmokeStep?.run).toContain( + "node scripts/release-readiness.js pack-smoke", + ); + expect(helperSmokeStep?.run).not.toContain("npm run build"); + expect(releaseReadinessStep?.if).toContain("release_helper_only != 'true'"); + }); + + it("keeps public registry smoke install helper exports", async () => { + const helpers = (await import( + "../../scripts/install-smoke-utils.js" + )) as Record; + + for (const exportName of [ + "assertInstallablePackageMetadata", + "getBunCommand", + "getNpmCommand", + "getNpxCommand", + "readInstalledPackageJson", + "runInstalledCliSmoke", + "runInstalledPackageAudit", + ]) { + expect(helpers[exportName]).toEqual(expect.any(Function)); + } + }); + + it("keeps packed CLI smoke aligned with registry install validation", () => { + const script = readFileSync( + new URL("../../scripts/smoke-packed-cli.js", import.meta.url), + { encoding: "utf8" }, + ); + + expect(script).toContain("assertInstallablePackageMetadata"); + expect(script).toContain("runInstalledCliSmoke"); + expect(script).toContain("getBunCommand"); + expect(script).toContain("runNpmInstallSmoke();"); + expect(script).toContain("runBunInstallSmoke();"); + }); + + it("keeps packed CLI smoke enabled independently of package-lock management", () => { + const script = readFileSync( + new URL("../../scripts/release-readiness.js", import.meta.url), + { encoding: "utf8" }, + ); + const ciChecksIndex = script.indexOf("function runCiChecks()"); + const releaseChecksIndex = script.indexOf("function runReleaseChecks()"); + + expect(script).not.toContain( + "Skipping packed CLI smoke test (package is not npm-installable from a tarball in this repo)", + ); + expect(script.indexOf("runPackSmoke();", ciChecksIndex)).toBeGreaterThan( + ciChecksIndex, + ); + expect( + script.indexOf("runPackSmoke();", releaseChecksIndex), + ).toBeGreaterThan(releaseChecksIndex); + expect(script).toContain("MAESTRO_INSTALL_AUDIT_LEVEL"); + expect(script).toContain( + 'process.env.MAESTRO_INSTALL_AUDIT_LEVEL ?? "critical"', + ); + expect(script).toContain("removeStandaloneBinaryArtifacts();"); + expect(script).toContain('case "pack-smoke":'); + }); + it("gives evals workflow test shards enough time to finish", () => { const workflow = parse( readFileSync( @@ -436,24 +638,17 @@ describe("ci workflow guardrails", () => { encoding: "utf8", }), ) as Workflow; - const isInternalReleaseMirrorSource = existsSync( - new URL("../../.github/release-mirror-manifest.json", import.meta.url), - ); const prChecksJob = workflow.jobs?.["pr-checks"]; const setupRustStep = prChecksJob?.steps?.find( (step) => step.uses === "./.github/actions/setup-rust", ); - const isPublicMirrorPrChecks = - workflow.jobs?.["public-release-mirror"] === undefined && - prChecksJob?.["runs-on"] === - "${{ vars.PUBLIC_PR_VALIDATION_RUNNER || 'ubuntu-latest' }}"; + const prChecksRunsOn = String(prChecksJob?.["runs-on"] ?? ""); + const isPublicMirrorPrChecks = prChecksRunsOn.includes( + "PUBLIC_PR_VALIDATION_RUNNER", + ); if (!setupRustStep) { expect(isPublicMirrorPrChecks).toBe(true); - expect(workflow.jobs?.changes).toBeDefined(); - expect(workflow.jobs?.["rust-hosted-conformance"]?.if).toBe( - "${{ github.event_name != 'pull_request' || needs.changes.outputs.rust_hosted_conformance == 'true' }}", - ); const rustHostedSteps = workflow.jobs?.["rust-hosted-conformance"]?.steps ?? []; expect( @@ -464,12 +659,12 @@ describe("ci workflow guardrails", () => { return; } - if (isInternalReleaseMirrorSource) { + if (!isPublicMirrorPrChecks) { expect(workflow.jobs?.changes).toBeDefined(); expect(workflow.jobs?.["public-release-mirror"]).toBeDefined(); } const proofHarnessSkipCondition = - "${{ github.event_name != 'pull_request' || (needs.changes.outputs.ci_infrastructure_only != 'true' && needs.changes.outputs.proof_harness_only != 'true') }}"; + "${{ github.event_name != 'pull_request' || (needs.changes.outputs.ci_infrastructure_only != 'true' && needs.changes.outputs.proof_harness_only != 'true' && needs.changes.outputs.release_helper_only != 'true') }}"; expect(setupRustStep?.if).toBe(proofHarnessSkipCondition); expect( prChecksJob?.steps?.find( @@ -786,6 +981,23 @@ describe("planNxTestCommand", () => { }); }); + it("keeps release package helper changes out of Nx affected tests", () => { + expect( + planNxTestCommand({ + basePackage, + changedFiles: [ + "scripts/install-smoke-utils.js", + "scripts/plan-ci-checks.mjs", + "scripts/release-readiness.js", + "scripts/smoke-packed-cli.js", + "scripts/workspace-utils.js", + "test/scripts/ci-guardrails.test.ts", + ], + headPackage: basePackage, + }), + ).toEqual({ files: [], mode: "none" }); + }); + it("skips Nx when package scripts are the only changed files", () => { expect( planNxTestCommand({ @@ -844,6 +1056,18 @@ describe("planNxTestCommand", () => { headPackage: basePackage, }), ).toBe(true); + expect( + runtimePackageValidatorsRequired({ + basePackage, + changedFiles: [ + "scripts/install-smoke-utils.js", + "scripts/release-readiness.js", + "scripts/smoke-packed-cli.js", + "scripts/workspace-utils.js", + ], + headPackage: basePackage, + }), + ).toBe(true); }); it("treats runtime workspace package metadata as release metadata", () => { diff --git a/test/scripts/install-smoke-utils.test.ts b/test/scripts/install-smoke-utils.test.ts deleted file mode 100644 index 389fd2642..000000000 --- a/test/scripts/install-smoke-utils.test.ts +++ /dev/null @@ -1,61 +0,0 @@ -import { describe, expect, it } from "vitest"; -import { assertInstallablePackageMetadata } from "../../scripts/install-smoke-utils.js"; - -describe("assertInstallablePackageMetadata", () => { - it("allows ordinary registry dependencies", () => { - expect(() => - assertInstallablePackageMetadata( - { - dependencies: { - "@bufbuild/protobuf": "^2.11.0", - zod: "^4.3.6", - }, - }, - { - label: "packed package", - forbiddenWorkspaceNames: ["@evalops/contracts", "@evalops/tui"], - }, - ), - ).not.toThrow(); - }); - - it("rejects private runtime workspaces in install-time dependencies", () => { - expect(() => - assertInstallablePackageMetadata( - { - dependencies: { - "@evalops/contracts": "^0.10.21", - }, - optionalDependencies: { - "@evalops/tui": "^0.10.21", - }, - }, - { - label: "published package", - forbiddenWorkspaceNames: ["@evalops/contracts", "@evalops/tui"], - }, - ), - ).toThrow( - "published package exposes non-registry workspace metadata: dependencies.@evalops/contracts, optionalDependencies.@evalops/tui", - ); - }); - - it("rejects workspace protocol specs and bundled private workspaces", () => { - expect(() => - assertInstallablePackageMetadata( - { - dependencies: { - "@evalops/maestro-helper": "workspace:*", - }, - bundleDependencies: ["@evalops/contracts"], - }, - { - label: "packed package", - forbiddenWorkspaceNames: ["@evalops/contracts"], - }, - ), - ).toThrow( - "packed package exposes non-registry workspace metadata: bundleDependencies.@evalops/contracts, dependencies.@evalops/maestro-helper=workspace:", - ); - }); -});