diff --git a/package.json b/package.json index 74e80efbd..fa99a179f 100644 --- a/package.json +++ b/package.json @@ -113,14 +113,15 @@ "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", - "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", + "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", "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 206498745..4d53f8a48 100644 --- a/scripts/check-smoke-scripts.mjs +++ b/scripts/check-smoke-scripts.mjs @@ -9,16 +9,18 @@ if (entryPoints.length === 0) { process.exit(0); } -await build({ - bundle: true, - entryPoints, - external: ["tree-sitter", "tree-sitter-bash"], - format: "esm", - logLevel: "silent", - packages: "external", - platform: "node", - target: "node20", - write: false, -}); +for (const entryPoint of entryPoints) { + await build({ + bundle: true, + entryPoints: [entryPoint], + external: ["tree-sitter", "tree-sitter-bash"], + format: "esm", + logLevel: "silent", + packages: "external", + platform: "node", + target: "node20", + write: false, + }); +} console.log(`Checked ${entryPoints.length} smoke script(s).`); diff --git a/scripts/install-smoke-utils.js b/scripts/install-smoke-utils.js index ee15de593..02bcf4d14 100644 --- a/scripts/install-smoke-utils.js +++ b/scripts/install-smoke-utils.js @@ -2,6 +2,8 @@ // @ts-check import { execFileSync } from "node:child_process"; +import { readFileSync } from "node:fs"; +import { join } from "node:path"; export function getNpmCommand() { return process.platform === "win32" ? "npm.cmd" : "npm"; @@ -11,6 +13,113 @@ export function getNpxCommand() { return process.platform === "win32" ? "npx.cmd" : "npx"; } +export function getBunCommand() { + return process.platform === "win32" ? "bun.exe" : "bun"; +} + +export function installedPackageJsonPath(packageName, installRoot) { + return join( + installRoot, + "node_modules", + ...packageName.split("/"), + "package.json", + ); +} + +export function installedBinPath(installRoot, cliCommand) { + return process.platform === "win32" + ? join(installRoot, "node_modules", ".bin", `${cliCommand}.cmd`) + : join(installRoot, "node_modules", ".bin", cliCommand); +} + +export function readInstalledPackageJson(packageName, installRoot) { + const packageJsonPath = installedPackageJsonPath(packageName, installRoot); + try { + const parsed = JSON.parse(readFileSync(packageJsonPath, "utf8")); + if (!parsed || typeof parsed !== "object" || Array.isArray(parsed)) { + throw new Error("installed package.json did not contain an object"); + } + return parsed; + } catch (error) { + const reason = + error instanceof Error ? error.message : "unknown package read error"; + throw new Error( + `Could not read installed package metadata at ${packageJsonPath}: ${reason}`, + ); + } +} + +function arrayValues(value) { + return Array.isArray(value) + ? value.filter((entry) => typeof entry === "string" && entry.length > 0) + : []; +} + +function objectEntries(value) { + return value && typeof value === "object" && !Array.isArray(value) + ? Object.entries(value) + : []; +} + +export function assertInstallablePackageMetadata( + installedPackage, + { label, forbiddenWorkspaceNames = [] }, +) { + const forbiddenNames = new Set(forbiddenWorkspaceNames); + const offenders = []; + for (const section of [ + "dependencies", + "optionalDependencies", + "peerDependencies", + ]) { + for (const [name, spec] of objectEntries(installedPackage[section])) { + if (forbiddenNames.has(name)) { + offenders.push(`${section}.${name}`); + } + if (typeof spec === "string" && spec.startsWith("workspace:")) { + offenders.push(`${section}.${name}=workspace:`); + } + } + } + + for (const section of ["bundleDependencies", "bundledDependencies"]) { + for (const name of arrayValues(installedPackage[section])) { + if (forbiddenNames.has(name)) { + offenders.push(`${section}.${name}`); + } + } + } + + if (offenders.length > 0) { + throw new Error( + `${label} exposes non-registry workspace metadata: ${offenders + .sort() + .join(", ")}`, + ); + } +} + +export function runInstalledCliSmoke( + cwd, + { cliCommand, expectedVersion, label }, +) { + const binPath = installedBinPath(cwd, cliCommand); + const versionOutput = execFileSync(binPath, ["--version"], { + cwd, + encoding: "utf8", + }); + if (!versionOutput.includes(expectedVersion)) { + throw new Error( + `Expected ${label} ${cliCommand} --version output to include ${expectedVersion}, received: ${versionOutput.trim()}`, + ); + } + + execFileSync(binPath, ["--help"], { + cwd, + stdio: "ignore", + }); +} + function parseAuditJson(output) { try { return JSON.parse(output); diff --git a/scripts/release-readiness.js b/scripts/release-readiness.js index a0293b07b..ebc7050c6 100644 --- a/scripts/release-readiness.js +++ b/scripts/release-readiness.js @@ -8,9 +8,9 @@ import { loadRootPackage, shouldManagePackageLock } from "./workspace-utils.js"; const mode = process.argv[2] ?? "release"; const rootPackage = loadRootPackage(); -function run(command) { +function run(command, env = {}) { console.log(`$ ${command}`); - execSync(command, { stdio: "inherit" }); + execSync(command, { stdio: "inherit", env: { ...process.env, ...env } }); } function hasScript(name) { @@ -32,12 +32,6 @@ function runPackSmoke() { console.log("Skipping packed CLI smoke test (script missing)"); return; } - if (!shouldManagePackageLock(rootPackage)) { - console.log( - "Skipping packed CLI smoke test (package is not npm-installable from a tarball in this repo)", - ); - return; - } const tarball = execSync("npm pack --silent", { encoding: "utf8" }) .trim() @@ -49,7 +43,10 @@ function runPackSmoke() { } try { - run(`node scripts/smoke-packed-cli.js "${tarball}"`); + run(`node scripts/smoke-packed-cli.js "${tarball}"`, { + MAESTRO_INSTALL_AUDIT_LEVEL: + process.env.MAESTRO_INSTALL_AUDIT_LEVEL ?? "critical", + }); } finally { rmSync(resolve(process.cwd(), tarball), { force: true }); } @@ -61,6 +58,8 @@ function runCiChecks() { run("bun run bun:lint"); run("npm run build"); run("npm run verify:runtime-deps"); + runPackSmoke(); + maybeRunScript("smoke:exec-replay-e2e"); maybeRunScript("openapi:check"); } @@ -78,6 +77,7 @@ function runReleaseChecks() { console.log("Skipping npm audit (package-lock not managed in this repo)"); } runPackSmoke(); + maybeRunScript("smoke:exec-replay-e2e"); } switch (mode) { diff --git a/scripts/smoke-cli.js b/scripts/smoke-cli.js index fa0a993eb..65b843bdf 100755 --- a/scripts/smoke-cli.js +++ b/scripts/smoke-cli.js @@ -17,6 +17,11 @@ 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 new file mode 100644 index 000000000..67c97a382 --- /dev/null +++ b/scripts/smoke-exec-replay-e2e.js @@ -0,0 +1,415 @@ +#!/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; + const timer = setTimeout(() => { + finish(new Error("RPC replay smoke timed out.")); + }, timeoutMs); + + function finish(error) { + if (finished) return; + finished = true; + clearTimeout(timer); + child.kill("SIGTERM"); + rmSync(context.runDir, { recursive: true, force: true }); + if (error) reject(error); + else resolve(); + } + + 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-packed-cli.js b/scripts/smoke-packed-cli.js index f7cb7f370..c3f5f3fc6 100644 --- a/scripts/smoke-packed-cli.js +++ b/scripts/smoke-packed-cli.js @@ -5,12 +5,20 @@ import { execFileSync } from "node:child_process"; import { mkdtempSync, rmSync, statSync } from "node:fs"; import { tmpdir } from "node:os"; import { join, resolve } from "node:path"; +import { getRuntimeWorkspaceNames } from "./runtime-workspaces.mjs"; import { + assertInstallablePackageMetadata, + getBunCommand, getNpmCommand, - getNpxCommand, + readInstalledPackageJson, + runInstalledCliSmoke, runInstalledPackageAudit, } from "./install-smoke-utils.js"; import { getPackageMetadata } from "./package-metadata.js"; +import { + getWorkspacePackages, + loadRootPackage, +} from "./workspace-utils.js"; const tarballArg = process.argv[2]; if (!tarballArg) { @@ -37,37 +45,88 @@ if (tarballSizeBytes > maxTarballSizeBytes) { process.exit(1); } -const { version, cliCommand } = getPackageMetadata(); -const tempDir = mkdtempSync(join(tmpdir(), "maestro-pack-smoke-")); +const rootPackage = loadRootPackage(); +const { name, version, cliCommand } = getPackageMetadata(); +const runtimeWorkspaceNames = getRuntimeWorkspaceNames(rootPackage); +const workspacePackages = await getWorkspacePackages(rootPackage); +const forbiddenWorkspaceNames = Array.from( + new Set([ + ...runtimeWorkspaceNames, + ...workspacePackages + .filter((workspacePackage) => workspacePackage.data.private === true) + .map((workspacePackage) => workspacePackage.name), + ]), +).sort(); const npmCommand = getNpmCommand(); -const npxCommand = getNpxCommand(); +const bunCommand = getBunCommand(); -try { - execFileSync(npmCommand, ["init", "-y"], { - cwd: tempDir, - stdio: "ignore", - }); - execFileSync(npmCommand, ["install", tarballPath], { - cwd: tempDir, - stdio: "inherit", - }); - runInstalledPackageAudit(tempDir, { - label: tarballPath, - }); - const output = execFileSync(npxCommand, [cliCommand, "--version"], { - cwd: tempDir, - encoding: "utf-8", +function assertInstalledMetadata(installRoot, label) { + const installedPackage = readInstalledPackageJson(name, installRoot); + assertInstallablePackageMetadata(installedPackage, { + label, + forbiddenWorkspaceNames, }); +} + +function runNpmInstallSmoke() { + const tempDir = mkdtempSync(join(tmpdir(), "maestro-pack-smoke-npm-")); + try { + execFileSync(npmCommand, ["init", "-y"], { + cwd: tempDir, + stdio: "ignore", + }); + execFileSync(npmCommand, ["install", tarballPath], { + cwd: tempDir, + stdio: "inherit", + }); + assertInstalledMetadata(tempDir, `${tarballPath} via npm`); + runInstalledPackageAudit(tempDir, { + label: tarballPath, + }); + runInstalledCliSmoke(tempDir, { + cliCommand, + expectedVersion: version, + label: "npm-installed packed CLI", + }); - if (!output.includes(version)) { - throw new Error( - `Expected ${cliCommand} --version output to include ${version}, received: ${output.trim()}`, + console.log( + `Smoke-tested ${cliCommand} from ${tarballPath} with npm (${tarballSizeBytes} bytes).`, ); + } finally { + rmSync(tempDir, { recursive: true, force: true }); + } +} + +function runBunInstallSmoke() { + if (process.env.MAESTRO_SKIP_BUN_INSTALL_SMOKE === "1") { + console.log(`Skipping Bun packed install smoke for ${tarballPath}.`); + return; } - console.log( - `Smoke-tested ${cliCommand} from ${tarballPath} (${tarballSizeBytes} bytes).`, - ); -} finally { - rmSync(tempDir, { recursive: true, force: true }); + const tempDir = mkdtempSync(join(tmpdir(), "maestro-pack-smoke-bun-")); + try { + execFileSync(bunCommand, ["init", "-y"], { + cwd: tempDir, + stdio: "ignore", + }); + execFileSync(bunCommand, ["add", tarballPath], { + cwd: tempDir, + stdio: "inherit", + }); + assertInstalledMetadata(tempDir, `${tarballPath} via Bun`); + runInstalledCliSmoke(tempDir, { + cliCommand, + expectedVersion: version, + label: "Bun-installed packed CLI", + }); + + console.log( + `Smoke-tested ${cliCommand} from ${tarballPath} with Bun (${tarballSizeBytes} bytes).`, + ); + } finally { + rmSync(tempDir, { recursive: true, force: true }); + } } + +runNpmInstallSmoke(); +runBunInstallSmoke(); diff --git a/scripts/smoke-registry-install.js b/scripts/smoke-registry-install.js index ac94a3497..0852e9f74 100644 --- a/scripts/smoke-registry-install.js +++ b/scripts/smoke-registry-install.js @@ -2,25 +2,23 @@ // @ts-check import { execFileSync } from "node:child_process"; -import { mkdtempSync, readFileSync, rmSync } from "node:fs"; +import { mkdtempSync, rmSync } from "node:fs"; import { tmpdir } from "node:os"; import { join } from "node:path"; +import { getRuntimeWorkspaceNames } from "./runtime-workspaces.mjs"; import { + assertInstallablePackageMetadata, + getBunCommand, getNpmCommand, - getNpxCommand, + readInstalledPackageJson, + runInstalledCliSmoke, runInstalledPackageAudit, } from "./install-smoke-utils.js"; import { getPackageMetadata } from "./package-metadata.js"; - -/** - * @param {unknown} value - * @returns {string[]} - */ -function asStringArray(value) { - return Array.isArray(value) - ? value.filter((entry) => typeof entry === "string" && entry.length > 0) - : []; -} +import { + getWorkspacePackages, + loadRootPackage, +} from "./workspace-utils.js"; function parseArgs(argv) { /** @type {{packageName: string; version: string; cliCommand: string}} */ @@ -56,9 +54,19 @@ const cliCommand = overrides.cliCommand || defaults.cliCommand; const name = overrides.packageName || defaults.name; const version = overrides.version || defaults.version; const packageSpec = `${name}@${version}`; +const rootPackage = loadRootPackage(); +const runtimeWorkspaceNames = getRuntimeWorkspaceNames(rootPackage); +const workspacePackages = await getWorkspacePackages(rootPackage); +const forbiddenWorkspaceNames = Array.from( + new Set([ + ...runtimeWorkspaceNames, + ...workspacePackages + .filter((workspacePackage) => workspacePackage.data.private === true) + .map((workspacePackage) => workspacePackage.name), + ]), +).sort(); const npmCommand = getNpmCommand(); -const npxCommand = getNpxCommand(); -const bunCommand = process.platform === "win32" ? "bun.exe" : "bun"; +const bunCommand = getBunCommand(); const maxAttempts = Number.parseInt( process.env.MAESTRO_REGISTRY_POLL_ATTEMPTS ?? "120", 10, @@ -72,56 +80,23 @@ function sleep(milliseconds) { return new Promise((resolve) => setTimeout(resolve, milliseconds)); } -function installedPackageJsonPath(packageName, installRoot) { - return join( - installRoot, - "node_modules", - ...packageName.split("/"), - "package.json", - ); -} - -function readInstalledBundledDependencies(installRoot) { - const packageJsonPath = installedPackageJsonPath(name, installRoot); - try { - const parsed = JSON.parse(readFileSync(packageJsonPath, "utf8")); - if (!parsed || typeof parsed !== "object" || Array.isArray(parsed)) { - throw new Error("installed package.json did not contain an object"); - } - return asStringArray( - parsed.bundleDependencies ?? parsed.bundledDependencies, - ); - } catch (error) { - const reason = - error instanceof Error ? error.message : "unknown package read error"; - throw new Error( - `Could not read installed package metadata at ${packageJsonPath}: ${reason}`, - ); - } -} - -function shouldRunBunInstallSmoke(bundledDependencies) { +function shouldRunBunInstallSmoke() { if (process.env.MAESTRO_SKIP_BUN_INSTALL_SMOKE === "1") { console.log(`Skipping Bun install smoke for ${packageSpec}.`); return false; } - if (process.env.MAESTRO_FORCE_BUN_INSTALL_SMOKE === "1") { - return true; - } - - if (bundledDependencies.length > 0) { - console.log( - `Skipping Bun install smoke for ${packageSpec}; package bundles ${bundledDependencies.join( - ", ", - )}, and the npm install smoke already verified the published tarball contents.`, - ); - return false; - } - return true; } +function assertInstalledMetadata(installRoot, label) { + const installedPackage = readInstalledPackageJson(name, installRoot); + assertInstallablePackageMetadata(installedPackage, { + label, + forbiddenWorkspaceNames, + }); +} + async function waitForPackage() { for (let attempt = 1; attempt <= maxAttempts; attempt += 1) { try { @@ -158,7 +133,6 @@ async function waitForPackage() { async function main() { await waitForPackage(); - let installedBundledDependencies = []; const tempDir = mkdtempSync(join(tmpdir(), "maestro-registry-smoke-")); try { execFileSync(npmCommand, ["init", "-y"], { @@ -169,24 +143,14 @@ async function main() { cwd: tempDir, stdio: "inherit", }); - installedBundledDependencies = readInstalledBundledDependencies(tempDir); + assertInstalledMetadata(tempDir, `${packageSpec} via npm`); runInstalledPackageAudit(tempDir, { label: packageSpec, }); - - const versionOutput = execFileSync(npxCommand, [cliCommand, "--version"], { - cwd: tempDir, - encoding: "utf8", - }); - if (!versionOutput.includes(version)) { - throw new Error( - `Expected ${cliCommand} --version output to include ${version}, received: ${versionOutput.trim()}`, - ); - } - - execFileSync(npxCommand, [cliCommand, "--help"], { - cwd: tempDir, - stdio: "ignore", + runInstalledCliSmoke(tempDir, { + cliCommand, + expectedVersion: version, + label: "npm-installed registry CLI", }); console.log(`Smoke-tested ${packageSpec} from npm.`); @@ -194,7 +158,7 @@ async function main() { rmSync(tempDir, { recursive: true, force: true }); } - if (!shouldRunBunInstallSmoke(installedBundledDependencies)) { + if (!shouldRunBunInstallSmoke()) { return; } @@ -208,20 +172,12 @@ async function main() { cwd: bunTempDir, stdio: "inherit", }); - - const binPath = - process.platform === "win32" - ? join(bunTempDir, "node_modules", ".bin", `${cliCommand}.cmd`) - : join(bunTempDir, "node_modules", ".bin", cliCommand); - const versionOutput = execFileSync(binPath, ["--version"], { - cwd: bunTempDir, - encoding: "utf8", + assertInstalledMetadata(bunTempDir, `${packageSpec} via Bun`); + runInstalledCliSmoke(bunTempDir, { + cliCommand, + expectedVersion: version, + label: "Bun-installed registry CLI", }); - if (!versionOutput.includes(version)) { - throw new Error( - `Expected Bun-installed ${cliCommand} --version output to include ${version}, received: ${versionOutput.trim()}`, - ); - } console.log(`Smoke-tested ${packageSpec} from Bun.`); } finally { diff --git a/test/scripts/install-smoke-utils.test.ts b/test/scripts/install-smoke-utils.test.ts new file mode 100644 index 000000000..389fd2642 --- /dev/null +++ b/test/scripts/install-smoke-utils.test.ts @@ -0,0 +1,61 @@ +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:", + ); + }); +});