diff --git a/CHANGELOG.md b/CHANGELOG.md index e9cb1c74..cb4b3a69 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -4,6 +4,18 @@ All notable changes to the claude-plugins project will be documented in this fil The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.1.0/). Entries are listed newest-first; each plugin section is treated as released when merged to `main`. +### vibe v1.1.123 + +#### Fixed + +- ISS-15065: Independent cloud validations can launch when ready. A platform limit delays that launch and records the refusal before retrying. +- ISS-15054: Fleet slot waits record their cadence with macOS and GNU awk. +- ISS-15055: Cloud outcomes retain bounded redacted failure details. A caller-written lane that differs from its named CI recipe is flagged in the receipt. +- ISS-15048: The reconnect supervision regression releases its live timer when the test fails. +- ISS-15066: A new pull request needs its full package test and compatibility tasks run on the head merged with current main. Pushes and open pull requests only warn. +- ISS-15068: Cloud control lanes can bring up loopback with Python when `ip` fails. Cloud validation returns the measured capability failure, carries redacted failed-test excerpts on the required result line, and recovers inline outcomes or explains a missing result branch. +- Across all plugin Markdown, including eval prompts and graders, the release is about 48 words longer than v1.1.122. The count covers the source files in `plugins/vibe` and excludes the generated ClosedLoop edition. + ### vibe v1.1.122 #### Added @@ -28,7 +40,7 @@ The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.1.0/). #### Fixed - ISS-15038: A queued cloud validation waits for the queue lock until its own deadline instead of failing after 5 seconds with "cloud validation queue state is busy". Launcher liveness checks run outside the lock, and a run that ends past its queue deadline still releases the account. -- One account runs up to 7 cloud validations at once instead of 1, the number measured running together on the pinned environment. A request waiting behind a long run moves to a slot that frees. +- Added concurrent cloud validation and allowed pending requests to move when a local slot freed. - A run Claude refuses as rate-limited fails with `CLOUD_ROUTINE_HOURLY_LIMIT`, naming the documented 30-an-hour routine cap and when to retry. vibe does not count runs itself: one routine started 41 runs in an hour without a refusal. - The cloud agent installs the outcome reporter with a short `git fetch` of its tooling commit (the request's `runtimeTool`, else the commit Claude Code recorded installing this vibe version, else the commit under test when the tooling repository itself is validated and holds the same reporter), checked against the installed bytes. It no longer copies a 15 KB inline payload, which Sonnet could not reproduce, so a lane that exited 0 is recorded passed. The inline payload remains only when none of these commits is known. - The managed cloud runner's result record is read in its own short call, so lane timing lines no longer push it past the run log's cut. diff --git a/plugins/vibe-closedloop/.claude-plugin/plugin.json b/plugins/vibe-closedloop/.claude-plugin/plugin.json index 8df73f3a..0fe9fdc7 100644 --- a/plugins/vibe-closedloop/.claude-plugin/plugin.json +++ b/plugins/vibe-closedloop/.claude-plugin/plugin.json @@ -1,7 +1,7 @@ { "name": "vibe", "description": "Vibe sessions, handoff, seed refresh, and ClosedLoop ticket workflows", - "version": "1.1.122", + "version": "1.1.123", "dependencies": [ "closedloop-core", "vibe-core" diff --git a/plugins/vibe-closedloop/.codex-plugin/plugin.json b/plugins/vibe-closedloop/.codex-plugin/plugin.json index c72a7554..dee584c5 100644 --- a/plugins/vibe-closedloop/.codex-plugin/plugin.json +++ b/plugins/vibe-closedloop/.codex-plugin/plugin.json @@ -1,6 +1,6 @@ { "name": "vibe", - "version": "1.1.122", + "version": "1.1.123", "description": "Vibe sessions, handoff, seed refresh, and ClosedLoop ticket workflows", "author": { "name": "ClosedLoop", diff --git a/plugins/vibe-closedloop/README.md b/plugins/vibe-closedloop/README.md index f206a623..a2437db6 100644 --- a/plugins/vibe-closedloop/README.md +++ b/plugins/vibe-closedloop/README.md @@ -314,7 +314,7 @@ Run the matching Codex suite from the repository root with ### Runtime files -Version `1.1.122` contains 17 skills and 17 agents, and no hook manifest: the +Version `1.1.123` contains 17 skills and 17 agents, and no hook manifest: the `vibe-core` plugin, which vibe declares as a dependency, registers the hooks and runs `hooks/runtime.mjs` from the vibe a session uses. Skill commands forward to guards in `hooks/` and runtime modules in `lib/`. The package has no standalone commands, root shell scripts or production Python tools. Tests sit beside their owners; Python contract helpers and the generic scan live in `tools/python/`. diff --git a/plugins/vibe-closedloop/hooks/pr-create-guard.mjs b/plugins/vibe-closedloop/hooks/pr-create-guard.mjs index 1e0361f8..b62bc33b 100644 --- a/plugins/vibe-closedloop/hooks/pr-create-guard.mjs +++ b/plugins/vibe-closedloop/hooks/pr-create-guard.mjs @@ -29,7 +29,7 @@ import { deliveryPlacementProblem, deliveryRepository, fleetRowHasPullRequest } import { validChat } from "../lib/fleet-orchestrator/scripts/chat-binding.mjs"; import os from "node:os"; import { BodyFileError, OVERRIDE_CHECKS, overriddenChecks, readPrBodyFile } from "../lib/handoff/scripts/gate-override.mjs"; -import { declaredWorkflowLanes, fullCiProblem } from "../lib/handoff/scripts/full-ci-check.mjs"; +import { declaresPackageLanes, declaredWorkflowLanes, fullCiProblem } from "../lib/handoff/scripts/full-ci-check.mjs"; import { refusalReplayProblem } from "../lib/handoff/scripts/refusing-check-replay.mjs"; import { e2eGateProblems } from "../lib/handoff/scripts/e2e-gate-check.mjs"; @@ -219,7 +219,12 @@ function prHeadTarget(cwd, head, repositoryOverrides) { // `--head` may name the remote branch the worktree's branch is pushed to under another name (#438); it stands for // that local branch, so its owner and handoff gate are the local branch's. const local = localBranchExists(cwd, head) ? head : pushedUpstreamBranch(cwd, head) ?? head; - headCommit = git(cwd, ["rev-parse", "--verify", `refs/heads/${local}^{commit}`]); + try { headCommit = git(cwd, ["rev-parse", "--verify", `refs/heads/${local}^{commit}`]); } + catch { + if (head.startsWith(VIBE_BRANCH)) return null; + const remoteHead = git(cwd, ["rev-parse", "--verify", `refs/remotes/origin/${head}^{commit}`]); + return sessionCwd && carriesSessionWork(cwd, remoteHead) ? { cwd } : { nonVibe: true }; + } for (const entry of git(cwd, ["worktree", "list", "--porcelain"]).split(/\n\s*\n/)) { const worktree = /^worktree (.+)$/m.exec(entry)?.[1]; if (!worktree) continue; @@ -308,7 +313,10 @@ function prReadinessProblem(call, target, binding) { let headCommit; try { headCommit = git(call.cwd, ["rev-parse", "--verify", `${call.head ? prHeadRef(call.cwd, call.head) : "HEAD"}^{commit}`]); } catch { - try { return declaredWorkflowLanes(call.cwd, "HEAD") ? "the PR head cannot be read to check its CI workflow runs" : null; } + try { + return declaresPackageLanes(call.cwd, "HEAD") || declaredWorkflowLanes(call.cwd, "HEAD") + ? "the PR head cannot be read to check its test lanes" : null; + } catch { return null; } } const worktree = git(call.cwd, ["worktree", "list", "--porcelain"]).split(/\n\s*\n/) diff --git a/plugins/vibe-closedloop/lib/handoff/scripts/full-ci-check.mjs b/plugins/vibe-closedloop/lib/handoff/scripts/full-ci-check.mjs index 2fffa1b7..29082e9e 100644 --- a/plugins/vibe-closedloop/lib/handoff/scripts/full-ci-check.mjs +++ b/plugins/vibe-closedloop/lib/handoff/scripts/full-ci-check.mjs @@ -1,25 +1,22 @@ -// A pull request to a repository whose vibe-handoff-paths.json declares a github-workflow lane source is refused at PR -// create until every job and matrix entry of that workflow, read at the PR head, has a passing -// run of the head's exact tree recorded by pre-pr-lanes.mjs with its run witness, unless a ticketed gate override for -// "ci lanes" quotes the ruling that allows the skip (operator ruling, 2026-12-02 about 9:10 PM CST: "stop allowing -// things like this to even make it to a PR without adequate testing"). A pull request once opened after only its -// focused test files ran, and CI failed on tests outside them and on a missed plugin version bump. +// A new pull request needs a head that contains fetched origin/main and records from that head for the whole lanes. +// Workflow repositories declare their jobs in vibe-handoff-paths.json. pnpm/Turbo workspaces declare package tests +// and compatibility scripts in their manifests. Focused tests remain useful for development and push checks warn. // -// Usage: full-ci-check.mjs report --worktree writes the workflow lane report for HEAD into the git dir and -// prints `REPORT ` and one `UNRUN ` line per job still to run with -// pre-pr-lanes.mjs run --fleet-where remote --fleet-orch --fleet-owner --worktree -// --head --command '' --report (the recipe is the job's `command` in the report; the heavy -// host needs a worktree at the same path and HEAD). Exits 1 while any job is unrun. +// Usage: full-ci-check.mjs report --worktree writes the reports pre-pr-lanes.mjs takes with --report and prints +// one UNRUN line per missing lane. Run package lanes on an allowed host with pre-pr-lanes.mjs run, or use +// witness on the runner and record its evidence. Replay workflow jobs with run --fleet-where remote. -import { execFileSync } from "node:child_process"; +import { execFileSync, spawnSync } from "node:child_process"; import { createHash } from "node:crypto"; import { existsSync, readFileSync, writeFileSync } from "node:fs"; import path from "node:path"; import { parseArgs } from "node:util"; import { capturedJson } from "../../vibe/scripts/captured-json.mjs"; -import { workflowLaneDefinitions } from "../../vibe/scripts/workflow-lane-definitions.mjs"; +import { readGitInventory } from "../../vibe/scripts/git-inventory.mjs"; +import { workflowLaneDefinitions, workspacePackages } from "../../vibe/scripts/workflow-lane-definitions.mjs"; import { committedSourceIdentity } from "../../vibe/scripts/tested-head.mjs"; -import { witnessProblem } from "../../../skills/vibe/scripts/lane-run-witness.mjs"; +import { globMatcher } from "../../../skills/vibe/scripts/e2e-requirement.mjs"; +import { laneRunCommit, witnessProblem } from "../../../skills/vibe/scripts/lane-run-witness.mjs"; import { LANE_RECORDS_FILE } from "../../../skills/vibe/scripts/lane-outcomes.mjs"; import { quotedRulingOverride } from "./gate-override.mjs"; import { isEntryPoint } from "../../../shared/plugin-roots.mjs"; @@ -37,6 +34,103 @@ export function pushCheckAsksPrePrChecks(createdAt) { export const CI_LANES_OVERRIDE = "ci lanes"; const git = (worktree, args) => execFileSync("git", ["-C", worktree, ...args], { encoding: "utf8", stdio: ["ignore", "pipe", "pipe"], maxBuffer: 64 * 1024 * 1024 }); +const PNPM_WORKSPACE = "pnpm-workspace.yaml"; +const COMPATIBILITY_TASK = "test:compatibility"; +const NAMES = /^(?:@[a-z0-9_.-]+\/)?[a-z0-9_.-]+$/i; +const fullTest = (name) => `pnpm turbo run test --filter=${name} --force`; +const compatibilityTest = (name) => `pnpm --filter=${name} ${COMPATIBILITY_TASK}`; + +/** Identify the exact full-task commands so local lane runs capture their own witness. */ +export function fullPackageLaneCommand(command) { + const name = /(?:^|\s)--filter=([^\s]+)/.exec(command)?.[1]; + return Boolean(name && NAMES.test(name) && [fullTest(name), compatibilityTest(name)].includes(command)); +} + +function gitStatus(worktree, args) { + const result = spawnSync("git", ["-C", worktree, ...args], { stdio: "ignore" }); + if (result.error) throw result.error; + return result.status; +} + +function fetchedMain(worktree) { + try { return git(worktree, ["rev-parse", "--verify", "refs/remotes/origin/main^{commit}"]).trim(); } + catch { return null; } +} + +function mainAncestryNotice(worktree, head, main) { + if (!main || gitStatus(worktree, ["merge-base", "--is-ancestor", main, head]) === 0) return null; + return `PR head ${head.slice(0, 12)} does not contain fetched origin/main ${main.slice(0, 12)}. Merge or rebase onto it and rerun the lanes`; +} + +/** Whether the committed source uses pnpm and Turbo to define package test lanes. */ +export function declaresPackageLanes(worktree, head) { + const has = (file) => gitStatus(worktree, ["cat-file", "-e", `${head}:${file}`]) === 0; + return has(PNPM_WORKSPACE) && (has("turbo.json") || has("turbo.jsonc")); +} + +/** Derive whole tasks from committed workspace manifests and the diff against fetched origin/main. */ +export function packageLaneRequirements(worktree, head) { + if (!declaresPackageLanes(worktree, head)) return null; + const main = fetchedMain(worktree); + const problem = main ? mainAncestryNotice(worktree, head, main) : "fetch origin/main before checking package test lanes"; + if (problem) return { problem, lanes: [] }; + + const patterns = (workspacePackages(git(worktree, ["show", `${head}:${PNPM_WORKSPACE}`])) ?? ["**"]) + .map((pattern) => ({ exclude: pattern.startsWith("!"), glob: globMatcher(pattern.replace(/^!/, "").replace(/^\.\//, "").replace(/\/$/, "")) })); + const matches = (directory) => patterns.some(({ exclude, glob }) => !exclude && glob.test(directory)) + && !patterns.some(({ exclude, glob }) => exclude && glob.test(directory)); + const changed = git(worktree, ["diff", "--name-only", "--no-renames", "-z", main, head, "--"]).split("\0").filter(Boolean); + if (!changed.length) return { lanes: [] }; + const directories = readGitInventory(worktree, ["ls-tree", "-r", "--name-only", "-z", head]) + .split("\0").filter((file) => file.endsWith("/package.json")).map((file) => path.posix.dirname(file)).filter(matches); + const workspace = new Set(directories); + const touched = new Set(); + for (const file of changed) { + // A nested workspace package owns its own paths. + for (let directory = path.posix.dirname(file); directory !== "."; directory = path.posix.dirname(directory)) { + if (!workspace.has(directory)) continue; + touched.add(directory); + break; + } + } + const lanes = []; + for (const directory of [...touched].sort()) { + const { name, scripts } = capturedJson(git(worktree, ["show", `${head}:${directory}/package.json`])); + const test = typeof scripts?.test === "string" && scripts.test.trim(); + const compatibility = typeof scripts?.[COMPATIBILITY_TASK] === "string" && scripts[COMPATIBILITY_TASK].trim(); + if (!test && !compatibility) continue; + if (!NAMES.test(name ?? "")) throw new Error(`invalid workspace package name in ${directory}/package.json`); + if (test) lanes.push({ name: `${name}#test`, command: fullTest(name) }); + if (compatibility) lanes.push({ name: `${name}#${COMPATIBILITY_TASK}`, command: compatibilityTest(name) }); + } + return { lanes }; +} + +function missingPackageLanes(worktree, head, lanes) { + if (!lanes.length) return []; + const records = laneRecords(worktree).filter((record) => record?.head === head && laneRunCommit(record) === head + && record.result === "pass" && record.targeted === undefined); + if (!records.length) return lanes; + const source = committedSourceIdentity(worktree, head); + return lanes.filter(({ command }) => !records.some((record) => record.command === command + && record.source?.head === head && record.source.treeSha256 === source.treeSha256 + && record.source.diffSha256 === source.diffSha256 && record.witness && !witnessProblem(record))); +} + +/** The package requirements and remaining work. This computation never runs a test or writes a record. */ +export function packageLaneStatus(worktree, head) { + const requirements = packageLaneRequirements(worktree, head); + return requirements && { ...requirements, missing: missingPackageLanes(worktree, head, requirements.lanes) }; +} + +/** Readiness text for the same package lanes at PR create and in advisory checks. */ +export function packageLaneNotice(worktree, head) { + const status = packageLaneStatus(worktree, head); + if (status?.problem) return status.problem; + if (!status?.missing.length) return null; + return `PR head ${head.slice(0, 12)} needs witnessed whole package lanes: ${status.missing.map(({ command }) => command).join(", ")}. ` + + `Run full-ci-check.mjs report --worktree ${worktree} for the required commands`; +} /** The declared workflow's path and lanes at `head`, or null when the repository declares no github-workflow lane source there. */ export function declaredWorkflowLanes(worktree, head) { @@ -56,19 +150,26 @@ function laneRecords(worktree) { } /** The declared workflow lanes with no witnessed passing run of `head`'s tree, as `[{ name, command }]`; [] when none are declared. */ -export function unrunCiLanes(worktree, head) { - const declared = declaredWorkflowLanes(worktree, head); +export function unrunCiLanes(worktree, head, { exactCommit = false, declared = declaredWorkflowLanes(worktree, head) } = {}) { if (!declared) return []; - const tree = committedSourceIdentity(worktree, head).treeSha256; const records = laneRecords(worktree); + if (!records.length) return declared.lanes; + const tree = committedSourceIdentity(worktree, head).treeSha256; return declared.lanes.filter(({ command }) => !records.some((record) => record?.command === command && record.result === "pass" + && (!exactCommit || (record.head === head && record.source?.head === head && laneRunCommit(record) === head)) && record.targeted === undefined && record.source?.treeSha256 === tree && !witnessProblem(record))); } /** Why `head` may not be raised as a pull request yet, or null. `bodyText` may be a function, read only when a job is unrun. */ export function fullCiProblem(worktree, head, { bodyText = "", binding = null } = {}) { - const unrun = unrunCiLanes(worktree, head); - if (!unrun.length || quotedRulingOverride(typeof bodyText === "function" ? bodyText() : bodyText, binding, CI_LANES_OVERRIDE)) return null; + const declared = declaredWorkflowLanes(worktree, head); + const main = declared ? fetchedMain(worktree) : null; + const mainNotice = mainAncestryNotice(worktree, head, main); + if (mainNotice) return mainNotice; + const unrun = unrunCiLanes(worktree, head, { exactCommit: Boolean(main), declared }); + if (!unrun.length || quotedRulingOverride(typeof bodyText === "function" ? bodyText() : bodyText, binding, CI_LANES_OVERRIDE)) { + return packageLaneNotice(worktree, head); + } return `every CI workflow job runs in full on the exact head before a pull request, and ${unrun.length} have no witnessed passing run of ${head.slice(0, 12)}: ` + `${unrun.map(({ name }) => name).join(", ")}; full-ci-check.mjs report --worktree ${worktree} names each job's run, ` + `or add "Vibe gate override: : ${CI_LANES_OVERRIDE}: "`; @@ -89,10 +190,23 @@ function main(argv) { const { positionals, values } = parseArgs({ args: argv, allowPositionals: true, options: { worktree: { type: "string" } } }); if (positionals[0] !== "report" || !values.worktree) throw new Error("usage: full-ci-check.mjs report --worktree "); const head = git(values.worktree, ["rev-parse", "HEAD"]).trim(); + const packages = packageLaneStatus(values.worktree, head); + if (packages?.problem) throw new Error(packages.problem); + const declared = declaredWorkflowLanes(values.worktree, head); + const main = declared ? fetchedMain(values.worktree) : null; + const mainNotice = mainAncestryNotice(values.worktree, head, main); + if (mainNotice) throw new Error(mainNotice); + if (packages?.lanes.length) { + const file = path.join(git(values.worktree, ["rev-parse", "--absolute-git-dir"]).trim(), "vibe-package-lane-report.txt"); + writeFileSync(file, packages.lanes.map(({ command }) => ` ${command}\n`).join("")); + process.stdout.write(`REPORT ${file}\n`); + for (const { name, command } of packages.missing) process.stdout.write(`UNRUN ${name}: ${command}\n`); + } + if (!declared && packages) return packages.missing.length ? 1 : 0; process.stdout.write(`REPORT ${writeWorkflowLaneReport(values.worktree, head)}\n`); - const unrun = unrunCiLanes(values.worktree, head); + const unrun = unrunCiLanes(values.worktree, head, { exactCommit: Boolean(main), declared }); for (const { name } of unrun) process.stdout.write(`UNRUN ${name}\n`); - return unrun.length ? 1 : 0; + return unrun.length || packages?.missing.length ? 1 : 0; } if (isEntryPoint(import.meta.url)) { diff --git a/plugins/vibe-closedloop/lib/handoff/scripts/refusing-checks.mjs b/plugins/vibe-closedloop/lib/handoff/scripts/refusing-checks.mjs index 1c83f459..81f768cd 100644 --- a/plugins/vibe-closedloop/lib/handoff/scripts/refusing-checks.mjs +++ b/plugins/vibe-closedloop/lib/handoff/scripts/refusing-checks.mjs @@ -16,8 +16,14 @@ import { proofGateProblems, pushReadyProofProblems } from "./proof-receipts.mjs" import { refusalReplayProblem } from "./refusing-check-replay.mjs"; const HANDOFF = "plugins/vibe/lib/handoff/scripts"; +const LANE_SCRIPTS = "plugins/vibe/skills/vibe/scripts"; +const PR_CREATE = "plugins/vibe/hooks/pr-create-guard.mjs"; const PROOF_FILES = [`${HANDOFF}/proof-receipts.mjs`, `${HANDOFF}/proof-scope.mjs`, `${HANDOFF}/proof-parsers.mjs`]; -const E2E_FILES = [`${HANDOFF}/e2e-gate-check.mjs`, "plugins/vibe/skills/vibe/scripts/e2e-requirement.mjs"]; +const LANE_RECORDERS = [`${LANE_SCRIPTS}/pre-pr-lanes.mjs`, `${LANE_SCRIPTS}/lane-run-witness.mjs`]; +const E2E_FILES = [`${HANDOFF}/e2e-gate-check.mjs`, `${LANE_SCRIPTS}/e2e-requirement.mjs`, ...LANE_RECORDERS]; + +// These receipts gate a new PR. Replay accepted work as an in-flight update, for which findings are advisory. +const alreadyAccepted = (head, pushed = [], passed = []) => pushed.includes(head) || passed.includes(head); /** * Each replayed check: the source files that define it and `replay(input)`, its refusals for a branch at `head`, given @@ -30,9 +36,11 @@ export const REFUSING_CHECKS = Object.freeze({ pushReadyProofProblems: { files: [...PROOF_FILES, "plugins/vibe/skills/fleet-orchestrator/scripts/push-proof.mjs"], gates: ["push-check"], replay: ({ worktree, base, head, pushed }) => pushReadyProofProblems(worktree, { base, head, pushed }) }, e2eGateProblems: { files: E2E_FILES, gates: ["PR create"], - replay: ({ worktree, base, head, bodyText, binding }) => e2eGateProblems(worktree, { base, head, bodyText, binding }) }, - fullCiProblem: { files: [`${HANDOFF}/full-ci-check.mjs`], gates: ["PR create"], - replay: ({ worktree, head, bodyText, binding }) => [fullCiProblem(worktree, head, { bodyText, binding })].filter(Boolean) }, + replay: ({ worktree, base, head, pushed, passed, bodyText, binding }) => alreadyAccepted(head, pushed, passed) + ? [] : e2eGateProblems(worktree, { base, head, bodyText, binding }) }, + fullCiProblem: { files: [`${HANDOFF}/full-ci-check.mjs`, ...LANE_RECORDERS, PR_CREATE], gates: ["PR create"], + replay: ({ worktree, head, pushed, passed, bodyText, binding }) => alreadyAccepted(head, pushed, passed) + ? [] : [fullCiProblem(worktree, head, { bodyText, binding })].filter(Boolean) }, refusalReplayProblem: { files: [`${HANDOFF}/refusing-check-replay.mjs`, `${HANDOFF}/refusing-checks.mjs`], gates: ["PR create"], replay: ({ worktree, base, head, bodyText, binding }) => [refusalReplayProblem(worktree, { base, head, bodyText, binding })].filter(Boolean) }, "PROOF-MISSING": { via: "pushReadyProofProblems" }, diff --git a/plugins/vibe-closedloop/lib/vibe/scripts/cloud-capability-probe.mjs b/plugins/vibe-closedloop/lib/vibe/scripts/cloud-capability-probe.mjs index de9e8cf7..05df2c40 100644 --- a/plugins/vibe-closedloop/lib/vibe/scripts/cloud-capability-probe.mjs +++ b/plugins/vibe-closedloop/lib/vibe/scripts/cloud-capability-probe.mjs @@ -5,7 +5,7 @@ import path from "node:path"; import { fileURLToPath } from "node:url"; import { setTimeout as sleep } from "node:timers/promises"; import { dockerDaemonArgs } from "./cloud-docker-daemon.mjs"; -import { boundedFailureLine, FAILURES_LINE_BYTES } from "./cloud-outcome-artifact.mjs"; +import { boundedFailureLine, boundedDiagnostic, FAILURES_LINE_BYTES, diagnosticSecrets } from "./cloud-outcome-artifact.mjs"; import { probeCloudHostRuntime, redactSecrets } from "./cloud-validation-host.mjs"; import { runBoundedDetailed } from "../../../skills/vibe/scripts/run-bounded.mjs"; import { isEntryPoint } from "../../../shared/plugin-roots.mjs"; @@ -45,7 +45,11 @@ export async function measureLaneTools(command = run, failures = {}) { // The capture merges stderr, where uv prints environment deprecation warnings ahead of the version line. const output = result.output.split("\n").filter((line) => !/^warning: /.test(line)).join("\n").trim(); flags[name] = result.result === "YES" && version.test(output); - if (!flags[name]) failures[name] = result.result === "YES" ? { ...result, reason: "unexpected version output" } : result; + if (!flags[name]) { + const step = [binary, ...args].join(" "); + const reason = result.result === "YES" ? "unexpected version output" : result.reason; + failures[name] = { ...result, result: "NO", reason: reason ? `${step}: ${reason}` : step }; + } } return flags; } @@ -184,9 +188,10 @@ const FAILURE_LINE_CHARS = 160; * again, to the lane result, so the result shows why a check failed. The probe's full streams stay private; this line * carries only the tail of each failing command. */ -export function capabilityFailureLine({ defaultDriver, vfsDriver, compose, electron }, laneTools = {}) { - const outcomes = { compose, defaultDaemon: defaultDriver?.daemon, defaultHello: defaultDriver?.helloWorld, vfsDaemon: vfsDriver?.daemon, - vfsHello: vfsDriver?.helloWorld, electronVersion: electron?.version, electronWindow: electron?.window, ...laneTools }; +export function capabilityFailureLine({ defaultDriver, vfsDriver, compose, electron }, laneTools = {}, host = null) { + const outcomes = { ...hostCapabilityFailures(host), ...laneTools, compose, defaultDaemon: defaultDriver?.daemon, + defaultHello: defaultDriver?.helloWorld, vfsDaemon: vfsDriver?.daemon, vfsHello: vfsDriver?.helloWorld, + electronVersion: electron?.version, electronWindow: electron?.window }; const failures = {}; for (const [name, outcome] of Object.entries(outcomes)) { if (!outcome || outcome.result === "YES") continue; @@ -197,6 +202,24 @@ export function capabilityFailureLine({ defaultDriver, vfsDriver, compose, elect return boundedFailureLine(failures, FAILURES_LINE_BYTES); } +/** Pair each failed runtime flag with the measured step that stopped it. A missing resident daemon is expected. */ +function hostCapabilityFailures(host) { + if (!host) return {}; + const { checks, details } = host; + const steps = { ...details, + controlNamespace: details.controlNamespace?.exitCode === 0 ? details.nonRoot : details.controlNamespace, + chromium: details.chromiumLaunch ?? details.chromiumFetch ?? details.chromiumInstall, + chromium1254: details.chromiumInstall, + }; + const secrets = diagnosticSecrets(); + return Object.fromEntries(Object.entries(checks).flatMap(([name, passed]) => { + const step = steps[name]; + if (passed || !step) return []; + const output = boundedDiagnostic([step.stderrTail, step.diagnosis].filter(Boolean).join("\n"), secrets); + return [[name, { result: "NO", exitCode: step.exitCode, reason: step.step, output }]]; + })); +} + /** * Remove the probe's private daemon state after its report is out. A failed removal is reported on its own line and * never replaces the measured report or the lane's exit status: the files sit under .git in a throwaway checkout. @@ -256,7 +279,7 @@ if (isEntryPoint(import.meta.url)) { process.stdout.write(`CLOUD_HOST_DETAILS ${JSON.stringify(host.details)}\n`); process.stdout.write(capabilityStatusLine(outcome)+"\n"); process.stdout.write(capabilityReasonLine(outcome)+"\n"); - process.stdout.write(capabilityFailureLine(outcome, laneToolFailures)+"\n"); + process.stdout.write(capabilityFailureLine(outcome, laneToolFailures, host)+"\n"); process.stdout.write(`CLOUD_HOST_RUNTIME ${JSON.stringify({ commit, checks })}\n`); } } catch (error) { diff --git a/plugins/vibe-closedloop/lib/vibe/scripts/cloud-outcome-artifact.mjs b/plugins/vibe-closedloop/lib/vibe/scripts/cloud-outcome-artifact.mjs index 474ba8c8..10e44d5e 100644 --- a/plugins/vibe-closedloop/lib/vibe/scripts/cloud-outcome-artifact.mjs +++ b/plugins/vibe-closedloop/lib/vibe/scripts/cloud-outcome-artifact.mjs @@ -1,3 +1,4 @@ +import { redactSecrets } from "./cloud-redaction.mjs"; import { createHash } from "node:crypto"; import { capturedJson, jsonValueAt } from "./captured-json.mjs"; @@ -129,16 +130,29 @@ const failuresAt = (label) => new RegExp("(? bytes && Object.values(failures).some(({ tail }) => tail.length)) { - const longest = Object.values(failures).reduce((a, b) => (b.tail.length > a.tail.length ? b : a)); - longest.tail.shift(); + const entries = Object.values(failures); + // Preserve names and exits first. Trim older stderr lines before shortening commands to fit an unusually large report. + while (entries.length && Buffer.byteLength(line) > bytes) { + const longest = entries.reduce((a, b) => b.tail.length > a.tail.length ? b : a); + if (longest.tail.length > 1) longest.tail.shift(); + else { + const widest = entries.reduce((a, b) => Buffer.byteLength(b.tail[0] ?? "") > Buffer.byteLength(a.tail[0] ?? "") ? b : a); + const width = Buffer.byteLength(widest.tail[0] ?? ""); + if (width) widest.tail = width > 16 ? [truncateDiagnostic(widest.tail[0], width - 16)] : []; + else { + const [reason] = entries.filter((entry) => entry.reason).sort((a, b) => b.reason.length - a.reason.length); + if (!reason) break; + if (reason.reason.length > 16) reason.reason = reason.reason.slice(0, -16); + else delete reason.reason; + } + } line = label + " " + JSON.stringify(failures); } - return line; + return Buffer.byteLength(line) <= bytes ? line : ""; } /** @@ -206,6 +220,95 @@ export function probeFailureLine(text, { bytes = FAILURES_MESSAGE_BYTES, redact return found.size === 1 ? boundedFailureLine(JSON.parse([...found][0]), bytes, label) : ""; } +export const DIAGNOSTIC_LABEL = "VIBE_VALIDATION_FAILURES"; +export const DIAGNOSTIC_BYTES = 320; +const ARTIFACT_DIAGNOSTIC_BYTES = 512 * 1024; + +/** Values to redact even when a command prints a secret without its variable name. */ +export function diagnosticSecrets(env = process.env) { + return [...new Set(Object.entries(env) + .filter(([key, value]) => value?.length >= 8 && /TOKEN|SECRET|PASSWORD|PASSWD|API.?KEY|PRIVATE.?KEY|ACCESS.?KEY|CREDENTIAL|AUTH/i.test(key)) + .map(([, value]) => value))].sort((a, b) => b.length - a.length); +} + +/** Redact before truncating so a clipped token never becomes an unrecognized secret. */ +export function boundedDiagnostic(value, secrets = []) { + const plain = String(value ?? "").replace(/\x1b\[[0-?]*[ -/]*[@-~]|[\x00-\x08\x0b-\x1f\x7f]/g, ""); + const clean = redactSecrets(secrets.reduce((text, secret) => text.replaceAll(secret, ""), plain)); + return truncateDiagnostic(clean, DIAGNOSTIC_BYTES); +} + +/** Shorten a redacted channel at a UTF-8 character boundary. */ +function truncateDiagnostic(clean, limit) { + const bytes = Buffer.from(clean); + if (bytes.length <= limit) return clean; + let end = limit; + while ((bytes[end] & 0xc0) === 0x80) end--; + return bytes.subarray(0, end).toString("utf8"); +} + +/** Keep only bounded channels for numeric lane positions. The size applies to the actual JSON bytes. */ +export function boundedDiagnostics(records, maxBytes = ARTIFACT_DIAGNOSTIC_BYTES) { + if (!records || typeof records !== "object" || Array.isArray(records)) return {}; + const diagnostics = {}; + let remaining = maxBytes - 2; + for (const [key, channels] of Object.entries(records)) { + if (!/^lane\d{1,5}$/.test(key) || !Array.isArray(channels) || channels.length !== 2 || + channels.some((value) => typeof value !== "string" || Buffer.byteLength(value) > DIAGNOSTIC_BYTES)) continue; + const clean = channels.map((value) => boundedDiagnostic(value)); + if (!clean.some(Boolean)) continue; + const size = Buffer.byteLength(JSON.stringify({ [key]: clean })) - 1; + if (size > remaining) break; + remaining -= size; + diagnostics[key] = clean; + } + return diagnostics; +} + +/** Fit redacted diagnostics to the output budget, packing them when they share the machine record's line. */ +export function diagnosticLine(records, bytes = 1200, { attached = false } = {}) { + const entries = Object.entries(boundedDiagnostics(records)); + if (!entries.length) return ""; + const render = (limit) => { + const diagnostics = Object.fromEntries(entries.map(([key, channels]) => + [key, channels.map((channel) => truncateDiagnostic(channel, limit))])); + const json = JSON.stringify(diagnostics); + return DIAGNOSTIC_LABEL + " " + (attached ? Buffer.from(json).toString("base64url") : json); + }; + const full = render(DIAGNOSTIC_BYTES); + if (Buffer.byteLength(full) <= bytes) return full; + + // Fit by shortening each channel, since counting channel bytes alone misses JSON escaping overhead. + let low = 1, high = DIAGNOSTIC_BYTES - 1, fitting = ""; + while (low <= high) { + const limit = Math.floor((low + high) / 2); + const line = render(limit); + if (Buffer.byteLength(line) <= bytes) { + fitting = line; + low = limit + 1; + } else high = limit - 1; + } + return fitting; +} + +/** Use an attachment only on the selected machine record, skipping cut copies in the run log. */ +function readDiagnosticLine(log, encoded) { + const text = String(log ?? ""); + const attachment = new RegExp("(? FAILURES_LINE_BYTES) continue; + const json = Buffer.from(packed, "base64url").toString("utf8"); + const diagnostics = boundedDiagnostics(jsonValueAt(json, 0), FAILURES_LINE_BYTES); + if (Object.keys(diagnostics).length) return diagnostics; + } + for (const match of text.matchAll(failuresAt(DIAGNOSTIC_LABEL))) { + const record = jsonValueAt(text, match.index + match[0].length); + const diagnostics = boundedDiagnostics(record, FAILURES_LINE_BYTES); + if (Object.keys(diagnostics).length) return diagnostics; + } + return {}; +} + export const MACHINE_OUTCOMES = "machine-v2"; /** Encode the exact approved request and machine outcomes. The caller has already checked the actual checkout, cloud marker and origin. */ export function encodeOutcomes({ key, commit, host, repository, directory, lanes, probe = -1 }) { @@ -378,6 +481,8 @@ export function outcomeRecords(log, marker) { return records.filter((record) => !records.some((other) => other !== record && other.startsWith(record))); } export const ARTIFACT_MARKER = "VIBE_OUTCOME_ARTIFACT"; +export const PUBLICATION_MARKER = "VIBE_OUTCOME_PUBLICATION"; +export const MISSING_RESULT_BRANCH = "VIBE_RESULT_BRANCH_MISSING"; export function artifactPointer(log, request) { // A plain word the agent writes after the marker in prose ("VIBE_OUTCOME_ARTIFACT recorded") is not a second // pointer; anything else that is not one exact commit:sha256 pair still refuses. @@ -405,29 +510,51 @@ export function checkOutcomeArtifact(request) { ); } export const outcomeArtifact = (request) => request.resultArtifact?.kind === "validation-outcomes"; + +function inlineOutcome(log, context) { + // Exact width discards prose and clipped copies. The decoder still verifies the request identity and all lanes. + const size = 4 * Math.ceil((HEADER + LANE * (context?.names?.length ?? 0)) / 3); + const records = outcomeRecords(log, OUTCOMES_MARKER).filter((record) => record.length === size); + if (!records.length) return null; + if (records.length !== 1 || MARKER.length + records[0].length > LIMIT) fail("has conflicting or oversized inline evidence"); + return records[0]; +} + +/** A missing branch can use a complete inline outcome for this request. Other fetch and integrity errors still refuse. */ export function readOutcomeReport(log, request, context, artifactReader) { - let encoded, artifact; + let encoded, artifact, diagnostics; if (outcomeArtifact(request)) { artifact = artifactPointer(log, request); - const fetched = artifactReader(request, artifact); + let fetched; + try { + fetched = artifactReader(request, artifact); + } catch (error) { + if (error.code !== MISSING_RESULT_BRANCH) throw error; + encoded = outcomeTransportBytes(context.names.length) <= LIMIT ? inlineOutcome(log, context) : null; + if (encoded) return { ...decodeOutcomes(encoded, context), diagnostics: readDiagnosticLine(log, encoded) }; + const publication = String(log ?? "").match(new RegExp(`\\b${PUBLICATION_MARKER} (push-denied|push-failed|publication-failed)\\b`))?.[1]; + const reason = { + "push-denied": "the cloud session's Git push was denied", + "push-failed": "the cloud session's Git push failed or could not be verified", + "publication-failed": "the cloud session's reporter stopped while preparing the result branch", + }[publication] ?? (artifact.commit ? "the cloud session reported publication, but the result branch is now missing" + : "the cloud session returned no publication record. The publication step may have been skipped or interrupted"); + throw Object.assign(new Error(`cloud validation result branch ${artifact.branch} is missing: ${reason}. No complete inline outcome was returned.`), + { code: MISSING_RESULT_BRANCH }); + } const stored = fetched?.result; artifact = { ...artifact, commit: fetched?.commit ?? artifact.commit, sha256: fetched?.sha256 ?? artifact.sha256, }; - if (!stored || Object.keys(stored).sort().join() !== "encoded,version" || stored.version !== 1) + if (!stored || Object.keys(stored).some((key) => !["diagnostics", "encoded", "version"].includes(key)) || stored.version !== 1) fail("artifact is not an allowlisted versioned report"); encoded = stored.encoded; + diagnostics = boundedDiagnostics(stored.diagnostics); } else { - // Only a record of the exact encoded size this request's lanes produce is one: the agent's prose can follow the - // marker with a word ("VIBE_OUTCOMES_V1 emitted") or a cut copy, and neither is a second record. - const size = 4 * Math.ceil((HEADER + LANE * (context?.names?.length ?? 0)) / 3); - const records = outcomeRecords(log, MARKER.trim()).filter((record) => record.length === size); - if (!records.length) return null; - if (records.length !== 1 || MARKER.length + records[0].length > LIMIT) - fail("has conflicting or oversized inline evidence"); - encoded = records[0]; + encoded = inlineOutcome(log, context); + if (!encoded) return null; } - return { ...decodeOutcomes(encoded, context), ...(artifact ? { artifact } : {}) }; + return { ...decodeOutcomes(encoded, context), diagnostics: diagnostics ?? readDiagnosticLine(log, encoded), ...(artifact ? { artifact } : {}) }; } diff --git a/plugins/vibe-closedloop/lib/vibe/scripts/cloud-outcome-instruction.mjs b/plugins/vibe-closedloop/lib/vibe/scripts/cloud-outcome-instruction.mjs index 606cb4cf..a27f4379 100644 --- a/plugins/vibe-closedloop/lib/vibe/scripts/cloud-outcome-instruction.mjs +++ b/plugins/vibe-closedloop/lib/vibe/scripts/cloud-outcome-instruction.mjs @@ -5,7 +5,7 @@ import { readFileSync } from "node:fs"; import os from "node:os"; import path from "node:path"; import { pluginInstall, pluginMarketplace } from "../../../shared/plugin-roots.mjs"; -import { FAILURES_LABEL, LANE_FAILURES_LABEL, outcomeArtifact, requireOutcomeCapacity } from "./cloud-outcome-artifact.mjs"; +import { DIAGNOSTIC_LABEL, FAILURES_LABEL, LANE_FAILURES_LABEL, PUBLICATION_MARKER, outcomeArtifact, requireOutcomeCapacity } from "./cloud-outcome-artifact.mjs"; import { TOOL_REPO, validTool } from "./cloud-validation-environment.mjs"; import { toolingRoot } from "./cloud-validation-recipes.mjs"; @@ -15,6 +15,7 @@ const SHA = /^[a-f0-9]{40}$/; export const reporterFiles = Object.freeze([ "captured-json.mjs", "github-remote.mjs", + "cloud-redaction.mjs", "cloud-outcome-artifact.mjs", "cloud-outcome-writer.mjs", ]); @@ -102,24 +103,23 @@ function portableReporter(spec) { return {install:"node -e '"+install+"' "+dir+" "+sha+" "+encoded,reporter:"node "+dir+"/cloud-outcome-writer.mjs "+packed+' "$d"'}; } -/** - * The capability probe's failed checks, and a managed lane's failed Chromium preflight, reach the lane result only - * through the run log: the record is fixed-width and the outcomes JSON carries no lane output, so the reporter prints - * the redacted failures line after its record and the final message keeps it. - */ -const copyFailures = (label) => `When the reporter's output has a ${label} line after its first line, copy that line exactly as the last line of your final message, after the result line; it is the only line allowed there and counts toward the 1,800 characters.`; +/** Capability probe and Chromium preflight failures reach the run log as the last line. */ +const copyFinalFailures = (label) => `When the reporter's output has a ${label} line after its first line, copy that line exactly as the last line of your final message, directly after the complete result line. It counts toward the 1,800 characters.`; /** Install the shipped reporter into Git's private state, including application checkouts without Vibe source. */ export function outcomeInstruction(request, lanes, key, managedHost, compact = null) { const artifact = outcomeArtifact(request) ? request.resultArtifact : null; requireOutcomeCapacity(lanes, artifact); + const failures = [ + `Copy the reporter's complete result line, including any ${DIAGNOSTIC_LABEL} or ${PUBLICATION_MARKER} suffix. This line is required in your final message and counts toward the 1,800 characters.`, + ]; // The managed host's failed Chromium preflight reaches the lane result the same way (session cse_0197q288AogeAdHPSVDTnXAd had empty tails). - const failures = lanes.some((lane) => lane.capabilityProbe) ? [copyFailures(FAILURES_LABEL)] - : managedHost && !compact ? [copyFailures(LANE_FAILURES_LABEL)] : []; + if (lanes.some((lane) => lane.capabilityProbe)) failures.push(copyFinalFailures(FAILURES_LABEL)); + else if (managedHost && !compact) failures.push(copyFinalFailures(LANE_FAILURES_LABEL)); if (managedHost && !compact) return [ - 'The machine record replaces the archival VIBE_VALIDATION_RESULT carrier. Keep the private lane JSON fields "tail" and "diagnosis" with bounded redacted output for failures. Never place these in an outcome artifact.', + 'The machine record replaces the archival VIBE_VALIDATION_RESULT carrier. Keep the private lane JSON fields "tail" and "diagnosis" with bounded redacted output for failures. The reporter alone selects and redacts diagnostic excerpts for the outcome.', artifact - ? "The managed runner runs the shipped reporter itself after its lanes. It publishes the typed outcomes JSON as one child commit on the authorized fresh result branch, and its first output line is the verified result pointer. Do not run a reporter yourself; report that line." + ? `The managed runner runs the shipped reporter itself after its lanes. It pushes and verifies the authorized result branch. Read the verified result pointer or the ${PUBLICATION_MARKER} refusal or fallback from its output before you finish. Do not run a reporter yourself.` : "The managed runner runs the shipped reporter itself after its lanes, and its first output line is the bounded machine record. Do not run a reporter yourself; keep that line in the run log by reading the runner's output.", ...failures, ].join("\n\n"); @@ -128,10 +128,10 @@ export function outcomeInstruction(request, lanes, key, managedHost, compact = n const reporter=compact ?? (commit ? fetchedReporter(spec(), commit) : portableReporter(spec())); // A workflow brief's runner writes every lane record itself (cloud-workflow-brief.mjs), so the agent is told to write none. const records = compact ? [ - "The machine record replaces the archival VIBE_VALIDATION_RESULT carrier. Never place private lane evidence in an outcome artifact.", + "The machine record replaces the archival VIBE_VALIDATION_RESULT carrier. Only the shipped reporter may put redacted diagnostic excerpts in an outcome artifact.", "Keep the results directory d you created before the first lane. Do not show its contents.", ] : [ - 'The machine record replaces the archival VIBE_VALIDATION_RESULT carrier. Keep the private lane JSON fields "tail" and "diagnosis" with bounded redacted output for failures. Never place these in an outcome artifact.', + 'The machine record replaces the archival VIBE_VALIDATION_RESULT carrier. Keep the private lane JSON fields "tail" and "diagnosis" with bounded redacted output for failures. The reporter alone selects and redacts diagnostic excerpts for the outcome.', "Save both full streams outside the checkout. Use the directory printed by the managed host, or create the direct lane directory with mktemp -d /tmp/vibe-lane-results-XXXXXX. Set d to its absolute path. Do not show its contents.", "For each direct lane, redirect stdout and stderr into $d/.stdout and .stderr. Record the actual foreground exit in $d/.json as JSON with the exact lane name and numeric exitCode (or null and notRun when it never executed). The managed host already writes these. A preflight that ran no lane can have empty channel files only alongside its recorded nonzero preflight or notRun outcome.", ]; @@ -142,7 +142,7 @@ export function outcomeInstruction(request, lanes, key, managedHost, compact = n reporter.reporter, ...(artifact ? [ - "The reporter will publish only the typed outcomes JSON, as one child commit on the explicitly authorized fresh result branch. Its first output line is the complete verified result pointer. It refuses a previously existing result branch.", + `Run the reporter command above before writing a summary. This command builds, pushes and verifies the result-only child commit on the authorized fresh branch. Wait for its output, including when lanes fail. Copy its verified result pointer or its ${PUBLICATION_MARKER} refusal or fallback. If Bash denies the reporter call, report that denial verbatim.`, ] : []), ...failures, @@ -167,5 +167,5 @@ export const LANE_DISCIPLINE = "and never infer one from the output. A lane that never finished, or whose exit code you could not read, is reported " + 'with "exitCode": null and "notRun": the reason. Print the result line only after every lane has finished. In the private session evidence, ' + "list every failing test of each failed lane by name, as its runner printed it. Your " + - "final message is the result line alone, under 1,800 characters: the run log keeps only the first 2,000 characters of a " + + "final message keeps the result line and any reporter-directed diagnostic lines under 1,800 characters: the run log keeps only the first 2,000 characters of a " + "message. Keep detailed lane evidence in its private files; do not shorten or drop tails to fit."; diff --git a/plugins/vibe-closedloop/lib/vibe/scripts/cloud-outcome-writer.mjs b/plugins/vibe-closedloop/lib/vibe/scripts/cloud-outcome-writer.mjs index 0f3b8d1c..2010fa8b 100644 --- a/plugins/vibe-closedloop/lib/vibe/scripts/cloud-outcome-writer.mjs +++ b/plugins/vibe-closedloop/lib/vibe/scripts/cloud-outcome-writer.mjs @@ -20,7 +20,12 @@ import { pathToFileURL } from "node:url"; import { execFileSync } from "node:child_process"; import { githubRepository } from "./github-remote.mjs"; import { + boundedDiagnostic, + boundedDiagnostics, checkOutcomeArtifact, + diagnosticSecrets, + diagnosticLine, + DIAGNOSTIC_BYTES, encodeOutcomes, FAILURES_LABEL, laneFailureLine, @@ -29,6 +34,8 @@ import { outcomeLine, requireOutcomeCapacity, ARTIFACT_MARKER, + OUTCOME_LOG_LIMIT, + PUBLICATION_MARKER, } from "./cloud-outcome-artifact.mjs"; const deny = (message) => { @@ -47,11 +54,35 @@ function gitOutput(args, input, cwd) { stdio: [input === undefined ? "ignore" : "pipe", "pipe", "pipe"], timeout: 30000, }); - } catch { + } catch (error) { + if (args[0] === "push") { + // Classify the push without returning Git output, which can contain credential-bearing URLs. + const denied = /permission.*denied|access denied|not (?:authorized|allowed)|authentication failed|write access.*not granted|error: (?:403|401)\b|returned error: (?:403|401)\b/i + .test(error.stderr ?? ""); + throw Object.assign(new Error("cloud outcome writer: git push failed; inspect the provider session privately"), + { publication: denied ? "push-denied" : "push-failed" }); + } deny("git " + args.find((arg) => !arg.includes("=") && arg !== "-c") + " failed; inspect the provider session privately"); } } -function checkedStream(file, probe, commit, frozenLane) { +// Keep runner failure names and pytest's count summary even when workflow steps print a postamble. +const NAMED_FAILURE = /^(?:not ok \d+ - |[✖×]\s+(?!\d+\b)|FAIL(?:ED)?\s+|ERROR\s+)/u; +const PYTEST_SUMMARY = /^=+\s+.*\b\d+\s+(?:failed|errors?)\b.*\s+=+$/u; +const WORKFLOW_STATUS = /^CLOUD_WORKFLOW_(?:STEP|LANE) /u; + +/** Prefer recognized failures. Otherwise keep as many of the latest output lines as the channel can hold. */ +function streamDiagnostic(named, summary, tail) { + if (named.length || summary) return boundedDiagnostic([summary, ...named].filter(Boolean).join("\n")); + let excerpt = ""; + for (const line of tail.reverse()) { + const candidate = excerpt ? `${line}\n${excerpt}` : line; + if (Buffer.byteLength(candidate) > DIAGNOSTIC_BYTES) break; + excerpt = candidate; + } + return excerpt; +} + +function checkedStream(file, probe, commit, frozenLane, secrets = null) { const fd = openSync(file, constants.O_RDONLY | constants.O_NOFOLLOW), sum = createHash("sha256"), buffer = Buffer.alloc(65536); @@ -60,8 +91,18 @@ function checkedStream(file, probe, commit, frozenLane) { discard = false, frozen; const evidence={}; - let failures = ""; + let failures = "", summary = ""; + const named = [], tail = []; function consume(final) { + if (secrets) { + const clean = discard ? "[output line exceeded the diagnostic limit]" : boundedDiagnostic(Buffer.from(final, "latin1").toString("utf8"), secrets).trim(); + if (PYTEST_SUMMARY.test(clean)) summary = clean; + else if (clean && !WORKFLOW_STATUS.test(clean)) { + const kept = NAMED_FAILURE.test(clean) ? named : tail; + kept.push(clean); + if (kept.length > 4) kept.shift(); + } + } if (discard) return; if (frozenLane) { const match = /^FROZEN PASS (\d+) files (\d+) stories inputs ([0-9a-f]{16})$/.exec(final); @@ -94,7 +135,7 @@ function checkedStream(file, probe, commit, frozenLane) { const data = buffer.subarray(0, n); sum.update(data); bytes += n; - if (probe || frozenLane) + if (probe || frozenLane || secrets) for (const part of data.toString("latin1").split(/(\n)/)) { if (part === "\n") { consume(line); @@ -108,7 +149,7 @@ function checkedStream(file, probe, commit, frozenLane) { } } } - if (probe || frozenLane) consume(line); + if (probe || frozenLane || secrets) consume(line); } finally { closeSync(fd); } @@ -116,11 +157,16 @@ function checkedStream(file, probe, commit, frozenLane) { stream: { file, bytes, sha256: sum.digest("hex") }, ...(frozen ? { frozen } : {}), ...(failures ? { failures } : {}), + ...(secrets ? { diagnostic: streamDiagnostic(named, summary, tail) } : {}), ...evidence, }; } /** Pin the pnpm wrapper's combined output with an owned hard link before hashing the actual bytes. */ export function retainedContainerStream(directory,index,status) { + return retainedContainerOutput(directory, index, status).stream; +} + +function retainedContainerOutput(directory,index,status,secrets) { const fd=openSync(path.join(directory,index+".stdout"),constants.O_RDONLY|constants.O_NOFOLLOW); let summary; try{ @@ -137,14 +183,10 @@ export function retainedContainerStream(directory,index,status) { try{linkSync(file,target)}catch(error){if(error.code!=="EEXIST")throw error} const linked=lstatSync(target); if(!linked.isFile() || linked.dev!==source.dev || linked.ino!==source.ino) deny("combined output identity changed"); - return checkedStream(target,false).stream; + return checkedStream(target,false,undefined,false,secrets); } -/** - * Consume only fixed private stream filenames. Raw bytes and diagnostics never enter the publication document: the - * record is fixed-width, and the probe's own bounded failures line, or a failed Chromium preflight's redacted last - * lines, is returned beside it for the reporter's output only. - */ +/** Read only fixed private stream files and carry bounded, redacted diagnostics from failed lanes. */ export function machineOutcomes(spec, directory) { let failures = ""; if ( @@ -165,6 +207,8 @@ export function machineOutcomes(spec, directory) { deny("stream directory permissions or owner differ"); requireOutcomeCapacity(spec.names.length, spec.artifact); const records = []; + const diagnostics = {}; + const secrets = diagnosticSecrets(); const lanes = spec.names.map((name, index) => { const file = path.join(directory, index + ".json"), fd = openSync(file, constants.O_RDONLY | constants.O_NOFOLLOW); @@ -180,27 +224,35 @@ export function machineOutcomes(spec, directory) { deny("actual lane name or missing status differs"); records.push(rec); const evidence = { exitCode: rec.exitCode, diagnosis: rec.diagnosis, privateStreams: {} }; + const capture = Number.isInteger(rec.exitCode) && rec.exitCode !== 0 && index !== spec.probe ? secrets : null; + const tails = {}; for (const ch of ["stdout", "stderr"]) { const read = checkedStream( path.join(directory, index + "." + ch), ch === "stdout" && index === spec.probe, spec.commit, spec.frozen?.includes(index), + capture, ); if (read.frozen) evidence.frozen = read.frozen; - if (read.failures) failures = probeFailureLine(read.failures); + if (read.failures) failures = probeFailureLine(read.failures, { redact: (value) => boundedDiagnostic(value, secrets) }); evidence.privateStreams[ch] = read.stream; + tails[ch] = read.diagnostic ?? ""; if (read.checks) evidence.checks = read.checks; if (read.capabilities) evidence.capabilities = read.capabilities; } - if(spec.combined?.includes(index) && rec.exitCode!==null) evidence.privateStreams.stdout=retainedContainerStream(directory,index,rec.exitCode); + if (spec.combined?.includes(index) && rec.exitCode !== null) { + const retained = retainedContainerOutput(directory, index, rec.exitCode, capture); + evidence.privateStreams.stdout = retained.stream; + tails.stdout = retained.diagnostic ?? ""; + } + if (tails.stdout || tails.stderr) diagnostics["lane" + index] = [tails.stdout, tails.stderr]; if (spec.frozen?.includes(index) && rec.exitCode === 0 && evidence.frozen?.verdict !== 1) deny("missing successful frozen verdict"); return evidence; }); - // One line follows the record, within the final message's 1,800 characters: the probe runs alone, never on the - // managed host that writes a failed Chromium preflight. - return { encoded: encodeOutcomes({ ...spec, directory: "/tmp/" + path.basename(directory), host: hostname(), lanes }), failures: failures || laneFailureLine(records) }; + return { encoded: encodeOutcomes({ ...spec, directory: "/tmp/" + path.basename(directory), host: hostname(), lanes }), + failures: failures || laneFailureLine(records), diagnostics: boundedDiagnostics(diagnostics) }; } /** * A new bare repository with no hooks installed (`--template=` copies none) that reads the checkout's objects through @@ -230,13 +282,14 @@ function hookFreeRepository() { * the checkout's own push URL, so no hook of the checkout runs and none is bypassed. The checkout's HEAD, index, * working tree and object store stay as they were. */ -export function publishOutcomes(artifact, parent, encoded) { +export function publishOutcomes(artifact, parent, encoded, diagnostics) { if(artifact?.kind !== "validation-outcomes") deny("expected typed result artifact"); checkOutcomeArtifact({ resultArtifact: artifact }); const ref = "refs/heads/" + artifact.branch; if (git("ls-remote", "--refs", "origin", ref)) deny("result reference already exists; authorize a new proof ref"); - const bytes = JSON.stringify({ version: 1, encoded }) + "\n", + const safe = boundedDiagnostics(diagnostics); + const bytes = JSON.stringify({ version: 1, encoded, ...(Object.keys(safe).length ? { diagnostics: safe } : {}) }) + "\n", hash = createHash("sha256").update(bytes).digest("hex"); const url = git("remote", "get-url", "--push", "origin"); const publisher = hookFreeRepository(); @@ -255,9 +308,9 @@ export function publishOutcomes(artifact, parent, encoded) { git("status", "--porcelain") ) deny("unexpected outcome parent, tree or status"); - const push = at("push", "--porcelain", url, child + ":" + ref); - if (!push.includes("[new branch]") || git("ls-remote", "--refs", "origin", ref).split(/\s+/)[0] !== child) - deny("result reference was not newly published at the outcome commit"); + at("push", "--porcelain", "--force-with-lease=" + ref + ":", url, child + ":" + ref); + if (git("ls-remote", "--refs", "origin", ref).split(/\s+/)[0] !== child) + throw Object.assign(new Error("cloud outcome writer: result reference was not verified at the outcome commit"), { publication: "push-failed" }); return ARTIFACT_MARKER + " " + child + ":" + hash; } finally { rmSync(publisher, { recursive: true, force: true }); @@ -267,10 +320,25 @@ export function publishOutcomes(artifact, parent, encoded) { if (process.argv[1] && import.meta.url === pathToFileURL(process.argv[1]).href) { try { const spec = JSON.parse(Buffer.from(process.argv[2], "base64url").toString("utf8")); - const { encoded, failures } = machineOutcomes(spec, process.argv[3]); - const line = spec.artifact ? publishOutcomes(spec.artifact, spec.commit, encoded) : outcomeLine(encoded); - // The record first: the condensed run log keeps only the start of a tool result. - process.stdout.write(line + "\n" + (failures ? failures + "\n" : "")); + const { encoded, failures, diagnostics } = machineOutcomes(spec, process.argv[3]); + let line = outcomeLine(encoded); + let publication = ""; + if (spec.artifact) { + try { line = publishOutcomes(spec.artifact, spec.commit, encoded, diagnostics); } + catch (error) { + publication = `${PUBLICATION_MARKER} ${error.publication ?? "publication-failed"}`; + } + } + if (publication && line.length > OUTCOME_LOG_LIMIT) { + process.stdout.write(publication + "\n"); + process.exitCode = 1; + } else { + const budget = 1750 - Buffer.byteLength([line, failures, publication].join(" ")); + const detail = (!spec.artifact || publication) && diagnosticLine(diagnostics, budget, { attached: true }); + // Keep ordinary lane excerpts on the required result line. Probe and preflight failures keep their existing line. + const record = [line, detail, publication].filter(Boolean).join(" "); + process.stdout.write([record, failures].filter(Boolean).join("\n") + "\n"); + } } catch (e) { process.stderr.write( (String(e.message).startsWith("cloud outcome writer:") || diff --git a/plugins/vibe-closedloop/lib/vibe/scripts/cloud-redaction.mjs b/plugins/vibe-closedloop/lib/vibe/scripts/cloud-redaction.mjs new file mode 100644 index 00000000..be691834 --- /dev/null +++ b/plugins/vibe-closedloop/lib/vibe/scripts/cloud-redaction.mjs @@ -0,0 +1,40 @@ +/** + * `text` with each URL's userinfo (a credential) replaced by ``, through the authority's last `@`, and the + * same for a schemeless `user:password@host` such as a proxy set without a scheme. A password may hold `#`, `?`, `@` + * or a slash, so a path with an `@` after a port may go too. + */ +export function redactUserinfo(text) { + return String(text).replace(/\S+/g, (word) => throughLastAt(word, /(:\/\/)(?:[^/:@]+:.*|[^/]+)@/gis)) + .replace(/[^\s"']+/g, (part) => throughLastAt(part, /(^|[=(<,;])[^/@=(<,;:]+:(?!\/\/).*@/s, /[/?#@]/)); +} + +/** `word` with what `pattern` finds up to its last `@` (one not followed by a `not` character) redacted, in time linear in the word. */ +function throughLastAt(word, pattern, not = /[]/) { + let end = word.length + 1; + do end = word.lastIndexOf("@", end - 2) + 1; while (end > 1 && not.test(word[end] ?? "")); + return word.slice(0, end).replace(pattern, "$1@") + word.slice(end); +} + +const SECRET_VALUE = /(?`. A secret-named value that holds an `@` goes + * first and keeps one, so no part of it is left as a host and a URL around it is still read as one; `afterAt` leaves an + * unquoted one's rest to the rules below. A URL's own user name is left to the URL rule. Other values wait for the + * bearer pass, which needs the word before the token. + */ +export function redactSecrets(text) { + return redactUserinfo(String(text ?? "").replace(SECRET_VALUE, (all, key, sep, value, at, whole) => value.includes("@") && whole.slice(at - 3, at) !== "://" ? `${key}${sep}@${/^\\*["']/.test(value) ? "" : afterAt(value)}` : all).replace(/\S+/g, (word) => throughLastAt(word, /(:\/\/)[^/:@]+:.*@/is))) + .replace(/\b((?:set-)?cookie["']?\s*[:=]).*/gi, "$1 ") + .replace(/\b(Bearer|Basic|token)\s+[A-Za-z0-9._~+/=-]{8,}/gi, "$1 ") + .replace(/\b(?:gh[pousr]_[A-Za-z0-9]{16,}|github_pat_[A-Za-z0-9_]{16,}|sk-[A-Za-z0-9_-]{16,}|xox[abprs]-[A-Za-z0-9-]{10,}|npm_[A-Za-z0-9]{8,}|glpat-[\w-]{8,}|AKIA[A-Z0-9]{16})\b|(?") + .replace(/(?") + .replace(SECRET_VALUE, "$1$2"); +} diff --git a/plugins/vibe-closedloop/lib/vibe/scripts/cloud-routines.mjs b/plugins/vibe-closedloop/lib/vibe/scripts/cloud-routines.mjs index fcb0ca8c..4b43f8a9 100644 --- a/plugins/vibe-closedloop/lib/vibe/scripts/cloud-routines.mjs +++ b/plugins/vibe-closedloop/lib/vibe/scripts/cloud-routines.mjs @@ -48,6 +48,18 @@ const KEEP_RUNS = 200; */ const ROUTINE_RUNS_PER_HOUR = 30; const RATE_LIMITED = 429; +const LAUNCH_LIMIT = /temporarily limiting requests|rate[ _-]?limit(?:ed| exceeded)?|(?:concurren\w*|capacity) (?:limit|full|reached|exceeded)|too many (?:requests|(?:concurrent |active )?(?:runs|sessions|tasks))/i; + +function isLaunchLimit(error) { + return !error.launchUncertain && !["CLOUD_CALL_TIMEOUT", "CLOUD_RUN_NOT_CREATED"].includes(error.code) + && (error.httpStatus === undefined || [400, 403, 409, 429, 503, 529].includes(error.httpStatus)) + && LAUNCH_LIMIT.test(error.providerMessage || error.message); +} + +function noteLaunchRefusal(error) { + if (error.httpStatus === RATE_LIMITED || isLaunchLimit(error)) error.validationLaunchRefusal = error.providerMessage || error.message; + return error; +} const ROUTINE_ID = /^[\w-]+$/; const RECEIPT_BYTES = 1024 * 1024; const LOCK_POLL_MS = 1000; @@ -196,6 +208,7 @@ function createStanding(ledger, { home, remote, ccr, environment, refusal }) { writeLedger(home, ledger); } if (notSent && attempt < CREATE_ATTEMPTS) continue; + if (error.httpStatus === RATE_LIMITED) throw noteLaunchRefusal(error); throw refusal ? refusal(error) : error; } } @@ -270,15 +283,20 @@ export async function runOnStanding({ remote, home = os.homedir(), environment, const launch = beforeRun ? {launchToken:randomUUID(), startedAt:new Date().toISOString(),...binding} : null; if (launch) brief = brief.replace(/^[^\n]*/, opening => opening + "\nRecord this exact line at the start of the run log:\nVIBE_VALIDATION_LAUNCH " + launch.launchToken); + const updateStanding = () => { + const body = updateBody(ccr, brief, connectorsFor(standing)); + try { return remote("update", { trigger_id: standing.id, body }); } + catch (error) { throw noteLaunchRefusal(error); } + }; let updated; - try { updated = remote("update", { trigger_id: standing.id, body: updateBody(ccr, brief, connectorsFor(standing)) }); } + try { updated = updateStanding(); } catch (error) { if (error?.httpStatus !== 404) throw error; // The standing routine is gone from the account: that is its proof of removal; make a new one. ledger.removed.push({ id: standing.id, provedAt: new Date().toISOString() }); ledger.standing = null; standing = createStanding(ledger, { home, remote, ccr, environment, refusal }); - updated = remote("update", { trigger_id: standing.id, body: updateBody(ccr, brief, connectorsFor(standing)) }); + updated = updateStanding(); } confirmConnectors(updated, allowlist); await beforeRun?.({...launch,routineId:standing.id}); @@ -286,6 +304,8 @@ export async function runOnStanding({ remote, home = os.homedir(), environment, try { started = remote("run", { trigger_id: standing.id }); } catch (error) { if (error.httpStatus === RATE_LIMITED) throw hourlyLimit(error); + // A recognizable provider refusal proves no run was accepted. An ambiguous transport failure still needs recovery. + if (isLaunchLimit(error)) throw noteLaunchRefusal(error); if (![400,401,403,404].includes(error.httpStatus)) error.launchUncertain = true; throw error; } @@ -580,5 +600,5 @@ export async function adoptStanding({ home = os.homedir(), remote, id, waitMs = /** Claude refused the run as rate-limited, so no run started: name the documented cap and when to retry. */ function hourlyLimit(cause) { - return Object.assign(new Error(`CLOUD_ROUTINE_HOURLY_LIMIT: Claude refused the run as rate-limited (HTTP ${RATE_LIMITED}). A routine may start ${ROUTINE_RUNS_PER_HOUR} runs an hour (https://code.claude.com/docs/en/routines, "Usage and limits"); no run started. Retry the same request after the hour's oldest run ages out`), { code: "CLOUD_ROUTINE_HOURLY_LIMIT", cause }); + return Object.assign(new Error(`CLOUD_ROUTINE_HOURLY_LIMIT: Claude refused the run as rate-limited (HTTP ${RATE_LIMITED}). A routine may start ${ROUTINE_RUNS_PER_HOUR} runs an hour (https://code.claude.com/docs/en/routines, "Usage and limits"); no run started. Retry the same request after the hour's oldest run ages out`), { code: "CLOUD_ROUTINE_HOURLY_LIMIT", validationLaunchRefusal: cause.providerMessage || cause.message, cause }); } diff --git a/plugins/vibe-closedloop/lib/vibe/scripts/cloud-validation-admission.mjs b/plugins/vibe-closedloop/lib/vibe/scripts/cloud-validation-admission.mjs index b2d279ed..6e54378f 100644 --- a/plugins/vibe-closedloop/lib/vibe/scripts/cloud-validation-admission.mjs +++ b/plugins/vibe-closedloop/lib/vibe/scripts/cloud-validation-admission.mjs @@ -6,15 +6,8 @@ import { processIdentityStatus, readProcessIdentity } from "../../../shared/proc import { acquire, release } from "./e2e-lock.mjs"; import { regularJson, writeAtomic } from "./owned-state.mjs"; -// Validations one account runs at once. Measured 2026-12-02 on the pinned environment: seven Sonnet sessions ran at -// once and none was refused (cse_01H58iagixaiYxaLKWAi8tzq, cse_01H58iaebWoaUBxK7wprDhCH, cse_01H58iafVjKHHNew73tsYcEJ, -// cse_01H58iacg8JfytzdBfyQvmfx, cse_01H58iah25UcRZLU85icXi5s, cse_01H58iagK5PXKJM6UC7ES1Zr, cse_01H58iagWGazkKdUCDGCUQEh). -// Seven is the most tried, a lower bound, not a ceiling: https://code.claude.com/docs/en/routines ("Usage and limits") -// names an account limit on tasks running at the same time without a number. Launches still pass one at a time through -// the standing routine's lock and its hourly run limit (cloud-routines.mjs ROUTINE_RUNS_PER_HOUR). -export const CLOUD_VALIDATION_CAPACITY = 7; // An accepted run logs its launch marker within minutes. Past this window a launch whose launcher is gone, that no -// provider run acknowledged and that every provider read proved absent is reclaimed, so the queue never waits on it forever. +// provider run acknowledged and that every provider read proved absent is reclaimed, so the same request can launch again. export const LAUNCH_WINDOW_MS = 10 * 60 * 1000; const BUSY = "CLOUD_VALIDATION_QUEUE_TIMEOUT"; // The lock wait every queue change gets at least, so a request past its deadline still leaves the queue. @@ -23,11 +16,26 @@ const TERMINAL = new Set(["completed", "failed", "canceled", "cancelled", "archi // Recovery's answers when the provider proves nothing: every read succeeded, or a read threw. const UNPROVEN = new Set(["unknown", "unreadable"]); -function identityKey(account) { - return createHash("sha256").update(account).digest("hex"); +function queuesDir(home) { return path.join(home, ".codex", "vibe", "cloud", "validation-queues"); } + +/** Find stored reservations from releases that assigned distinct requests to shared account slots. */ +function reservationFiles(home) { + const queues = queuesDir(home); + return (existsSync(queues) ? readdirSync(queues) : []).map((name) => path.join(queues, name, "queue.json")); } -function queuesDir(home) { return path.join(home, ".codex", "vibe", "cloud", "validation-queues"); } +function reservationFile(home, key, receipt) { + const digest = createHash("sha256").update(key).update("\0").update(receipt).digest("hex"); + const current = path.join(queuesDir(home), `request-${digest}`, "queue.json"); + if (existsSync(current)) return current; + return reservationFiles(home).find((file) => { + if (path.basename(path.dirname(file)).startsWith("request-")) return false; + try { + const { active } = readQueue(file); + return active?.key === key && active.receipt === receipt; + } catch { return false; } + }) ?? current; +} function readQueue(file) { if (!existsSync(file)) return { version: 1, active: null, queued: [], abandoned: [] }; @@ -64,31 +72,15 @@ function abandonedRecord(entry, reason) { return { key: entry.key, reason, ...(entry.launch?.sessionId ? { sessionId: entry.launch.sessionId } : {}) }; } -/** Serialize local admission state for one pinned Claude account and preserve an interrupted running reservation. */ -export async function withCloudValidationAdmission({ home, account, key, receipt, metadata, timeoutMs, signal, recover, now = Date.now, +/** Reserve only this exact request and preserve its interrupted launch for recovery or abandon. */ +export async function withCloudValidationAdmission({ home, key, receipt, metadata, timeoutMs, signal, recover, now = Date.now, wait = (ms, currentSignal) => delay(ms, undefined, { signal: currentSignal }), sleepMs = 500, - drainUnbound = false, report = (line) => process.stderr.write(`${line}\n`), identityOf = readProcessIdentity, launchWindowMs = LAUNCH_WINDOW_MS, - capacity = CLOUD_VALIDATION_CAPACITY, + identityOf = readProcessIdentity, launchWindowMs = LAUNCH_WINDOW_MS, }, action) { - const queues = queuesDir(home); - // The first verified pin must wait for any earlier unbound provider run, including an interrupted launch. - if (!drainUnbound && account !== "unbound-validation" && existsSync(path.join(queues,identityKey("unbound-validation"),"queue.json"))) { - await withCloudValidationAdmission({home, account:"unbound-validation", key:"drain:"+account+":"+key, receipt, metadata, - timeoutMs,signal,recover,now,wait,sleepMs,report,identityOf,launchWindowMs,drainUnbound:true},async()=>{}); - } - // Each slot is its own one-run queue; slot 0 keeps the account's original queue file. Unbound runs keep one slot. - const slots = Array.from({ length: account === "unbound-validation" ? 1 : Math.max(1, capacity) }, - (_, slot) => path.join(queues, identityKey(slot === 0 ? account : `${account}#${slot}`), "queue.json")); - const load = (candidate) => { - const state = readQueue(candidate); - return state.active?.key === key || state.queued.some((entry) => entry.key === key) ? -1 : (state.active ? 1 : 0) + state.queued.length; - }; - // The slot already holding this request, else the least loaded, the lowest first. - let file = slots.reduce((best, candidate) => load(candidate) < load(best) ? candidate : best); + const file = reservationFile(home, key, receipt); const owner = { token: randomUUID(), pid: process.pid, identity: identityOf(process.pid), key, receipt, metadata }; const deadline = now() + timeoutMs; if (!owner.identity) throw new Error("cloud validation could not determine its exact queue process identity"); - report(`CLOUD_VALIDATION_CAPACITY ${slots.length}: at most ${slots.length} active validation${slots.length === 1 ? "" : "s"} per account; excess requests wait in order`); const alive = (entry) => launcherAlive(entry, identityOf); let selected = false; // Waiting, a change waits up to the request's own deadline; admitted, it may be past that deadline after a long run, @@ -127,11 +119,11 @@ export async function withCloudValidationAdmission({ home, account, key, receipt const disposition = active.phase === "reserved" ? "terminal" : await recover(active); const launch = active.phase === "launching"; const recorded = existsSync(active.receipt) ? regularJson(active.receipt) : null; - // A run the provider acknowledged, or a receipt, holds the account until the provider ends it, however old. + // An acknowledged run keeps its request reservation until the provider ends it, however old. // Only a launch with neither, past its window, whose every provider read proved nothing, is reclaimed. const reclaim = launch && !active.launch?.runId && recorded === null && disposition === "unknown" && !(now() - Date.parse(active.launchingAt ?? active.launch?.startedAt) < launchWindowMs); - const identical = !drainUnbound && active.key === key && active.receipt === receipt; + const identical = active.key === key && active.receipt === receipt; // The identical request adopts the run its receipt names, active or launched but not yet listed or readable. const resume = identical && recorded?.status !== "abandoned" && (disposition === "active" || (launch && UNPROVEN.has(disposition) && recorded !== null)); @@ -148,15 +140,7 @@ export async function withCloudValidationAdmission({ home, account, key, receipt }); } if (selected) break; - // A slot that is free with nobody waiting takes this request rather than leaving it behind a long run. - const free = slots.find((candidate) => candidate !== file && load(candidate) === 0); - if (free && active?.token !== owner.token) { - await update((state) => { state.queued = state.queued.filter((entry) => entry.token !== owner.token); }); - file = free; - await update((state) => { state.queued.push(owner); }); - continue; - } - if (now() >= deadline) throw Object.assign(new Error(`${BUSY}: this request did not launch before its queue deadline; every validation slot stayed taken. Retry the same request after one settles`), { code: BUSY }); + if (now() >= deadline) throw Object.assign(new Error(`${BUSY}: this request did not launch before its recovery deadline. Retry the same request to resume its reservation`), { code: BUSY }); await wait(Math.min(sleepMs, Math.max(1, deadline - now())), signal); } // Called before the provider run with its launch nonce, and again with the run and session ids the moment it is acknowledged. @@ -168,7 +152,14 @@ export async function withCloudValidationAdmission({ home, account, key, receipt if (requirements?.outcomeTransport) state.active.metadata={...state.active.metadata,outcomeTransport:requirements.outcomeTransport}; if (requirements?.managedHost === true) state.active.metadata = {...state.active.metadata,managedHost:true}; }); - return await action({ launching }); + // An explicit provider refusal proves this attempt did not start a run. Drop its nonce before waiting to retry. + const launchRefused = () => update((state) => { + if (state.active?.token !== owner.token) throw new Error("cloud validation admission no longer belongs to this request"); + state.active.phase = "reserved"; + delete state.active.launch; + delete state.active.launchingAt; + }); + return await action({ launching, launchRefused }); } catch (error) { unresolved = error?.launchUncertain || ["CLOUD_CALL_TIMEOUT", "CLOUD_RUN_NOT_CREATED"].includes(error?.code); throw error; @@ -176,9 +167,8 @@ export async function withCloudValidationAdmission({ home, account, key, receipt await update((state) => { state.queued = state.queued.filter((entry) => entry.token !== owner.token); if (state.active?.token !== owner.token) return; - if (drainUnbound) { state.active = null; return; } const latest = existsSync(receipt) ? regularJson(receipt) : null; - // A request that never launched and still finds the receipt abandoned leaves the account free; one that launched, + // A request that never launched and still finds the receipt abandoned releases the request; one that launched, // or polled a run whose receipt was abandoned during its poll, holds until the provider ends that run. const refused = abandonedBefore && state.active.phase === "reserved" && latest?.status === "abandoned"; if (latest && !TERMINAL.has(latest.status) && !refused) Object.assign(state.active, { phase: "running", pid: null, identity: null }); @@ -196,18 +186,23 @@ function entryView(entry) { } /** - * Abandon's one release step for a request, with or without its receipt: the request's queue reservation, found by its - * request key in any account's queue, is released once its launcher is gone. A launcher that is still alive keeps it: + * Abandon releases the exact request's reservation once its launcher is gone, including an unambiguous receipt-less + * launch from before an account pin. A launcher that is still alive keeps it: * without a receipt abandon refuses, and with one abandon still marks the receipt. `receipt` is null when the launch * wrote none, else `{ plan, write, runId }`: the dry run's receipt change, its synchronous write, done under the queue * lock so no resume or release interleaves, and the run id it ends (null for a terminal receipt). Without confirm it * reports the plan and changes nothing. Every run this abandon ends is marked abandoned in the routine ledger through * `markRun`; the release is the person's way out when the provider never ends or lists that run. */ -export async function releaseValidationReservation({ home, key, receipt = null, confirm = false, unconfirmed, markRun, identityOf = readProcessIdentity }) { - const queues = queuesDir(home); - const file = (existsSync(queues) ? readdirSync(queues) : []).map((name) => path.join(queues, name, "queue.json")) - .find((candidate) => existsSync(candidate) && readQueue(candidate).active?.key === key); +export async function releaseValidationReservation({ home, key, receiptFile, receipt = null, confirm = false, unconfirmed, markRun, identityOf = readProcessIdentity }) { + const candidate = reservationFile(home, key, receiptFile); + let file = readQueue(candidate).active?.key === key ? candidate : null; + if (!file && !receipt) { + const matches = reservationFiles(home).filter((other) => { + try { return readQueue(other).active?.key === key; } catch { return false; } + }); + if (matches.length === 1) file = matches[0]; + } if (!file && !receipt) throw new Error("no cloud task exists to poll and no queue reservation holds this request"); const live = (entry) => { if (!launcherAlive(entry, identityOf)) return false; @@ -289,11 +284,8 @@ function locateLaunch(launch, remote) { return null; } -// An inventory cut at LIST_RUNS_PAGES is read, not refused, so a lost launch is still reclaimed past its window on a -// standing routine whose run history outgrew the limit. Runs are listed newest first and no other validation launches -// while a reservation holds the account, but dispatch runs on the same standing routine outside the queue, so enough -// newer dispatch runs can push a launch that did happen past the limit; that rare launch is then reclaimed while it may -// still run. Any other thrown provider read leaves the run unreadable. +// A bounded inventory can miss an older nonce. As with a complete empty read, reclaim an unacknowledged launch +// only after its recovery window. A failed provider read leaves that launch unreadable. const unproven = (error) => error instanceof IncompleteRunInventory ? "unknown" : "unreadable"; /** diff --git a/plugins/vibe-closedloop/lib/vibe/scripts/cloud-validation-environment.mjs b/plugins/vibe-closedloop/lib/vibe/scripts/cloud-validation-environment.mjs index af7ce31e..3aa1fd42 100644 --- a/plugins/vibe-closedloop/lib/vibe/scripts/cloud-validation-environment.mjs +++ b/plugins/vibe-closedloop/lib/vibe/scripts/cloud-validation-environment.mjs @@ -1,6 +1,7 @@ import { bootstrapCommand, cloudRecipe, recipeProvider, toolingRoot } from "./cloud-validation-recipes.mjs"; import { capturedJson } from "./captured-json.mjs"; -import { ARTIFACT_MARKER, OUTCOMES_MARKER } from "./cloud-outcome-artifact.mjs"; +import { ARTIFACT_MARKER, DIAGNOSTIC_LABEL, FAILURES_LABEL, LANE_FAILURES_LABEL, OUTCOMES_MARKER, PUBLICATION_MARKER, probeFailureLine } from "./cloud-outcome-artifact.mjs"; +import { redactSecrets } from "./cloud-redaction.mjs"; import { createHash } from "node:crypto"; import { existsSync, renameSync } from "node:fs"; import path from "node:path"; @@ -22,6 +23,8 @@ const OPTIONAL_PROOF_KEYS = ["controlNamespace", "chromium1254", "docker", "dock const API_TEST = cloudRecipe.apiTestPattern ? new RegExp(cloudRecipe.apiTestPattern) : null; export const TOOL_REPO = "https://github.com/closedloop-ai/claude-plugins.git"; const RUNNER = `${toolingRoot}/lib/vibe/scripts/cloud-validation-host.mjs`; +const PROBE_COMMAND = `node ${toolingRoot}/lib/vibe/scripts/cloud-worker.mjs validate --request cloud-capabilities-request.json`; +const PROBE_REQUEST = 'with `lanes: [{"name":"cloud-capabilities"}]` on the exact tooling checkout and the same pinned account and environment'; const SAFE_REF = /^refs\/(?:heads|tags)\/[A-Za-z0-9][A-Za-z0-9_.\/-]+$/; const CONTROL_PORTS = /(?:--filter(?:=|\s+)|-F\s+)(?:@repo\/)?control\b|\bpkgs-a\b|\bweb-stack-env\b/i; const AFFECTED = new Map([ @@ -147,23 +150,48 @@ export function requiredCloudEnvironment(lanes) { .map(({ name, prerequisites }) => ({ name, ...prerequisites })); } +/** Name the command that stopped a measured capability, including the component check of a composite capability. */ +function capabilityRefusal(key, failures) { + const components = { dockerBootstrap: { compose: "docker compose version", vfsDaemon: "dockerd (vfs)", + vfsHello: "docker run --rm hello-world (vfs)" }, display: { electronVersion: "xvfb-run electron --version", + electronWindow: "xvfb-run Electron window smoke" } }; + const component = Object.entries(components[key] ?? {}).find(([name]) => failures[name]); + const entry = component ? failures[component[0]] : failures[key]; + if (!entry) return key; + const step = [component?.[1], entry.reason].filter(Boolean).join(": ") || "probe command"; + const exit = entry.exitCode === null ? "no process exit" : `exit ${entry.exitCode}`; + const stderr = entry.tail.join(" | ").replace(/\s+/g, " "); + return `${key}: ${step} (${exit})${stderr ? `: ${stderr}` : ""}`; +} + /** Reject dependent lanes before provider I/O until the exact account image and committed host runner are proven. */ export function admitCloudEnvironment(lanes, { home, environmentId, pin, currentAccount, tool, now = Date.now() }) { const affected = requiredCloudEnvironment(lanes); if (affected.length === 0) return null; const usable = pin?.environmentId === environmentId && pin?.accountUuid === currentAccount && validTool(tool); const proof = usable ? matchingProof(home, pin, tool, now) : null; + const line = probeFailureLine(proof?.failureLine, { redact: redactSecrets }); + const failures = line ? JSON.parse(line.slice(FAILURES_LABEL.length + 1)) : {}; + const noDetails = new Set(); const problems = affected.flatMap(({ name, capabilities }) => { - const missing = capabilities.filter((key) => proof?.checks?.[key] !== true); + const missing = capabilities.filter((key) => proof?.checks?.[key] !== true).map((key) => { + const detail = capabilityRefusal(key, failures); + if (proof && detail === key) noDetails.add(key); + return detail; + }); const lane = lanes.find((entry) => entry.name === name); if (lane.workflow) missing.unshift("non-root workflow step execution"); return missing.length ? [`${name} (${missing.join(", ")})`] : []; }); if (problems.length && tool === undefined) { - throw new Error(`CLOUD_LANES_UNAVAILABLE: ${problems.join("; ")} need the capability probe's proof, and the request names no runtimeTool; add the tooling commit and ref the capability probe measured and submit it again, or run on L2 (remote slot heavy)`); + throw new Error(`CLOUD_LANES_UNAVAILABLE: ${problems.join("; ")} need the capability probe's proof. The request names no runtimeTool. Run \`${PROBE_COMMAND}\` ${PROBE_REQUEST}, then set runtimeTool.commit and runtimeTool.ref to that commit and ref, or run on L2 (remote slot heavy)`); + } + if (problems.length && !proof) { + throw new Error(`CLOUD_LANES_UNAVAILABLE: ${problems.join("; ")} have no current exact environment, account and tooling proof. Run \`${PROBE_COMMAND}\` ${PROBE_REQUEST}, or run on L2 (remote slot heavy)`); } if (problems.length) { - throw new Error(`CLOUD_LANES_UNAVAILABLE: ${problems.join("; ")} have no current exact environment, account and tooling proof; run on L2 (remote slot heavy)`); + const detail = noDetails.size ? `. The capability probe did not return command details for ${[...noDetails].join(", ")}. Run \`${PROBE_COMMAND}\` ${PROBE_REQUEST} to collect them` : ""; + throw new Error(`CLOUD_LANES_UNAVAILABLE: ${problems.join("; ")}${detail}; run on L2 (remote slot heavy)`); } // Every cloud E2E lane runs its own committed workflow command on the portable route: the managed host runs only a // lane's bare command, which skips the Desktop workflow's pre-suite steps (verify Electron binary, build, D-Bus, keyring). @@ -202,7 +230,9 @@ export function confirmCloudEnvironment({ home, pin, environmentId, tool, sessio && Object.keys(evidence.checks).every((key) => [...PROOF_KEYS, ...OPTIONAL_PROOF_KEYS].includes(key) && typeof evidence.checks[key] === "boolean") && PROOF_KEYS.every((key) => typeof evidence.checks[key] === "boolean"); const checks = valid ? evidence.checks : Object.fromEntries([...PROOF_KEYS, ...OPTIONAL_PROOF_KEYS].map((key) => [key, false])); - writeAtomic(proofPath(home, pin), { schema: PROOF_SCHEMA, ...pin, tool, sessionId, at: now, checks }); + const failureLine = probeFailureLine(outcome?.stdoutTail, { redact: redactSecrets }); + writeAtomic(proofPath(home, pin), { schema: PROOF_SCHEMA, ...pin, tool, sessionId, at: now, checks, + ...(failureLine ? { failureLine } : {}) }); return Boolean(valid); } @@ -239,6 +269,8 @@ export function cloudHostInstruction({ tool, affected }, { lanes, commit, report return [ "This request uses the verified non-root lane runner. Execute the following commands once, in order. If setup cannot complete, report the exact failure and mark the lanes unrun.", `git fetch --no-tags ${TOOL_REPO} ${tool.ref} && git merge-base --is-ancestor ${tool.commit} FETCH_HEAD && git show ${tool.commit}:${RUNNER} > ${target}`, + // An older pinned host runner is self-contained. Newer runners load the shared secret redactor beside this file. + `if git cat-file -e ${tool.commit}:${toolingRoot}/lib/vibe/scripts/cloud-redaction.mjs 2>/dev/null; then git show ${tool.commit}:${toolingRoot}/lib/vibe/scripts/cloud-redaction.mjs > .git/cloud-redaction.mjs; fi`, ...(recipeProvider ? [`git show ${tool.commit}:${toolingRoot}/provider/provider.json > ${target}.provider.json`] : []), // Run as its own call with its output visible. It writes its own output and exit files, since it usually outlasts the // Bash tool's 10-minute wait, and a shell redirect that hid a fetched runner's output was refused as undermining oversight. @@ -249,7 +281,8 @@ export function cloudHostInstruction({ tool, affected }, { lanes, commit, report // The runner prints its record first, but its timing lines come before it in the output file, and the // condensed run log cut the record off there (cse_01H58iaeEVzoR7WVfUQooHjt); one call that prints only the record // keeps it whole whatever the agent writes afterwards. - ...(reporter ? [`After ${target}.exit exists, run \`grep -m1 -E '^(${OUTCOMES_MARKER}|${ARTIFACT_MARKER}) ' ${target}.out\` as its own Bash call, exactly as written, so the runner's result record reaches the run log whole.`] : []), + ...(reporter ? [`After ${target}.exit exists, run \`grep -m1 -E '^(${OUTCOMES_MARKER}|${ARTIFACT_MARKER}|${PUBLICATION_MARKER}) ' ${target}.out\` as its own Bash call, exactly as written, so the runner's result record reaches the run log whole. Keep that entire line in your final message.`, + `If the pinned reporter wrote a separate preflight or legacy diagnostic line, read it with \`grep -m1 -E '^(${LANE_FAILURES_LABEL}|${DIAGNOSTIC_LABEL}) ' ${target}.out\` in its own Bash call and copy it after the result line.`] : []), "CLOUD_HOST_LANES gives a private directory and count. Read each zero-based .json file separately, preserving exitCode, stdoutTail, stderrTail and diagnosis in the indexed report parts. Keep the private files in this provider session. Include only each privateStreams locator, byte count and SHA-256 with its lane. Never publish or emit full stream contents. Do not run a requested command a second time.", ].join("\n"); } @@ -276,10 +309,9 @@ export function boundProbeReceipt(file, lanes, state, env) { /** Keep one exact validation request and its account reservation coherent through launch, poll and import. */ export async function executeCloudValidation({ file, digest, request, env, lanes, laneKeys, home, ledger, currentAccount, signal, remote, timeoutMs, - start, poll, archiveProblem, mark, parse, endedDetail, artifactReader, onReport }) { + start, poll, archiveProblem, mark, parse, endedDetail, artifactReader, onReport, warnings = [] }) { const state = ledger(); const pin = state.environmentPin; - const account = pin?.accountUuid ?? "unbound-validation"; file = boundProbeReceipt(file, lanes, state, env); const verifyAccount = () => { if (!pin) { @@ -292,7 +324,7 @@ export async function executeCloudValidation({ file, digest, request, env, lanes if (latest?.accountUuid !== pin.accountUuid || latest?.environmentId !== pin.environmentId) throw new Error("validation account or environment changed during admission"); }; verifyAccount(); - const enter = (action) => withCloudValidationAdmission({ home, account, key: digest, receipt: file, signal, + const enter = (action) => withCloudValidationAdmission({ home, key: digest, receipt: file, signal, metadata: { commit: request.commit, environment: env, laneKeys, ...(request.cloudProof ? { proof: cloudcheckProofIdentity(request.commit, digest) } : {}) }, timeoutMs, recover: async entry => { const disposition = recoverValidationReservation(entry,{ledger:ledger(),remote}); @@ -302,7 +334,7 @@ export async function executeCloudValidation({ file, digest, request, env, lanes } return disposition; } }, action); - return withValidationReportLock(file, () => enter(async ({ launching }) => { + return withValidationReportLock(file, () => enter(async ({ launching, launchRefused }) => { verifyAccount(); let started; if (existsSync(file)) { @@ -321,13 +353,13 @@ export async function executeCloudValidation({ file, digest, request, env, lanes } if (!started) { started = await start((launch,requirements) => { - // The provider builds this binding under its routine lock. A repin while queued cannot move the run. + // The provider builds this binding under its routine lock. A repin before dispatch cannot move the run. if (pin ? launch?.accountUuid !== pin.accountUuid || launch?.environmentId !== env.id : launch?.accountUuid !== undefined) { throw new Error("validation account or environment changed before launch"); } return launching(launch,requirements); - }); - started = { ...started, ...(pin ? {accountUuid: pin.accountUuid} : {}), requestDigest: digest, commit: request.commit, laneKeys }; + }, launchRefused); + started = { ...started, ...(pin ? {accountUuid: pin.accountUuid} : {}), requestDigest: digest, commit: request.commit, laneKeys, ...(warnings.length ? { warnings } : {}) }; // The provider has acknowledged the run. Keep its nonce even if local persistence fails. try { writeAtomic(file, started); } catch (error) { error.launchUncertain = true; throw error; } } @@ -346,6 +378,7 @@ export async function executeCloudValidation({ file, digest, request, env, lanes // Each lane report says where it ran; a lane routed elsewhere was refused before dispatch. const lanesWhere = Array.isArray(result.lanes) ? { lanes: result.lanes.map((lane) => ({ ...lane, ranOn: "claude-cloud" })) } : {}; return { ...result, ...lanesWhere, ...(artifact ? { artifact } : {}), provider: "claude", taskId: finished.taskId, - sessionId: finished.sessionId, wallMs: finished.wallMs, receipt: file, ...(finished.proof ? { proof: finished.proof } : {}) }; + sessionId: finished.sessionId, wallMs: finished.wallMs, receipt: file, ...(finished.proof ? { proof: finished.proof } : {}), + ...(warnings.length ? { warnings } : {}), ...(finished.launchRefusals ? { launchRefusals: finished.launchRefusals } : {}) }; })); } diff --git a/plugins/vibe-closedloop/lib/vibe/scripts/cloud-validation-host.mjs b/plugins/vibe-closedloop/lib/vibe/scripts/cloud-validation-host.mjs index 5ca9d06f..7b835096 100644 --- a/plugins/vibe-closedloop/lib/vibe/scripts/cloud-validation-host.mjs +++ b/plugins/vibe-closedloop/lib/vibe/scripts/cloud-validation-host.mjs @@ -4,6 +4,8 @@ import { appendFileSync, chmodSync, closeSync, copyFileSync, existsSync, fstatSy import os from "node:os"; import path from "node:path"; import { fileURLToPath } from "node:url"; +import { redactSecrets, redactUserinfo } from "./cloud-redaction.mjs"; +export { redactSecrets, redactUserinfo } from "./cloud-redaction.mjs"; const NO_INPUT = "ignore"; const UNPRIVILEGED_FALLBACK = 65534; @@ -106,47 +108,6 @@ export function rootSetupEnvironment(env, current, checkout) { return rootSetupGitEnvironment({ ...env, ...hostNetworkEnvironment(current) }, checkout); } -/** - * `text` with each URL's userinfo (a credential) replaced by ``, through the authority's last `@`, and the - * same for a schemeless `user:password@host` such as a proxy set without a scheme. A password may hold `#`, `?`, `@` - * or a slash, so a path with an `@` after a port may go too. - */ -export function redactUserinfo(text) { - return String(text).replace(/\S+/g, (word) => throughLastAt(word, /(:\/\/)(?:[^/:@]+:.*|[^/]+)@/gis)) - .replace(/[^\s"']+/g, (part) => throughLastAt(part, /(^|[=(<,;])[^/@=(<,;:]+:(?!\/\/).*@/s, /[/?#@]/)); -} - -/** `word` with what `pattern` finds up to its last `@` (one not followed by a `not` character) redacted, in time linear in the word. */ -function throughLastAt(word, pattern, not = /[]/) { - let end = word.length + 1; - do end = word.lastIndexOf("@", end - 2) + 1; while (end > 1 && not.test(word[end] ?? "")); - return word.slice(0, end).replace(pattern, "$1@") + word.slice(end); -} - -const SECRET_VALUE = /(?`. A secret-named value that holds an `@` goes - * first and keeps one, so no part of it is left as a host and a URL around it is still read as one; `afterAt` leaves an - * unquoted one's rest to the rules below. A URL's own user name is left to the URL rule. Other values wait for the - * bearer pass, which needs the word before the token. - */ -export function redactSecrets(text) { - return redactUserinfo(String(text ?? "").replace(SECRET_VALUE, (all, key, sep, value, at, whole) => value.includes("@") && whole.slice(at - 3, at) !== "://" ? `${key}${sep}@${/^\\*["']/.test(value) ? "" : afterAt(value)}` : all).replace(/\S+/g, (word) => throughLastAt(word, /(:\/\/)[^/:@]+:.*@/is))) - .replace(/\b((?:set-)?cookie["']?\s*[:=]).*/gi, "$1 ") - .replace(/\b(Bearer|Basic|token)\s+[A-Za-z0-9._~+/=-]{8,}/gi, "$1 ") - .replace(/\b(?:gh[pousr]_[A-Za-z0-9]{16,}|github_pat_[A-Za-z0-9_]{16,}|sk-[A-Za-z0-9_-]{16,}|xox[abprs]-[A-Za-z0-9-]{10,}|npm_[A-Za-z0-9]{8,}|glpat-[\w-]{8,}|AKIA[A-Z0-9]{16})\b|(?") - .replace(/(?") - .replace(SECRET_VALUE, "$1$2"); -} - /** * An actor's CA and proxy settings, a workflow step's or an ordinary lane's, its proxy values without userinfo through * the authority's last `@`, with or without a URL scheme: no proxy credential reaches commit code (V11-5). A value @@ -364,9 +325,41 @@ function runLane(command, args, options, directory, index, limits) { } } -function inControlNamespace(binary,args) { - return ["unshare",["--user","--map-current-user","--net","--","sh","-ec", - 'ip link set lo up || exit 78; exec "$@"',"control-lane",binary,...args]]; +const CONTROL_PYTHON_MISSING = "control-lane: python3 not found for loopback fallback"; +const CONTROL_PYTHON_FAILED = "control-lane: python3 loopback fallback failed"; +const CONTROL_BIND_FAILED = "control-lane: loopback bind failed"; + +// Linux ifreq holds the 16-byte interface name followed by a union whose flags member is a short. Reserve the +// full 64-bit struct size and preserve every flag except the IFF_UP bit we set. +const CONTROL_LOOPBACK_IOCTL = `import fcntl, socket, struct, sys + +sys.tracebacklimit = 0 +SIOCGIFFLAGS, SIOCSIFFLAGS, IFF_UP = 0x8913, 0x8914, 0x1 +request = bytearray(40) +struct.pack_into("16s", request, 0, b"lo") +with socket.socket(socket.AF_INET, socket.SOCK_DGRAM) as sock: + fcntl.ioctl(sock, SIOCGIFFLAGS, request) + flags, = struct.unpack_from("H", request, 16) + struct.pack_into("H", request, 16, flags | IFF_UP) + fcntl.ioctl(sock, SIOCSIFFLAGS, request)`; + +const CONTROL_LAUNCH = `if ! ip link set lo up; then + if ! command -v python3 >/dev/null 2>&1; then + echo '${CONTROL_PYTHON_MISSING}' >&2 + exit 78 + fi + if ! python3 -IS -c '${CONTROL_LOOPBACK_IOCTL}'; then + echo '${CONTROL_PYTHON_FAILED}' >&2 + exit 78 + fi +fi +exec setpriv --inh-caps=-all --ambient-caps=-all -- "$@"`; + +/** Keep the actor UID and both namespaces. Across exec, only loopback setup inherits namespace CAP_NET_ADMIN. */ +function inControlNamespace(binary, args) { + return ["unshare", ["--user", "--map-current-user", "--net", "--keep-caps", "--", + "setpriv", "--inh-caps=-all,+net_admin", "--ambient-caps=-all,+net_admin", "--", + "sh", "-ec", CONTROL_LAUNCH, "control-lane", binary, ...args]]; } /** @@ -699,8 +692,7 @@ const TOOL_ROOT = /^[A-Za-z0-9_-]+(?:\/[A-Za-z0-9_-]+)*$/; /** * The writer's outcome identity, built from the plan the runner already holds. The plan carries only the plain fields * the lanes do not give: a long opaque copy of them was mis-transcribed by the cloud agent (cse_01H58iad1kG6cfaiG3mSZnoM - * cut the plan's last brace). Its shape is outcomeSpec's in cloud-outcome-instruction.mjs, which this single shipped - * file cannot import; a test holds the two equal. + * cut the plan's last brace). Its shape is outcomeSpec's in cloud-outcome-instruction.mjs, which the host runner does not import; a test holds the two equal. */ export function hostOutcomeSpec(plan) { const { key, repository, probe, frozen, artifact } = plan.reporter; @@ -756,6 +748,7 @@ export function probeCloudHostRuntime(directory, checkout = process.cwd(), run = const actor = validationHostActor(); const runtime = { workspace: false, nonRoot: false, ports: false, chromium: false, gitUtc: false }; const details = {}; + const measure = (name, step, binary, args, options) => details[name] = { ...run(binary, args, options), step }; try { const marker = path.join(sandbox, "restricted"); const child = path.join(sandbox, "probe.cjs"); @@ -766,15 +759,26 @@ export function probeCloudHostRuntime(directory, checkout = process.cwd(), run = const options = { cwd: sandbox, env: environment, ...actor, timeout: 120_000 }; // The actor finds node on its PATH, as every lane does: the runner's own binary can sit in root's closed home // (the cloud setup puts Node 24 in $HOME/.node24), which the actor cannot execute. - details.nonRoot = run("node", [child, marker], options); + measure("nonRoot", "node probe.cjs (actor UID and file permissions)", "node", [child, marker], options); runtime.nonRoot = details.nonRoot.exitCode === 0; - const [binary,argv] = inControlNamespace("node",["-e","const net=require('node:net');const s=net.createServer();s.listen(0,'127.0.0.1',()=>s.close());"]); - details.controlNamespace = run(binary,argv,options); + const [binary, argv] = inControlNamespace("node", ["-e", `const net = require('node:net'); + const server = net.createServer(); + server.on('error', error => { console.error('${CONTROL_BIND_FAILED}:', error.message); process.exitCode = 1; }); + server.listen(0, '127.0.0.1', () => server.close());`]); + const namespace = measure("controlNamespace", [binary, ...argv.slice(0, argv.indexOf("--"))].join(" "), binary, argv, options); + const namespaceError = (namespace.stderrTail ?? "").trimEnd(); + if (namespaceError.endsWith(CONTROL_PYTHON_MISSING)) namespace.step = "command -v python3 (inside unshare)"; + else if (namespaceError.endsWith(CONTROL_PYTHON_FAILED)) namespace.step = "python3 loopback fallback (inside unshare)"; + else if (/^setpriv:/m.test(namespaceError)) namespace.step = "setpriv (inside unshare)"; + else if (namespaceError.includes(CONTROL_BIND_FAILED)) namespace.step = "node bind to 127.0.0.1 (inside unshare)"; runtime.controlNamespace = runtime.nonRoot && details.controlNamespace.exitCode === 0; const leases = []; try { for (let index = 0; index < 10; index++) leases.push(reserveCloudPorts(path.join(directory, "capability-ports"))); runtime.ports = leases.every((lease, index) => index === 0 || lease.first > leases[index - 1].last); + if (!runtime.ports) details.ports = { step: "reserveCloudPorts", exitCode: null, diagnosis: "port reservations overlapped" }; + } catch (error) { + details.ports = { step: "reserveCloudPorts", exitCode: null, diagnosis: error.message }; } finally { for (const lease of leases) lease.release(); } const sample = path.join(sandbox, "packages/check"); mkdirSync(sample, { recursive: true }); @@ -783,10 +787,11 @@ export function probeCloudHostRuntime(directory, checkout = process.cwd(), run = writeFileSync(path.join(sample, "package.json"), '{"name":"vibe-runtime-workspace","scripts":{"build":"node build.cjs"}}'); writeFileSync(path.join(sample, "build.cjs"), 'require("node:fs").writeFileSync("dist.js", "workspace build ran")'); if (process.getuid() === 0) ownTree(sandbox, actor); - details.workspace = run("pnpm", ["--filter", "vibe-runtime-workspace", "build"], options); + measure("workspace", "pnpm --filter vibe-runtime-workspace build", "pnpm", ["--filter", "vibe-runtime-workspace", "build"], options); runtime.workspace = details.workspace.exitCode === 0 && existsSync(path.join(sample, "dist.js")); + if (details.workspace.exitCode === 0 && !runtime.workspace) details.workspace.diagnosis = "build did not produce dist.js"; // chromium1254 is the setup's browser revision alone; chromium is the actor's headless launch of it. - details.chromiumInstall = run("test", ["-x", HEADLESS_SHELL], options); + measure("chromiumInstall", `test -x ${HEADLESS_SHELL}`, "test", ["-x", HEADLESS_SHELL], options); runtime.chromium1254 = details.chromiumInstall.exitCode === 0; if (runtime.chromium1254) { // Root fetches the pinned Playwright with the host's network settings, as root setup installs a lane's @@ -796,18 +801,18 @@ export function probeCloudHostRuntime(directory, checkout = process.cwd(), run = const browser = path.join(sandbox, "browser"); mkdirSync(browser); writeFileSync(path.join(browser, "package.json"), '{"name":"vibe-runtime-browser","private":true}'); - details.chromiumFetch = run("pnpm", ["add", "--ignore-workspace", "playwright@" + BROWSER_VERSION], + measure("chromiumFetch", `pnpm add --ignore-workspace playwright@${BROWSER_VERSION}`, "pnpm", ["add", "--ignore-workspace", "playwright@" + BROWSER_VERSION], { cwd: browser, env: rootSetupEnvironment(environment, process.env, browser), timeout: 120_000 }); if (process.getuid() === 0) ownTree(sandbox, actor); if (details.chromiumFetch.exitCode === 0) { - details.chromiumLaunch = run("pnpm", ["exec", "playwright", "screenshot", "--browser=chromium", "data:text/html,probe", path.join(sandbox, "probe.png")], + measure("chromiumLaunch", "pnpm exec playwright screenshot --browser=chromium", "pnpm", ["exec", "playwright", "screenshot", "--browser=chromium", "data:text/html,probe", path.join(sandbox, "probe.png")], { ...options, cwd: browser }); runtime.chromium = details.chromiumLaunch.exitCode === 0; } } - details.gitUtc = run("git", ["log", "-1", "--format=%ad", "--date=iso-strict-local"], { cwd: checkout, env: environment }); + measure("gitUtc", "git log -1 --format=%ad --date=iso-strict-local", "git", ["log", "-1", "--format=%ad", "--date=iso-strict-local"], { cwd: checkout, env: environment }); try { runtime.gitUtc = details.gitUtc.exitCode === 0 && Boolean(canonicalGitTimestamp(details.gitUtc.stdoutTail.trim())); } - catch { /* Preserve the failed exact UTC probe. */ } + catch { details.gitUtc.diagnosis = "git log did not emit a valid UTC timestamp"; } return { checks: runtime, details }; } finally { rmSync(sandbox, { recursive: true }); } } diff --git a/plugins/vibe-closedloop/lib/vibe/scripts/cloud-worker.mjs b/plugins/vibe-closedloop/lib/vibe/scripts/cloud-worker.mjs index b9820388..c8920ccc 100644 --- a/plugins/vibe-closedloop/lib/vibe/scripts/cloud-worker.mjs +++ b/plugins/vibe-closedloop/lib/vibe/scripts/cloud-worker.mjs @@ -43,7 +43,7 @@ import { logText } from "./cloud-validation-log.mjs"; import { capturedJson, firstLine } from "./captured-json.mjs"; import { keepCreateStream, redactedLine, rejectedBeforeRun, remoteTriggerPrompt, remoteTriggerStream, TOOL_NOT_EXECUTED } from "./cloud-trigger-stream.mjs"; -import { MACHINE_OUTCOMES, measuredProbeTranscript, withCarriedFailures, outcomeArtifact, checkOutcomeArtifact, OUTCOME_LOG_LIMIT, outcomeTransportBytes, requireOutcomeCapacity, readOutcomeReport } from "./cloud-outcome-artifact.mjs"; +import { MACHINE_OUTCOMES, measuredProbeTranscript, withCarriedFailures, outcomeArtifact, checkOutcomeArtifact, OUTCOME_LOG_LIMIT, MISSING_RESULT_BRANCH, outcomeTransportBytes, requireOutcomeCapacity, readOutcomeReport } from "./cloud-outcome-artifact.mjs"; import { compactWorkflowBrief } from "./cloud-workflow-brief.mjs"; import { redactSecrets } from "./cloud-validation-host.mjs"; import { hostReporter, outcomeInstruction, LANE_DISCIPLINE } from "./cloud-outcome-instruction.mjs"; @@ -55,6 +55,7 @@ import { existsSync, lstatSync, readFileSync, realpathSync, renameSync, unlinkSy import os from "node:os"; import path from "node:path"; import { isDeepStrictEqual, parseArgs } from "node:util"; +import { setTimeout as delay } from "node:timers/promises"; import { recordCloudCheck } from "../../fleet-orchestrator/scripts/cloud-slot-routing.mjs"; import { resolveWorkDir } from "../../codex-fleet-monitor/scripts/work-dir.mjs"; import { decideCloudPlacement } from "../../fleet-orchestrator/scripts/cloud-placement.mjs"; @@ -349,7 +350,11 @@ function triggerAnswer(action, sent, result, timeout) { try { response = capturedJson(jsonLine); } catch { /* preserve the HTTP refusal without structured data */ } const codes = [response?.error, response?.code, response?.type, response?.error?.code, response?.error?.type, response]; if (status === 401 && codes.includes("github_token_missing")) throw githubTokenMissing(diagnostic); + const providerMessage = response?.error?.message ?? response?.message ?? (typeof response?.error === "string" ? response.error : jsonLine); const http = Number.isInteger(status) ? { httpStatus: status } : {}; + if (["create", "update", "run"].includes(action) && typeof providerMessage === "string") { + http.providerMessage = redactedLine(redactSecrets(providerMessage)).slice(0, 400); + } if (action === "create" && status === 400 && codes.includes("environment_not_found")) http.apiCode = "environment_not_found"; throw Object.assign(new Error(`RemoteTrigger ${action} failed: ${firstLine(body)}${details}`), http); } @@ -624,7 +629,7 @@ export async function abandonValidation(request, { confirm = false, home = os.ho ? boundProbeReceipt(base, validationLanes(withRepository(request)).lanes, readLedger(home), resolveClaudeEnvironment(request)) : base; const receipt = existsSync(file) ? JSON.parse(readFileSync(file, "utf8")) : null; const abandoned = receipt && (TERMINAL.has(receipt.status) ? receipt : { ...receipt, status: "abandoned", finishedAt: new Date().toISOString() }); - const result = await releaseValidationReservation({ home, key, confirm, unconfirmed: (plan) => unconfirmed("abandon", plan), markRun: (runId) => markRun(home, runId, "abandoned", DEFAULT_WALL_MS), + const result = await releaseValidationReservation({ home, key, receiptFile: file, confirm, unconfirmed: (plan) => unconfirmed("abandon", plan), markRun: (runId) => markRun(home, runId, "abandoned", DEFAULT_WALL_MS), receipt: abandoned && { plan: { receipt: file, from: receipt.status ?? null, to: abandoned.status, sweepsRoutines: true }, runId: abandoned.status === "abandoned" ? abandoned.runId ?? abandoned.taskId : null, write: () => writeFileSync(file, `${JSON.stringify(abandoned, null, 2)}\n`, { mode: 0o600 }) } }); if (!confirm || !abandoned) return result; @@ -771,6 +776,32 @@ export function validationLanes(request) { return { lanes: describeCloudLanes(lanes, { read, commit: request.commit }), laneSource: source }; } +/** Flag a hand-written command using the name of a job in the validated commit's CI workflow. */ +export function validationWorkflowWarnings(request) { + if (request.laneSource) return []; + const ci = ".github/workflows/ci.yml"; + let definitions; + try { + definitions = workflowLaneDefinitions(committedFile(request.worktree, request.commit, ci)); + } catch { + // A checkout without a readable, supported CI workflow can still run unrelated direct validation. + return []; + } + const normalize = (name) => name?.toLowerCase().replace(/[^a-z0-9]+/g, "-").replace(/^-|-$/g, ""); + const jobs = definitions.map(({ name, job, matrix, command }) => { + const recipe = JSON.parse(command).job; + const names = [name, job, recipe.name]; + if (matrix.shard !== undefined) names.push(`${job}-${matrix.shard}`, `${job}-shard-${matrix.shard}`); + const steps = recipe.steps.filter(({ run }) => typeof run === "string"); + return { names: new Set(names.filter(Boolean).map(normalize)), recipe: steps.map(({ run }) => run.trim()).join("\n") }; + }); + return request.lanes.flatMap(({ name, command }) => { + const matching = jobs.filter((job) => job.names.has(normalize(name))); + if (!matching.length || matching.every(({ recipe }) => recipe === command.trim())) return []; + return [`CLOUD_VALIDATION_WORKFLOW_MISMATCH: caller-written lane "${redactedLine(name)}" differs from its ${ci} job recipe; use laneSource for CI evidence`]; + }); +} + /** Check a validation-only request; Codex Cloud returns no task report to bind lane results to. */ export function validateValidationRequest(request) { if (!request || typeof request !== "object") throw new Error("structured validation request is required"); @@ -866,11 +897,16 @@ export function parseValidationResult(text, request, {managedHost = false, outco if (outcomeTransport && lane.capabilityProbe && result.passed) result.stdoutTail=measuredProbeTranscript(raw.stdoutTail,request.commit); withCarriedFailures(result,{probe:lane.capabilityProbe===true,index,sources:lane.capabilityProbe?[raw.stdoutTail,text]:[text],redact:redactSecrets}); + const diagnostic = machine?.diagnostics?.["lane" + index]; + if (diagnostic && !result.passed && Number.isInteger(result.exitCode)) { + result.stdoutTail ||= diagnostic[0]; + result.stderrTail ||= diagnostic[1]; + } return result; }); let artifact; if (machine) for (const [index,row] of machine.lanes.entries()) if(row.combinedOutput) lanes[index].combinedOutput=row.combinedOutput; - if (request.resultArtifact) { + if (request.resultArtifact && (!outcomeArtifact(request) || result.artifact)) { artifact = result.artifact; if (artifact?.path !== request.resultArtifact.path || artifact?.branch !== request.resultArtifact.branch || !/^[0-9a-f]{40}$/.test(artifact?.commit ?? "") || !/^[0-9a-f]{64}$/.test(artifact?.sha256 ?? "")) { @@ -917,7 +953,14 @@ function reportedLane(lane, reported, structured,index,managedHost) { export function readValidationArtifact(request, artifact, { run = runCommand, gitRead = git } = {}) { const ref = `refs/vibe/cloud-validation/${sha256(`${request.commit}:${artifact.branch}`)}`; const fetched = run("git", ["-C", request.worktree, "fetch", "--force", "origin", `refs/heads/${artifact.branch}:${ref}`], { cwd: request.worktree, timeout: COMMAND_MS }); - if (fetched.status !== 0) throw new Error(`cloud validation result branch fetch failed: ${firstLine(fetched.stderr || fetched.error?.message)}`); + if (fetched.status !== 0) { + const reason = fetched.stderr || fetched.error?.message || "unknown error"; + if (/^fatal: couldn't find remote ref\b/im.test(reason)) { + throw Object.assign(new Error(`cloud validation result branch ${artifact.branch} is missing; the cloud session did not leave a published result`), + { code: MISSING_RESULT_BRANCH }); + } + throw new Error(`cloud validation result branch fetch failed: ${redactedLine(firstLine(reason))}`); + } const commit = gitRead(request.worktree, ["rev-parse", ref]); const discover = outcomeArtifact(request) && artifact.commit === undefined && artifact.sha256 === undefined; if ((!discover && commit !== artifact.commit) || gitRead(request.worktree, ["rev-parse", `${commit}^`]) !== request.commit) { @@ -952,7 +995,8 @@ const PERMISSION_DENIAL = /Permission for this action (?:has been denied|was den /** A result that never arrived because the session was denied permission names that denial as the cause. */ function deniedResult(log, error) { - const denial = /result branch fetch failed|requires machine outcome evidence/.test(error.message) && PERMISSION_DENIAL.exec(log)?.[0]; + const missing = error.code === MISSING_RESULT_BRANCH || /result branch fetch failed|requires machine outcome evidence/.test(error.message); + const denial = missing && PERMISSION_DENIAL.exec(log)?.[0]; return denial ? new Error(`cloud validation session was denied permission to run a command: ${redactedLine(denial).slice(0, DIAGNOSIS_CHARS)} (${error.message})`) : error; } @@ -969,6 +1013,36 @@ function withOverflowArtifact(request, count, digest) { function validationReceiptPath(request, digest) { return path.join(gitDir(request.worktree), validationReceiptName(request.commit, digest)); } +/** Retry only provider-proven refusals, outside the routine lock and inside the request's launch window. */ +export async function retryValidationLaunch(start, { launchRefused, timeoutMs, signal, now = Date.now, + sleep = (ms) => delay(ms, undefined, { signal }), report = (line) => process.stderr.write(line + "\n") }) { + const deadline = now() + timeoutMs; + const refusals = []; + let backoffMs = 30_000; + let lastError; + for (;;) { + signal?.throwIfAborted(); + if (lastError && now() >= deadline) throw lastError; + try { + const started = await start(); + return { ...started, ...(refusals.length ? { launchRefusals: refusals } : {}) }; + } catch (error) { + if (!error.validationLaunchRefusal || error.launchUncertain) throw error; + lastError = error; + const observed = now(); + const time = new Date(observed).toISOString(); + const message = redactedLine(redactSecrets(error.validationLaunchRefusal)).slice(0, 400); + refusals.push({ time, message }); + const waitMs = Math.min(backoffMs, deadline - observed); + report(`CLOUD_VALIDATION_LAUNCH_LIMIT ${time}: ${message}${waitMs > 0 ? `; retrying in ${Math.ceil(waitMs / 1000)}s` : "; the launch deadline expired"}`); + await launchRefused(); + if (waitMs <= 0) throw error; + await sleep(waitMs); + backoffMs = Math.min(backoffMs * 2, 120_000); + } + } +} + /** Start (or resume) a Claude cloud session on the commit, poll it, and return results bound to that commit. */ export async function validateCommit(request, { remote = cliRemote(request.worktree), sleep, now, home = os.homedir(), executor = chromeRemoval(), stderr, artifactReader = readValidationArtifact, signal, proofGit = git, currentAccount = currentClaudeAccount } = {}) { validateValidationRequest(request); @@ -977,6 +1051,9 @@ export async function validateCommit(request, { remote = cliRemote(request.workt const routed = withOverflowArtifact(verified, validationLanes(verified).lanes.length, digest); const file = validationReceiptPath(request, digest); const { lanes } = validationLanes(routed); + const warnings = validationWorkflowWarnings(routed); + const report = stderr ?? ((line) => process.stderr.write(line + "\n")); + for (const warning of warnings) report(warning); const laneKeys = lanes.map(({ command }) => validationCommandKey(command)); const env = resolveClaudeEnvironment(routed); const ledger = () => readLedger(home); @@ -984,8 +1061,8 @@ export async function validateCommit(request, { remote = cliRemote(request.workt const selected = boundProbeReceipt(file, lanes, ledger(), env); if (!existsSync(selected)) validationBrief(routed, admission(), null, digest); // Before the hold and proof push: a refused brief takes no slot. const resume = `run the same cloud-worker.mjs validate --request again; its receipt ${selected} resumes this poll`; - return executeCloudValidation({ file, digest, request: routed, env, lanes, laneKeys, home, ledger, currentAccount, remote, signal, timeoutMs: DEFAULT_WALL_MS, - async start(launching) { + return executeCloudValidation({ file, digest, request: routed, env, lanes, laneKeys, home, ledger, currentAccount, remote, signal, warnings, timeoutMs: DEFAULT_WALL_MS, + async start(launching, launchRefused) { if (!routed.resultArtifact || outcomeArtifact(routed)) requireOutcomeCapacity(lanes,outcomeArtifact(routed)); if (outcomeArtifact(routed) && proofGit(request.worktree,["ls-remote","--refs","origin","refs/heads/"+routed.resultArtifact.branch])) throw new Error("outcome proof branch already exists; supply a fresh resultArtifact branch before dispatch"); const managedHost = admission(); @@ -993,8 +1070,10 @@ export async function validateCommit(request, { remote = cliRemote(request.workt const proof = request.cloudProof ? prepareCloudcheckProof({ worktree: request.worktree, commit: request.commit, key: digest, gitDir: path.dirname(file), git: proofGit }) : null; await sweepRemovals({ home, remote, worktree: request.worktree, executor, account: currentAccount, ...(stderr ? { stderr } : {}) }); const subject = proof ? { ...routed, branch: proof.branch } : routed; - const started = await startClaude({ ...subject, connectorAllowlist: [] }, validationBrief(routed, managedHost, proof?.branch,digest), { remote, home, - account: currentAccount, requestKey: digest, beforeRun: launch => launching(launch,{managedHost:Boolean(managedHost),outcomeTransport}), afterRun: launching, label: `validate ${request.commit.slice(0, 12)}` }); + const brief = validationBrief(routed, managedHost, proof?.branch, digest); + const started = await retryValidationLaunch(() => startClaude({ ...subject, connectorAllowlist: [] }, brief, { remote, home, + account: currentAccount, requestKey: digest, beforeRun: launch => launching(launch,{managedHost:Boolean(managedHost),outcomeTransport}), afterRun: launching, label: `validate ${request.commit.slice(0, 12)}` }), + { launchRefused, signal, sleep, now, timeoutMs: request.maxWallMs ?? DEFAULT_WALL_MS, report }); return { ...started, outcomeTransport, ...(managedHost ? {managedHost:true} : {}), ...(proof ? {proof} : {}) }; }, poll: (started) => pollTask(started, routed, { remote, resume, waitForVisibility: true, ...(sleep ? { sleep } : {}), ...(now ? { now } : {}) }), diff --git a/plugins/vibe-closedloop/skills/cl-sweep/scripts/app-server-worker-session.mjs b/plugins/vibe-closedloop/skills/cl-sweep/scripts/app-server-worker-session.mjs index aa401ca1..b99bcd6e 100644 --- a/plugins/vibe-closedloop/skills/cl-sweep/scripts/app-server-worker-session.mjs +++ b/plugins/vibe-closedloop/skills/cl-sweep/scripts/app-server-worker-session.mjs @@ -1494,7 +1494,7 @@ async function superviseTurn(args, dependencies = {}) { try { await initializeClient(client); validateModelBinding(session); - collector = createTurnCollector(client, session.appServerThreadId); + collector = (dependencies.createTurnCollector ?? createTurnCollector)(client, session.appServerThreadId); const lifecycle = lifecycleView(session); const resumed = await ensureDurableThread( client, diff --git a/plugins/vibe-closedloop/skills/fleet-orchestrator/SKILL.md b/plugins/vibe-closedloop/skills/fleet-orchestrator/SKILL.md index 3bce3546..f9c0fa31 100644 --- a/plugins/vibe-closedloop/skills/fleet-orchestrator/SKILL.md +++ b/plugins/vibe-closedloop/skills/fleet-orchestrator/SKILL.md @@ -172,6 +172,7 @@ For a publisher plugin version bump, attach the handoff run report with `board.m - A screenshot capture through a slot passes `--capture ` (`ticket`, `ref`, `pages`, `states`, optional `override`) after the worktree path; `scripts/fleet.sh` runs `../vibe/scripts/capture-guard.mjs` first and refuses it (exit 79) as `../vibe/references/quality-loop-visual-qa.md`, block `when-to-capture`, says; only an operator ruling recorded for that ticket in the program rulings, carrying `capture-guard override: baseline` or `capture-guard override: budget` for the refusal it lifts and quoted in the spec's `override`, lets it run. Before approving any capture, including after a compaction, read `../vibe/scripts/capture-guard.mjs status --ticket --ledger /captures`. - Before reporting or waiting on remaining work, identify true dependencies. Start independent repository selected integration, unit, typecheck and lint lanes at once through available heavy slots on allowed machines, even while e2e is queued or running elsewhere. A lane waiting only for a full slot or load moves to another allowed machine with capacity; report the move. With a passing cloud check, start those lanes in the cloud first (`CLOUD-VALIDATE` once the exact head is pushed); without one, route an eligible refused lane that way. Respect operator exclusions, machine load and slot limits, no dagger restrictions and the daily machine's no visible e2e rule. Keep the repository lane selector and `qa-impact.mjs` decision on which checks are needed. A lane runs the way its CI job runs: a proof harness never sets `umask 077` or exports `VITEST_MAX_WORKERS` above a tool's configured cap. - A shared e2e stack with fixed ports runs only under vibe's machine-wide e2e lock: `node ../vibe/scripts/e2e-lock.mjs run --head --source-hash --owner --label --ticket ` on the machine that runs it, where the machine slot reports the owner, label, ticket and compose project; receipts name HEAD plus diff/tree hashes, including dirty source. Each run gets its own compose project, so a teardown removes only its own stack; name a stack another tool started with `--foreign-compose `. Unit tests, typecheck, story runs and stand-in server tests run outside it. +- Submit independent cloud validations as soon as their inputs are ready. If the platform rate-limits a launch or reports that capacity is full, keep the other runs going. Validation reports the time and text of the refusal and waits before retrying that launch within its request timeout. - `scripts/slot-lock.sh --status ` on a machine lists slot holders. - Stop only owned processes with `fleet.sh local stop-owned `, even during plugin upgrades. `hooks/kill-guard.mjs` refuses the rest; its `tree ` prints that process and its descendants as pid, parent and elapsed time, so never list other command lines. Run signal tests on another machine and keep fleet guards trusted. - Stop an orphan on the heavy host with `fleet.sh remote stop-owned ` only when its slot record identifies the same owner and process. diff --git a/plugins/vibe-closedloop/skills/fleet-orchestrator/scripts/slot-lock.sh b/plugins/vibe-closedloop/skills/fleet-orchestrator/scripts/slot-lock.sh index c94e27da..b9bd19c0 100755 --- a/plugins/vibe-closedloop/skills/fleet-orchestrator/scripts/slot-lock.sh +++ b/plugins/vibe-closedloop/skills/fleet-orchestrator/scripts/slot-lock.sh @@ -157,7 +157,7 @@ until acquire; do if [ "$name" = heavy ] && [ -n "$queue_scope" ] && [ -z "$wait_dir" ] && [[ "$owner" != *$'\t'* && "$owner" != *$'\n'* ]]; then wait_dir=$(mktemp -d "$lock_root/$name-$$-XXXXXX") || exit 2 # The directory is published only after its identity and capacity are recorded. - cadence=$(awk -v poll="$poll" 'BEGIN { n = int(poll); print n >= 1 ? n + (n < poll) : 1 }') + cadence=$(awk -v poll="$poll" 'BEGIN { n = int(poll); print (n >= 1 ? n + (n < poll) : 1) }') printf '%s\t%s\t%s\t%s\t%s\t%s\t%s\n' "$$" "$slots" "$(start_of "$$")" "$queue_scope" "$(date +%s)" "$cadence" "$owner" >"$wait_dir/queue" mv "$wait_dir" "$wait_dir.wait" || exit 2 wait_dir=$wait_dir.wait diff --git a/plugins/vibe-closedloop/skills/vibe/scripts/e2e-requirement.mjs b/plugins/vibe-closedloop/skills/vibe/scripts/e2e-requirement.mjs index 9223dad6..31d7f1cb 100644 --- a/plugins/vibe-closedloop/skills/vibe/scripts/e2e-requirement.mjs +++ b/plugins/vibe-closedloop/skills/vibe/scripts/e2e-requirement.mjs @@ -1,8 +1,9 @@ #!/usr/bin/env node // The e2e specs a change owes locally before its pull request opens, beyond what the graph test selector chose. The // repository's rule: an e2e lane is satisfied by the graph-selected specs, plus specs the branch's own changes newly -// reach, plus every spec the change adds or edits; without a graph result, by the CI changes job's changed-spec union, -// and by the whole lane wherever that union cannot narrow. A pull request once changed a shared e2e helper, six +// reach, plus every spec the change adds or edits; without a graph result, by the CI changes job's changed-spec union. +// Changes to shared suite inputs that the workflow cannot narrow require the whole lane even with a graph result. +// A pull request once changed a shared e2e helper, six // stories and one spec, ran two targeted specs, and broke main in a spec that opens one of those stories by its // Storybook URL. The graph selector cannot see that edge (a spec reaches its story through the id parameter of the iframe page, // not an import), so this module computes it: a changed story owes every suite spec that names the story's id, read @@ -26,9 +27,10 @@ import { isEntryPoint } from "../../../shared/plugin-roots.mjs"; import { containerizedIntent } from "../../../lib/vibe/scripts/docker-disk-admission.mjs"; import { LANE_RECORDS_FILE } from "./lane-outcomes.mjs"; +import { E2E_SELECTION_KEYS, laneRunCommit } from "./lane-run-witness.mjs"; import { witnessProblem } from "./lane-witness-check.mjs"; -const { git } = await vibeCore("lib/vibe/scripts/session-record.mjs"); +const { absoluteGitDir, git } = await vibeCore("lib/vibe/scripts/session-record.mjs"); const { boundWith, installedProviders } = await vibeCore("lib/vibe/scripts/provider.mjs"); export const E2eSurface = Object.freeze({ Web: "web", Desktop: "desktop" }); @@ -63,8 +65,8 @@ const RAN_RESULTS = new Set(["pass", "env-skip", "main-preexisting"]); * What the change from `base` to `head` owes each e2e lane the provider declares: * `[{ surface, required, full, reasons, lane, specs }]`. `specs` are the specs owed beyond the graph selection (those a * changed story's id reaches, those that import a file the change adds, and the surface's changed specs). `full` is true - * only for a fallback: a changed story whose specs cannot be found completely, or, with no graph result for the surface - * (`graphSelection[surface]` not a list), a change the changes job's union cannot narrow. `reasons` name the story ids that + * for a changed story whose specs cannot be found completely, a shared input the workflow cannot narrow, + * or a change the changes job's union cannot narrow when there is no graph result. `reasons` name the story ids that * added specs, the incomplete story, or the missing graph and the paths the union could not narrow. * `binding` is the session's provider binding; with none (a row outside a vibe session) the installed provider serving * this repository's origin is read. `files` replaces the committed diff with the caller's changed-file set, read from @@ -132,10 +134,21 @@ export function laneSurface(command) { return null; } +/** A plain full-lane name is insufficient when the command or its witnessed environment filters the run. */ +function ranWholeE2e({ command, environment, targeted }) { + if (targeted || /\btest:web-smoke\b/.test(command)) return false; + const args = /(?:^|\s)(?:--(?:grep(?:-invert)?|project|shard|last-failed|only-changed|list)|-g)(?=\s|=|$)/; + if (args.test(command) || /\btest:e2e\b.*\s[^\s]*\.spec\.[cm]?[jt]sx?/.test(command)) return false; + return !E2E_SELECTION_KEYS.some((key) => { + const assignment = new RegExp(`(?:^|\\s)${key}=(?:"([^"]*)"|'([^']*)'|([^\\s]*))`).exec(command); + return Boolean(assignment ? (assignment[1] ?? assignment[2] ?? assignment[3]) : environment?.[key]); + }); +} + /** * The e2e evidence pre-pr-lanes.mjs recorded for `head` (default: the worktree's HEAD) in the session's lane records. * `receipts`: one per witnessed e2e lane run that `check` accepts as run (`pass`, `env-skip`, `main-preexisting`), `full` - * unless it was a targeted run, with the specs it ran. `notRun`: the e2e lanes recorded not-run, with the record's reason + * when it ran without a spec, tag, shard or project filter, with the known specs otherwise. `notRun`: the e2e lanes recorded not-run, with the record's reason * and the skip ruling it quotes (`{ id, source }`, else null); only a quoted ruling lets one stand in for a run. `graphSelection`: the union of the graph selections the targeted records carry, * null when none does. No records (a worktree outside a vibe session) is empty evidence; an unparseable file throws. */ @@ -149,9 +162,9 @@ export function recordedE2eEvidence(worktree, { head } = {}) { if (!Array.isArray(records)) throw new Error(`${file} is not a list of lane records`); const at = head ?? git(worktree, ["rev-parse", "HEAD"]); const current = records.filter((record) => record?.head === at && typeof record.command === "string" && laneSurface(record.command)); - const ran = current.filter((record) => RAN_RESULTS.has(record.result) && !witnessProblem(record)); + const ran = current.filter((record) => RAN_RESULTS.has(record.result) && laneRunCommit(record) === at && !witnessProblem(record)); const receipts = ran.map((record) => ({ surface: laneSurface(record.command), lane: record.command, result: record.result, - full: !record.targeted, specs: Array.isArray(record.targeted?.specs) ? [...record.targeted.specs] : [] })); + full: ranWholeE2e(record), specs: Array.isArray(record.targeted?.specs) ? [...record.targeted.specs] : [] })); const notRun = current.filter((record) => record.result === "not-run").map((record) => ({ surface: laneSurface(record.command), lane: record.command, reason: record.reason ?? null, ruling: quotedRuling(record) })); let graphSelection = null; @@ -224,8 +237,18 @@ function surfaceRequirement(context, surface, spec, graphSelection) { } const owed = (extra) => [...new Set([...stories.specs, ...reached, ...extra])].sort(); if (stories.incomplete.length) return row({ full: true, reasons: stories.incomplete, specs: owed(changedSpecs) }); - if (Array.isArray(graphSelection)) return row({ reasons: stories.ids, specs: owed(changedSpecs) }); const suite = changed.filter(inSuite); + if (Array.isArray(graphSelection)) { + const shared = suite.filter((file) => !SPEC.test(file)); + try { + if (shared.length && runClassifier(context, classifier, shared).length === 0) { + return row({ full: true, reasons: shared, specs: owed(changedSpecs) }); + } + } catch (error) { + return row({ full: true, reasons: [`${spec.classifier} could not check shared inputs (${error.message})`], specs: owed(changedSpecs) }); + } + return row({ reasons: stories.ids, specs: owed(changedSpecs) }); + } if (suite.length === 0) return row({ reasons: [NO_GRAPH, ...stories.ids], specs: owed([]) }); try { // The whole set decides, as in CI; each path is then asked alone so the reasons name only those it cannot narrow. @@ -379,13 +402,13 @@ function classifierInput(step) { } /** - * Runs the classifier step's own shell, as the changes job runs it on a pull request, in a scratch folder holding the - * changed suite files and every repository file its script names, as they are at `head`. Returns the specs it names. + * Runs the classifier step's own shell, as the changes job runs it on a pull request, in the worktree's private Git + * directory. Its scratch folder holds the changed suite files and every repository file its script names, as they are + * at `head`. Returns the specs it names and removes the scratch folder after execution. */ function runClassifier({ worktree, head, fromWorktree }, step, suite) { const input = classifierInput(step); - const gitDir = git(worktree, ["rev-parse", "--absolute-git-dir"]); - const scratch = mkdtempSync(path.join(gitDir, "vibe-e2e-classifier-")); + const scratch = mkdtempSync(path.join(absoluteGitDir(worktree), "vibe-e2e-classifier-")); try { const tree = path.join(scratch, "tree"); mkdirSync(tree); diff --git a/plugins/vibe-closedloop/skills/vibe/scripts/lane-run-witness.mjs b/plugins/vibe-closedloop/skills/vibe/scripts/lane-run-witness.mjs index ee5d4843..681f4ddc 100644 --- a/plugins/vibe-closedloop/skills/vibe/scripts/lane-run-witness.mjs +++ b/plugins/vibe-closedloop/skills/vibe/scripts/lane-run-witness.mjs @@ -18,6 +18,18 @@ import { RUNNER_HOST } from "../../handoff/scripts/e2e-tier.mjs"; const COMMIT = /^[a-f0-9]{40}$/; const NO_DIFF = createHash("sha256").digest("hex"); +/** Controls that turn a whole E2E command into a subset without changing its argv. */ +export const E2E_SELECTION_KEYS = Object.freeze([ + "E2E_CHANGED_SPECS", "E2E_SMOKE_TAG", "E2E_SHARD", + "DESKTOP_E2E_CHANGED_SPECS", "DESKTOP_E2E_SMOKE_TAG", "DESKTOP_E2E_SHARD", + "DESKTOP_E2E_SPECS", "DESKTOP_E2E_PROJECTS", +]); + +/** The actual tested commit, including an external proof commit when the local record names a same-tree head. */ +export function laneRunCommit(record) { + return record?.ranOn ? record.ranOn.proofCommit : record?.head; +} + /** A unique private directory even when multiple lanes start together. */ function witnessDirectory(worktree) { const root = path.join(absoluteGitDir(worktree), "vibe-lane-witnesses"); @@ -26,9 +38,8 @@ function witnessDirectory(worktree) { } /** The values of the named environment keys this run sees, sorted by key; an unset key is null. */ -function witnessEnvironment(keys, env = process.env) { - // These existing controls can turn a full E2E lane into a subset without changing the command. - const selectors = ["E2E_CHANGED_SPECS", "E2E_SMOKE_TAG", "E2E_QUARANTINE_TAG", "E2E_SHARD", "DESKTOP_E2E_SPECS", "DESKTOP_E2E_PROJECTS"]; +export function witnessEnvironment(keys, env = process.env) { + const selectors = [...E2E_SELECTION_KEYS, "E2E_QUARANTINE_TAG"]; return Object.fromEntries([...new Set([...keys, ...selectors.filter((key) => env[key] !== undefined)])] .sort().map((key) => [key, env[key] ?? null])); } @@ -46,6 +57,11 @@ export function declaredEnvironment(pairs) { /** Runs the lane command in the worktree and keeps its log, source, command, environment and exit code beside the records. */ export function witnessRun(values, source) { + return witnessedLaneRun(values, source).status ?? 1; +} + +/** Execute a local lane and return the evidence the lane recorder can attach directly. */ +export function witnessedLaneRun(values, source) { const command = values.command.trim(); const outcomes = values.outcomes && path.resolve(values.outcomes); if (outcomes && existsSync(outcomes)) throw new Error(`--outcomes ${outcomes} already exists; move an earlier run's report away, so the file is the one this run writes`); @@ -54,18 +70,19 @@ export function witnessRun(values, source) { const environment = witnessEnvironment(values.env ?? []); const gitTree = git(values.worktree, ["rev-parse", "--verify", `${source.head}^{tree}`]); const log = openSync(`${stem}.log`, "wx", 0o600); - let exitCode; + let result; + process.stdout.write(`witness ${stem}.json\n`); try { - exitCode = withStableSource(values.worktree, (current) => { + result = withStableSource(values.worktree, (current) => { if (!sameSource(source, current)) throw new Error("SOURCE-MOVED before lane startup"); - return { status: spawnSync(command, { cwd: values.worktree, shell: true, stdio: ["ignore", log, log] }).status ?? 1 }; - }, { head: source.head }).status; + return spawnSync(command, { cwd: values.worktree, shell: true, stdio: ["ignore", log, log] }); + }, { head: source.head }); } finally { closeSync(log); } - const witness = { command, head: source.head, gitTree, source, environment, exitCode, log: evidenceFingerprint(`${stem}.log`, LANE_LOG_MAX_BYTES), + if (result.error) throw result.error; + const witness = { command, head: source.head, gitTree, source, environment, exitCode: result.status ?? 1, log: evidenceFingerprint(`${stem}.log`, LANE_LOG_MAX_BYTES), ...(outcomes && existsSync(outcomes) ? { outcomes: evidenceFingerprint(outcomes) } : {}), startedAt, finishedAt: new Date().toISOString() }; writeFileSync(`${stem}.json`, `${JSON.stringify(witness, null, 2)}\n`, { mode: 0o600, flag: "wx" }); - process.stdout.write(`witness ${stem}.json\n`); - return exitCode; + return { status: result.status, signal: result.signal, recorded: { witness: evidenceFingerprint(`${stem}.json`), environment } }; } /** Stream the heavy-host output to the caller and retain the exact bytes beside the runner's completion facts. */ diff --git a/plugins/vibe-closedloop/skills/vibe/scripts/pre-pr-lanes.mjs b/plugins/vibe-closedloop/skills/vibe/scripts/pre-pr-lanes.mjs index 4a5286d2..754c9260 100644 --- a/plugins/vibe-closedloop/skills/vibe/scripts/pre-pr-lanes.mjs +++ b/plugins/vibe-closedloop/skills/vibe/scripts/pre-pr-lanes.mjs @@ -132,8 +132,9 @@ import { CACHED_RESULT, cachedRecord, findReusable, laneKeyFor, Provenance } fro import { storyTypecheckLane } from "./story-typecheck.mjs"; import { launchedReviewerOrVerifier } from "./agent-models.mjs"; import { E2E_SPEC, observedGraphSelection, relativePath } from "./lane-graph.mjs"; -import { E2eSurface, FULL_LANE, isDesktopE2eLane, isWebE2eLane, missingE2eSpecs, RUN_ELSEWHERE } from "./e2e-requirement.mjs"; -import { declaredEnvironment, remoteRun, remoteRunLog, witnessProblem, witnessRun, witnessWorkflowRun } from "./lane-run-witness.mjs"; +import { E2eSurface, FULL_LANE, isDesktopE2eLane, isWebE2eLane, laneSurface, missingE2eSpecs, RUN_ELSEWHERE } from "./e2e-requirement.mjs"; +import { declaredEnvironment, remoteRun, remoteRunLog, witnessedLaneRun, witnessEnvironment, witnessProblem, witnessRun, witnessWorkflowRun } from "./lane-run-witness.mjs"; +import { fullPackageLaneCommand, packageLaneNotice } from "../../../lib/handoff/scripts/full-ci-check.mjs"; export { witnessProblem }; import { environmentalSkipProblem, interruptedRuns, LANE_RECORDS_FILE, laneRunOutcome, readLaneOutcomes, rerunOf, runningRecord, startLaneInBackground } from "./lane-outcomes.mjs"; import { vibeCore } from "../../../shared/vibe-core.mjs"; @@ -607,7 +608,7 @@ function sameStringList(left, right) { } /** Valid targeted E2E receipts for the current source and changed-file scope. */ -export async function targetedE2eCoverage(values, lanes, records, selected, readTurn) { +export async function targetedE2eCoverage(values, lanes, records, selected, readTurn, warn = () => {}) { if (!allowsTargetedE2e(values.worktree)) return []; const scope = targetedScope(values); const covered = []; @@ -630,7 +631,10 @@ export async function targetedE2eCoverage(values, lanes, records, selected, read || (current.runtime === "claude" && JSON.stringify(current.evidence) !== JSON.stringify(record.targeted.graph?.evidence))) continue; let requirement; try { requirement = targetedSpecRequirements(values, current, scope, lane, record.targeted.specs); } catch { continue; } - if (requirement.accepted) covered.push({ lane, specs: record.targeted.specs }); + if (requirement.accepted) { + if (requirement.warning) warn(requirement.warning); + covered.push({ lane, specs: record.targeted.specs }); + } } return covered; } @@ -764,16 +768,22 @@ async function main(argv) { if (mainSource && mainSource.diffSha256 !== createHash('sha256').digest('hex')) throw new Error('captured main must be clean to establish a main-preexisting failure'); if (command === "run") { const ticket = containerizedIntent("sh", ["-c", values.command],values.worktree) ? originatingStackTicket(values.worktree) : null; - const execute = (tree, expected) => withStableSource(tree, async (current) => { - if (!sameSource(expected, current)) throw new Error('SOURCE-MOVED before lane startup'); + const wholePackage = fullPackageLaneCommand(values.command.trim()); + const execute = async (tree, expected) => { const preflight = lanePreflightProblem(values.command); if (preflight) throw new Error(preflight); const fleet = fleetLaneInvocation(values, expected, tree, ticket); - const run = values.recipe ? await witnessWorkflowRun(fleet, tree, expected, values.command.trim()) - : fleet ? spawnSync(fleet.bin, fleet.args, { cwd: tree, stdio: 'inherit' }) - : spawnSync(values.command, { cwd: tree, shell: true, stdio: 'inherit' }); - return { status: run.status, recorded: run.recorded, outcome: laneRunOutcome(run, { fleet: Boolean(fleet?.receipt) && !run.recorded }), fleet: fleet?.receipt }; - }, { head: expected.head }); + const run = !fleet && wholePackage ? witnessedLaneRun({ ...values, worktree: tree }, expected) + : await withStableSource(tree, (current) => { + if (!sameSource(expected, current)) throw new Error('SOURCE-MOVED before lane startup'); + if (values.recipe) return witnessWorkflowRun(fleet, tree, expected, values.command.trim()); + if (fleet) return spawnSync(fleet.bin, fleet.args, { cwd: tree, stdio: 'inherit' }); + return spawnSync(values.command, { cwd: tree, shell: true, stdio: 'inherit' }); + }, { head: expected.head }); + const environment = !fleet && !run.recorded && laneSurface(values.command) ? witnessEnvironment([]) : null; + return { status: run.status, recorded: run.recorded ?? (environment && { environment }), + outcome: laneRunOutcome(run, { fleet: Boolean(fleet?.receipt) && !run.recorded }), fleet: fleet?.receipt }; + }; const lane = { command: values.command.trim(), head: tested, source, laneKey: selected.laneKey }; // A run killed with its process leaves this record, which check reports as interrupted. withRecordsLock(values.worktree, () => writeRecords(values.worktree, [...readRecords(values.worktree), runningRecord(lane)])); @@ -809,6 +819,9 @@ async function main(argv) { process.stderr.write(`Both runs failed at ${tested} and main ${mainTested}. Record matching test ids and assertions with record --result main-preexisting --main-sha --failures .\n`); } values.fleetReceipt = fleetReceipt; + if (result === "pass" && wholePackage && !witnessed) { + process.stderr.write("CI-NOT-RUN: this full package lane needs a run witness at PR create. Use witness on the runner and record its evidence.\n"); + } } const cacheKey = source.diffSha256 === createHash("sha256").digest("hex") ? laneKeyFor(values.worktree, { command: values.command, base: values.base, config: values.config }) : null; // Two lanes of one pool finish close together: the read, the change and the write happen under one lock so neither record is lost. @@ -845,7 +858,8 @@ async function main(argv) { } const witnessedRecords = records.filter((record) => !unwitnessed.has(record)); const targeted = targetedLaneDecision(values, named); - const targetedRuns = await targetedE2eCoverage(values, named, witnessedRecords, selected); + const targetedRuns = await targetedE2eCoverage(values, named, witnessedRecords, selected, undefined, + (warning) => process.stdout.write(`${warning}\n`)); const targetedRunLanes = targetedRuns.map((item) => item.lane); const left = notRunLanes(named.filter((lane) => !skip?.test(lane) && !targeted.left.includes(lane) && !targetedRunLanes.includes(lane)), witnessedRecords, selected, { identity: hasStagingE2eIdentity(values.worktree), harness: hasDisplaylessElectronHarness(), worktree: values.worktree }); @@ -906,6 +920,13 @@ async function main(argv) { for (const line of hints.full) process.stdout.write(`${line}\n`); if (hints.targetable.length > 0) process.stdout.write(`TARGETED-E2E: this repository allows a targeted E2E lane in place of the full one for ${hints.targetable.join(", ")}; ${TARGETED_RECORD}\n`); } + // An impact report can still drive focused work. The new whole-package policy applies at PR create. + try { + const notice = packageLaneNotice(values.worktree, head); + if (notice) process.stdout.write(`CI-NOT-RUN ${notice}\n`); + } catch (error) { + process.stdout.write(`CI-NOT-RUN could not check full package lanes: ${error.message}\n`); + } process.stdout.write(`pre-pr lanes: ${lanes.length} lanes, ${missing.length} missing${notRun.length ? `, ${notRun.length} not run locally` : ""}${values["reuse-cache"] || values["reuse-unaffected"] ? `, ${covered.length + unaffected.length} cached` : ""} for changed-file scope ${selected.laneKey ?? "none"}\n`); return { exitCode: missing.length === 0 ? 0 : 1 }; })(); diff --git a/plugins/vibe/.claude-plugin/plugin.json b/plugins/vibe/.claude-plugin/plugin.json index b2c76c2e..92e54204 100644 --- a/plugins/vibe/.claude-plugin/plugin.json +++ b/plugins/vibe/.claude-plugin/plugin.json @@ -1,7 +1,7 @@ { "name": "vibe-generic", "description": "Vibe sessions and handoff in any git repository, with fleet orchestration, seed refresh and ticket workflows", - "version": "1.1.122", + "version": "1.1.123", "dependencies": ["closedloop-core", "vibe-core"], "author": {"name": "ClosedLoop", "email": "support@closedloop.ai"} } diff --git a/plugins/vibe/.codex-plugin/plugin.json b/plugins/vibe/.codex-plugin/plugin.json index b2f87225..879f8974 100644 --- a/plugins/vibe/.codex-plugin/plugin.json +++ b/plugins/vibe/.codex-plugin/plugin.json @@ -1,6 +1,6 @@ { "name": "vibe-generic", - "version": "1.1.122", + "version": "1.1.123", "description": "Vibe sessions and handoff in any git repository, with fleet orchestration, seed refresh and ticket workflows", "author": {"name": "ClosedLoop", "email": "support@closedloop.ai"}, "homepage": "https://github.com/closedloop-ai/claude-plugins", diff --git a/plugins/vibe/README.md b/plugins/vibe/README.md index eb2e37bf..0d0bacd3 100644 --- a/plugins/vibe/README.md +++ b/plugins/vibe/README.md @@ -337,7 +337,7 @@ Run the matching Codex suite from the repository root with ### Runtime files -Version `1.1.122` contains 17 skills and 17 agents, and no hook manifest: the +Version `1.1.123` contains 17 skills and 17 agents, and no hook manifest: the `vibe-core` plugin, which vibe declares as a dependency, registers the hooks and runs `hooks/runtime.mjs` from the vibe a session uses. Skill commands forward to guards in `hooks/` and runtime modules in `lib/`. The package has no standalone commands, root shell scripts or production Python tools. Tests sit beside their owners; Python contract helpers and the generic scan live in `tools/python/`. diff --git a/plugins/vibe/hooks/pr-create-full-ci.test.mjs b/plugins/vibe/hooks/pr-create-full-ci.test.mjs index 7bf3f9dc..dbb01c3a 100644 --- a/plugins/vibe/hooks/pr-create-full-ci.test.mjs +++ b/plugins/vibe/hooks/pr-create-full-ci.test.mjs @@ -1,12 +1,19 @@ // PR create refuses any head in scope, vibe or not, until every declared CI workflow job ran on it in full (full-ci-check.mjs). import assert from "node:assert/strict"; -import { mkdtempSync, rmSync, writeFileSync } from "node:fs"; +import { spawnSync } from "node:child_process"; +import { mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from "node:fs"; import { tmpdir } from "node:os"; import path from "node:path"; import test from "node:test"; +import { fileURLToPath } from "node:url"; import { prCreateGuard } from "./pr-create-guard.mjs"; import { recordHookSkill } from "./hook-session-scope.mjs"; -import { ciRepository } from "../lib/handoff/scripts/full-ci-fixture.mjs"; +import { ciRepository, recordLanes } from "../lib/handoff/scripts/full-ci-fixture.mjs"; +import { passingPnpmPath } from "../skills/vibe/scripts/test-fixtures.mjs"; +import { REFUSING_CHECKS } from "../lib/handoff/scripts/refusing-checks.mjs"; + +const FULL_CI = fileURLToPath(new URL("../lib/handoff/scripts/full-ci-check.mjs", import.meta.url)); +const LANES = fileURLToPath(new URL("../skills/vibe/scripts/pre-pr-lanes.mjs", import.meta.url)); test("class B: a plain worker's PR from a fleet conversation is refused until every CI job ran in full on its head", (t) => { const home = mkdtempSync(path.join(tmpdir(), "pr-full-ci-home-")); @@ -26,3 +33,94 @@ test("class B: a plain worker's PR from a fleet conversation is refused until ev r.record(r.lanes.map(({ command }) => command)); assert.equal(create(`gh pr create --base main --body-file ${body}`), null, "every job ran on the head's tree"); }); + +function packagePr(t) { + const home = mkdtempSync(path.join(tmpdir(), "pr-package-lanes-home-")); + t.after(() => rmSync(home, { recursive: true, force: true })); + recordHookSkill("fleet-lanes", "vibe:fleet-orchestrator", home); + const r = ciRepository(t, { declared: false }); + mkdirSync(path.join(r.worktree, "apps/api"), { recursive: true }); + writeFileSync(path.join(r.worktree, "pnpm-workspace.yaml"), "packages:\n - 'apps/*'\n"); + writeFileSync(path.join(r.worktree, "turbo.json"), '{"tasks":{"test":{}}}\n'); + writeFileSync(path.join(r.worktree, "apps/api/package.json"), JSON.stringify({ name: "api", scripts: { + test: "vitest run", "test:compatibility": "vitest run --config vitest.config.compatibility.mts", + } })); + r.git("add", "."); + r.git("commit", "-qm", "declare workspace"); + const base = r.git("rev-parse", "HEAD"); + r.git("update-ref", "refs/remotes/origin/main", base); + writeFileSync(path.join(r.worktree, "apps/api/api.ts"), "export const changed = 1;\n"); + r.git("add", "."); + r.git("commit", "-qm", "change API"); + const head = () => r.git("rev-parse", "HEAD"); + const record = (commands, extra) => recordLanes(r.worktree, head(), commands, extra); + const guard = (command) => prCreateGuard({ cwd: r.worktree, session_id: "fleet-lanes", transcript_path: null, + tool_input: { command } }, home); + const env = { ...process.env, HOME: home, PATH: passingPnpmPath(home), CLAUDE_CODE_SESSION_ID: "", CODEX_THREAD_ID: "" }; + const run = (script, ...args) => spawnSync(process.execPath, [script, ...args, "--worktree", r.worktree], { encoding: "utf8", env }); + const report = run(FULL_CI, "report"); + const runWhole = (...commands) => { + assert.equal(report.status, 1, report.stderr); + const file = /^REPORT (.+)$/m.exec(report.stdout)[1]; + for (const command of commands) { + const result = run(LANES, "run", "--report", file, "--head", head(), "--command", command); + assert.equal(result.status, 0, result.stderr + result.stdout); + } + }; + return { ...r, base, head, record, guard, run, runWhole }; +} + +const FULL_TEST = "pnpm turbo run test --filter=api --force"; +const COMPATIBILITY = "pnpm --filter=api test:compatibility"; + +test("a new PR needs the full Turbo task and compatibility command for a touched package", (t) => { + const r = packagePr(t); + r.record(["pnpm --filter api exec vitest run changed.test.ts"]); + assert.match(r.guard("gh pr create --fill")?.reason ?? "", /pnpm turbo run test --filter=api.*pnpm --filter=api test:compatibility/); + r.runWhole(FULL_TEST); + assert.match(r.guard("gh pr create --fill")?.reason ?? "", /test:compatibility/); + r.runWhole(COMPATIBILITY); + assert.equal(r.guard("gh pr create --fill"), null); + const file = path.join(r.git("rev-parse", "--absolute-git-dir"), "vibe-lane-results.json"); + const records = JSON.parse(readFileSync(file, "utf8")); + writeFileSync(file, JSON.stringify(records.map((record) => record.command === FULL_TEST + ? { ...record, targeted: { specs: ["changed.test.ts"] } } : record))); + assert.match(r.guard("gh pr create --fill")?.reason ?? "", /pnpm turbo run test --filter=api/); +}); + +test("a later origin/main invalidates lane evidence even when the merged head has the same tree", (t) => { + const r = packagePr(t); + r.runWhole(FULL_TEST, COMPATIBILITY); + const oldHead = r.head(); + const main = r.git("commit-tree", r.git("rev-parse", `${r.base}^{tree}`), "-p", r.base, "-m", "later main"); + r.git("update-ref", "refs/remotes/origin/main", main); + assert.match(r.guard("gh pr create --fill")?.reason ?? "", /origin\/main/); + assert.equal(r.guard("git push origin HEAD"), null); + r.git("merge", "--no-edit", main); + assert.equal(r.git("rev-parse", "HEAD^{tree}"), r.git("rev-parse", `${oldHead}^{tree}`)); + assert.match(r.guard("gh pr create --fill")?.reason ?? "", /pnpm turbo run test --filter=api/); + r.runWhole(FULL_TEST, COMPATIBILITY); + assert.equal(r.guard("gh pr create --fill"), null); +}); + +test("in-flight lane checks warn without changing the focused check verdict", (t) => { + const r = packagePr(t); + // Keep the report outside the worktree so it cannot affect the witnessed source. + const focused = "pnpm --filter api exec vitest run changed.test.ts"; + const file = path.join(r.git("rev-parse", "--absolute-git-dir"), "focused.txt"); + writeFileSync(file, ` ${focused}\n`); + const run = r.run(LANES, "run", "--command", focused, "--head", r.head(), "--report", file); + assert.equal(run.status, 0, run.stderr); + const check = r.run(LANES, "check", "--report", file); + assert.equal(check.status, 0, check.stderr + check.stdout); + assert.match(check.stdout, /^CI-NOT-RUN .*needs witnessed whole package lanes:/m); + const input = { worktree: r.worktree, head: r.head() }; + assert.deepEqual(REFUSING_CHECKS.fullCiProblem.replay({ ...input, pushed: [r.head()] }), []); + assert.match(REFUSING_CHECKS.fullCiProblem.replay(input)[0], /needs witnessed whole package lanes/); +}); + +test("a fetched remote-only head cannot bypass new-PR checks from a plain fleet checkout", (t) => { + const r = packagePr(t); + r.git("update-ref", "refs/remotes/origin/remote-only-topic", r.head()); + assert.match(r.guard("gh pr create --head remote-only-topic --fill")?.reason ?? "", /needs witnessed whole package lanes/); +}); diff --git a/plugins/vibe/hooks/pr-create-guard.mjs b/plugins/vibe/hooks/pr-create-guard.mjs index 1e0361f8..b62bc33b 100644 --- a/plugins/vibe/hooks/pr-create-guard.mjs +++ b/plugins/vibe/hooks/pr-create-guard.mjs @@ -29,7 +29,7 @@ import { deliveryPlacementProblem, deliveryRepository, fleetRowHasPullRequest } import { validChat } from "../lib/fleet-orchestrator/scripts/chat-binding.mjs"; import os from "node:os"; import { BodyFileError, OVERRIDE_CHECKS, overriddenChecks, readPrBodyFile } from "../lib/handoff/scripts/gate-override.mjs"; -import { declaredWorkflowLanes, fullCiProblem } from "../lib/handoff/scripts/full-ci-check.mjs"; +import { declaresPackageLanes, declaredWorkflowLanes, fullCiProblem } from "../lib/handoff/scripts/full-ci-check.mjs"; import { refusalReplayProblem } from "../lib/handoff/scripts/refusing-check-replay.mjs"; import { e2eGateProblems } from "../lib/handoff/scripts/e2e-gate-check.mjs"; @@ -219,7 +219,12 @@ function prHeadTarget(cwd, head, repositoryOverrides) { // `--head` may name the remote branch the worktree's branch is pushed to under another name (#438); it stands for // that local branch, so its owner and handoff gate are the local branch's. const local = localBranchExists(cwd, head) ? head : pushedUpstreamBranch(cwd, head) ?? head; - headCommit = git(cwd, ["rev-parse", "--verify", `refs/heads/${local}^{commit}`]); + try { headCommit = git(cwd, ["rev-parse", "--verify", `refs/heads/${local}^{commit}`]); } + catch { + if (head.startsWith(VIBE_BRANCH)) return null; + const remoteHead = git(cwd, ["rev-parse", "--verify", `refs/remotes/origin/${head}^{commit}`]); + return sessionCwd && carriesSessionWork(cwd, remoteHead) ? { cwd } : { nonVibe: true }; + } for (const entry of git(cwd, ["worktree", "list", "--porcelain"]).split(/\n\s*\n/)) { const worktree = /^worktree (.+)$/m.exec(entry)?.[1]; if (!worktree) continue; @@ -308,7 +313,10 @@ function prReadinessProblem(call, target, binding) { let headCommit; try { headCommit = git(call.cwd, ["rev-parse", "--verify", `${call.head ? prHeadRef(call.cwd, call.head) : "HEAD"}^{commit}`]); } catch { - try { return declaredWorkflowLanes(call.cwd, "HEAD") ? "the PR head cannot be read to check its CI workflow runs" : null; } + try { + return declaresPackageLanes(call.cwd, "HEAD") || declaredWorkflowLanes(call.cwd, "HEAD") + ? "the PR head cannot be read to check its test lanes" : null; + } catch { return null; } } const worktree = git(call.cwd, ["worktree", "list", "--porcelain"]).split(/\n\s*\n/) diff --git a/plugins/vibe/lib/handoff/scripts/full-ci-check.mjs b/plugins/vibe/lib/handoff/scripts/full-ci-check.mjs index 2fffa1b7..29082e9e 100644 --- a/plugins/vibe/lib/handoff/scripts/full-ci-check.mjs +++ b/plugins/vibe/lib/handoff/scripts/full-ci-check.mjs @@ -1,25 +1,22 @@ -// A pull request to a repository whose vibe-handoff-paths.json declares a github-workflow lane source is refused at PR -// create until every job and matrix entry of that workflow, read at the PR head, has a passing -// run of the head's exact tree recorded by pre-pr-lanes.mjs with its run witness, unless a ticketed gate override for -// "ci lanes" quotes the ruling that allows the skip (operator ruling, 2026-12-02 about 9:10 PM CST: "stop allowing -// things like this to even make it to a PR without adequate testing"). A pull request once opened after only its -// focused test files ran, and CI failed on tests outside them and on a missed plugin version bump. +// A new pull request needs a head that contains fetched origin/main and records from that head for the whole lanes. +// Workflow repositories declare their jobs in vibe-handoff-paths.json. pnpm/Turbo workspaces declare package tests +// and compatibility scripts in their manifests. Focused tests remain useful for development and push checks warn. // -// Usage: full-ci-check.mjs report --worktree writes the workflow lane report for HEAD into the git dir and -// prints `REPORT ` and one `UNRUN ` line per job still to run with -// pre-pr-lanes.mjs run --fleet-where remote --fleet-orch --fleet-owner --worktree -// --head --command '' --report (the recipe is the job's `command` in the report; the heavy -// host needs a worktree at the same path and HEAD). Exits 1 while any job is unrun. +// Usage: full-ci-check.mjs report --worktree writes the reports pre-pr-lanes.mjs takes with --report and prints +// one UNRUN line per missing lane. Run package lanes on an allowed host with pre-pr-lanes.mjs run, or use +// witness on the runner and record its evidence. Replay workflow jobs with run --fleet-where remote. -import { execFileSync } from "node:child_process"; +import { execFileSync, spawnSync } from "node:child_process"; import { createHash } from "node:crypto"; import { existsSync, readFileSync, writeFileSync } from "node:fs"; import path from "node:path"; import { parseArgs } from "node:util"; import { capturedJson } from "../../vibe/scripts/captured-json.mjs"; -import { workflowLaneDefinitions } from "../../vibe/scripts/workflow-lane-definitions.mjs"; +import { readGitInventory } from "../../vibe/scripts/git-inventory.mjs"; +import { workflowLaneDefinitions, workspacePackages } from "../../vibe/scripts/workflow-lane-definitions.mjs"; import { committedSourceIdentity } from "../../vibe/scripts/tested-head.mjs"; -import { witnessProblem } from "../../../skills/vibe/scripts/lane-run-witness.mjs"; +import { globMatcher } from "../../../skills/vibe/scripts/e2e-requirement.mjs"; +import { laneRunCommit, witnessProblem } from "../../../skills/vibe/scripts/lane-run-witness.mjs"; import { LANE_RECORDS_FILE } from "../../../skills/vibe/scripts/lane-outcomes.mjs"; import { quotedRulingOverride } from "./gate-override.mjs"; import { isEntryPoint } from "../../../shared/plugin-roots.mjs"; @@ -37,6 +34,103 @@ export function pushCheckAsksPrePrChecks(createdAt) { export const CI_LANES_OVERRIDE = "ci lanes"; const git = (worktree, args) => execFileSync("git", ["-C", worktree, ...args], { encoding: "utf8", stdio: ["ignore", "pipe", "pipe"], maxBuffer: 64 * 1024 * 1024 }); +const PNPM_WORKSPACE = "pnpm-workspace.yaml"; +const COMPATIBILITY_TASK = "test:compatibility"; +const NAMES = /^(?:@[a-z0-9_.-]+\/)?[a-z0-9_.-]+$/i; +const fullTest = (name) => `pnpm turbo run test --filter=${name} --force`; +const compatibilityTest = (name) => `pnpm --filter=${name} ${COMPATIBILITY_TASK}`; + +/** Identify the exact full-task commands so local lane runs capture their own witness. */ +export function fullPackageLaneCommand(command) { + const name = /(?:^|\s)--filter=([^\s]+)/.exec(command)?.[1]; + return Boolean(name && NAMES.test(name) && [fullTest(name), compatibilityTest(name)].includes(command)); +} + +function gitStatus(worktree, args) { + const result = spawnSync("git", ["-C", worktree, ...args], { stdio: "ignore" }); + if (result.error) throw result.error; + return result.status; +} + +function fetchedMain(worktree) { + try { return git(worktree, ["rev-parse", "--verify", "refs/remotes/origin/main^{commit}"]).trim(); } + catch { return null; } +} + +function mainAncestryNotice(worktree, head, main) { + if (!main || gitStatus(worktree, ["merge-base", "--is-ancestor", main, head]) === 0) return null; + return `PR head ${head.slice(0, 12)} does not contain fetched origin/main ${main.slice(0, 12)}. Merge or rebase onto it and rerun the lanes`; +} + +/** Whether the committed source uses pnpm and Turbo to define package test lanes. */ +export function declaresPackageLanes(worktree, head) { + const has = (file) => gitStatus(worktree, ["cat-file", "-e", `${head}:${file}`]) === 0; + return has(PNPM_WORKSPACE) && (has("turbo.json") || has("turbo.jsonc")); +} + +/** Derive whole tasks from committed workspace manifests and the diff against fetched origin/main. */ +export function packageLaneRequirements(worktree, head) { + if (!declaresPackageLanes(worktree, head)) return null; + const main = fetchedMain(worktree); + const problem = main ? mainAncestryNotice(worktree, head, main) : "fetch origin/main before checking package test lanes"; + if (problem) return { problem, lanes: [] }; + + const patterns = (workspacePackages(git(worktree, ["show", `${head}:${PNPM_WORKSPACE}`])) ?? ["**"]) + .map((pattern) => ({ exclude: pattern.startsWith("!"), glob: globMatcher(pattern.replace(/^!/, "").replace(/^\.\//, "").replace(/\/$/, "")) })); + const matches = (directory) => patterns.some(({ exclude, glob }) => !exclude && glob.test(directory)) + && !patterns.some(({ exclude, glob }) => exclude && glob.test(directory)); + const changed = git(worktree, ["diff", "--name-only", "--no-renames", "-z", main, head, "--"]).split("\0").filter(Boolean); + if (!changed.length) return { lanes: [] }; + const directories = readGitInventory(worktree, ["ls-tree", "-r", "--name-only", "-z", head]) + .split("\0").filter((file) => file.endsWith("/package.json")).map((file) => path.posix.dirname(file)).filter(matches); + const workspace = new Set(directories); + const touched = new Set(); + for (const file of changed) { + // A nested workspace package owns its own paths. + for (let directory = path.posix.dirname(file); directory !== "."; directory = path.posix.dirname(directory)) { + if (!workspace.has(directory)) continue; + touched.add(directory); + break; + } + } + const lanes = []; + for (const directory of [...touched].sort()) { + const { name, scripts } = capturedJson(git(worktree, ["show", `${head}:${directory}/package.json`])); + const test = typeof scripts?.test === "string" && scripts.test.trim(); + const compatibility = typeof scripts?.[COMPATIBILITY_TASK] === "string" && scripts[COMPATIBILITY_TASK].trim(); + if (!test && !compatibility) continue; + if (!NAMES.test(name ?? "")) throw new Error(`invalid workspace package name in ${directory}/package.json`); + if (test) lanes.push({ name: `${name}#test`, command: fullTest(name) }); + if (compatibility) lanes.push({ name: `${name}#${COMPATIBILITY_TASK}`, command: compatibilityTest(name) }); + } + return { lanes }; +} + +function missingPackageLanes(worktree, head, lanes) { + if (!lanes.length) return []; + const records = laneRecords(worktree).filter((record) => record?.head === head && laneRunCommit(record) === head + && record.result === "pass" && record.targeted === undefined); + if (!records.length) return lanes; + const source = committedSourceIdentity(worktree, head); + return lanes.filter(({ command }) => !records.some((record) => record.command === command + && record.source?.head === head && record.source.treeSha256 === source.treeSha256 + && record.source.diffSha256 === source.diffSha256 && record.witness && !witnessProblem(record))); +} + +/** The package requirements and remaining work. This computation never runs a test or writes a record. */ +export function packageLaneStatus(worktree, head) { + const requirements = packageLaneRequirements(worktree, head); + return requirements && { ...requirements, missing: missingPackageLanes(worktree, head, requirements.lanes) }; +} + +/** Readiness text for the same package lanes at PR create and in advisory checks. */ +export function packageLaneNotice(worktree, head) { + const status = packageLaneStatus(worktree, head); + if (status?.problem) return status.problem; + if (!status?.missing.length) return null; + return `PR head ${head.slice(0, 12)} needs witnessed whole package lanes: ${status.missing.map(({ command }) => command).join(", ")}. ` + + `Run full-ci-check.mjs report --worktree ${worktree} for the required commands`; +} /** The declared workflow's path and lanes at `head`, or null when the repository declares no github-workflow lane source there. */ export function declaredWorkflowLanes(worktree, head) { @@ -56,19 +150,26 @@ function laneRecords(worktree) { } /** The declared workflow lanes with no witnessed passing run of `head`'s tree, as `[{ name, command }]`; [] when none are declared. */ -export function unrunCiLanes(worktree, head) { - const declared = declaredWorkflowLanes(worktree, head); +export function unrunCiLanes(worktree, head, { exactCommit = false, declared = declaredWorkflowLanes(worktree, head) } = {}) { if (!declared) return []; - const tree = committedSourceIdentity(worktree, head).treeSha256; const records = laneRecords(worktree); + if (!records.length) return declared.lanes; + const tree = committedSourceIdentity(worktree, head).treeSha256; return declared.lanes.filter(({ command }) => !records.some((record) => record?.command === command && record.result === "pass" + && (!exactCommit || (record.head === head && record.source?.head === head && laneRunCommit(record) === head)) && record.targeted === undefined && record.source?.treeSha256 === tree && !witnessProblem(record))); } /** Why `head` may not be raised as a pull request yet, or null. `bodyText` may be a function, read only when a job is unrun. */ export function fullCiProblem(worktree, head, { bodyText = "", binding = null } = {}) { - const unrun = unrunCiLanes(worktree, head); - if (!unrun.length || quotedRulingOverride(typeof bodyText === "function" ? bodyText() : bodyText, binding, CI_LANES_OVERRIDE)) return null; + const declared = declaredWorkflowLanes(worktree, head); + const main = declared ? fetchedMain(worktree) : null; + const mainNotice = mainAncestryNotice(worktree, head, main); + if (mainNotice) return mainNotice; + const unrun = unrunCiLanes(worktree, head, { exactCommit: Boolean(main), declared }); + if (!unrun.length || quotedRulingOverride(typeof bodyText === "function" ? bodyText() : bodyText, binding, CI_LANES_OVERRIDE)) { + return packageLaneNotice(worktree, head); + } return `every CI workflow job runs in full on the exact head before a pull request, and ${unrun.length} have no witnessed passing run of ${head.slice(0, 12)}: ` + `${unrun.map(({ name }) => name).join(", ")}; full-ci-check.mjs report --worktree ${worktree} names each job's run, ` + `or add "Vibe gate override: : ${CI_LANES_OVERRIDE}: "`; @@ -89,10 +190,23 @@ function main(argv) { const { positionals, values } = parseArgs({ args: argv, allowPositionals: true, options: { worktree: { type: "string" } } }); if (positionals[0] !== "report" || !values.worktree) throw new Error("usage: full-ci-check.mjs report --worktree "); const head = git(values.worktree, ["rev-parse", "HEAD"]).trim(); + const packages = packageLaneStatus(values.worktree, head); + if (packages?.problem) throw new Error(packages.problem); + const declared = declaredWorkflowLanes(values.worktree, head); + const main = declared ? fetchedMain(values.worktree) : null; + const mainNotice = mainAncestryNotice(values.worktree, head, main); + if (mainNotice) throw new Error(mainNotice); + if (packages?.lanes.length) { + const file = path.join(git(values.worktree, ["rev-parse", "--absolute-git-dir"]).trim(), "vibe-package-lane-report.txt"); + writeFileSync(file, packages.lanes.map(({ command }) => ` ${command}\n`).join("")); + process.stdout.write(`REPORT ${file}\n`); + for (const { name, command } of packages.missing) process.stdout.write(`UNRUN ${name}: ${command}\n`); + } + if (!declared && packages) return packages.missing.length ? 1 : 0; process.stdout.write(`REPORT ${writeWorkflowLaneReport(values.worktree, head)}\n`); - const unrun = unrunCiLanes(values.worktree, head); + const unrun = unrunCiLanes(values.worktree, head, { exactCommit: Boolean(main), declared }); for (const { name } of unrun) process.stdout.write(`UNRUN ${name}\n`); - return unrun.length ? 1 : 0; + return unrun.length || packages?.missing.length ? 1 : 0; } if (isEntryPoint(import.meta.url)) { diff --git a/plugins/vibe/lib/handoff/scripts/full-ci-check.test.mjs b/plugins/vibe/lib/handoff/scripts/full-ci-check.test.mjs index b24c3a7b..e8adac00 100644 --- a/plugins/vibe/lib/handoff/scripts/full-ci-check.test.mjs +++ b/plugins/vibe/lib/handoff/scripts/full-ci-check.test.mjs @@ -1,11 +1,12 @@ import assert from "node:assert/strict"; import { spawnSync } from "node:child_process"; -import { readFileSync } from "node:fs"; +import { mkdirSync, readFileSync, writeFileSync } from "node:fs"; +import path from "node:path"; import test from "node:test"; import { fileURLToPath } from "node:url"; import { repositoryLaneReportProblems } from "../../../skills/handoff/scripts/ci-job-shape.mjs"; -import { CI_LANES_OVERRIDE, fullCiProblem, unrunCiLanes } from "./full-ci-check.mjs"; -import { ciRepository } from "./full-ci-fixture.mjs"; +import { CI_LANES_OVERRIDE, fullCiProblem, packageLaneRequirements, unrunCiLanes } from "./full-ci-check.mjs"; +import { ciRepository, recordLanes } from "./full-ci-fixture.mjs"; test("class B: a head whose only recorded run is its focused test files has every CI job unrun, the version bump check included", (t) => { const r = ciRepository(t); @@ -49,3 +50,48 @@ test("class B: the report command writes the lane report pre-pr-lanes.mjs verifi const report = JSON.parse(readFileSync(/^REPORT (.+)$/m.exec(run.stdout)[1], "utf8")); assert.deepEqual(repositoryLaneReportProblems(report, r.worktree, r.head), []); }); + +test("whole workflow jobs on a pre-main commit cannot be carried across a same-tree merge", (t) => { + const r = ciRepository(t); + const commands = r.lanes.map(({ command }) => command); + r.record(commands); + const base = r.git("rev-parse", "main"); + const upstream = r.git("commit-tree", r.git("rev-parse", "main^{tree}"), "-p", base, "-m", "later main"); + r.git("update-ref", "refs/remotes/origin/main", upstream); + assert.match(fullCiProblem(r.worktree, r.head) ?? "", /does not contain fetched origin\/main/); + r.git("merge", "--no-edit", upstream); + const merged = r.git("rev-parse", "HEAD"); + assert.equal(r.git("rev-parse", "HEAD^{tree}"), r.git("rev-parse", `${r.head}^{tree}`)); + assert.match(fullCiProblem(r.worktree, merged) ?? "", /2 have no witnessed passing run/); + recordLanes(r.worktree, merged, commands); + assert.equal(fullCiProblem(r.worktree, merged), null); +}); + +test("the committed workspace maps the diff to every touched package and its declared tiers", (t) => { + const r = ciRepository(t, { declared: false }); + const write = (file, text) => { + const dest = path.join(r.worktree, file); + mkdirSync(path.dirname(dest), { recursive: true }); + writeFileSync(dest, text); + }; + write("pnpm-workspace.yaml", "packages: ['apps/*', '!apps/excluded', 'tools']\n"); + write("turbo.json", '{"tasks":{"test":{}}}\n'); + for (const name of ["api", "app", "excluded", "unaffected"]) { + write(`apps/${name}/package.json`, JSON.stringify({ name, scripts: { test: "vitest run", "test:compatibility": "vitest run --config compat.mts" } })); + } + write("tools/package.json", JSON.stringify({ name: "@repo/tools", scripts: { test: "node --test" } })); + r.git("add", "."); + r.git("commit", "-qm", "declare workspace packages"); + r.git("update-ref", "refs/remotes/origin/main", r.git("rev-parse", "HEAD")); + for (const file of ["apps/api/source.ts", "apps/app/source.ts", "apps/excluded/source.ts", "tools/source.ts"]) write(file, "export {};\n"); + r.git("add", "."); + r.git("commit", "-qm", "change multiple packages"); + const requirements = packageLaneRequirements(r.worktree, r.git("rev-parse", "HEAD")); + assert.deepEqual(requirements.lanes.map(({ command }) => command), [ + "pnpm turbo run test --filter=api --force", + "pnpm --filter=api test:compatibility", + "pnpm turbo run test --filter=app --force", + "pnpm --filter=app test:compatibility", + "pnpm turbo run test --filter=@repo/tools --force", + ]); +}); diff --git a/plugins/vibe/lib/handoff/scripts/refusing-checks.mjs b/plugins/vibe/lib/handoff/scripts/refusing-checks.mjs index 1c83f459..81f768cd 100644 --- a/plugins/vibe/lib/handoff/scripts/refusing-checks.mjs +++ b/plugins/vibe/lib/handoff/scripts/refusing-checks.mjs @@ -16,8 +16,14 @@ import { proofGateProblems, pushReadyProofProblems } from "./proof-receipts.mjs" import { refusalReplayProblem } from "./refusing-check-replay.mjs"; const HANDOFF = "plugins/vibe/lib/handoff/scripts"; +const LANE_SCRIPTS = "plugins/vibe/skills/vibe/scripts"; +const PR_CREATE = "plugins/vibe/hooks/pr-create-guard.mjs"; const PROOF_FILES = [`${HANDOFF}/proof-receipts.mjs`, `${HANDOFF}/proof-scope.mjs`, `${HANDOFF}/proof-parsers.mjs`]; -const E2E_FILES = [`${HANDOFF}/e2e-gate-check.mjs`, "plugins/vibe/skills/vibe/scripts/e2e-requirement.mjs"]; +const LANE_RECORDERS = [`${LANE_SCRIPTS}/pre-pr-lanes.mjs`, `${LANE_SCRIPTS}/lane-run-witness.mjs`]; +const E2E_FILES = [`${HANDOFF}/e2e-gate-check.mjs`, `${LANE_SCRIPTS}/e2e-requirement.mjs`, ...LANE_RECORDERS]; + +// These receipts gate a new PR. Replay accepted work as an in-flight update, for which findings are advisory. +const alreadyAccepted = (head, pushed = [], passed = []) => pushed.includes(head) || passed.includes(head); /** * Each replayed check: the source files that define it and `replay(input)`, its refusals for a branch at `head`, given @@ -30,9 +36,11 @@ export const REFUSING_CHECKS = Object.freeze({ pushReadyProofProblems: { files: [...PROOF_FILES, "plugins/vibe/skills/fleet-orchestrator/scripts/push-proof.mjs"], gates: ["push-check"], replay: ({ worktree, base, head, pushed }) => pushReadyProofProblems(worktree, { base, head, pushed }) }, e2eGateProblems: { files: E2E_FILES, gates: ["PR create"], - replay: ({ worktree, base, head, bodyText, binding }) => e2eGateProblems(worktree, { base, head, bodyText, binding }) }, - fullCiProblem: { files: [`${HANDOFF}/full-ci-check.mjs`], gates: ["PR create"], - replay: ({ worktree, head, bodyText, binding }) => [fullCiProblem(worktree, head, { bodyText, binding })].filter(Boolean) }, + replay: ({ worktree, base, head, pushed, passed, bodyText, binding }) => alreadyAccepted(head, pushed, passed) + ? [] : e2eGateProblems(worktree, { base, head, bodyText, binding }) }, + fullCiProblem: { files: [`${HANDOFF}/full-ci-check.mjs`, ...LANE_RECORDERS, PR_CREATE], gates: ["PR create"], + replay: ({ worktree, head, pushed, passed, bodyText, binding }) => alreadyAccepted(head, pushed, passed) + ? [] : [fullCiProblem(worktree, head, { bodyText, binding })].filter(Boolean) }, refusalReplayProblem: { files: [`${HANDOFF}/refusing-check-replay.mjs`, `${HANDOFF}/refusing-checks.mjs`], gates: ["PR create"], replay: ({ worktree, base, head, bodyText, binding }) => [refusalReplayProblem(worktree, { base, head, bodyText, binding })].filter(Boolean) }, "PROOF-MISSING": { via: "pushReadyProofProblems" }, diff --git a/plugins/vibe/lib/vibe/scripts/cloud-capability-probe.mjs b/plugins/vibe/lib/vibe/scripts/cloud-capability-probe.mjs index de9e8cf7..05df2c40 100644 --- a/plugins/vibe/lib/vibe/scripts/cloud-capability-probe.mjs +++ b/plugins/vibe/lib/vibe/scripts/cloud-capability-probe.mjs @@ -5,7 +5,7 @@ import path from "node:path"; import { fileURLToPath } from "node:url"; import { setTimeout as sleep } from "node:timers/promises"; import { dockerDaemonArgs } from "./cloud-docker-daemon.mjs"; -import { boundedFailureLine, FAILURES_LINE_BYTES } from "./cloud-outcome-artifact.mjs"; +import { boundedFailureLine, boundedDiagnostic, FAILURES_LINE_BYTES, diagnosticSecrets } from "./cloud-outcome-artifact.mjs"; import { probeCloudHostRuntime, redactSecrets } from "./cloud-validation-host.mjs"; import { runBoundedDetailed } from "../../../skills/vibe/scripts/run-bounded.mjs"; import { isEntryPoint } from "../../../shared/plugin-roots.mjs"; @@ -45,7 +45,11 @@ export async function measureLaneTools(command = run, failures = {}) { // The capture merges stderr, where uv prints environment deprecation warnings ahead of the version line. const output = result.output.split("\n").filter((line) => !/^warning: /.test(line)).join("\n").trim(); flags[name] = result.result === "YES" && version.test(output); - if (!flags[name]) failures[name] = result.result === "YES" ? { ...result, reason: "unexpected version output" } : result; + if (!flags[name]) { + const step = [binary, ...args].join(" "); + const reason = result.result === "YES" ? "unexpected version output" : result.reason; + failures[name] = { ...result, result: "NO", reason: reason ? `${step}: ${reason}` : step }; + } } return flags; } @@ -184,9 +188,10 @@ const FAILURE_LINE_CHARS = 160; * again, to the lane result, so the result shows why a check failed. The probe's full streams stay private; this line * carries only the tail of each failing command. */ -export function capabilityFailureLine({ defaultDriver, vfsDriver, compose, electron }, laneTools = {}) { - const outcomes = { compose, defaultDaemon: defaultDriver?.daemon, defaultHello: defaultDriver?.helloWorld, vfsDaemon: vfsDriver?.daemon, - vfsHello: vfsDriver?.helloWorld, electronVersion: electron?.version, electronWindow: electron?.window, ...laneTools }; +export function capabilityFailureLine({ defaultDriver, vfsDriver, compose, electron }, laneTools = {}, host = null) { + const outcomes = { ...hostCapabilityFailures(host), ...laneTools, compose, defaultDaemon: defaultDriver?.daemon, + defaultHello: defaultDriver?.helloWorld, vfsDaemon: vfsDriver?.daemon, vfsHello: vfsDriver?.helloWorld, + electronVersion: electron?.version, electronWindow: electron?.window }; const failures = {}; for (const [name, outcome] of Object.entries(outcomes)) { if (!outcome || outcome.result === "YES") continue; @@ -197,6 +202,24 @@ export function capabilityFailureLine({ defaultDriver, vfsDriver, compose, elect return boundedFailureLine(failures, FAILURES_LINE_BYTES); } +/** Pair each failed runtime flag with the measured step that stopped it. A missing resident daemon is expected. */ +function hostCapabilityFailures(host) { + if (!host) return {}; + const { checks, details } = host; + const steps = { ...details, + controlNamespace: details.controlNamespace?.exitCode === 0 ? details.nonRoot : details.controlNamespace, + chromium: details.chromiumLaunch ?? details.chromiumFetch ?? details.chromiumInstall, + chromium1254: details.chromiumInstall, + }; + const secrets = diagnosticSecrets(); + return Object.fromEntries(Object.entries(checks).flatMap(([name, passed]) => { + const step = steps[name]; + if (passed || !step) return []; + const output = boundedDiagnostic([step.stderrTail, step.diagnosis].filter(Boolean).join("\n"), secrets); + return [[name, { result: "NO", exitCode: step.exitCode, reason: step.step, output }]]; + })); +} + /** * Remove the probe's private daemon state after its report is out. A failed removal is reported on its own line and * never replaces the measured report or the lane's exit status: the files sit under .git in a throwaway checkout. @@ -256,7 +279,7 @@ if (isEntryPoint(import.meta.url)) { process.stdout.write(`CLOUD_HOST_DETAILS ${JSON.stringify(host.details)}\n`); process.stdout.write(capabilityStatusLine(outcome)+"\n"); process.stdout.write(capabilityReasonLine(outcome)+"\n"); - process.stdout.write(capabilityFailureLine(outcome, laneToolFailures)+"\n"); + process.stdout.write(capabilityFailureLine(outcome, laneToolFailures, host)+"\n"); process.stdout.write(`CLOUD_HOST_RUNTIME ${JSON.stringify({ commit, checks })}\n`); } } catch (error) { diff --git a/plugins/vibe/lib/vibe/scripts/cloud-capability-probe.test.mjs b/plugins/vibe/lib/vibe/scripts/cloud-capability-probe.test.mjs index 89833e87..3f6ac704 100644 --- a/plugins/vibe/lib/vibe/scripts/cloud-capability-probe.test.mjs +++ b/plugins/vibe/lib/vibe/scripts/cloud-capability-probe.test.mjs @@ -4,7 +4,7 @@ import path from "node:path"; import test from "node:test"; import { makeHome } from "../../../../vibe/skills/vibe/scripts/test-fixtures.mjs"; import { capabilityFailureLine, electronProbeArgs, probeCloudCapabilities, startDockerProbe } from "./cloud-capability-probe.mjs"; -import { redactSecrets, redactUserinfo } from "./cloud-validation-host.mjs"; +import { probeCloudHostRuntime, redactSecrets, redactUserinfo } from "./cloud-validation-host.mjs"; import { CLOUD_CAPABILITIES_COMMAND, directValidationLanes, isCheckCommand } from "./cloud-check-command.mjs"; const COMMIT = "a".repeat(40); @@ -321,6 +321,23 @@ test("ISS-14874 AC-2 a passed probe's failed checks reach the validate lane resu assert.match(returned.electronVersion.tail.at(-1), /Electron failed to install correctly/); assert.equal(returned.electronVersion.tail[0], "GITHUB_TOKEN="); assert.doesNotMatch(failed.lane.stdoutTail, /ghp_abcdefghijklmnop/); + const measureNamespace = (exitCode, stderrTail) => { + const host = probeCloudHostRuntime(path.join(f.root, "probe-state"), worktree, (command) => command === "unshare" + ? { exitCode, stderrTail } : { exitCode: 0, stdoutTail: "2026-12-03T12:00:00Z" }); + return report(capabilityFailureLine({}, {}, { checks: { controlNamespace: host.checks.controlNamespace }, details: host.details })).lane.stdoutTail; + }; + const denied = measureNamespace(1, "unshare: unshare failed: Operation not permitted\nTOKEN=ghp_abcdefghijklmnopqrstuvwxyz0123"); + assert.match(denied, /"controlNamespace":\{"exitCode":1,"reason":"unshare --user --map-current-user --net --keep-caps".*Operation not permitted/); + assert.doesNotMatch(denied, /ghp_|"docker":\{"exitCode"/); + const ipDenied = "control-lane: 1: ip: Permission denied"; + const noPython = measureNamespace(78, `${ipDenied}\ncontrol-lane: python3 not found for loopback fallback`); + assert.match(noPython, /"controlNamespace":\{"exitCode":78,"reason":"command -v python3 \(inside unshare\)".*ip: Permission denied.*python3 not found/); + const loopback = measureNamespace(78, `${ipDenied}\nPermissionError: [Errno 1] Operation not permitted\ncontrol-lane: python3 loopback fallback failed`); + assert.match(loopback, /"controlNamespace":\{"exitCode":78,"reason":"python3 loopback fallback \(inside unshare\)".*ip: Permission denied.*Operation not permitted/); + const capabilities = measureNamespace(127, "setpriv: apply capabilities: Operation not permitted"); + assert.match(capabilities, /"controlNamespace":\{"exitCode":127,"reason":"setpriv \(inside unshare\)".*apply capabilities/); + const bind = measureNamespace(1, "control-lane: loopback bind failed: listen EADDRNOTAVAIL"); + assert.match(bind, /"controlNamespace":\{"exitCode":1,"reason":"node bind to 127\.0\.0\.1 \(inside unshare\)".*EADDRNOTAVAIL/); const copied = failed.output.trim().split("\n"); for (const [how, message] of [["in backticks", copied.map((line) => "`" + line + "`").join("\n")], ["on the record's line", copied.join(" ")]]) { assert.equal(parse(failed.output, message).stdoutTail, failed.lane.stdoutTail, "the agent's copy " + how + " is read"); diff --git a/plugins/vibe/lib/vibe/scripts/cloud-outcome-artifact.mjs b/plugins/vibe/lib/vibe/scripts/cloud-outcome-artifact.mjs index 474ba8c8..10e44d5e 100644 --- a/plugins/vibe/lib/vibe/scripts/cloud-outcome-artifact.mjs +++ b/plugins/vibe/lib/vibe/scripts/cloud-outcome-artifact.mjs @@ -1,3 +1,4 @@ +import { redactSecrets } from "./cloud-redaction.mjs"; import { createHash } from "node:crypto"; import { capturedJson, jsonValueAt } from "./captured-json.mjs"; @@ -129,16 +130,29 @@ const failuresAt = (label) => new RegExp("(? bytes && Object.values(failures).some(({ tail }) => tail.length)) { - const longest = Object.values(failures).reduce((a, b) => (b.tail.length > a.tail.length ? b : a)); - longest.tail.shift(); + const entries = Object.values(failures); + // Preserve names and exits first. Trim older stderr lines before shortening commands to fit an unusually large report. + while (entries.length && Buffer.byteLength(line) > bytes) { + const longest = entries.reduce((a, b) => b.tail.length > a.tail.length ? b : a); + if (longest.tail.length > 1) longest.tail.shift(); + else { + const widest = entries.reduce((a, b) => Buffer.byteLength(b.tail[0] ?? "") > Buffer.byteLength(a.tail[0] ?? "") ? b : a); + const width = Buffer.byteLength(widest.tail[0] ?? ""); + if (width) widest.tail = width > 16 ? [truncateDiagnostic(widest.tail[0], width - 16)] : []; + else { + const [reason] = entries.filter((entry) => entry.reason).sort((a, b) => b.reason.length - a.reason.length); + if (!reason) break; + if (reason.reason.length > 16) reason.reason = reason.reason.slice(0, -16); + else delete reason.reason; + } + } line = label + " " + JSON.stringify(failures); } - return line; + return Buffer.byteLength(line) <= bytes ? line : ""; } /** @@ -206,6 +220,95 @@ export function probeFailureLine(text, { bytes = FAILURES_MESSAGE_BYTES, redact return found.size === 1 ? boundedFailureLine(JSON.parse([...found][0]), bytes, label) : ""; } +export const DIAGNOSTIC_LABEL = "VIBE_VALIDATION_FAILURES"; +export const DIAGNOSTIC_BYTES = 320; +const ARTIFACT_DIAGNOSTIC_BYTES = 512 * 1024; + +/** Values to redact even when a command prints a secret without its variable name. */ +export function diagnosticSecrets(env = process.env) { + return [...new Set(Object.entries(env) + .filter(([key, value]) => value?.length >= 8 && /TOKEN|SECRET|PASSWORD|PASSWD|API.?KEY|PRIVATE.?KEY|ACCESS.?KEY|CREDENTIAL|AUTH/i.test(key)) + .map(([, value]) => value))].sort((a, b) => b.length - a.length); +} + +/** Redact before truncating so a clipped token never becomes an unrecognized secret. */ +export function boundedDiagnostic(value, secrets = []) { + const plain = String(value ?? "").replace(/\x1b\[[0-?]*[ -/]*[@-~]|[\x00-\x08\x0b-\x1f\x7f]/g, ""); + const clean = redactSecrets(secrets.reduce((text, secret) => text.replaceAll(secret, ""), plain)); + return truncateDiagnostic(clean, DIAGNOSTIC_BYTES); +} + +/** Shorten a redacted channel at a UTF-8 character boundary. */ +function truncateDiagnostic(clean, limit) { + const bytes = Buffer.from(clean); + if (bytes.length <= limit) return clean; + let end = limit; + while ((bytes[end] & 0xc0) === 0x80) end--; + return bytes.subarray(0, end).toString("utf8"); +} + +/** Keep only bounded channels for numeric lane positions. The size applies to the actual JSON bytes. */ +export function boundedDiagnostics(records, maxBytes = ARTIFACT_DIAGNOSTIC_BYTES) { + if (!records || typeof records !== "object" || Array.isArray(records)) return {}; + const diagnostics = {}; + let remaining = maxBytes - 2; + for (const [key, channels] of Object.entries(records)) { + if (!/^lane\d{1,5}$/.test(key) || !Array.isArray(channels) || channels.length !== 2 || + channels.some((value) => typeof value !== "string" || Buffer.byteLength(value) > DIAGNOSTIC_BYTES)) continue; + const clean = channels.map((value) => boundedDiagnostic(value)); + if (!clean.some(Boolean)) continue; + const size = Buffer.byteLength(JSON.stringify({ [key]: clean })) - 1; + if (size > remaining) break; + remaining -= size; + diagnostics[key] = clean; + } + return diagnostics; +} + +/** Fit redacted diagnostics to the output budget, packing them when they share the machine record's line. */ +export function diagnosticLine(records, bytes = 1200, { attached = false } = {}) { + const entries = Object.entries(boundedDiagnostics(records)); + if (!entries.length) return ""; + const render = (limit) => { + const diagnostics = Object.fromEntries(entries.map(([key, channels]) => + [key, channels.map((channel) => truncateDiagnostic(channel, limit))])); + const json = JSON.stringify(diagnostics); + return DIAGNOSTIC_LABEL + " " + (attached ? Buffer.from(json).toString("base64url") : json); + }; + const full = render(DIAGNOSTIC_BYTES); + if (Buffer.byteLength(full) <= bytes) return full; + + // Fit by shortening each channel, since counting channel bytes alone misses JSON escaping overhead. + let low = 1, high = DIAGNOSTIC_BYTES - 1, fitting = ""; + while (low <= high) { + const limit = Math.floor((low + high) / 2); + const line = render(limit); + if (Buffer.byteLength(line) <= bytes) { + fitting = line; + low = limit + 1; + } else high = limit - 1; + } + return fitting; +} + +/** Use an attachment only on the selected machine record, skipping cut copies in the run log. */ +function readDiagnosticLine(log, encoded) { + const text = String(log ?? ""); + const attachment = new RegExp("(? FAILURES_LINE_BYTES) continue; + const json = Buffer.from(packed, "base64url").toString("utf8"); + const diagnostics = boundedDiagnostics(jsonValueAt(json, 0), FAILURES_LINE_BYTES); + if (Object.keys(diagnostics).length) return diagnostics; + } + for (const match of text.matchAll(failuresAt(DIAGNOSTIC_LABEL))) { + const record = jsonValueAt(text, match.index + match[0].length); + const diagnostics = boundedDiagnostics(record, FAILURES_LINE_BYTES); + if (Object.keys(diagnostics).length) return diagnostics; + } + return {}; +} + export const MACHINE_OUTCOMES = "machine-v2"; /** Encode the exact approved request and machine outcomes. The caller has already checked the actual checkout, cloud marker and origin. */ export function encodeOutcomes({ key, commit, host, repository, directory, lanes, probe = -1 }) { @@ -378,6 +481,8 @@ export function outcomeRecords(log, marker) { return records.filter((record) => !records.some((other) => other !== record && other.startsWith(record))); } export const ARTIFACT_MARKER = "VIBE_OUTCOME_ARTIFACT"; +export const PUBLICATION_MARKER = "VIBE_OUTCOME_PUBLICATION"; +export const MISSING_RESULT_BRANCH = "VIBE_RESULT_BRANCH_MISSING"; export function artifactPointer(log, request) { // A plain word the agent writes after the marker in prose ("VIBE_OUTCOME_ARTIFACT recorded") is not a second // pointer; anything else that is not one exact commit:sha256 pair still refuses. @@ -405,29 +510,51 @@ export function checkOutcomeArtifact(request) { ); } export const outcomeArtifact = (request) => request.resultArtifact?.kind === "validation-outcomes"; + +function inlineOutcome(log, context) { + // Exact width discards prose and clipped copies. The decoder still verifies the request identity and all lanes. + const size = 4 * Math.ceil((HEADER + LANE * (context?.names?.length ?? 0)) / 3); + const records = outcomeRecords(log, OUTCOMES_MARKER).filter((record) => record.length === size); + if (!records.length) return null; + if (records.length !== 1 || MARKER.length + records[0].length > LIMIT) fail("has conflicting or oversized inline evidence"); + return records[0]; +} + +/** A missing branch can use a complete inline outcome for this request. Other fetch and integrity errors still refuse. */ export function readOutcomeReport(log, request, context, artifactReader) { - let encoded, artifact; + let encoded, artifact, diagnostics; if (outcomeArtifact(request)) { artifact = artifactPointer(log, request); - const fetched = artifactReader(request, artifact); + let fetched; + try { + fetched = artifactReader(request, artifact); + } catch (error) { + if (error.code !== MISSING_RESULT_BRANCH) throw error; + encoded = outcomeTransportBytes(context.names.length) <= LIMIT ? inlineOutcome(log, context) : null; + if (encoded) return { ...decodeOutcomes(encoded, context), diagnostics: readDiagnosticLine(log, encoded) }; + const publication = String(log ?? "").match(new RegExp(`\\b${PUBLICATION_MARKER} (push-denied|push-failed|publication-failed)\\b`))?.[1]; + const reason = { + "push-denied": "the cloud session's Git push was denied", + "push-failed": "the cloud session's Git push failed or could not be verified", + "publication-failed": "the cloud session's reporter stopped while preparing the result branch", + }[publication] ?? (artifact.commit ? "the cloud session reported publication, but the result branch is now missing" + : "the cloud session returned no publication record. The publication step may have been skipped or interrupted"); + throw Object.assign(new Error(`cloud validation result branch ${artifact.branch} is missing: ${reason}. No complete inline outcome was returned.`), + { code: MISSING_RESULT_BRANCH }); + } const stored = fetched?.result; artifact = { ...artifact, commit: fetched?.commit ?? artifact.commit, sha256: fetched?.sha256 ?? artifact.sha256, }; - if (!stored || Object.keys(stored).sort().join() !== "encoded,version" || stored.version !== 1) + if (!stored || Object.keys(stored).some((key) => !["diagnostics", "encoded", "version"].includes(key)) || stored.version !== 1) fail("artifact is not an allowlisted versioned report"); encoded = stored.encoded; + diagnostics = boundedDiagnostics(stored.diagnostics); } else { - // Only a record of the exact encoded size this request's lanes produce is one: the agent's prose can follow the - // marker with a word ("VIBE_OUTCOMES_V1 emitted") or a cut copy, and neither is a second record. - const size = 4 * Math.ceil((HEADER + LANE * (context?.names?.length ?? 0)) / 3); - const records = outcomeRecords(log, MARKER.trim()).filter((record) => record.length === size); - if (!records.length) return null; - if (records.length !== 1 || MARKER.length + records[0].length > LIMIT) - fail("has conflicting or oversized inline evidence"); - encoded = records[0]; + encoded = inlineOutcome(log, context); + if (!encoded) return null; } - return { ...decodeOutcomes(encoded, context), ...(artifact ? { artifact } : {}) }; + return { ...decodeOutcomes(encoded, context), diagnostics: diagnostics ?? readDiagnosticLine(log, encoded), ...(artifact ? { artifact } : {}) }; } diff --git a/plugins/vibe/lib/vibe/scripts/cloud-outcome-instruction.mjs b/plugins/vibe/lib/vibe/scripts/cloud-outcome-instruction.mjs index 606cb4cf..a27f4379 100644 --- a/plugins/vibe/lib/vibe/scripts/cloud-outcome-instruction.mjs +++ b/plugins/vibe/lib/vibe/scripts/cloud-outcome-instruction.mjs @@ -5,7 +5,7 @@ import { readFileSync } from "node:fs"; import os from "node:os"; import path from "node:path"; import { pluginInstall, pluginMarketplace } from "../../../shared/plugin-roots.mjs"; -import { FAILURES_LABEL, LANE_FAILURES_LABEL, outcomeArtifact, requireOutcomeCapacity } from "./cloud-outcome-artifact.mjs"; +import { DIAGNOSTIC_LABEL, FAILURES_LABEL, LANE_FAILURES_LABEL, PUBLICATION_MARKER, outcomeArtifact, requireOutcomeCapacity } from "./cloud-outcome-artifact.mjs"; import { TOOL_REPO, validTool } from "./cloud-validation-environment.mjs"; import { toolingRoot } from "./cloud-validation-recipes.mjs"; @@ -15,6 +15,7 @@ const SHA = /^[a-f0-9]{40}$/; export const reporterFiles = Object.freeze([ "captured-json.mjs", "github-remote.mjs", + "cloud-redaction.mjs", "cloud-outcome-artifact.mjs", "cloud-outcome-writer.mjs", ]); @@ -102,24 +103,23 @@ function portableReporter(spec) { return {install:"node -e '"+install+"' "+dir+" "+sha+" "+encoded,reporter:"node "+dir+"/cloud-outcome-writer.mjs "+packed+' "$d"'}; } -/** - * The capability probe's failed checks, and a managed lane's failed Chromium preflight, reach the lane result only - * through the run log: the record is fixed-width and the outcomes JSON carries no lane output, so the reporter prints - * the redacted failures line after its record and the final message keeps it. - */ -const copyFailures = (label) => `When the reporter's output has a ${label} line after its first line, copy that line exactly as the last line of your final message, after the result line; it is the only line allowed there and counts toward the 1,800 characters.`; +/** Capability probe and Chromium preflight failures reach the run log as the last line. */ +const copyFinalFailures = (label) => `When the reporter's output has a ${label} line after its first line, copy that line exactly as the last line of your final message, directly after the complete result line. It counts toward the 1,800 characters.`; /** Install the shipped reporter into Git's private state, including application checkouts without Vibe source. */ export function outcomeInstruction(request, lanes, key, managedHost, compact = null) { const artifact = outcomeArtifact(request) ? request.resultArtifact : null; requireOutcomeCapacity(lanes, artifact); + const failures = [ + `Copy the reporter's complete result line, including any ${DIAGNOSTIC_LABEL} or ${PUBLICATION_MARKER} suffix. This line is required in your final message and counts toward the 1,800 characters.`, + ]; // The managed host's failed Chromium preflight reaches the lane result the same way (session cse_0197q288AogeAdHPSVDTnXAd had empty tails). - const failures = lanes.some((lane) => lane.capabilityProbe) ? [copyFailures(FAILURES_LABEL)] - : managedHost && !compact ? [copyFailures(LANE_FAILURES_LABEL)] : []; + if (lanes.some((lane) => lane.capabilityProbe)) failures.push(copyFinalFailures(FAILURES_LABEL)); + else if (managedHost && !compact) failures.push(copyFinalFailures(LANE_FAILURES_LABEL)); if (managedHost && !compact) return [ - 'The machine record replaces the archival VIBE_VALIDATION_RESULT carrier. Keep the private lane JSON fields "tail" and "diagnosis" with bounded redacted output for failures. Never place these in an outcome artifact.', + 'The machine record replaces the archival VIBE_VALIDATION_RESULT carrier. Keep the private lane JSON fields "tail" and "diagnosis" with bounded redacted output for failures. The reporter alone selects and redacts diagnostic excerpts for the outcome.', artifact - ? "The managed runner runs the shipped reporter itself after its lanes. It publishes the typed outcomes JSON as one child commit on the authorized fresh result branch, and its first output line is the verified result pointer. Do not run a reporter yourself; report that line." + ? `The managed runner runs the shipped reporter itself after its lanes. It pushes and verifies the authorized result branch. Read the verified result pointer or the ${PUBLICATION_MARKER} refusal or fallback from its output before you finish. Do not run a reporter yourself.` : "The managed runner runs the shipped reporter itself after its lanes, and its first output line is the bounded machine record. Do not run a reporter yourself; keep that line in the run log by reading the runner's output.", ...failures, ].join("\n\n"); @@ -128,10 +128,10 @@ export function outcomeInstruction(request, lanes, key, managedHost, compact = n const reporter=compact ?? (commit ? fetchedReporter(spec(), commit) : portableReporter(spec())); // A workflow brief's runner writes every lane record itself (cloud-workflow-brief.mjs), so the agent is told to write none. const records = compact ? [ - "The machine record replaces the archival VIBE_VALIDATION_RESULT carrier. Never place private lane evidence in an outcome artifact.", + "The machine record replaces the archival VIBE_VALIDATION_RESULT carrier. Only the shipped reporter may put redacted diagnostic excerpts in an outcome artifact.", "Keep the results directory d you created before the first lane. Do not show its contents.", ] : [ - 'The machine record replaces the archival VIBE_VALIDATION_RESULT carrier. Keep the private lane JSON fields "tail" and "diagnosis" with bounded redacted output for failures. Never place these in an outcome artifact.', + 'The machine record replaces the archival VIBE_VALIDATION_RESULT carrier. Keep the private lane JSON fields "tail" and "diagnosis" with bounded redacted output for failures. The reporter alone selects and redacts diagnostic excerpts for the outcome.', "Save both full streams outside the checkout. Use the directory printed by the managed host, or create the direct lane directory with mktemp -d /tmp/vibe-lane-results-XXXXXX. Set d to its absolute path. Do not show its contents.", "For each direct lane, redirect stdout and stderr into $d/.stdout and .stderr. Record the actual foreground exit in $d/.json as JSON with the exact lane name and numeric exitCode (or null and notRun when it never executed). The managed host already writes these. A preflight that ran no lane can have empty channel files only alongside its recorded nonzero preflight or notRun outcome.", ]; @@ -142,7 +142,7 @@ export function outcomeInstruction(request, lanes, key, managedHost, compact = n reporter.reporter, ...(artifact ? [ - "The reporter will publish only the typed outcomes JSON, as one child commit on the explicitly authorized fresh result branch. Its first output line is the complete verified result pointer. It refuses a previously existing result branch.", + `Run the reporter command above before writing a summary. This command builds, pushes and verifies the result-only child commit on the authorized fresh branch. Wait for its output, including when lanes fail. Copy its verified result pointer or its ${PUBLICATION_MARKER} refusal or fallback. If Bash denies the reporter call, report that denial verbatim.`, ] : []), ...failures, @@ -167,5 +167,5 @@ export const LANE_DISCIPLINE = "and never infer one from the output. A lane that never finished, or whose exit code you could not read, is reported " + 'with "exitCode": null and "notRun": the reason. Print the result line only after every lane has finished. In the private session evidence, ' + "list every failing test of each failed lane by name, as its runner printed it. Your " + - "final message is the result line alone, under 1,800 characters: the run log keeps only the first 2,000 characters of a " + + "final message keeps the result line and any reporter-directed diagnostic lines under 1,800 characters: the run log keeps only the first 2,000 characters of a " + "message. Keep detailed lane evidence in its private files; do not shorten or drop tails to fit."; diff --git a/plugins/vibe/lib/vibe/scripts/cloud-outcome-transport.test.mjs b/plugins/vibe/lib/vibe/scripts/cloud-outcome-transport.test.mjs index 17fefee3..1b8fed59 100644 --- a/plugins/vibe/lib/vibe/scripts/cloud-outcome-transport.test.mjs +++ b/plugins/vibe/lib/vibe/scripts/cloud-outcome-transport.test.mjs @@ -20,6 +20,86 @@ const subject = { test("oversized unapproved validation refuses before dispatch with the exact split capacity", () => { assert.throws(() => validationBrief(subject), /resolves to 11 lanes, and the log holds at most 2; send at most 2 caller lanes per request or authorize a validation-outcomes resultArtifact/); }); +test("ISS-15068 a missing outcomes branch imports only matching inline evidence or explains the publication failure", async () => { + const { encodeOutcomes, outcomeLine } = await import("./cloud-outcome-artifact.mjs"); + const { readValidationArtifact } = await import("./cloud-worker.mjs"); + const request = { ...subject, lanes: specs.slice(0, 1), resultArtifact: { + kind: "validation-outcomes", path: ".vibe-validation-outcomes-12345678.json", branch: "vibe-validation-results/fixture", + } }; + const key = createHash("sha256").update(JSON.stringify(request)).digest("hex"); + const stream = { bytes: 0, sha256: "b".repeat(64) }; + const inline = outcomeLine(encodeOutcomes({ key, commit, repository: request.repository, host: "worker", + directory: "/tmp/vibe-lane-results-abc123", lanes: [{ exitCode: 1, privateStreams: { stdout: stream, stderr: stream } }] })); + const reader = (request, artifact) => readValidationArtifact(request, artifact, { run: () => ({ status: 128, + stderr: `fatal: couldn't find remote ref refs/heads/${artifact.branch}` }) }); + const parse = (log, options) => parseValidationResult(log, request, { artifactReader: reader, ...options }); + const imported = parse(inline + " VIBE_OUTCOME_PUBLICATION push-denied"); + assert.equal(imported.lanes[0].exitCode, 1); + assert.equal(imported.artifact, undefined); + assert.throws(() => parse(inline, { requestKey: "f".repeat(64) }), /different request/); + assert.throws(() => parse("VIBE_OUTCOME_PUBLICATION push-denied"), /cloud session.*push.*denied/); + assert.throws(() => parse("assistant: done"), /publication.*may have been skipped/); + assert.throws(() => parse(inline, { artifactReader: () => ({ result: { version: 99 } }) }), /allowlisted versioned report/); +}); + +test("ISS-15068 the reporter returns a bounded inline result on push denial or a refusal when it cannot fit", async (t) => { + const { execFileSync, spawnSync } = await import("node:child_process"); + const { mkdirSync, mkdtempSync, realpathSync, rmSync, writeFileSync } = await import("node:fs"); + const { tmpdir } = await import("node:os"); + const { join } = await import("node:path"); + const { fileURLToPath } = await import("node:url"); + const { git, makeCheckout, makeHome } = await import("../../../skills/vibe/scripts/test-fixtures.mjs"); + const { readValidationArtifact } = await import("./cloud-worker.mjs"); + const fixture = makeHome("outcome-push-denied-"); + t.after(fixture.cleanup); + const worktree = join(fixture.root, "checkout"); + makeCheckout({ ...fixture, checkout: worktree, remoteUrl: "https://github.com/example/widgets.git" }); + const gitAt = (...args) => git(worktree, args, fixture.home); + gitAt("config", "--unset", gitAt("config", "--name-only", "--get-regexp", "^url\\..*\\.insteadof$")); + const commit = gitAt("rev-parse", "HEAD"); + const dir = mkdtempSync(join(realpathSync(tmpdir()), "vibe-lane-results-")); + t.after(() => rmSync(dir, { recursive: true, force: true })); + const bin = join(fixture.root, "bin"); + mkdirSync(bin); + const gitBinary = execFileSync("which", ["git"], { encoding: "utf8" }).trim(); + const secret = "credential-from-private-git-error"; + writeFileSync(join(bin, "git"), `#!/bin/sh +case "$1" in + ls-remote) exit 0 ;; + push) echo 'remote: Write access to repository not granted. ${secret}' >&2; exit 128 ;; + *) exec '${gitBinary.replaceAll("'", "'\"'\"'")}' "$@" ;; +esac +`, { mode: 0o700 }); + const artifact = { kind: "validation-outcomes", path: ".vibe-validation-outcomes-12345678.json", branch: "vibe-validation-results/fixture" }; + const artifactReader = (request, pointer) => readValidationArtifact(request, pointer, { run: () => ({ status: 128, + stderr: `fatal: couldn't find remote ref refs/heads/${pointer.branch}` }) }); + const run = (count) => { + const request = { ...subject, worktree, commit, lanes: specs.slice(0, count), resultArtifact: artifact }; + const key = createHash("sha256").update(JSON.stringify(request)).digest("hex"); + const names = request.lanes.map(({ name }) => name); + for (const [index, name] of names.entries()) { + writeFileSync(join(dir, `${index}.json`), JSON.stringify({ name, exitCode: 1 })); + writeFileSync(join(dir, `${index}.stdout`), `FAILED tests/test_cloud.py::test_lane_${index}\n`); + writeFileSync(join(dir, `${index}.stderr`), ""); + } + const spec = Buffer.from(JSON.stringify({ key, commit, repository: request.repository, names, probe: -1, artifact })).toString("base64url"); + const result = spawnSync(process.execPath, [fileURLToPath(new URL("./cloud-outcome-writer.mjs", import.meta.url)), spec, dir], { + cwd: worktree, encoding: "utf8", env: { ...process.env, PATH: `${bin}:${process.env.PATH}`, CLAUDE_CODE_REMOTE: "true" }, + }); + assert.doesNotMatch(result.stdout + result.stderr, new RegExp(secret)); + return { result, parse: () => parseValidationResult(result.stdout, request, { artifactReader }) }; + }; + const inline = run(2); + assert.equal(inline.result.status, 0, inline.result.stderr); + assert.match(inline.result.stdout, /^VIBE_OUTCOMES_V1 .* VIBE_OUTCOME_PUBLICATION push-denied\n$/); + assert.deepEqual(inline.parse().lanes.map(({ stdoutTail }) => stdoutTail), [ + "FAILED tests/test_cloud.py::test_lane_0", "FAILED tests/test_cloud.py::test_lane_1", + ]); + const oversized = run(3); + assert.equal(oversized.result.status, 1); + assert.equal(oversized.result.stdout, "VIBE_OUTCOME_PUBLICATION push-denied\n"); + assert.throws(oversized.parse, /Git push was denied/); +}); test("a clipped one-of-eight provider log can import all approved artifact outcomes", async () => { const { encodeOutcomes, artifactPointer } = await import("./cloud-outcome-artifact.mjs"); const req = { @@ -244,11 +324,10 @@ test("standalone reporter hashes both real streams and emits only the canonical writeFileSync(join(dir, "0.stdout"), stdout); writeFileSync(join(dir, "0.stderr"), "private fixture output"); writeFileSync(join(dir, "0.json"), JSON.stringify({ name: "probe", exitCode: 0 })); - const args = Buffer.from(JSON.stringify({ key, commit, repository, names, probe: 0 })).toString("base64url"); - const run = () => + const run = (spec = { key, commit, repository, names, probe: 0 }) => execFileSync( process.execPath, - [fileURLToPath(new URL("./cloud-outcome-writer.mjs", import.meta.url)), args, dir], + [fileURLToPath(new URL("./cloud-outcome-writer.mjs", import.meta.url)), Buffer.from(JSON.stringify(spec)).toString("base64url"), dir], { cwd: worktree, env: { ...process.env, CLAUDE_CODE_REMOTE: "true" }, @@ -269,10 +348,123 @@ test("standalone reporter hashes both real streams and emits only the canonical assert.match(decoded.stdoutTail, /"electronWindow":"NO"/); assert.match(decoded.stdoutTail, /"nonRoot":true/); assert.doesNotMatch(line, /private fixture output/); + + const request = { ...subject, worktree, commit, lanes: [specs[0]] }; + const spec = { key, commit, repository, names: [specs[0].name], probe: -1 }; + const { NODE_TEST_CONTEXT: _parentTest, ...env } = process.env; + const lane = execFileSync.bind(null, process.execPath, ["--input-type=module", "-e", [ + "import test from 'node:test';", + "test('refuses a stale turn', () => { throw new Error('fixture') });", + "test('preserves the live turn', () => { throw new Error('fixture') });", + ].join("\n")], { cwd: worktree, env, encoding: "utf8", stdio: ["ignore", "pipe", "pipe"] }); + let failedOutput; + assert.throws(lane, (error) => { + failedOutput = error.stdout; + return error.status === 1; + }); + const secret = "fixture-value-that-must-stay-private"; + writeFileSync(join(dir, "0.stdout"), failedOutput + "nonfailure filler\n".repeat(10_000)); + writeFileSync(join(dir, "0.stderr"), `API_TOKEN=${secret}\n`); + writeFileSync(join(dir, "0.json"), JSON.stringify({ name: specs[0].name, exitCode: 1 })); + const failureLog = run(spec); + const outcome = parseValidationResult(failureLog, request, { requestKey: key }).lanes[0]; + assert.match(outcome.stdoutTail, /refuses a stale turn/); + assert.match(outcome.stdoutTail, /preserves the live turn/); + assert.match(outcome.stderrTail, /redacted/); + assert.ok(outcome.stdoutTail.length < 512); + assert.doesNotMatch(failureLog, new RegExp(secret)); + + const artifact = { kind: "validation-outcomes", path: ".vibe-validation-outcomes-12345678.json", + branch: "vibe-validation-results/failed-lane" }; + const writer = new URL("./cloud-outcome-writer.mjs", import.meta.url).href; + const invoke = (source, args) => execFileSync(process.execPath, ["--input-type=module", "-e", source, ...args], { + cwd: worktree, encoding: "utf8", env: { ...env, CLAUDE_CODE_REMOTE: "true" }, stdio: ["ignore", "pipe", "pipe"], + }); + const report = invoke(`import { machineOutcomes } from ${JSON.stringify(writer)}; + console.log(JSON.stringify(machineOutcomes(JSON.parse(process.argv[1]), process.argv[2])))`, + [JSON.stringify({ ...spec, artifact }), dir]); + const origin = join(fixture.root, "results.git"); + const gitAt = (...args) => git(worktree, args, fixture.home); + gitAt("init", "--bare", origin); + gitAt("remote", "set-url", "origin", origin); + invoke(`import { publishOutcomes } from ${JSON.stringify(writer)}; + const { encoded, diagnostics } = JSON.parse(process.argv[3]); + publishOutcomes(JSON.parse(process.argv[1]), process.argv[2], encoded, diagnostics)`, + [JSON.stringify(artifact), commit, report]); + const artifactContents = gitAt("--git-dir", origin, "show", `${artifact.branch}:${artifact.path}`); + assert.doesNotMatch(artifactContents, new RegExp(secret)); + const imported = parseValidationResult("", { ...request, resultArtifact: artifact }, { requestKey: key }).lanes[0]; + assert.match(imported.stdoutTail, /refuses a stale turn/); + assert.match(imported.stdoutTail, /preserves the live turn/); + assert.match(imported.stderrTail, /redacted/); + + gitAt("remote", "set-url", "origin", "https://github.com/example/widgets.git"); writeFileSync(join(worktree, "uncommitted.txt"), "fixture"); assert.throws(run, /checkout has tracked or untracked changes/); }); +test("ISS-15055 inline workflow outcomes preserve pytest failures and a bounded fallback for each lane", async (t) => { + const { execFileSync } = await import("node:child_process"); + const { mkdtempSync, realpathSync, rmSync, writeFileSync } = await import("node:fs"); + const { tmpdir } = await import("node:os"); + const { join } = await import("node:path"); + const { fileURLToPath } = await import("node:url"); + const { git, makeCheckout, makeHome } = await import("../../../skills/vibe/scripts/test-fixtures.mjs"); + const fixture = makeHome("outcome-pytest-"); + t.after(fixture.cleanup); + const worktree = join(fixture.root, "checkout"); + const path = ".github/workflows/ci.yml"; + const names = ["test", "vibe-eval-t0"]; + const workflow = "on: pull_request\njobs:\n" + names.map((name) => + ` ${name}:\n runs-on: ubuntu-latest\n steps:\n - run: uv run pytest\n`).join(""); + makeCheckout({ ...fixture, checkout: worktree, remoteUrl: "https://github.com/example/widgets.git", files: { [path]: workflow } }); + const gitAt = (...args) => git(worktree, args, fixture.home); + gitAt("config", "--unset", gitAt("config", "--name-only", "--get-regexp", "^url\\..*\\.insteadof$")); + const commit = gitAt("rev-parse", "HEAD"); + const request = { ...subject, worktree, commit, lanes: names.map((name) => ({ name })), laneSource: { + kind: "github-workflow", path, commit, sha256: createHash("sha256").update(workflow).digest("hex"), + } }; + const key = createHash("sha256").update(JSON.stringify(request)).digest("hex"); + const dir = mkdtempSync(join(realpathSync(tmpdir()), "vibe-lane-results-")); + t.after(() => rmSync(dir, { recursive: true, force: true })); + const secret = "fixture-value-that-must-stay-private"; + // JSON escaping makes the two rows too wide for the inline budget even though each private channel fits its cap. + const escaped = "\\".repeat(550); + const postamble = "private post-run output\n".repeat(2_000); + const summary = "=== 1 failed, 1 error in 0.12s ==="; + const stdout = [ + `${postamble}\x1b[31mFAILED tests/test_workflow.py::test_checkout - AssertionError\x1b[0m\n` + + `ERROR tests/test_workflow.py::test_collect - RuntimeError: ${secret}\n${summary}\n${postamble}CLOUD_WORKFLOW_LANE {}\n`, + `${postamble}FAILED tests/test_parallel.py::test_second_lane - AssertionError\n${postamble}CLOUD_WORKFLOW_LANE {}\n`, + ]; + for (const [index, name] of names.entries()) { + writeFileSync(join(dir, `${index}.stdout`), stdout[index]); + writeFileSync(join(dir, `${index}.stderr`), `API_TOKEN=${secret}\nlast stderr warning: ${escaped}\n`); + writeFileSync(join(dir, `${index}.json`), JSON.stringify({ name, exitCode: 1, diagnosis: "process failed; see private stream evidence" })); + } + const spec = { key, commit, repository: request.repository, names, probe: -1 }; + const log = execFileSync(process.execPath, [fileURLToPath(new URL("./cloud-outcome-writer.mjs", import.meta.url)), + Buffer.from(JSON.stringify(spec)).toString("base64url"), dir], { + cwd: worktree, env: { ...process.env, CLAUDE_CODE_REMOTE: "true", API_TOKEN: secret }, encoding: "utf8", + }); + const [required, supplemental] = log.trim().split("\n"); + assert.equal(supplemental, undefined, "failure evidence travels on the required result line"); + const condensed = `tool_result: ${required.slice(0, 400)}\nassistant: ${required}`; + const [pytest, fallback] = parseValidationResult(condensed, request).lanes; + assert.deepEqual([ + /^FAILED tests\/test_workflow\.py::test_checkout\b/m.test(pytest.stdoutTail), + /^ERROR tests\/test_workflow\.py::test_collect\b/m.test(pytest.stdoutTail), + pytest.stdoutTail.includes(summary), + /^FAILED tests\/test_parallel\.py::test_second_lane\b/m.test(fallback.stdoutTail), + [pytest, fallback].every((lane) => lane.stderrTail.includes("last stderr warning")), + ], [true, true, true, true, true]); + assert.ok(Buffer.byteLength(log) < 1800); + assert.doesNotMatch(log, new RegExp(secret)); + const [marker, encoded, label, packed] = required.split(" "); + const legacy = `${marker} ${encoded}\n${label} ${Buffer.from(packed, "base64url").toString("utf8")}`; + assert.equal(parseValidationResult(legacy, request).lanes[0].stdoutTail, pytest.stdoutTail, "saved supplemental results still import"); +}); + test("fixed records preserve allowed frozen facts and reject a successful gate without its verdict", async () => { const { encodeOutcomes, decodeOutcomes } = await import("./cloud-outcome-artifact.mjs"); const key = "a".repeat(64), @@ -329,7 +521,7 @@ test("a session denied permission to run its lanes is reported by its denial, an const fixture=makeHome("denied-runner-");t.after(fixture.cleanup); const worktree=join(fixture.root,"checkout");makeCheckout({...fixture,checkout:worktree,remoteUrl:"https://github.com/example/widgets.git"}); const base=git(worktree,["rev-parse","HEAD"],fixture.home); - const missing=new Error("cloud validation result branch fetch failed: fatal: couldn't find remote ref refs/heads/vibe-validation-results/x"); + const missing=Object.assign(new Error("missing result branch"), { code: "VIBE_RESULT_BRANCH_MISSING" }); const validate=(branch,log,artifactReader=()=>{throw missing;},artifact=true)=>validateCommit({...subject,worktree,commit:base,branch,lanes:specs.slice(0,1),model:"model", claudeEnvironment:"env_01Fixture",pollMs:1000,...(artifact ? {resultArtifact:{kind:"validation-outcomes",path:".vibe-validation-outcomes-12345678.json", branch:"vibe-validation-results/"+branch}} : {})},{home:fixture.home,executor:NO_EXECUTOR,sleep:async()=>{},artifactReader, @@ -344,12 +536,12 @@ test("a session denied permission to run its lanes is reported by its denial, an "Permission for this action was denied by the Claude Code auto mode classifier. Reason: Undermining Oversight"].entries()) { await assert.rejects(validate("denied-"+index,"tool_result: "+text),(error)=>{ assert.match(error.message,/^cloud validation session was denied permission to run a command: Permission for this action .*Undermining Oversight/); - assert.match(error.message,/result branch fetch failed/,"the read failure it caused stays named"); + assert.match(error.message,/result branch .* is missing/,"the publication failure it caused stays named"); return true; }); await assert.rejects(validate("inline-"+index,"tool_result: "+text,undefined,false),/^Error: cloud validation session was denied permission.*requires machine outcome evidence/); } - await assert.rejects(validate("absent","assistant: done"),(error)=>error===missing,"no denial in the log: the read failure is the cause"); + await assert.rejects(validate("absent","assistant: done"),/publication step may have been skipped or interrupted/); await assert.rejects(validate("other","Permission for this action has been denied. Reason: x",()=>({result:{}})),/^Error: cloud validation outcome artifact is not an allowlisted/, "a result that was pushed and is wrong keeps its own refusal"); }); @@ -513,5 +705,5 @@ test("ISS-15038 validate picks a fresh outcomes artifact itself when the resolve assert.equal(lsRemote.length, 2, "the fresh branch is checked absent before each launch"); assert.deepEqual(lsRemote[1], lsRemote[0], "the same request names the same branch, so a later poll of its receipt imports from it"); assert.match(lsRemote[0].join(" "), new RegExp(`^ls-remote --refs origin refs/heads/vibe-validation-results/${commit.slice(0, 12)}-[a-f0-9]{12}$`)); - assert.match(brief, /publish only the typed outcomes JSON, as one child commit on the explicitly authorized fresh result branch/); + assert.match(brief, /builds, pushes and verifies the result-only child commit on the authorized fresh branch/); }); diff --git a/plugins/vibe/lib/vibe/scripts/cloud-outcome-writer.mjs b/plugins/vibe/lib/vibe/scripts/cloud-outcome-writer.mjs index 0f3b8d1c..2010fa8b 100644 --- a/plugins/vibe/lib/vibe/scripts/cloud-outcome-writer.mjs +++ b/plugins/vibe/lib/vibe/scripts/cloud-outcome-writer.mjs @@ -20,7 +20,12 @@ import { pathToFileURL } from "node:url"; import { execFileSync } from "node:child_process"; import { githubRepository } from "./github-remote.mjs"; import { + boundedDiagnostic, + boundedDiagnostics, checkOutcomeArtifact, + diagnosticSecrets, + diagnosticLine, + DIAGNOSTIC_BYTES, encodeOutcomes, FAILURES_LABEL, laneFailureLine, @@ -29,6 +34,8 @@ import { outcomeLine, requireOutcomeCapacity, ARTIFACT_MARKER, + OUTCOME_LOG_LIMIT, + PUBLICATION_MARKER, } from "./cloud-outcome-artifact.mjs"; const deny = (message) => { @@ -47,11 +54,35 @@ function gitOutput(args, input, cwd) { stdio: [input === undefined ? "ignore" : "pipe", "pipe", "pipe"], timeout: 30000, }); - } catch { + } catch (error) { + if (args[0] === "push") { + // Classify the push without returning Git output, which can contain credential-bearing URLs. + const denied = /permission.*denied|access denied|not (?:authorized|allowed)|authentication failed|write access.*not granted|error: (?:403|401)\b|returned error: (?:403|401)\b/i + .test(error.stderr ?? ""); + throw Object.assign(new Error("cloud outcome writer: git push failed; inspect the provider session privately"), + { publication: denied ? "push-denied" : "push-failed" }); + } deny("git " + args.find((arg) => !arg.includes("=") && arg !== "-c") + " failed; inspect the provider session privately"); } } -function checkedStream(file, probe, commit, frozenLane) { +// Keep runner failure names and pytest's count summary even when workflow steps print a postamble. +const NAMED_FAILURE = /^(?:not ok \d+ - |[✖×]\s+(?!\d+\b)|FAIL(?:ED)?\s+|ERROR\s+)/u; +const PYTEST_SUMMARY = /^=+\s+.*\b\d+\s+(?:failed|errors?)\b.*\s+=+$/u; +const WORKFLOW_STATUS = /^CLOUD_WORKFLOW_(?:STEP|LANE) /u; + +/** Prefer recognized failures. Otherwise keep as many of the latest output lines as the channel can hold. */ +function streamDiagnostic(named, summary, tail) { + if (named.length || summary) return boundedDiagnostic([summary, ...named].filter(Boolean).join("\n")); + let excerpt = ""; + for (const line of tail.reverse()) { + const candidate = excerpt ? `${line}\n${excerpt}` : line; + if (Buffer.byteLength(candidate) > DIAGNOSTIC_BYTES) break; + excerpt = candidate; + } + return excerpt; +} + +function checkedStream(file, probe, commit, frozenLane, secrets = null) { const fd = openSync(file, constants.O_RDONLY | constants.O_NOFOLLOW), sum = createHash("sha256"), buffer = Buffer.alloc(65536); @@ -60,8 +91,18 @@ function checkedStream(file, probe, commit, frozenLane) { discard = false, frozen; const evidence={}; - let failures = ""; + let failures = "", summary = ""; + const named = [], tail = []; function consume(final) { + if (secrets) { + const clean = discard ? "[output line exceeded the diagnostic limit]" : boundedDiagnostic(Buffer.from(final, "latin1").toString("utf8"), secrets).trim(); + if (PYTEST_SUMMARY.test(clean)) summary = clean; + else if (clean && !WORKFLOW_STATUS.test(clean)) { + const kept = NAMED_FAILURE.test(clean) ? named : tail; + kept.push(clean); + if (kept.length > 4) kept.shift(); + } + } if (discard) return; if (frozenLane) { const match = /^FROZEN PASS (\d+) files (\d+) stories inputs ([0-9a-f]{16})$/.exec(final); @@ -94,7 +135,7 @@ function checkedStream(file, probe, commit, frozenLane) { const data = buffer.subarray(0, n); sum.update(data); bytes += n; - if (probe || frozenLane) + if (probe || frozenLane || secrets) for (const part of data.toString("latin1").split(/(\n)/)) { if (part === "\n") { consume(line); @@ -108,7 +149,7 @@ function checkedStream(file, probe, commit, frozenLane) { } } } - if (probe || frozenLane) consume(line); + if (probe || frozenLane || secrets) consume(line); } finally { closeSync(fd); } @@ -116,11 +157,16 @@ function checkedStream(file, probe, commit, frozenLane) { stream: { file, bytes, sha256: sum.digest("hex") }, ...(frozen ? { frozen } : {}), ...(failures ? { failures } : {}), + ...(secrets ? { diagnostic: streamDiagnostic(named, summary, tail) } : {}), ...evidence, }; } /** Pin the pnpm wrapper's combined output with an owned hard link before hashing the actual bytes. */ export function retainedContainerStream(directory,index,status) { + return retainedContainerOutput(directory, index, status).stream; +} + +function retainedContainerOutput(directory,index,status,secrets) { const fd=openSync(path.join(directory,index+".stdout"),constants.O_RDONLY|constants.O_NOFOLLOW); let summary; try{ @@ -137,14 +183,10 @@ export function retainedContainerStream(directory,index,status) { try{linkSync(file,target)}catch(error){if(error.code!=="EEXIST")throw error} const linked=lstatSync(target); if(!linked.isFile() || linked.dev!==source.dev || linked.ino!==source.ino) deny("combined output identity changed"); - return checkedStream(target,false).stream; + return checkedStream(target,false,undefined,false,secrets); } -/** - * Consume only fixed private stream filenames. Raw bytes and diagnostics never enter the publication document: the - * record is fixed-width, and the probe's own bounded failures line, or a failed Chromium preflight's redacted last - * lines, is returned beside it for the reporter's output only. - */ +/** Read only fixed private stream files and carry bounded, redacted diagnostics from failed lanes. */ export function machineOutcomes(spec, directory) { let failures = ""; if ( @@ -165,6 +207,8 @@ export function machineOutcomes(spec, directory) { deny("stream directory permissions or owner differ"); requireOutcomeCapacity(spec.names.length, spec.artifact); const records = []; + const diagnostics = {}; + const secrets = diagnosticSecrets(); const lanes = spec.names.map((name, index) => { const file = path.join(directory, index + ".json"), fd = openSync(file, constants.O_RDONLY | constants.O_NOFOLLOW); @@ -180,27 +224,35 @@ export function machineOutcomes(spec, directory) { deny("actual lane name or missing status differs"); records.push(rec); const evidence = { exitCode: rec.exitCode, diagnosis: rec.diagnosis, privateStreams: {} }; + const capture = Number.isInteger(rec.exitCode) && rec.exitCode !== 0 && index !== spec.probe ? secrets : null; + const tails = {}; for (const ch of ["stdout", "stderr"]) { const read = checkedStream( path.join(directory, index + "." + ch), ch === "stdout" && index === spec.probe, spec.commit, spec.frozen?.includes(index), + capture, ); if (read.frozen) evidence.frozen = read.frozen; - if (read.failures) failures = probeFailureLine(read.failures); + if (read.failures) failures = probeFailureLine(read.failures, { redact: (value) => boundedDiagnostic(value, secrets) }); evidence.privateStreams[ch] = read.stream; + tails[ch] = read.diagnostic ?? ""; if (read.checks) evidence.checks = read.checks; if (read.capabilities) evidence.capabilities = read.capabilities; } - if(spec.combined?.includes(index) && rec.exitCode!==null) evidence.privateStreams.stdout=retainedContainerStream(directory,index,rec.exitCode); + if (spec.combined?.includes(index) && rec.exitCode !== null) { + const retained = retainedContainerOutput(directory, index, rec.exitCode, capture); + evidence.privateStreams.stdout = retained.stream; + tails.stdout = retained.diagnostic ?? ""; + } + if (tails.stdout || tails.stderr) diagnostics["lane" + index] = [tails.stdout, tails.stderr]; if (spec.frozen?.includes(index) && rec.exitCode === 0 && evidence.frozen?.verdict !== 1) deny("missing successful frozen verdict"); return evidence; }); - // One line follows the record, within the final message's 1,800 characters: the probe runs alone, never on the - // managed host that writes a failed Chromium preflight. - return { encoded: encodeOutcomes({ ...spec, directory: "/tmp/" + path.basename(directory), host: hostname(), lanes }), failures: failures || laneFailureLine(records) }; + return { encoded: encodeOutcomes({ ...spec, directory: "/tmp/" + path.basename(directory), host: hostname(), lanes }), + failures: failures || laneFailureLine(records), diagnostics: boundedDiagnostics(diagnostics) }; } /** * A new bare repository with no hooks installed (`--template=` copies none) that reads the checkout's objects through @@ -230,13 +282,14 @@ function hookFreeRepository() { * the checkout's own push URL, so no hook of the checkout runs and none is bypassed. The checkout's HEAD, index, * working tree and object store stay as they were. */ -export function publishOutcomes(artifact, parent, encoded) { +export function publishOutcomes(artifact, parent, encoded, diagnostics) { if(artifact?.kind !== "validation-outcomes") deny("expected typed result artifact"); checkOutcomeArtifact({ resultArtifact: artifact }); const ref = "refs/heads/" + artifact.branch; if (git("ls-remote", "--refs", "origin", ref)) deny("result reference already exists; authorize a new proof ref"); - const bytes = JSON.stringify({ version: 1, encoded }) + "\n", + const safe = boundedDiagnostics(diagnostics); + const bytes = JSON.stringify({ version: 1, encoded, ...(Object.keys(safe).length ? { diagnostics: safe } : {}) }) + "\n", hash = createHash("sha256").update(bytes).digest("hex"); const url = git("remote", "get-url", "--push", "origin"); const publisher = hookFreeRepository(); @@ -255,9 +308,9 @@ export function publishOutcomes(artifact, parent, encoded) { git("status", "--porcelain") ) deny("unexpected outcome parent, tree or status"); - const push = at("push", "--porcelain", url, child + ":" + ref); - if (!push.includes("[new branch]") || git("ls-remote", "--refs", "origin", ref).split(/\s+/)[0] !== child) - deny("result reference was not newly published at the outcome commit"); + at("push", "--porcelain", "--force-with-lease=" + ref + ":", url, child + ":" + ref); + if (git("ls-remote", "--refs", "origin", ref).split(/\s+/)[0] !== child) + throw Object.assign(new Error("cloud outcome writer: result reference was not verified at the outcome commit"), { publication: "push-failed" }); return ARTIFACT_MARKER + " " + child + ":" + hash; } finally { rmSync(publisher, { recursive: true, force: true }); @@ -267,10 +320,25 @@ export function publishOutcomes(artifact, parent, encoded) { if (process.argv[1] && import.meta.url === pathToFileURL(process.argv[1]).href) { try { const spec = JSON.parse(Buffer.from(process.argv[2], "base64url").toString("utf8")); - const { encoded, failures } = machineOutcomes(spec, process.argv[3]); - const line = spec.artifact ? publishOutcomes(spec.artifact, spec.commit, encoded) : outcomeLine(encoded); - // The record first: the condensed run log keeps only the start of a tool result. - process.stdout.write(line + "\n" + (failures ? failures + "\n" : "")); + const { encoded, failures, diagnostics } = machineOutcomes(spec, process.argv[3]); + let line = outcomeLine(encoded); + let publication = ""; + if (spec.artifact) { + try { line = publishOutcomes(spec.artifact, spec.commit, encoded, diagnostics); } + catch (error) { + publication = `${PUBLICATION_MARKER} ${error.publication ?? "publication-failed"}`; + } + } + if (publication && line.length > OUTCOME_LOG_LIMIT) { + process.stdout.write(publication + "\n"); + process.exitCode = 1; + } else { + const budget = 1750 - Buffer.byteLength([line, failures, publication].join(" ")); + const detail = (!spec.artifact || publication) && diagnosticLine(diagnostics, budget, { attached: true }); + // Keep ordinary lane excerpts on the required result line. Probe and preflight failures keep their existing line. + const record = [line, detail, publication].filter(Boolean).join(" "); + process.stdout.write([record, failures].filter(Boolean).join("\n") + "\n"); + } } catch (e) { process.stderr.write( (String(e.message).startsWith("cloud outcome writer:") || diff --git a/plugins/vibe/lib/vibe/scripts/cloud-redaction.mjs b/plugins/vibe/lib/vibe/scripts/cloud-redaction.mjs new file mode 100644 index 00000000..be691834 --- /dev/null +++ b/plugins/vibe/lib/vibe/scripts/cloud-redaction.mjs @@ -0,0 +1,40 @@ +/** + * `text` with each URL's userinfo (a credential) replaced by ``, through the authority's last `@`, and the + * same for a schemeless `user:password@host` such as a proxy set without a scheme. A password may hold `#`, `?`, `@` + * or a slash, so a path with an `@` after a port may go too. + */ +export function redactUserinfo(text) { + return String(text).replace(/\S+/g, (word) => throughLastAt(word, /(:\/\/)(?:[^/:@]+:.*|[^/]+)@/gis)) + .replace(/[^\s"']+/g, (part) => throughLastAt(part, /(^|[=(<,;])[^/@=(<,;:]+:(?!\/\/).*@/s, /[/?#@]/)); +} + +/** `word` with what `pattern` finds up to its last `@` (one not followed by a `not` character) redacted, in time linear in the word. */ +function throughLastAt(word, pattern, not = /[]/) { + let end = word.length + 1; + do end = word.lastIndexOf("@", end - 2) + 1; while (end > 1 && not.test(word[end] ?? "")); + return word.slice(0, end).replace(pattern, "$1@") + word.slice(end); +} + +const SECRET_VALUE = /(?`. A secret-named value that holds an `@` goes + * first and keeps one, so no part of it is left as a host and a URL around it is still read as one; `afterAt` leaves an + * unquoted one's rest to the rules below. A URL's own user name is left to the URL rule. Other values wait for the + * bearer pass, which needs the word before the token. + */ +export function redactSecrets(text) { + return redactUserinfo(String(text ?? "").replace(SECRET_VALUE, (all, key, sep, value, at, whole) => value.includes("@") && whole.slice(at - 3, at) !== "://" ? `${key}${sep}@${/^\\*["']/.test(value) ? "" : afterAt(value)}` : all).replace(/\S+/g, (word) => throughLastAt(word, /(:\/\/)[^/:@]+:.*@/is))) + .replace(/\b((?:set-)?cookie["']?\s*[:=]).*/gi, "$1 ") + .replace(/\b(Bearer|Basic|token)\s+[A-Za-z0-9._~+/=-]{8,}/gi, "$1 ") + .replace(/\b(?:gh[pousr]_[A-Za-z0-9]{16,}|github_pat_[A-Za-z0-9_]{16,}|sk-[A-Za-z0-9_-]{16,}|xox[abprs]-[A-Za-z0-9-]{10,}|npm_[A-Za-z0-9]{8,}|glpat-[\w-]{8,}|AKIA[A-Z0-9]{16})\b|(?") + .replace(/(?") + .replace(SECRET_VALUE, "$1$2"); +} diff --git a/plugins/vibe/lib/vibe/scripts/cloud-routines.mjs b/plugins/vibe/lib/vibe/scripts/cloud-routines.mjs index fcb0ca8c..4b43f8a9 100644 --- a/plugins/vibe/lib/vibe/scripts/cloud-routines.mjs +++ b/plugins/vibe/lib/vibe/scripts/cloud-routines.mjs @@ -48,6 +48,18 @@ const KEEP_RUNS = 200; */ const ROUTINE_RUNS_PER_HOUR = 30; const RATE_LIMITED = 429; +const LAUNCH_LIMIT = /temporarily limiting requests|rate[ _-]?limit(?:ed| exceeded)?|(?:concurren\w*|capacity) (?:limit|full|reached|exceeded)|too many (?:requests|(?:concurrent |active )?(?:runs|sessions|tasks))/i; + +function isLaunchLimit(error) { + return !error.launchUncertain && !["CLOUD_CALL_TIMEOUT", "CLOUD_RUN_NOT_CREATED"].includes(error.code) + && (error.httpStatus === undefined || [400, 403, 409, 429, 503, 529].includes(error.httpStatus)) + && LAUNCH_LIMIT.test(error.providerMessage || error.message); +} + +function noteLaunchRefusal(error) { + if (error.httpStatus === RATE_LIMITED || isLaunchLimit(error)) error.validationLaunchRefusal = error.providerMessage || error.message; + return error; +} const ROUTINE_ID = /^[\w-]+$/; const RECEIPT_BYTES = 1024 * 1024; const LOCK_POLL_MS = 1000; @@ -196,6 +208,7 @@ function createStanding(ledger, { home, remote, ccr, environment, refusal }) { writeLedger(home, ledger); } if (notSent && attempt < CREATE_ATTEMPTS) continue; + if (error.httpStatus === RATE_LIMITED) throw noteLaunchRefusal(error); throw refusal ? refusal(error) : error; } } @@ -270,15 +283,20 @@ export async function runOnStanding({ remote, home = os.homedir(), environment, const launch = beforeRun ? {launchToken:randomUUID(), startedAt:new Date().toISOString(),...binding} : null; if (launch) brief = brief.replace(/^[^\n]*/, opening => opening + "\nRecord this exact line at the start of the run log:\nVIBE_VALIDATION_LAUNCH " + launch.launchToken); + const updateStanding = () => { + const body = updateBody(ccr, brief, connectorsFor(standing)); + try { return remote("update", { trigger_id: standing.id, body }); } + catch (error) { throw noteLaunchRefusal(error); } + }; let updated; - try { updated = remote("update", { trigger_id: standing.id, body: updateBody(ccr, brief, connectorsFor(standing)) }); } + try { updated = updateStanding(); } catch (error) { if (error?.httpStatus !== 404) throw error; // The standing routine is gone from the account: that is its proof of removal; make a new one. ledger.removed.push({ id: standing.id, provedAt: new Date().toISOString() }); ledger.standing = null; standing = createStanding(ledger, { home, remote, ccr, environment, refusal }); - updated = remote("update", { trigger_id: standing.id, body: updateBody(ccr, brief, connectorsFor(standing)) }); + updated = updateStanding(); } confirmConnectors(updated, allowlist); await beforeRun?.({...launch,routineId:standing.id}); @@ -286,6 +304,8 @@ export async function runOnStanding({ remote, home = os.homedir(), environment, try { started = remote("run", { trigger_id: standing.id }); } catch (error) { if (error.httpStatus === RATE_LIMITED) throw hourlyLimit(error); + // A recognizable provider refusal proves no run was accepted. An ambiguous transport failure still needs recovery. + if (isLaunchLimit(error)) throw noteLaunchRefusal(error); if (![400,401,403,404].includes(error.httpStatus)) error.launchUncertain = true; throw error; } @@ -580,5 +600,5 @@ export async function adoptStanding({ home = os.homedir(), remote, id, waitMs = /** Claude refused the run as rate-limited, so no run started: name the documented cap and when to retry. */ function hourlyLimit(cause) { - return Object.assign(new Error(`CLOUD_ROUTINE_HOURLY_LIMIT: Claude refused the run as rate-limited (HTTP ${RATE_LIMITED}). A routine may start ${ROUTINE_RUNS_PER_HOUR} runs an hour (https://code.claude.com/docs/en/routines, "Usage and limits"); no run started. Retry the same request after the hour's oldest run ages out`), { code: "CLOUD_ROUTINE_HOURLY_LIMIT", cause }); + return Object.assign(new Error(`CLOUD_ROUTINE_HOURLY_LIMIT: Claude refused the run as rate-limited (HTTP ${RATE_LIMITED}). A routine may start ${ROUTINE_RUNS_PER_HOUR} runs an hour (https://code.claude.com/docs/en/routines, "Usage and limits"); no run started. Retry the same request after the hour's oldest run ages out`), { code: "CLOUD_ROUTINE_HOURLY_LIMIT", validationLaunchRefusal: cause.providerMessage || cause.message, cause }); } diff --git a/plugins/vibe/lib/vibe/scripts/cloud-validation-admission-kill.test.mjs b/plugins/vibe/lib/vibe/scripts/cloud-validation-admission-kill.test.mjs index 43f87476..71dd05db 100644 --- a/plugins/vibe/lib/vibe/scripts/cloud-validation-admission-kill.test.mjs +++ b/plugins/vibe/lib/vibe/scripts/cloud-validation-admission-kill.test.mjs @@ -7,11 +7,10 @@ import test from "node:test"; import { fileURLToPath, pathToFileURL } from "node:url"; import { makeHome } from "../../../../vibe/skills/vibe/scripts/test-fixtures.mjs"; import { recoverValidationReservation, withCloudValidationAdmission } from "./cloud-validation-admission.mjs"; -import { markerlessProvider, queueState, unreadableProvider } from "./cloud-validation-queue-test-fixture.mjs"; -import { regularJson } from "./owned-state.mjs"; +import { markerlessProvider, queueFile, queueState, unreadableProvider } from "./cloud-validation-queue-test-fixture.mjs"; +import { regularJson, writeAtomic } from "./owned-state.mjs"; const here = path.dirname(fileURLToPath(import.meta.url)); -const ACCOUNT = "verified-fixture-account"; const LAUNCH = { routineId: "standing", launchToken: "5f0c1e0a-2b7d-4c8e-9a51-7d3f6b2e4c10", startedAt: "2026-11-25T00:00:00.000Z" }; // The launcher child holds request A's admission as `cloud-worker.mjs validate` does, then waits as its poll would. const LAUNCHER = ` @@ -19,8 +18,8 @@ const [admission, owned, home, receipt, acknowledged] = process.argv.slice(1); const { withCloudValidationAdmission } = await import(admission); const { writeAtomic } = await import(owned); const launch = ${JSON.stringify(LAUNCH)}; -await withCloudValidationAdmission({ home, account: ${JSON.stringify(ACCOUNT)}, key: "A", receipt, metadata: { laneKeys: ["unit-1"] }, timeoutMs: 5000, - recover: () => "terminal", report: () => {} }, async ({ launching }) => { +await withCloudValidationAdmission({ home, key: "A", receipt, metadata: { laneKeys: ["unit-1"] }, timeoutMs: 5000, + recover: () => "terminal" }, async ({ launching }) => { await launching(launch); if (acknowledged === "acknowledged") { await launching({ ...launch, runId: "run-A", sessionId: "cse_A" }); @@ -58,34 +57,32 @@ async function killedLauncher(t, signal, acknowledged) { /** * Request `key` asking for admission 15 minutes after the launch, past LAUNCH_WINDOW_MS, with `remote` as the provider. - * One slot, so the killed launcher's reservation fills the account. + * The killed launcher's receipt remains owned by its exact request. */ -const admitLater = (f, key, receipt, remote, action) => withCloudValidationAdmission({ home: f.home, account: ACCOUNT, key, receipt, metadata: {}, timeoutMs: 300, sleepMs: 20, capacity: 1, - now: () => Date.now() + 15 * 60 * 1000, report: () => {}, recover: (entry) => recoverValidationReservation(entry, { ledger: { runs: [] }, remote }) }, action); +const admitLater = (f, key, receipt, remote, action) => withCloudValidationAdmission({ home: f.home, key, receipt, metadata: {}, timeoutMs: 300, sleepMs: 20, + now: () => Date.now() + 15 * 60 * 1000, recover: (entry) => recoverValidationReservation(entry, { ledger: { runs: [] }, remote }) }, action); const BUSY = { code: "CLOUD_VALIDATION_QUEUE_TIMEOUT" }; test("ISS-14476 DT-156R a killed launcher whose launch no provider run acknowledged holds while the provider cannot be read and is reclaimed past its window once reads prove nothing", { timeout: 60_000 }, async (t) => { const f = await killedLauncher(t, "SIGTERM", false); assert.deepEqual([f.held.launch.runId, existsSync(f.receipt)], [undefined, false]); - const other = path.join(f.root, "receipt-B.json"); - await assert.rejects(admitLater(f, "B", other, unreadableProvider, () => assert.fail("B was admitted while the provider could not be read")), BUSY); await assert.rejects(admitLater(f, "A", f.receipt, unreadableProvider, () => assert.fail("A launched again while the provider could not be read")), BUSY); assert.deepEqual([queueState(f.home).active.token, queueState(f.home).abandoned], [f.held.token, []]); - assert.equal(await admitLater(f, "B", other, markerlessProvider, async () => "B admitted"), "B admitted"); + assert.equal(await admitLater(f, "A", f.receipt, markerlessProvider, async () => "A admitted"), "A admitted"); assert.deepEqual(queueState(f.home).abandoned, [{ key: "A", reason: "launcher exited during launch; no provider run was proven" }]); }); -test("ISS-14476 DT-156R DT-157R a launcher killed mid-poll keeps its running receipt past the window: another request holds and the identical request resumes", { timeout: 60_000 }, async (t) => { +test("ISS-14476 DT-156R DT-157R a launcher killed mid-poll keeps its running receipt past the window: the identical request resumes and an independent request can launch", { timeout: 60_000 }, async (t) => { const f = await killedLauncher(t, "SIGKILL", true); assert.deepEqual([f.held.launch.runId, regularJson(f.receipt).status], ["run-A", "running"]); - const other = path.join(f.root, "receipt-B.json"); for (const [name, remote] of [["reports it running", () => ({ data: [{ id: "run-A", session_id: "cse_A", status: "running" }] })], ["does not list it", () => ({ data: [] })], ["cannot be read", unreadableProvider]]) { - await assert.rejects(admitLater(f, "B", other, remote, () => assert.fail(`B was admitted while the provider ${name}`)), BUSY, name); - assert.equal(regularJson(f.receipt).status, "running", `A's receipt stays running while the provider ${name}`); - assert.equal(queueState(f.home).active.token, f.held.token, `A's reservation holds while the provider ${name}`); + const resumed = await admitLater(f, "A", f.receipt, remote, async () => regularJson(f.receipt)); + assert.deepEqual([resumed.runId, resumed.sessionId, resumed.status], ["run-A", "cse_A", "running"], name); + // Replay the same interrupted launch for each provider response. + writeAtomic(queueFile(f.home), { ...queueState(f.home), active: f.held }); } assert.deepEqual(queueState(f.home).abandoned, []); - const resumed = await admitLater(f, "A", f.receipt, unreadableProvider, async () => regularJson(f.receipt)); - assert.deepEqual([resumed.runId, resumed.sessionId, resumed.status], ["run-A", "cse_A", "running"], "the identical request resumes the run its receipt names"); + const other = path.join(f.root, "receipt-B.json"); + assert.equal(await admitLater(f, "B", other, () => assert.fail("independent request read A's provider state"), () => "B admitted"), "B admitted"); }); diff --git a/plugins/vibe/lib/vibe/scripts/cloud-validation-admission.mjs b/plugins/vibe/lib/vibe/scripts/cloud-validation-admission.mjs index b2d279ed..6e54378f 100644 --- a/plugins/vibe/lib/vibe/scripts/cloud-validation-admission.mjs +++ b/plugins/vibe/lib/vibe/scripts/cloud-validation-admission.mjs @@ -6,15 +6,8 @@ import { processIdentityStatus, readProcessIdentity } from "../../../shared/proc import { acquire, release } from "./e2e-lock.mjs"; import { regularJson, writeAtomic } from "./owned-state.mjs"; -// Validations one account runs at once. Measured 2026-12-02 on the pinned environment: seven Sonnet sessions ran at -// once and none was refused (cse_01H58iagixaiYxaLKWAi8tzq, cse_01H58iaebWoaUBxK7wprDhCH, cse_01H58iafVjKHHNew73tsYcEJ, -// cse_01H58iacg8JfytzdBfyQvmfx, cse_01H58iah25UcRZLU85icXi5s, cse_01H58iagK5PXKJM6UC7ES1Zr, cse_01H58iagWGazkKdUCDGCUQEh). -// Seven is the most tried, a lower bound, not a ceiling: https://code.claude.com/docs/en/routines ("Usage and limits") -// names an account limit on tasks running at the same time without a number. Launches still pass one at a time through -// the standing routine's lock and its hourly run limit (cloud-routines.mjs ROUTINE_RUNS_PER_HOUR). -export const CLOUD_VALIDATION_CAPACITY = 7; // An accepted run logs its launch marker within minutes. Past this window a launch whose launcher is gone, that no -// provider run acknowledged and that every provider read proved absent is reclaimed, so the queue never waits on it forever. +// provider run acknowledged and that every provider read proved absent is reclaimed, so the same request can launch again. export const LAUNCH_WINDOW_MS = 10 * 60 * 1000; const BUSY = "CLOUD_VALIDATION_QUEUE_TIMEOUT"; // The lock wait every queue change gets at least, so a request past its deadline still leaves the queue. @@ -23,11 +16,26 @@ const TERMINAL = new Set(["completed", "failed", "canceled", "cancelled", "archi // Recovery's answers when the provider proves nothing: every read succeeded, or a read threw. const UNPROVEN = new Set(["unknown", "unreadable"]); -function identityKey(account) { - return createHash("sha256").update(account).digest("hex"); +function queuesDir(home) { return path.join(home, ".codex", "vibe", "cloud", "validation-queues"); } + +/** Find stored reservations from releases that assigned distinct requests to shared account slots. */ +function reservationFiles(home) { + const queues = queuesDir(home); + return (existsSync(queues) ? readdirSync(queues) : []).map((name) => path.join(queues, name, "queue.json")); } -function queuesDir(home) { return path.join(home, ".codex", "vibe", "cloud", "validation-queues"); } +function reservationFile(home, key, receipt) { + const digest = createHash("sha256").update(key).update("\0").update(receipt).digest("hex"); + const current = path.join(queuesDir(home), `request-${digest}`, "queue.json"); + if (existsSync(current)) return current; + return reservationFiles(home).find((file) => { + if (path.basename(path.dirname(file)).startsWith("request-")) return false; + try { + const { active } = readQueue(file); + return active?.key === key && active.receipt === receipt; + } catch { return false; } + }) ?? current; +} function readQueue(file) { if (!existsSync(file)) return { version: 1, active: null, queued: [], abandoned: [] }; @@ -64,31 +72,15 @@ function abandonedRecord(entry, reason) { return { key: entry.key, reason, ...(entry.launch?.sessionId ? { sessionId: entry.launch.sessionId } : {}) }; } -/** Serialize local admission state for one pinned Claude account and preserve an interrupted running reservation. */ -export async function withCloudValidationAdmission({ home, account, key, receipt, metadata, timeoutMs, signal, recover, now = Date.now, +/** Reserve only this exact request and preserve its interrupted launch for recovery or abandon. */ +export async function withCloudValidationAdmission({ home, key, receipt, metadata, timeoutMs, signal, recover, now = Date.now, wait = (ms, currentSignal) => delay(ms, undefined, { signal: currentSignal }), sleepMs = 500, - drainUnbound = false, report = (line) => process.stderr.write(`${line}\n`), identityOf = readProcessIdentity, launchWindowMs = LAUNCH_WINDOW_MS, - capacity = CLOUD_VALIDATION_CAPACITY, + identityOf = readProcessIdentity, launchWindowMs = LAUNCH_WINDOW_MS, }, action) { - const queues = queuesDir(home); - // The first verified pin must wait for any earlier unbound provider run, including an interrupted launch. - if (!drainUnbound && account !== "unbound-validation" && existsSync(path.join(queues,identityKey("unbound-validation"),"queue.json"))) { - await withCloudValidationAdmission({home, account:"unbound-validation", key:"drain:"+account+":"+key, receipt, metadata, - timeoutMs,signal,recover,now,wait,sleepMs,report,identityOf,launchWindowMs,drainUnbound:true},async()=>{}); - } - // Each slot is its own one-run queue; slot 0 keeps the account's original queue file. Unbound runs keep one slot. - const slots = Array.from({ length: account === "unbound-validation" ? 1 : Math.max(1, capacity) }, - (_, slot) => path.join(queues, identityKey(slot === 0 ? account : `${account}#${slot}`), "queue.json")); - const load = (candidate) => { - const state = readQueue(candidate); - return state.active?.key === key || state.queued.some((entry) => entry.key === key) ? -1 : (state.active ? 1 : 0) + state.queued.length; - }; - // The slot already holding this request, else the least loaded, the lowest first. - let file = slots.reduce((best, candidate) => load(candidate) < load(best) ? candidate : best); + const file = reservationFile(home, key, receipt); const owner = { token: randomUUID(), pid: process.pid, identity: identityOf(process.pid), key, receipt, metadata }; const deadline = now() + timeoutMs; if (!owner.identity) throw new Error("cloud validation could not determine its exact queue process identity"); - report(`CLOUD_VALIDATION_CAPACITY ${slots.length}: at most ${slots.length} active validation${slots.length === 1 ? "" : "s"} per account; excess requests wait in order`); const alive = (entry) => launcherAlive(entry, identityOf); let selected = false; // Waiting, a change waits up to the request's own deadline; admitted, it may be past that deadline after a long run, @@ -127,11 +119,11 @@ export async function withCloudValidationAdmission({ home, account, key, receipt const disposition = active.phase === "reserved" ? "terminal" : await recover(active); const launch = active.phase === "launching"; const recorded = existsSync(active.receipt) ? regularJson(active.receipt) : null; - // A run the provider acknowledged, or a receipt, holds the account until the provider ends it, however old. + // An acknowledged run keeps its request reservation until the provider ends it, however old. // Only a launch with neither, past its window, whose every provider read proved nothing, is reclaimed. const reclaim = launch && !active.launch?.runId && recorded === null && disposition === "unknown" && !(now() - Date.parse(active.launchingAt ?? active.launch?.startedAt) < launchWindowMs); - const identical = !drainUnbound && active.key === key && active.receipt === receipt; + const identical = active.key === key && active.receipt === receipt; // The identical request adopts the run its receipt names, active or launched but not yet listed or readable. const resume = identical && recorded?.status !== "abandoned" && (disposition === "active" || (launch && UNPROVEN.has(disposition) && recorded !== null)); @@ -148,15 +140,7 @@ export async function withCloudValidationAdmission({ home, account, key, receipt }); } if (selected) break; - // A slot that is free with nobody waiting takes this request rather than leaving it behind a long run. - const free = slots.find((candidate) => candidate !== file && load(candidate) === 0); - if (free && active?.token !== owner.token) { - await update((state) => { state.queued = state.queued.filter((entry) => entry.token !== owner.token); }); - file = free; - await update((state) => { state.queued.push(owner); }); - continue; - } - if (now() >= deadline) throw Object.assign(new Error(`${BUSY}: this request did not launch before its queue deadline; every validation slot stayed taken. Retry the same request after one settles`), { code: BUSY }); + if (now() >= deadline) throw Object.assign(new Error(`${BUSY}: this request did not launch before its recovery deadline. Retry the same request to resume its reservation`), { code: BUSY }); await wait(Math.min(sleepMs, Math.max(1, deadline - now())), signal); } // Called before the provider run with its launch nonce, and again with the run and session ids the moment it is acknowledged. @@ -168,7 +152,14 @@ export async function withCloudValidationAdmission({ home, account, key, receipt if (requirements?.outcomeTransport) state.active.metadata={...state.active.metadata,outcomeTransport:requirements.outcomeTransport}; if (requirements?.managedHost === true) state.active.metadata = {...state.active.metadata,managedHost:true}; }); - return await action({ launching }); + // An explicit provider refusal proves this attempt did not start a run. Drop its nonce before waiting to retry. + const launchRefused = () => update((state) => { + if (state.active?.token !== owner.token) throw new Error("cloud validation admission no longer belongs to this request"); + state.active.phase = "reserved"; + delete state.active.launch; + delete state.active.launchingAt; + }); + return await action({ launching, launchRefused }); } catch (error) { unresolved = error?.launchUncertain || ["CLOUD_CALL_TIMEOUT", "CLOUD_RUN_NOT_CREATED"].includes(error?.code); throw error; @@ -176,9 +167,8 @@ export async function withCloudValidationAdmission({ home, account, key, receipt await update((state) => { state.queued = state.queued.filter((entry) => entry.token !== owner.token); if (state.active?.token !== owner.token) return; - if (drainUnbound) { state.active = null; return; } const latest = existsSync(receipt) ? regularJson(receipt) : null; - // A request that never launched and still finds the receipt abandoned leaves the account free; one that launched, + // A request that never launched and still finds the receipt abandoned releases the request; one that launched, // or polled a run whose receipt was abandoned during its poll, holds until the provider ends that run. const refused = abandonedBefore && state.active.phase === "reserved" && latest?.status === "abandoned"; if (latest && !TERMINAL.has(latest.status) && !refused) Object.assign(state.active, { phase: "running", pid: null, identity: null }); @@ -196,18 +186,23 @@ function entryView(entry) { } /** - * Abandon's one release step for a request, with or without its receipt: the request's queue reservation, found by its - * request key in any account's queue, is released once its launcher is gone. A launcher that is still alive keeps it: + * Abandon releases the exact request's reservation once its launcher is gone, including an unambiguous receipt-less + * launch from before an account pin. A launcher that is still alive keeps it: * without a receipt abandon refuses, and with one abandon still marks the receipt. `receipt` is null when the launch * wrote none, else `{ plan, write, runId }`: the dry run's receipt change, its synchronous write, done under the queue * lock so no resume or release interleaves, and the run id it ends (null for a terminal receipt). Without confirm it * reports the plan and changes nothing. Every run this abandon ends is marked abandoned in the routine ledger through * `markRun`; the release is the person's way out when the provider never ends or lists that run. */ -export async function releaseValidationReservation({ home, key, receipt = null, confirm = false, unconfirmed, markRun, identityOf = readProcessIdentity }) { - const queues = queuesDir(home); - const file = (existsSync(queues) ? readdirSync(queues) : []).map((name) => path.join(queues, name, "queue.json")) - .find((candidate) => existsSync(candidate) && readQueue(candidate).active?.key === key); +export async function releaseValidationReservation({ home, key, receiptFile, receipt = null, confirm = false, unconfirmed, markRun, identityOf = readProcessIdentity }) { + const candidate = reservationFile(home, key, receiptFile); + let file = readQueue(candidate).active?.key === key ? candidate : null; + if (!file && !receipt) { + const matches = reservationFiles(home).filter((other) => { + try { return readQueue(other).active?.key === key; } catch { return false; } + }); + if (matches.length === 1) file = matches[0]; + } if (!file && !receipt) throw new Error("no cloud task exists to poll and no queue reservation holds this request"); const live = (entry) => { if (!launcherAlive(entry, identityOf)) return false; @@ -289,11 +284,8 @@ function locateLaunch(launch, remote) { return null; } -// An inventory cut at LIST_RUNS_PAGES is read, not refused, so a lost launch is still reclaimed past its window on a -// standing routine whose run history outgrew the limit. Runs are listed newest first and no other validation launches -// while a reservation holds the account, but dispatch runs on the same standing routine outside the queue, so enough -// newer dispatch runs can push a launch that did happen past the limit; that rare launch is then reclaimed while it may -// still run. Any other thrown provider read leaves the run unreadable. +// A bounded inventory can miss an older nonce. As with a complete empty read, reclaim an unacknowledged launch +// only after its recovery window. A failed provider read leaves that launch unreadable. const unproven = (error) => error instanceof IncompleteRunInventory ? "unknown" : "unreadable"; /** diff --git a/plugins/vibe/lib/vibe/scripts/cloud-validation-admission.test.mjs b/plugins/vibe/lib/vibe/scripts/cloud-validation-admission.test.mjs index f1f97933..0e69c42c 100644 --- a/plugins/vibe/lib/vibe/scripts/cloud-validation-admission.test.mjs +++ b/plugins/vibe/lib/vibe/scripts/cloud-validation-admission.test.mjs @@ -8,93 +8,138 @@ import { git, makeCheckout, makeHome } from "../../../../vibe/skills/vibe/script import { readProcessIdentity } from "../../../shared/process-identity.mjs"; import { recoverValidationReservation, withCloudValidationAdmission } from "./cloud-validation-admission.mjs"; import { acquire, release as releaseLock } from "./e2e-lock.mjs"; -import { ledgerPath, NO_EXECUTOR, readLedger } from "./cloud-routines.mjs"; +import { ledgerPath, NO_EXECUTOR, readLedger, runOnStanding } from "./cloud-routines.mjs"; import {machineTestReport} from "./cloud-outcome-test-fixture.mjs"; -import { abandonValidation, pollTask, remoteTrigger, sha256, validateCommit } from "./cloud-worker.mjs"; +import { abandonValidation, pollTask, remoteTrigger, retryValidationLaunch, sha256, validateCommit } from "./cloud-worker.mjs"; import { regularJson, writeAtomic } from "./owned-state.mjs"; import { markerlessProvider, queueFile, queueState, unreadableProvider } from "./cloud-validation-queue-test-fixture.mjs"; -// One slot fills the account, so these cases exercise a full account; the slot cases pass their own capacity. function fixture(t) { const f = makeHome("vibe-cloud-validation-admission-"); t.after(f.cleanup); const receipt = (key) => path.join(f.root, `${key}.json`); - const lines = []; const execute = (key, action, options = {}) => withCloudValidationAdmission({ - home: f.home, account: "verified-fixture-account", key, receipt: receipt(key), timeoutMs: 3000, sleepMs: 5, - identityOf: () => "mock-process-start", recover: () => "terminal", report: (line) => lines.push(line), capacity: 1, ...options, + home: f.home, key, receipt: receipt(key), timeoutMs: 3000, sleepMs: 5, + identityOf: () => "mock-process-start", recover: () => "terminal", ...options, }, action); - return { home: f.home, receipt, lines, execute }; + return { home: f.home, receipt, execute }; } /** A validation request for a fresh fixture checkout, with the routine service the tests drive. */ -function adoptionFixture(t) { +function adoptionFixture(t, files = {}) { const f = makeHome("vibe-cloud-validation-adopt-"); t.after(f.cleanup); const repository = "closedloop-ai/claude-plugins"; const worktree = path.join(f.root, "checkout"); - makeCheckout({ ...f, checkout: worktree, remoteUrl: `https://github.com/${repository}.git` }); + makeCheckout({ ...f, checkout: worktree, remoteUrl: `https://github.com/${repository}.git`, files }); const commit = git(worktree, ["rev-parse", "HEAD"], f.home); const request = { commit, worktree, repository, provider: "claude", model: "claude-sonnet-5-5", branch: "proof", claudeEnvironment: "env_01QueueFixture", pollMs: 1000, lanes: [{ name: "unit-1", command: "node --test selected.test.mjs" }] }; return { ...f, request }; } -test("ISS-14476 ten concurrent cloud requests each fire once at declared one-run capacity", async (t) => { - const f = fixture(t); - let active = 0; - const started = []; - await Promise.all(Array.from({ length: 10 }, (_, index) => f.execute(String(index), async ({ launching }) => { - await launching(); - active++; - assert.equal(active, 1); - started.push(index); - await sleep(8); - active--; - }))); - assert.equal(new Set(started).size, 10); - assert.equal(f.lines.length, 10); - assert.ok(f.lines.every((line) => line.startsWith("CLOUD_VALIDATION_CAPACITY 1"))); -}); - -test("ISS-15038 ten concurrent requests run at most the measured capacity at once, each once", async (t) => { - const { CLOUD_VALIDATION_CAPACITY } = await import("./cloud-validation-admission.mjs"); +function providerRunLimit(payload, message) { + return remoteTrigger("run", payload, { run: () => ({ + status: 0, stderr: "", stdout: [ + { message: { content: [{ type: "tool_use", name: "RemoteTrigger", id: "one", input: { action: "run", ...payload } }] } }, + { message: { content: [{ type: "tool_result", tool_use_id: "one", content: "HTTP 503\n" + JSON.stringify({ error: { message } }) }] } }, + ].map((row) => JSON.stringify(row)).join("\n"), + }) }); +} + +test("ten different validations reach an accepting launcher without waiting for another to finish", async (t) => { const f = fixture(t); - let active = 0, peak = 0; - const started = []; - await Promise.all(Array.from({ length: 10 }, (_, index) => f.execute(String(index), async ({ launching }) => { + const finished = Promise.withResolvers(); + const launched = []; + const requests = Array.from({ length: 10 }, (_, index) => f.execute(String(index), async ({ launching }) => { await launching(); - peak = Math.max(peak, ++active); - started.push(index); - await sleep(40); - active--; - }, { capacity: CLOUD_VALIDATION_CAPACITY }))); - assert.equal(CLOUD_VALIDATION_CAPACITY, 7); - assert.equal(new Set(started).size, 10); - assert.equal(peak, CLOUD_VALIDATION_CAPACITY, "the slots fill before anyone waits, and never overfill"); - assert.ok(f.lines.every((line) => line.startsWith("CLOUD_VALIDATION_CAPACITY 7: at most 7 active validations per account"))); -}); - -test("ISS-15038 a request queued behind a long run moves to a slot that frees", async (t) => { + launched.push(index); + if (launched.length === 10) finished.resolve(); + await finished.promise; + }, { wait: () => assert.fail("an independent request waited for admission") })); + try { + await Promise.all(requests); + assert.equal(new Set(launched).size, 10); + } finally { + finished.resolve(); + await Promise.allSettled(requests); + } +}); + +test("a provider launch limit is reported and only the refused request is retried", async (t) => { + const f = adoptionFixture(t, { ".github/workflows/ci.yml": + "on: push\njobs:\n unit-1:\n runs-on: ubuntu-latest\n steps:\n - run: node --test ci.test.mjs\n" }); + const report = []; + let attempted = 0; + const refusal = "Server is temporarily limiting requests"; + const remote = (action, payload) => { + if (["create", "update"].includes(action)) return { trigger: { id: "standing", mcp_connections: [] } }; + if (action === "run") { + if (++attempted === 1) return providerRunLimit(payload, refusal); + return { run_id: "run", session_id: "session" }; + } + if (action === "list_runs") return { data: [{ id: "run", session_id: "session", status: "completed" }] }; + if (action === "get_run_log") return { log: machineTestReport(f.request, [0]) }; + assert.fail(action); + }; + const clock = Date.parse("2026-12-03T12:00:00Z"); + const waits = []; + const result = await validateCommit(f.request, { remote, home: f.home, executor: NO_EXECUTOR, + now: () => clock, sleep: async (ms) => { waits.push(ms); }, stderr: (line) => report.push(line) }); + assert.equal(result.passed, true); + assert.equal(attempted, 2); + assert.equal(waits.length, 1); + assert.ok(waits[0] > 0); + assert.match(report.join("\n"), /2026-12-03T12:00:00.000Z.*Server is temporarily limiting requests/); + const receipt = regularJson(result.receipt); + assert.deepEqual(receipt.launchRefusals, [{ time: new Date(clock).toISOString(), message: refusal }]); + assert.match(receipt.warnings[0], /unit-1.*ci\.yml.*recipe/); + assert.match(report[0], /CLOUD_VALIDATION_WORKFLOW_MISMATCH/); +}); + +test("a proven limit releases its launch nonce, waits, and records the redacted retry", async (t) => { + const f = makeHome("vibe-cloud-launch-limit-"); + t.after(f.cleanup); + const events = []; + let clock = 0; + const report = []; + const remote = (action, payload) => { + if (["create", "update"].includes(action)) return { trigger: { id: "standing", mcp_connections: [] } }; + assert.equal(action, "run"); + events.push("start"); + if (clock === 0) return providerRunLimit(payload, "Server is temporarily limiting requests. API_TOKEN=private-fixture"); + return { run_id: "accepted", session_id: "cse_accepted" }; + }; + const result = await retryValidationLaunch(() => runOnStanding({ + home: f.home, remote, environment: { id: "env_fixture" }, ccr: {}, brief: "fixture", waitMs: 1000, + }), { timeoutMs: 60_000, now: () => clock, report: (line) => report.push(line), + launchRefused: () => events.push("release nonce"), sleep: async (ms) => { events.push("wait"); clock += ms; } }); + assert.deepEqual(events, ["start", "release nonce", "wait", "start"]); + assert.equal(result.runId, "accepted"); + assert.deepEqual(readLedger(f.home).runs.map(({ runId }) => runId), ["accepted"]); + assert.deepEqual(result.launchRefusals, [{ time: "1970-01-01T00:00:00.000Z", + message: "Server is temporarily limiting requests. API_TOKEN=" }]); + assert.doesNotMatch(report[0], /private-fixture/); +}); + +test("the exact request can still recover its interrupted reservation from a previous release", async (t) => { const f = fixture(t); - let finishLong, finishShort; - const long = new Promise((resolve) => { finishLong = resolve; }); - const short = new Promise((resolve) => { finishShort = resolve; }); - const running = []; - const first = f.execute("long", async ({ launching }) => { await launching(); running.push("long"); await long; }, { capacity: 2 }); - const second = f.execute("short", async ({ launching }) => { await launching(); running.push("short"); await short; }, { capacity: 2 }); - while (running.length < 2) await sleep(5); - // Both slots are taken; the third waits in one of them, then the short run in the other ends. - const third = f.execute("third", () => "admitted", { capacity: 2 }); - await sleep(30); - finishShort(); - await second; - assert.equal(await third, "admitted", "admitted while the long run still holds its slot"); - finishLong(); - await first; -}); - -test("ISS-14476 queued cancellation and timeout do not launch or overtake a live reservation", async (t) => { + const key = "legacy"; + const receipt = f.receipt(key); + const legacy = path.join(f.home, ".codex", "vibe", "cloud", "validation-queues", "legacy-account-slot", "queue.json"); + mkdirSync(path.dirname(legacy), { recursive: true }); + writeAtomic(receipt, { status: "running", runId: "existing" }); + writeAtomic(legacy, { version: 1, active: { key, receipt, token: "old-owner", phase: "launching", pid: null }, + queued: [], abandoned: [] }); + const result = await f.execute(key, () => { + assert.notEqual(regularJson(legacy).active.token, "old-owner"); + return regularJson(receipt); + }, { recover: () => "active" }); + assert.equal(result.runId, "existing"); + assert.equal(queueFile(f.home), legacy); +}); + +test("ISS-14476 cancellation and timeout do not overtake a live reservation for the same request", async (t) => { const f = fixture(t); let begin; let finish; @@ -103,10 +148,10 @@ test("ISS-14476 queued cancellation and timeout do not launch or overtake a live const active = f.execute("first", async () => { begin(); await hold; }); await entered; const abort = new AbortController(); - const second = f.execute("cancelled", () => assert.fail("cancelled request launched"), { signal: abort.signal }); + const second = f.execute("first", () => assert.fail("cancelled request launched"), { signal: abort.signal }); abort.abort(); await assert.rejects(second, /aborted/i); - await assert.rejects(f.execute("timed-out", () => assert.fail("timed-out request launched"), { timeoutMs: 25 }), /did not launch/); + await assert.rejects(f.execute("first", () => assert.fail("timed-out request launched"), { timeoutMs: 25 }), /did not launch/); finish(); await active; assert.equal(await f.execute("next", () => "running"), "running"); @@ -142,7 +187,6 @@ test("ISS-14476 ten validate calls wait for routine visibility and start exactly const request = { commit, worktree, repository, provider: "claude", model: "claude-sonnet-5-5", branch: "proof", claudeEnvironment: "env_01QueueFixture", pollMs: 1000 }; let currentLane; - let outstanding; let creations = 0; const launched = []; const runs = new Map(); @@ -153,20 +197,19 @@ test("ISS-14476 ten validate calls wait for routine visibility and start exactly return { trigger: { id: "standing", mcp_connections: [] } }; } if (action === "run") { - assert.equal(outstanding, undefined); - outstanding = currentLane; - assert.ok(!runs.has(outstanding), "never dispatch the same request twice"); - const id = `run-${outstanding}`; - runs.set(outstanding, { id, reads: 0 }); - launched.push(outstanding); - return { run_id: id, session_id: outstanding }; + assert.ok(!runs.has(currentLane), "never dispatch the same request twice"); + const id = `run-${currentLane}`; + runs.set(currentLane, { id, reads: 0 }); + launched.push(currentLane); + return { run_id: id, session_id: currentLane }; } if (action === "list_runs") { - const run = runs.get(outstanding); - if (!run || run.reads++ === 0) return { data: [] }; - const name = outstanding; - outstanding = undefined; - return { data: [{ id: run.id, status: "active", worker_status: "idle", session_id: name }] }; + const data = []; + for (const [name, run] of runs) { + if (run.reads < 2) run.reads++; + if (run.reads === 2) data.push({ id: run.id, status: "active", worker_status: "idle", session_id: name }); + } + return { data }; } if (action === "get_run_log") return {log:machineTestReport({...request,lanes:[{name:payload.session_id,command:"node --test selected.test.mjs"}]},[0])}; assert.fail(action); @@ -204,7 +247,7 @@ test("ordinary captured JSON documents reject trailing input",()=>{ assert.deepEqual(capturedJson('{\n"data":[]\n}'),{data:[]}); }); -test("a lost provider acknowledgement releases the next queued request through its exact launch marker", async t => { +test("a lost provider acknowledgement is found by retrying the exact request with its launch marker", async t => { const f=fixture(t), identity={routineId:"standing",launchToken:"123e4567-e89b-42d3-a456-426614174000",startedAt:new Date().toISOString()}; await assert.rejects(f.execute("lost",async ({launching})=>{ await launching(identity); @@ -218,7 +261,7 @@ test("a lost provider acknowledgement releases the next queued request through i if(action==="get_run_log") return {log:input.session_id==="owned" ? "[2026-11-23T12:00:00Z] assistant: VIBE_VALIDATION_LAUNCH "+identity.launchToken : "VIBE_VALIDATION_LAUNCH another"}; assert.fail(action); }; - assert.equal(await f.execute("next",()=> "admitted",{recover:entry=>recoverValidationReservation(entry,{ledger:{runs:[]},remote}),timeoutMs:80}),"admitted"); + assert.equal(await f.execute("lost",()=> "admitted",{recover:entry=>recoverValidationReservation(entry,{ledger:{runs:[]},remote}),timeoutMs:80}),"admitted"); assert.equal(regularJson(f.receipt("lost")).runId,"launched"); }); @@ -232,7 +275,7 @@ test("ISS-14476 DT-162R recovery of a locally abandoned receipt whose reservatio } }); -test("ISS-14476 DT-162R another request waits behind a locally abandoned run whose reservation no abandon released until the provider confirms termination",async t=>{ +test("ISS-14476 DT-162R the same request waits for a locally abandoned run until the provider confirms termination",async t=>{ const f=fixture(t); await f.execute("active",async ({launching})=>{ await launching(); @@ -243,9 +286,9 @@ test("ISS-14476 DT-162R another request waits behind a locally abandoned run who now:()=>clock,wait:async delay=>{clock+=delay;}, timeoutMs:20, recover:entry=>recoverValidationReservation(entry,{ledger:{runs:[]},remote:()=>({data:[{id:"owned",status}]})}), }; - await assert.rejects(f.execute("next",()=>assert.fail("released before provider termination"),observed),/did not launch/); + await assert.rejects(f.execute("active",()=>assert.fail("released before provider termination"),observed),/did not launch/); status="completed"; - assert.equal(await f.execute("next",()=>"admitted",observed),"admitted"); + assert.equal(await f.execute("active",()=>"admitted",observed),"admitted"); assert.equal(regularJson(f.receipt("active")).status,"abandoned"); }); @@ -301,47 +344,6 @@ test("an unknown inventory at the deadline cannot become a missing run",async()= assert.equal(result.status,"overdue");assert.equal(result.remoteStatus,"unknown");assert.equal(result.runId,"owned"); }); -test("queued validations launch in the order they arrived once the active one releases", async (t) => { - const f = fixture(t); - const started = []; - let release; - const held = new Promise((resolve) => { release = resolve; }); - const first = f.execute("first", async ({ launching }) => { await launching(); started.push("first"); await held; }); - while (!started.length) await sleep(5); - const waiters = []; - for (const key of ["b", "c", "d", "e", "f"]) { - waiters.push(f.execute(key, async ({ launching }) => { await launching(); started.push(key); await sleep(2); })); - await sleep(25); - } - release(); - await Promise.all([first, ...waiters]); - assert.deepEqual(started, ["first", "b", "c", "d", "e", "f"]); -}); - -test("ISS-15038 fifty queued validations wait out queue-lock contention and each launch once before their own deadline", async (t) => { - const f = fixture(t); - const started = []; - let release; - const held = new Promise((resolve) => { release = resolve; }); - const first = f.execute("first", async ({ launching }) => { await launching(); started.push("first"); await held; }, { timeoutMs: 60_000 }); - while (!started.length) await sleep(5); - const keys = Array.from({ length: 50 }, (_, index) => `waiter-${index}`); - const waiters = keys.map((key) => f.execute(key, async ({ launching }) => { await launching(); started.push(key); }, { timeoutMs: 60_000 })); - while (queueState(f.home).queued.length < keys.length) await sleep(5); - // A peer holds the queue lock longer than any fixed lock wait shorter than the requests' own deadline. - const lock = path.join(path.dirname(queueFile(f.home)), "queue.lock"); - const peer = { pid: process.pid, token: "peer-holding-the-queue-lock", purpose: "cloud-validation-queue" }; - assert.equal((await acquire(lock, peer, { waitSeconds: 5, pollMs: 1 })).acquired, true); - await sleep(6_000); - releaseLock(lock, peer); - release(); - const settled = await Promise.allSettled([first, ...waiters]); - assert.deepEqual(settled.filter(({ status }) => status === "rejected").map(({ reason }) => reason.message), []); - assert.deepEqual([...started].sort(), ["first", ...keys].sort()); - const { active, queued } = queueState(f.home); - assert.deepEqual({ active, queued }, { active: null, queued: [] }); -}); - test("ISS-15038 a queued request checks launcher liveness outside the queue lock", async (t) => { const f = fixture(t); const lock = () => path.join(path.dirname(queueFile(f.home)), "queue.lock"); @@ -359,7 +361,7 @@ test("ISS-15038 a queued request checks launcher liveness outside the queue lock let running = false; const first = f.execute("first", async () => { running = true; await held; }, { identityOf }); while (!running) await sleep(5); - const waiter = f.execute("waiter", () => "launched", { identityOf }); + const waiter = f.execute("first", () => "launched", { identityOf }); while (queueState(f.home).queued.length < 1) await sleep(5); // A second live queued launcher behind the waiter, so every poll checks one entry besides its own. const peer = { pid: process.pid, token: "test-seeding-the-queue", purpose: "cloud-validation-queue" }; @@ -376,7 +378,7 @@ test("ISS-15038 a queued request checks launcher liveness outside the queue lock assert.equal(underLock, 0); }); -test("ISS-15038 a launched request past its queue deadline still releases the account through queue-lock contention", async (t) => { +test("ISS-15038 a launched request past its queue deadline still releases its reservation through queue-lock contention", async (t) => { const f = fixture(t); const lock = () => path.join(path.dirname(queueFile(f.home)), "queue.lock"); const peer = { pid: process.pid, token: "peer-holding-the-queue-lock", purpose: "cloud-validation-queue" }; @@ -406,15 +408,15 @@ test("ISS-14476 DT-149R a launching reservation whose launcher is gone is reclai const stuck = queueState(f.home).active; assert.deepEqual([stuck.key, stuck.phase, stuck.pid, stuck.identity], ["lost", "launching", null, null]); const waiting = { ...timed, timeoutMs: 30_000, recover: () => "unknown" }; - await assert.rejects(f.execute("next", () => assert.fail("admitted inside the launch window"), waiting), { code: "CLOUD_VALIDATION_QUEUE_TIMEOUT" }); - assert.equal(queueState(f.home).active.token, stuck.token, "inside the window the gone launcher's reservation still holds the account"); + await assert.rejects(f.execute("lost", () => assert.fail("admitted inside the launch window"), waiting), { code: "CLOUD_VALIDATION_QUEUE_TIMEOUT" }); + assert.equal(queueState(f.home).active.token, stuck.token, "inside the window the gone launcher's reservation still holds the request"); clock += 60_000; - assert.equal(await f.execute("next", () => "admitted", waiting), "admitted"); + assert.equal(await f.execute("lost", () => "admitted", waiting), "admitted"); assert.deepEqual(queueState(f.home).abandoned.at(-1), { key: "lost", reason: "launcher exited during launch; no provider run was proven" }); // A recorded launcher pid whose start time no longer matches is gone the same way. - writeAtomic(queueFile(f.home), { ...queueState(f.home), active: { ...stuck, token: "crashed", key: "crashed", pid: process.pid, identity: "an earlier process start" } }); - assert.equal(await f.execute("after-crash", () => "admitted", waiting), "admitted"); - assert.equal(queueState(f.home).abandoned.at(-1).key, "crashed"); + writeAtomic(queueFile(f.home), { ...queueState(f.home), active: { ...stuck, token: "crashed", pid: process.pid, identity: "an earlier process start" } }); + assert.equal(await f.execute("lost", () => "admitted", waiting), "admitted"); + assert.equal(queueState(f.home).abandoned.length, 2); assert.equal(queueState(f.home).active, null); }); @@ -436,14 +438,14 @@ test("ISS-14476 DT-153R a launching reservation whose launcher is alive is waite clock += 10 * 60_000; let recovered = 0; const waiting = { ...timed, timeoutMs: 30_000, recover: () => { recovered++; return "unknown"; } }; - await assert.rejects(f.execute("next", () => assert.fail("a live launcher's reservation was reclaimed"), waiting), { code: "CLOUD_VALIDATION_QUEUE_TIMEOUT" }); + await assert.rejects(f.execute("live", () => assert.fail("a live launcher's reservation was reclaimed"), waiting), { code: "CLOUD_VALIDATION_QUEUE_TIMEOUT" }); assert.equal(recovered, 0, "a live launcher is never reconciled"); assert.equal(queueState(f.home).active.key, "live"); finish(); assert.equal(await live, "live launcher finished"); }); -test("ISS-14476 DT-157R another request never marks a gone launcher's acknowledged run abandoned and holds the account at any age until the provider ends it", async (t) => { +test("ISS-14476 DT-157R the same request adopts an acknowledged run at any age without marking it abandoned", async (t) => { const f = fixture(t); let clock = 0; const timed = { now: () => clock, wait: async (ms) => { clock += ms; }, launchWindowMs: 60_000, sleepMs: 10_000, timeoutMs: 20_000 }; @@ -461,14 +463,14 @@ test("ISS-14476 DT-157R another request never marks a gone launcher's acknowledg for (const [name, answer] of [["reports it running", () => ({ data: [{ id: "run-lost", session_id: "cse_lost", status: "running" }] })], ["does not list it", () => ({ data: [] })], ["cannot be read", () => unreadableProvider("list_runs")]]) { provider = answer; - await assert.rejects(f.execute("next", () => assert.fail(`admitted while the provider ${name}`), { ...timed, recover }), { code: "CLOUD_VALIDATION_QUEUE_TIMEOUT" }, name); - assert.equal(queueState(f.home).active.token, stuck.token, `the gone launcher's reservation holds while the provider ${name}`); - const receipt = regularJson(f.receipt("lost")); + writeAtomic(queueFile(f.home), { ...queueState(f.home), active: stuck }); + const receipt = await f.execute("lost", () => regularJson(f.receipt("lost")), { ...timed, recover }); + assert.equal(queueState(f.home).active.key, stuck.key, `the same request holds its reservation while the provider ${name}`); assert.deepEqual([receipt.status, receipt.runId, receipt.sessionId, receipt.requestDigest], ["running", "run-lost", "cse_lost", "lost"], `its receipt stays running while the provider ${name}`); } assert.deepEqual(queueState(f.home).abandoned, [], "an acknowledged run is never reclaimed"); provider = () => ({ data: [{ id: "run-lost", session_id: "cse_lost", status: "completed" }] }); - assert.equal(await f.execute("next", () => "admitted", { ...timed, recover }), "admitted"); + assert.equal(await f.execute("lost", () => "admitted", { ...timed, recover }), "admitted"); }); test("ISS-14476 DT-156R GR6-2 a launch whose reservation recorded a run id is never reclaimed as unproven, even when recovery writes no receipt", async (t) => { @@ -482,7 +484,7 @@ test("ISS-14476 DT-156R GR6-2 a launch whose reservation recorded a run id is ne throw Object.assign(new Error("routine ledger write failed"), { launchUncertain: true }); }, timed), /ledger write failed/); clock += 60 * 60_000; - await assert.rejects(f.execute("next", () => assert.fail("a recorded run id was reclaimed"), { ...timed, recover: () => "unknown" }), { code: "CLOUD_VALIDATION_QUEUE_TIMEOUT" }); + await assert.rejects(f.execute("lost", () => assert.fail("a recorded run id was reclaimed"), { ...timed, recover: () => "unknown" }), { code: "CLOUD_VALIDATION_QUEUE_TIMEOUT" }); assert.deepEqual([queueState(f.home).active.launch.runId, existsSync(f.receipt("lost")), queueState(f.home).abandoned], ["run-lost", false, []], "no abandoned record says no provider run was proven for a reservation that recorded one"); }); @@ -498,11 +500,10 @@ test("ISS-14476 DT-156R a gone launcher's unacknowledged launch holds at any age clock += 60 * 60_000; let readable = false; const recover = (entry) => recoverValidationReservation(entry, { ledger: { runs: [] }, remote: (action) => (readable ? markerlessProvider : unreadableProvider)(action) }); - await assert.rejects(f.execute("next", () => assert.fail("admitted while the provider could not be read"), { ...timed, recover }), { code: "CLOUD_VALIDATION_QUEUE_TIMEOUT" }); await assert.rejects(f.execute("lost", () => assert.fail("the identical request launched again while the provider could not be read"), { ...timed, recover }), { code: "CLOUD_VALIDATION_QUEUE_TIMEOUT" }); assert.deepEqual([queueState(f.home).active.key, queueState(f.home).abandoned], ["lost", []]); readable = true; - assert.equal(await f.execute("next", () => "admitted", { ...timed, recover }), "admitted"); + assert.equal(await f.execute("lost", () => "admitted", { ...timed, recover }), "admitted"); assert.deepEqual(queueState(f.home).abandoned, [{ key: "lost", reason: "launcher exited during launch; no provider run was proven" }], "a reclaimed launch carries no run or session id"); assert.equal(existsSync(f.receipt("lost")), false); }); @@ -522,7 +523,7 @@ test("ISS-14476 DT-160R a gone launcher's unacknowledged launch is reclaimed pas pages++; return { data: [{ id: `run-${pages}`, session_id: `cse_${pages}`, status: "completed" }], next_cursor: `page-${pages + 1}` }; }; - assert.equal(await f.execute("next", () => "admitted", { ...timed, recover: (entry) => recoverValidationReservation(entry, { ledger: { runs: [] }, remote }) }), "admitted"); + assert.equal(await f.execute("lost", () => "admitted", { ...timed, recover: (entry) => recoverValidationReservation(entry, { ledger: { runs: [] }, remote }) }), "admitted"); assert.equal(pages, 10, "the inventory was read to its page limit"); assert.deepEqual(queueState(f.home).abandoned, [{ key: "lost", reason: "launcher exited during launch; no provider run was proven" }]); }); @@ -646,8 +647,8 @@ test("ISS-14476 DT-152R DT-159R abandon releases the queue reservation of a requ const f = adoptionFixture(t); const key = sha256(JSON.stringify(f.request)); const receipt = gitDirReceipt(f.request, key); - const admit = (action) => withCloudValidationAdmission({ home: f.home, account: "verified-fixture-account", key, receipt, - timeoutMs: 3000, sleepMs: 5, recover: () => "unknown", report: () => {} }, action); + const admit = (action) => withCloudValidationAdmission({ home: f.home, key, receipt, + timeoutMs: 3000, sleepMs: 5, recover: () => "unknown" }, action); await assert.rejects(admit(async ({ launching }) => { await launching({ ...LAUNCH, startedAt: new Date().toISOString() }); throw lostLaunch("Claude RemoteTrigger run timed out on this machine after 90 s"); @@ -677,8 +678,8 @@ test("ISS-14476 DT-152R DT-158R abandon releases a receipt-less reservation that const key = sha256(JSON.stringify(f.request)); const receipt = gitDirReceipt(f.request, key); const launch = { ...LAUNCH, startedAt: new Date().toISOString() }; - await assert.rejects(withCloudValidationAdmission({ home: f.home, account: "verified-fixture-account", key, receipt, - timeoutMs: 3000, sleepMs: 5, recover: () => "unknown", report: () => {} }, async ({ launching }) => { + await assert.rejects(withCloudValidationAdmission({ home: f.home, key, receipt, + timeoutMs: 3000, sleepMs: 5, recover: () => "unknown" }, async ({ launching }) => { await launching(launch); await launching({ ...launch, runId: "run-acknowledged", sessionId: "cse_acknowledged" }); throw Object.assign(new Error("routine ledger write failed"), { launchUncertain: true }); @@ -698,15 +699,15 @@ test("ISS-14476 DT-152R DT-158R abandon releases a receipt-less reservation that /** * A validation request whose acknowledged run lost its launcher (the reservation holds runId, pid null), with its routine - * ledger row, after another request's real recovery wrote the run's receipt and timed out while the provider listed nothing. + * ledger row, after real recovery wrote the run's receipt while the provider listed nothing. */ async function recoveredLostRun(t) { const f = adoptionFixture(t); const key = sha256(JSON.stringify(f.request)); const receipt = gitDirReceipt(f.request, key); let clock = 0; - const admit = (requestKey, file, action, options = {}) => withCloudValidationAdmission({ home: f.home, account: "unbound-validation", key: requestKey, - receipt: file, report: () => {}, now: () => clock, wait: async (ms) => { clock += ms; }, launchWindowMs: 60_000, sleepMs: 10_000, timeoutMs: 20_000, ...options }, action); + const admit = (requestKey, file, action, options = {}) => withCloudValidationAdmission({ home: f.home, key: requestKey, + receipt: file, now: () => clock, wait: async (ms) => { clock += ms; }, launchWindowMs: 60_000, sleepMs: 10_000, timeoutMs: 20_000, ...options }, action); const launch = { ...LAUNCH, startedAt: new Date(0).toISOString() }; await assert.rejects(admit(key, receipt, async ({ launching }) => { await launching(launch); @@ -715,13 +716,12 @@ async function recoveredLostRun(t) { }), /ledger write failed/); writeAtomic(ledgerPath(f.home), { ...readLedger(f.home), runs: [{ ...launch, runId: "run-lost", sessionId: "cse_lost", requestKey: key, status: "started" }] }); clock += 60 * 60_000; - const other = path.join(f.root, "other-request.json"); const recover = (entry) => recoverValidationReservation(entry, { ledger: readLedger(f.home), remote: () => ({ data: [] }) }); - const next = (action) => admit("other-request", other, action, { recover }); - await assert.rejects(next(() => assert.fail("admitted while the gone launcher's reservation holds")), { code: "CLOUD_VALIDATION_QUEUE_TIMEOUT" }); + const next = (action) => admit(key, receipt, action, { recover }); + await next(() => regularJson(receipt)); const stuck = queueState(f.home).active; assert.deepEqual([stuck.key, stuck.pid, stuck.launch.runId, regularJson(receipt).status, regularJson(receipt).runId], [key, null, "run-lost", "running", "run-lost"], - "another request's recovery wrote the acknowledged run's receipt and the reservation still holds the account"); + "recovery wrote the acknowledged run's receipt and the reservation still holds the exact request"); const options = (confirm) => ({ confirm, home: f.home, remote: () => ({ data: [] }), executor: NO_EXECUTOR, stderr: () => {} }); return { f, key, receipt, stuck, next, abandon: (confirm = false) => abandonValidation(f.request, options(confirm)) }; } @@ -748,7 +748,7 @@ test("ISS-14476 DT-162R abandon with a receipt marks it while a live launcher ke const marked = await abandon(true); assert.deepEqual([marked.status, marked.released, queueState(f.home).active.token], ["abandoned", undefined, stuck.token], "a live launcher keeps its reservation"); assert.deepEqual([regularJson(receipt).status, readLedger(f.home).runs[0].status, queueState(f.home).abandoned], ["abandoned", "abandoned", []]); - // That launcher exits with its receipt abandoned: another request holds behind the run until the provider ends it. + // That launcher exits with its receipt abandoned: the same request still holds until the provider ends it. writeAtomic(queueFile(f.home), { ...queueState(f.home), active: stuck }); await assert.rejects(next(() => assert.fail("admitted behind a locally abandoned run")), { code: "CLOUD_VALIDATION_QUEUE_TIMEOUT" }); const done = await abandon(true); @@ -774,23 +774,25 @@ test("ISS-14476 DT-165R abandon, then an identical rerun, leaves the queue activ assert.equal(queueState(f.home).active, null); const remote = (action) => action === "list_runs" ? { data: [] } : assert.fail(`the identical rerun called ${action}`); await assert.rejects(validateCommit(f.request, { remote, home: f.home, executor: NO_EXECUTOR, sleep: async () => {} }), /cloud validation already ended: abandoned/); - assert.equal(queueState(f.home).active, null, "the identical rerun refused as already ended and left the account free"); + assert.equal(queueState(f.home).active, null, "the identical rerun refused as already ended and released its own reservation"); assert.equal(regularJson(receipt).status, "abandoned"); - assert.equal(await next(() => "admitted"), "admitted", "another request is admitted after the rerun while the provider still lists nothing"); + assert.equal(await next(() => "admitted"), "admitted", "the same request reservation can be reacquired after the rerun while the provider still lists nothing"); }); -test("ISS-14476 DT-165R a request that launched, polled a receipt abandoned during its poll, or finds its abandoned receipt running again at exit, still holds the account on exit", async (t) => { +test("ISS-14476 DT-165R a request that launched, polled a receipt abandoned during its poll, or finds its abandoned receipt running again at exit, still holds its request reservation on exit", async (t) => { const f = fixture(t); writeAtomic(f.receipt("polled"), { status: "running", routineId: "standing", runId: "run-polled" }); await f.execute("polled", async () => { writeAtomic(f.receipt("polled"), { ...regularJson(f.receipt("polled")), status: "abandoned" }); }); assert.deepEqual([queueState(f.home).active?.key, queueState(f.home).active?.phase, queueState(f.home).active?.pid], ["polled", "running", null], "a poll whose receipt was abandoned during it holds until the provider ends the run"); - writeAtomic(f.receipt("relaunched"), { status: "abandoned", routineId: "standing", runId: "run-old" }); - await f.execute("relaunched", async ({ launching }) => { await launching(); }); - assert.deepEqual([queueState(f.home).active?.key, queueState(f.home).active?.phase, queueState(f.home).active?.pid], ["relaunched", "running", null], + writeAtomic(queueFile(f.home), { ...queueState(f.home), active: null }); + writeAtomic(f.receipt("polled"), { status: "abandoned", routineId: "standing", runId: "run-old" }); + await f.execute("polled", async ({ launching }) => { await launching(); }); + assert.deepEqual([queueState(f.home).active?.key, queueState(f.home).active?.phase, queueState(f.home).active?.pid], ["polled", "running", null], "a request that launched holds although its receipt still says abandoned"); - writeAtomic(f.receipt("rewritten"), { status: "abandoned", routineId: "standing", runId: "run-old" }); - await f.execute("rewritten", async () => { writeAtomic(f.receipt("rewritten"), { ...regularJson(f.receipt("rewritten")), status: "running", runId: "run-new" }); }); - assert.deepEqual([queueState(f.home).active?.key, queueState(f.home).active?.phase, queueState(f.home).active?.pid], ["rewritten", "running", null], + writeAtomic(queueFile(f.home), { ...queueState(f.home), active: null }); + writeAtomic(f.receipt("polled"), { status: "abandoned", routineId: "standing", runId: "run-old" }); + await f.execute("polled", async () => { writeAtomic(f.receipt("polled"), { ...regularJson(f.receipt("polled")), status: "running", runId: "run-new" }); }); + assert.deepEqual([queueState(f.home).active?.key, queueState(f.home).active?.phase, queueState(f.home).active?.pid], ["polled", "running", null], "a request admitted onto an abandoned receipt that names a running run at exit holds until the provider ends it"); }); diff --git a/plugins/vibe/lib/vibe/scripts/cloud-validation-environment.mjs b/plugins/vibe/lib/vibe/scripts/cloud-validation-environment.mjs index af7ce31e..3aa1fd42 100644 --- a/plugins/vibe/lib/vibe/scripts/cloud-validation-environment.mjs +++ b/plugins/vibe/lib/vibe/scripts/cloud-validation-environment.mjs @@ -1,6 +1,7 @@ import { bootstrapCommand, cloudRecipe, recipeProvider, toolingRoot } from "./cloud-validation-recipes.mjs"; import { capturedJson } from "./captured-json.mjs"; -import { ARTIFACT_MARKER, OUTCOMES_MARKER } from "./cloud-outcome-artifact.mjs"; +import { ARTIFACT_MARKER, DIAGNOSTIC_LABEL, FAILURES_LABEL, LANE_FAILURES_LABEL, OUTCOMES_MARKER, PUBLICATION_MARKER, probeFailureLine } from "./cloud-outcome-artifact.mjs"; +import { redactSecrets } from "./cloud-redaction.mjs"; import { createHash } from "node:crypto"; import { existsSync, renameSync } from "node:fs"; import path from "node:path"; @@ -22,6 +23,8 @@ const OPTIONAL_PROOF_KEYS = ["controlNamespace", "chromium1254", "docker", "dock const API_TEST = cloudRecipe.apiTestPattern ? new RegExp(cloudRecipe.apiTestPattern) : null; export const TOOL_REPO = "https://github.com/closedloop-ai/claude-plugins.git"; const RUNNER = `${toolingRoot}/lib/vibe/scripts/cloud-validation-host.mjs`; +const PROBE_COMMAND = `node ${toolingRoot}/lib/vibe/scripts/cloud-worker.mjs validate --request cloud-capabilities-request.json`; +const PROBE_REQUEST = 'with `lanes: [{"name":"cloud-capabilities"}]` on the exact tooling checkout and the same pinned account and environment'; const SAFE_REF = /^refs\/(?:heads|tags)\/[A-Za-z0-9][A-Za-z0-9_.\/-]+$/; const CONTROL_PORTS = /(?:--filter(?:=|\s+)|-F\s+)(?:@repo\/)?control\b|\bpkgs-a\b|\bweb-stack-env\b/i; const AFFECTED = new Map([ @@ -147,23 +150,48 @@ export function requiredCloudEnvironment(lanes) { .map(({ name, prerequisites }) => ({ name, ...prerequisites })); } +/** Name the command that stopped a measured capability, including the component check of a composite capability. */ +function capabilityRefusal(key, failures) { + const components = { dockerBootstrap: { compose: "docker compose version", vfsDaemon: "dockerd (vfs)", + vfsHello: "docker run --rm hello-world (vfs)" }, display: { electronVersion: "xvfb-run electron --version", + electronWindow: "xvfb-run Electron window smoke" } }; + const component = Object.entries(components[key] ?? {}).find(([name]) => failures[name]); + const entry = component ? failures[component[0]] : failures[key]; + if (!entry) return key; + const step = [component?.[1], entry.reason].filter(Boolean).join(": ") || "probe command"; + const exit = entry.exitCode === null ? "no process exit" : `exit ${entry.exitCode}`; + const stderr = entry.tail.join(" | ").replace(/\s+/g, " "); + return `${key}: ${step} (${exit})${stderr ? `: ${stderr}` : ""}`; +} + /** Reject dependent lanes before provider I/O until the exact account image and committed host runner are proven. */ export function admitCloudEnvironment(lanes, { home, environmentId, pin, currentAccount, tool, now = Date.now() }) { const affected = requiredCloudEnvironment(lanes); if (affected.length === 0) return null; const usable = pin?.environmentId === environmentId && pin?.accountUuid === currentAccount && validTool(tool); const proof = usable ? matchingProof(home, pin, tool, now) : null; + const line = probeFailureLine(proof?.failureLine, { redact: redactSecrets }); + const failures = line ? JSON.parse(line.slice(FAILURES_LABEL.length + 1)) : {}; + const noDetails = new Set(); const problems = affected.flatMap(({ name, capabilities }) => { - const missing = capabilities.filter((key) => proof?.checks?.[key] !== true); + const missing = capabilities.filter((key) => proof?.checks?.[key] !== true).map((key) => { + const detail = capabilityRefusal(key, failures); + if (proof && detail === key) noDetails.add(key); + return detail; + }); const lane = lanes.find((entry) => entry.name === name); if (lane.workflow) missing.unshift("non-root workflow step execution"); return missing.length ? [`${name} (${missing.join(", ")})`] : []; }); if (problems.length && tool === undefined) { - throw new Error(`CLOUD_LANES_UNAVAILABLE: ${problems.join("; ")} need the capability probe's proof, and the request names no runtimeTool; add the tooling commit and ref the capability probe measured and submit it again, or run on L2 (remote slot heavy)`); + throw new Error(`CLOUD_LANES_UNAVAILABLE: ${problems.join("; ")} need the capability probe's proof. The request names no runtimeTool. Run \`${PROBE_COMMAND}\` ${PROBE_REQUEST}, then set runtimeTool.commit and runtimeTool.ref to that commit and ref, or run on L2 (remote slot heavy)`); + } + if (problems.length && !proof) { + throw new Error(`CLOUD_LANES_UNAVAILABLE: ${problems.join("; ")} have no current exact environment, account and tooling proof. Run \`${PROBE_COMMAND}\` ${PROBE_REQUEST}, or run on L2 (remote slot heavy)`); } if (problems.length) { - throw new Error(`CLOUD_LANES_UNAVAILABLE: ${problems.join("; ")} have no current exact environment, account and tooling proof; run on L2 (remote slot heavy)`); + const detail = noDetails.size ? `. The capability probe did not return command details for ${[...noDetails].join(", ")}. Run \`${PROBE_COMMAND}\` ${PROBE_REQUEST} to collect them` : ""; + throw new Error(`CLOUD_LANES_UNAVAILABLE: ${problems.join("; ")}${detail}; run on L2 (remote slot heavy)`); } // Every cloud E2E lane runs its own committed workflow command on the portable route: the managed host runs only a // lane's bare command, which skips the Desktop workflow's pre-suite steps (verify Electron binary, build, D-Bus, keyring). @@ -202,7 +230,9 @@ export function confirmCloudEnvironment({ home, pin, environmentId, tool, sessio && Object.keys(evidence.checks).every((key) => [...PROOF_KEYS, ...OPTIONAL_PROOF_KEYS].includes(key) && typeof evidence.checks[key] === "boolean") && PROOF_KEYS.every((key) => typeof evidence.checks[key] === "boolean"); const checks = valid ? evidence.checks : Object.fromEntries([...PROOF_KEYS, ...OPTIONAL_PROOF_KEYS].map((key) => [key, false])); - writeAtomic(proofPath(home, pin), { schema: PROOF_SCHEMA, ...pin, tool, sessionId, at: now, checks }); + const failureLine = probeFailureLine(outcome?.stdoutTail, { redact: redactSecrets }); + writeAtomic(proofPath(home, pin), { schema: PROOF_SCHEMA, ...pin, tool, sessionId, at: now, checks, + ...(failureLine ? { failureLine } : {}) }); return Boolean(valid); } @@ -239,6 +269,8 @@ export function cloudHostInstruction({ tool, affected }, { lanes, commit, report return [ "This request uses the verified non-root lane runner. Execute the following commands once, in order. If setup cannot complete, report the exact failure and mark the lanes unrun.", `git fetch --no-tags ${TOOL_REPO} ${tool.ref} && git merge-base --is-ancestor ${tool.commit} FETCH_HEAD && git show ${tool.commit}:${RUNNER} > ${target}`, + // An older pinned host runner is self-contained. Newer runners load the shared secret redactor beside this file. + `if git cat-file -e ${tool.commit}:${toolingRoot}/lib/vibe/scripts/cloud-redaction.mjs 2>/dev/null; then git show ${tool.commit}:${toolingRoot}/lib/vibe/scripts/cloud-redaction.mjs > .git/cloud-redaction.mjs; fi`, ...(recipeProvider ? [`git show ${tool.commit}:${toolingRoot}/provider/provider.json > ${target}.provider.json`] : []), // Run as its own call with its output visible. It writes its own output and exit files, since it usually outlasts the // Bash tool's 10-minute wait, and a shell redirect that hid a fetched runner's output was refused as undermining oversight. @@ -249,7 +281,8 @@ export function cloudHostInstruction({ tool, affected }, { lanes, commit, report // The runner prints its record first, but its timing lines come before it in the output file, and the // condensed run log cut the record off there (cse_01H58iaeEVzoR7WVfUQooHjt); one call that prints only the record // keeps it whole whatever the agent writes afterwards. - ...(reporter ? [`After ${target}.exit exists, run \`grep -m1 -E '^(${OUTCOMES_MARKER}|${ARTIFACT_MARKER}) ' ${target}.out\` as its own Bash call, exactly as written, so the runner's result record reaches the run log whole.`] : []), + ...(reporter ? [`After ${target}.exit exists, run \`grep -m1 -E '^(${OUTCOMES_MARKER}|${ARTIFACT_MARKER}|${PUBLICATION_MARKER}) ' ${target}.out\` as its own Bash call, exactly as written, so the runner's result record reaches the run log whole. Keep that entire line in your final message.`, + `If the pinned reporter wrote a separate preflight or legacy diagnostic line, read it with \`grep -m1 -E '^(${LANE_FAILURES_LABEL}|${DIAGNOSTIC_LABEL}) ' ${target}.out\` in its own Bash call and copy it after the result line.`] : []), "CLOUD_HOST_LANES gives a private directory and count. Read each zero-based .json file separately, preserving exitCode, stdoutTail, stderrTail and diagnosis in the indexed report parts. Keep the private files in this provider session. Include only each privateStreams locator, byte count and SHA-256 with its lane. Never publish or emit full stream contents. Do not run a requested command a second time.", ].join("\n"); } @@ -276,10 +309,9 @@ export function boundProbeReceipt(file, lanes, state, env) { /** Keep one exact validation request and its account reservation coherent through launch, poll and import. */ export async function executeCloudValidation({ file, digest, request, env, lanes, laneKeys, home, ledger, currentAccount, signal, remote, timeoutMs, - start, poll, archiveProblem, mark, parse, endedDetail, artifactReader, onReport }) { + start, poll, archiveProblem, mark, parse, endedDetail, artifactReader, onReport, warnings = [] }) { const state = ledger(); const pin = state.environmentPin; - const account = pin?.accountUuid ?? "unbound-validation"; file = boundProbeReceipt(file, lanes, state, env); const verifyAccount = () => { if (!pin) { @@ -292,7 +324,7 @@ export async function executeCloudValidation({ file, digest, request, env, lanes if (latest?.accountUuid !== pin.accountUuid || latest?.environmentId !== pin.environmentId) throw new Error("validation account or environment changed during admission"); }; verifyAccount(); - const enter = (action) => withCloudValidationAdmission({ home, account, key: digest, receipt: file, signal, + const enter = (action) => withCloudValidationAdmission({ home, key: digest, receipt: file, signal, metadata: { commit: request.commit, environment: env, laneKeys, ...(request.cloudProof ? { proof: cloudcheckProofIdentity(request.commit, digest) } : {}) }, timeoutMs, recover: async entry => { const disposition = recoverValidationReservation(entry,{ledger:ledger(),remote}); @@ -302,7 +334,7 @@ export async function executeCloudValidation({ file, digest, request, env, lanes } return disposition; } }, action); - return withValidationReportLock(file, () => enter(async ({ launching }) => { + return withValidationReportLock(file, () => enter(async ({ launching, launchRefused }) => { verifyAccount(); let started; if (existsSync(file)) { @@ -321,13 +353,13 @@ export async function executeCloudValidation({ file, digest, request, env, lanes } if (!started) { started = await start((launch,requirements) => { - // The provider builds this binding under its routine lock. A repin while queued cannot move the run. + // The provider builds this binding under its routine lock. A repin before dispatch cannot move the run. if (pin ? launch?.accountUuid !== pin.accountUuid || launch?.environmentId !== env.id : launch?.accountUuid !== undefined) { throw new Error("validation account or environment changed before launch"); } return launching(launch,requirements); - }); - started = { ...started, ...(pin ? {accountUuid: pin.accountUuid} : {}), requestDigest: digest, commit: request.commit, laneKeys }; + }, launchRefused); + started = { ...started, ...(pin ? {accountUuid: pin.accountUuid} : {}), requestDigest: digest, commit: request.commit, laneKeys, ...(warnings.length ? { warnings } : {}) }; // The provider has acknowledged the run. Keep its nonce even if local persistence fails. try { writeAtomic(file, started); } catch (error) { error.launchUncertain = true; throw error; } } @@ -346,6 +378,7 @@ export async function executeCloudValidation({ file, digest, request, env, lanes // Each lane report says where it ran; a lane routed elsewhere was refused before dispatch. const lanesWhere = Array.isArray(result.lanes) ? { lanes: result.lanes.map((lane) => ({ ...lane, ranOn: "claude-cloud" })) } : {}; return { ...result, ...lanesWhere, ...(artifact ? { artifact } : {}), provider: "claude", taskId: finished.taskId, - sessionId: finished.sessionId, wallMs: finished.wallMs, receipt: file, ...(finished.proof ? { proof: finished.proof } : {}) }; + sessionId: finished.sessionId, wallMs: finished.wallMs, receipt: file, ...(finished.proof ? { proof: finished.proof } : {}), + ...(warnings.length ? { warnings } : {}), ...(finished.launchRefusals ? { launchRefusals: finished.launchRefusals } : {}) }; })); } diff --git a/plugins/vibe/lib/vibe/scripts/cloud-validation-environment.test.mjs b/plugins/vibe/lib/vibe/scripts/cloud-validation-environment.test.mjs index ca385843..e4b6e24f 100644 --- a/plugins/vibe/lib/vibe/scripts/cloud-validation-environment.test.mjs +++ b/plugins/vibe/lib/vibe/scripts/cloud-validation-environment.test.mjs @@ -85,6 +85,38 @@ test("ISS-14874 AC-4 a Desktop E2E lane stays off the managed host so its commit assert.throws(() => admitCloudEnvironment([desktop, LANES[0]], inputs), /separately from non-root application lanes/); }); +test("ISS-15068 refuses only dependent lanes and carries the measured namespace failure", (t) => { + const f = makeHome("vibe-runtime-namespace-"); + t.after(f.cleanup); + const inputs = { home: f.home, pin: PIN, tool: TOOL, environmentId: ENV, now: NOW, currentAccount: PIN.accountUuid }; + const control = { name: "control", command: "pnpm --filter @repo/control test" }; + const docker = { name: "docker", command: "pnpm docker:ensure", containerPnpm: true }; + const unit = { name: "unit", command: "node --test simple.test.mjs" }; + const check = (overrides) => admitCloudEnvironment([control, docker, unit], { ...inputs, ...overrides }); + const proofCommand = /node \S+\/cloud-worker\.mjs validate --request cloud-capabilities-request\.json/; + assert.throws(check, proofCommand); + assert.throws(() => check({ tool: undefined }), (error) => /runtimeTool/.test(error.message) && proofCommand.test(error.message)); + const runtime = (controlNamespace) => `CLOUD_HOST_RUNTIME ${JSON.stringify({ commit: TOOL.commit, + checks: { ...CHECKS, controlNamespace, docker: false, dockerBootstrap: true } })}`; + const record = (stdoutTail) => confirmCloudEnvironment({ ...inputs, completed: true, sessionId: "session-probe", + outcome: { name: "cloud-capabilities", exitCode: 0, stdoutTail } }); + assert.equal(record(runtime(false) + '\nCLOUD_CAPABILITY_FAILURES {"controlNamespace":{"reason":"future shape"}}'), true); + assert.throws(check, /control \(controlNamespace\).*did not return command details/); + assert.equal(record(runtime(false) + '\nCLOUD_CAPABILITY_FAILURES ' + JSON.stringify({ controlNamespace: { + exitCode: 1, reason: "unshare --user --map-current-user --net", tail: ["unshare: Operation not permitted", "TOKEN=ghp_abcdefghijklmnopqrstuvwxyz0123"], + } })), true); + assert.throws(check, (error) => { + assert.match(error.message, /control \(controlNamespace: unshare --user --map-current-user --net \(exit 1\).*Operation not permitted.*run on L2/); + assert.doesNotMatch(error.message, /ghp_|docker|unit/); + return true; + }); + assert.throws(() => check({ now: NOW + 31 * 60_000 }), proofCommand); + assert.equal(admitCloudEnvironment([docker], inputs), null); + assert.equal(admitCloudEnvironment([unit], inputs), null); + assert.equal(record(runtime(true)), true); + assert.equal(admitCloudEnvironment([control, unit], inputs).affected[0].name, "control"); +}); + test("ISS-14476 validate names unsupported lanes before any cloud create, update, run or test command", async (t) => { const f = makeHome("vibe-runtime-pre-mutation-"); t.after(f.cleanup); @@ -100,7 +132,7 @@ test("ISS-14476 validate names unsupported lanes before any cloud create, update const { runtimeTool: _tool, ...untooled } = request; const clients = { home: f.home, remote: (action) => { calls.push(action); } }; await assert.rejects(() => validateCommit(untooled, clients), - /CLOUD_LANES_UNAVAILABLE: desktop-tests.*the request names no runtimeTool; add the tooling commit and ref the capability probe measured and submit it again, or run on L2 \(remote slot heavy\)/); + /CLOUD_LANES_UNAVAILABLE: desktop-tests.*The request names no runtimeTool.*validate --request cloud-capabilities-request\.json.*run on L2 \(remote slot heavy\)/); await assert.rejects(() => validateCommit(request, clients), (error) => !/runtimeTool/.test(error.message), "a request that names its tool is told about the proof it lacks"); assert.deepEqual(calls, []); diff --git a/plugins/vibe/lib/vibe/scripts/cloud-validation-host.mjs b/plugins/vibe/lib/vibe/scripts/cloud-validation-host.mjs index 5ca9d06f..7b835096 100644 --- a/plugins/vibe/lib/vibe/scripts/cloud-validation-host.mjs +++ b/plugins/vibe/lib/vibe/scripts/cloud-validation-host.mjs @@ -4,6 +4,8 @@ import { appendFileSync, chmodSync, closeSync, copyFileSync, existsSync, fstatSy import os from "node:os"; import path from "node:path"; import { fileURLToPath } from "node:url"; +import { redactSecrets, redactUserinfo } from "./cloud-redaction.mjs"; +export { redactSecrets, redactUserinfo } from "./cloud-redaction.mjs"; const NO_INPUT = "ignore"; const UNPRIVILEGED_FALLBACK = 65534; @@ -106,47 +108,6 @@ export function rootSetupEnvironment(env, current, checkout) { return rootSetupGitEnvironment({ ...env, ...hostNetworkEnvironment(current) }, checkout); } -/** - * `text` with each URL's userinfo (a credential) replaced by ``, through the authority's last `@`, and the - * same for a schemeless `user:password@host` such as a proxy set without a scheme. A password may hold `#`, `?`, `@` - * or a slash, so a path with an `@` after a port may go too. - */ -export function redactUserinfo(text) { - return String(text).replace(/\S+/g, (word) => throughLastAt(word, /(:\/\/)(?:[^/:@]+:.*|[^/]+)@/gis)) - .replace(/[^\s"']+/g, (part) => throughLastAt(part, /(^|[=(<,;])[^/@=(<,;:]+:(?!\/\/).*@/s, /[/?#@]/)); -} - -/** `word` with what `pattern` finds up to its last `@` (one not followed by a `not` character) redacted, in time linear in the word. */ -function throughLastAt(word, pattern, not = /[]/) { - let end = word.length + 1; - do end = word.lastIndexOf("@", end - 2) + 1; while (end > 1 && not.test(word[end] ?? "")); - return word.slice(0, end).replace(pattern, "$1@") + word.slice(end); -} - -const SECRET_VALUE = /(?`. A secret-named value that holds an `@` goes - * first and keeps one, so no part of it is left as a host and a URL around it is still read as one; `afterAt` leaves an - * unquoted one's rest to the rules below. A URL's own user name is left to the URL rule. Other values wait for the - * bearer pass, which needs the word before the token. - */ -export function redactSecrets(text) { - return redactUserinfo(String(text ?? "").replace(SECRET_VALUE, (all, key, sep, value, at, whole) => value.includes("@") && whole.slice(at - 3, at) !== "://" ? `${key}${sep}@${/^\\*["']/.test(value) ? "" : afterAt(value)}` : all).replace(/\S+/g, (word) => throughLastAt(word, /(:\/\/)[^/:@]+:.*@/is))) - .replace(/\b((?:set-)?cookie["']?\s*[:=]).*/gi, "$1 ") - .replace(/\b(Bearer|Basic|token)\s+[A-Za-z0-9._~+/=-]{8,}/gi, "$1 ") - .replace(/\b(?:gh[pousr]_[A-Za-z0-9]{16,}|github_pat_[A-Za-z0-9_]{16,}|sk-[A-Za-z0-9_-]{16,}|xox[abprs]-[A-Za-z0-9-]{10,}|npm_[A-Za-z0-9]{8,}|glpat-[\w-]{8,}|AKIA[A-Z0-9]{16})\b|(?") - .replace(/(?") - .replace(SECRET_VALUE, "$1$2"); -} - /** * An actor's CA and proxy settings, a workflow step's or an ordinary lane's, its proxy values without userinfo through * the authority's last `@`, with or without a URL scheme: no proxy credential reaches commit code (V11-5). A value @@ -364,9 +325,41 @@ function runLane(command, args, options, directory, index, limits) { } } -function inControlNamespace(binary,args) { - return ["unshare",["--user","--map-current-user","--net","--","sh","-ec", - 'ip link set lo up || exit 78; exec "$@"',"control-lane",binary,...args]]; +const CONTROL_PYTHON_MISSING = "control-lane: python3 not found for loopback fallback"; +const CONTROL_PYTHON_FAILED = "control-lane: python3 loopback fallback failed"; +const CONTROL_BIND_FAILED = "control-lane: loopback bind failed"; + +// Linux ifreq holds the 16-byte interface name followed by a union whose flags member is a short. Reserve the +// full 64-bit struct size and preserve every flag except the IFF_UP bit we set. +const CONTROL_LOOPBACK_IOCTL = `import fcntl, socket, struct, sys + +sys.tracebacklimit = 0 +SIOCGIFFLAGS, SIOCSIFFLAGS, IFF_UP = 0x8913, 0x8914, 0x1 +request = bytearray(40) +struct.pack_into("16s", request, 0, b"lo") +with socket.socket(socket.AF_INET, socket.SOCK_DGRAM) as sock: + fcntl.ioctl(sock, SIOCGIFFLAGS, request) + flags, = struct.unpack_from("H", request, 16) + struct.pack_into("H", request, 16, flags | IFF_UP) + fcntl.ioctl(sock, SIOCSIFFLAGS, request)`; + +const CONTROL_LAUNCH = `if ! ip link set lo up; then + if ! command -v python3 >/dev/null 2>&1; then + echo '${CONTROL_PYTHON_MISSING}' >&2 + exit 78 + fi + if ! python3 -IS -c '${CONTROL_LOOPBACK_IOCTL}'; then + echo '${CONTROL_PYTHON_FAILED}' >&2 + exit 78 + fi +fi +exec setpriv --inh-caps=-all --ambient-caps=-all -- "$@"`; + +/** Keep the actor UID and both namespaces. Across exec, only loopback setup inherits namespace CAP_NET_ADMIN. */ +function inControlNamespace(binary, args) { + return ["unshare", ["--user", "--map-current-user", "--net", "--keep-caps", "--", + "setpriv", "--inh-caps=-all,+net_admin", "--ambient-caps=-all,+net_admin", "--", + "sh", "-ec", CONTROL_LAUNCH, "control-lane", binary, ...args]]; } /** @@ -699,8 +692,7 @@ const TOOL_ROOT = /^[A-Za-z0-9_-]+(?:\/[A-Za-z0-9_-]+)*$/; /** * The writer's outcome identity, built from the plan the runner already holds. The plan carries only the plain fields * the lanes do not give: a long opaque copy of them was mis-transcribed by the cloud agent (cse_01H58iad1kG6cfaiG3mSZnoM - * cut the plan's last brace). Its shape is outcomeSpec's in cloud-outcome-instruction.mjs, which this single shipped - * file cannot import; a test holds the two equal. + * cut the plan's last brace). Its shape is outcomeSpec's in cloud-outcome-instruction.mjs, which the host runner does not import; a test holds the two equal. */ export function hostOutcomeSpec(plan) { const { key, repository, probe, frozen, artifact } = plan.reporter; @@ -756,6 +748,7 @@ export function probeCloudHostRuntime(directory, checkout = process.cwd(), run = const actor = validationHostActor(); const runtime = { workspace: false, nonRoot: false, ports: false, chromium: false, gitUtc: false }; const details = {}; + const measure = (name, step, binary, args, options) => details[name] = { ...run(binary, args, options), step }; try { const marker = path.join(sandbox, "restricted"); const child = path.join(sandbox, "probe.cjs"); @@ -766,15 +759,26 @@ export function probeCloudHostRuntime(directory, checkout = process.cwd(), run = const options = { cwd: sandbox, env: environment, ...actor, timeout: 120_000 }; // The actor finds node on its PATH, as every lane does: the runner's own binary can sit in root's closed home // (the cloud setup puts Node 24 in $HOME/.node24), which the actor cannot execute. - details.nonRoot = run("node", [child, marker], options); + measure("nonRoot", "node probe.cjs (actor UID and file permissions)", "node", [child, marker], options); runtime.nonRoot = details.nonRoot.exitCode === 0; - const [binary,argv] = inControlNamespace("node",["-e","const net=require('node:net');const s=net.createServer();s.listen(0,'127.0.0.1',()=>s.close());"]); - details.controlNamespace = run(binary,argv,options); + const [binary, argv] = inControlNamespace("node", ["-e", `const net = require('node:net'); + const server = net.createServer(); + server.on('error', error => { console.error('${CONTROL_BIND_FAILED}:', error.message); process.exitCode = 1; }); + server.listen(0, '127.0.0.1', () => server.close());`]); + const namespace = measure("controlNamespace", [binary, ...argv.slice(0, argv.indexOf("--"))].join(" "), binary, argv, options); + const namespaceError = (namespace.stderrTail ?? "").trimEnd(); + if (namespaceError.endsWith(CONTROL_PYTHON_MISSING)) namespace.step = "command -v python3 (inside unshare)"; + else if (namespaceError.endsWith(CONTROL_PYTHON_FAILED)) namespace.step = "python3 loopback fallback (inside unshare)"; + else if (/^setpriv:/m.test(namespaceError)) namespace.step = "setpriv (inside unshare)"; + else if (namespaceError.includes(CONTROL_BIND_FAILED)) namespace.step = "node bind to 127.0.0.1 (inside unshare)"; runtime.controlNamespace = runtime.nonRoot && details.controlNamespace.exitCode === 0; const leases = []; try { for (let index = 0; index < 10; index++) leases.push(reserveCloudPorts(path.join(directory, "capability-ports"))); runtime.ports = leases.every((lease, index) => index === 0 || lease.first > leases[index - 1].last); + if (!runtime.ports) details.ports = { step: "reserveCloudPorts", exitCode: null, diagnosis: "port reservations overlapped" }; + } catch (error) { + details.ports = { step: "reserveCloudPorts", exitCode: null, diagnosis: error.message }; } finally { for (const lease of leases) lease.release(); } const sample = path.join(sandbox, "packages/check"); mkdirSync(sample, { recursive: true }); @@ -783,10 +787,11 @@ export function probeCloudHostRuntime(directory, checkout = process.cwd(), run = writeFileSync(path.join(sample, "package.json"), '{"name":"vibe-runtime-workspace","scripts":{"build":"node build.cjs"}}'); writeFileSync(path.join(sample, "build.cjs"), 'require("node:fs").writeFileSync("dist.js", "workspace build ran")'); if (process.getuid() === 0) ownTree(sandbox, actor); - details.workspace = run("pnpm", ["--filter", "vibe-runtime-workspace", "build"], options); + measure("workspace", "pnpm --filter vibe-runtime-workspace build", "pnpm", ["--filter", "vibe-runtime-workspace", "build"], options); runtime.workspace = details.workspace.exitCode === 0 && existsSync(path.join(sample, "dist.js")); + if (details.workspace.exitCode === 0 && !runtime.workspace) details.workspace.diagnosis = "build did not produce dist.js"; // chromium1254 is the setup's browser revision alone; chromium is the actor's headless launch of it. - details.chromiumInstall = run("test", ["-x", HEADLESS_SHELL], options); + measure("chromiumInstall", `test -x ${HEADLESS_SHELL}`, "test", ["-x", HEADLESS_SHELL], options); runtime.chromium1254 = details.chromiumInstall.exitCode === 0; if (runtime.chromium1254) { // Root fetches the pinned Playwright with the host's network settings, as root setup installs a lane's @@ -796,18 +801,18 @@ export function probeCloudHostRuntime(directory, checkout = process.cwd(), run = const browser = path.join(sandbox, "browser"); mkdirSync(browser); writeFileSync(path.join(browser, "package.json"), '{"name":"vibe-runtime-browser","private":true}'); - details.chromiumFetch = run("pnpm", ["add", "--ignore-workspace", "playwright@" + BROWSER_VERSION], + measure("chromiumFetch", `pnpm add --ignore-workspace playwright@${BROWSER_VERSION}`, "pnpm", ["add", "--ignore-workspace", "playwright@" + BROWSER_VERSION], { cwd: browser, env: rootSetupEnvironment(environment, process.env, browser), timeout: 120_000 }); if (process.getuid() === 0) ownTree(sandbox, actor); if (details.chromiumFetch.exitCode === 0) { - details.chromiumLaunch = run("pnpm", ["exec", "playwright", "screenshot", "--browser=chromium", "data:text/html,probe", path.join(sandbox, "probe.png")], + measure("chromiumLaunch", "pnpm exec playwright screenshot --browser=chromium", "pnpm", ["exec", "playwright", "screenshot", "--browser=chromium", "data:text/html,probe", path.join(sandbox, "probe.png")], { ...options, cwd: browser }); runtime.chromium = details.chromiumLaunch.exitCode === 0; } } - details.gitUtc = run("git", ["log", "-1", "--format=%ad", "--date=iso-strict-local"], { cwd: checkout, env: environment }); + measure("gitUtc", "git log -1 --format=%ad --date=iso-strict-local", "git", ["log", "-1", "--format=%ad", "--date=iso-strict-local"], { cwd: checkout, env: environment }); try { runtime.gitUtc = details.gitUtc.exitCode === 0 && Boolean(canonicalGitTimestamp(details.gitUtc.stdoutTail.trim())); } - catch { /* Preserve the failed exact UTC probe. */ } + catch { details.gitUtc.diagnosis = "git log did not emit a valid UTC timestamp"; } return { checks: runtime, details }; } finally { rmSync(sandbox, { recursive: true }); } } diff --git a/plugins/vibe/lib/vibe/scripts/cloud-validation-host.test.mjs b/plugins/vibe/lib/vibe/scripts/cloud-validation-host.test.mjs index e387d6a2..124669a6 100644 --- a/plugins/vibe/lib/vibe/scripts/cloud-validation-host.test.mjs +++ b/plugins/vibe/lib/vibe/scripts/cloud-validation-host.test.mjs @@ -1,5 +1,6 @@ import assert from "node:assert/strict"; -import { chmodSync, existsSync, mkdirSync, readdirSync, readFileSync, realpathSync, statSync, writeFileSync } from "node:fs"; +import { spawnSync } from "node:child_process"; +import { chmodSync, existsSync, mkdirSync, readdirSync, readFileSync, realpathSync, statSync, symlinkSync, writeFileSync } from "node:fs"; import path from "node:path"; import test from "node:test"; import { git, makeHome } from "../../../../vibe/skills/vibe/scripts/test-fixtures.mjs"; @@ -160,6 +161,50 @@ test("the nested control test gets its own loopback namespace and reports produc assert.ok(observed.every(result=>result.diagnosis.includes("CLOUD_PORT_RANGE_UNAVAILABLE"))); }); +for (const scenario of [ + { name: "ip works", ipMode: 0o755, pythonExit: 1, exitCode: 0, trace: ["ip", "drop", "lane"] }, + { name: "ip cannot execute and python3 succeeds", ipMode: 0o644, pythonExit: 0, exitCode: 0, trace: ["python3", "drop", "lane"] }, + { name: "ip cannot execute and the ioctl fails", ipMode: 0o644, pythonExit: 1, exitCode: 78, trace: ["python3"], error: /python3 loopback fallback failed/ }, + { name: "ip cannot execute and python3 is missing", ipMode: 0o644, exitCode: 78, trace: [], error: /python3 not found/ }, +]) { + test(`ISS-15068 control namespace setup when ${scenario.name}`, t => { + const f = fixture(t); + const bin = path.join(f.checkout, "bin"); + mkdirSync(bin); + symlinkSync("/bin/sh", path.join(bin, "sh")); + const script = (name, body, mode = 0o755) => writeFileSync(path.join(bin, name), `#!/bin/sh\nset -eu\n${body}\n`, { mode }); + script("setpriv", `case "$1 $2 $3" in + '--inh-caps=-all,+net_admin --ambient-caps=-all,+net_admin --') echo scope ;; + '--inh-caps=-all --ambient-caps=-all --') echo drop ;; + *) exit 99 ;; + esac + shift 3 + exec "$@"`); + script("ip", '[ "$*" = "link set lo up" ] && echo ip', scenario.ipMode); + if (scenario.pythonExit !== undefined) { + script("python3", `[ "$1 $2" = "-IS -c" ] + echo python3 + if [ ${scenario.pythonExit} = 1 ]; then echo "ioctl: Operation not permitted" >&2; fi + exit ${scenario.pythonExit}`); + } + script("node", '[ "$*" = "check.mjs" ] && echo lane'); + const [outcome] = runCloudHostPlan({ ...f, lanes: [{ name: "control", command: "node check.mjs", isolateControlPorts: true }], + uid: 0, gid: 0, provision: () => {}, environment: { PATH: bin }, run: (command, args, options) => { + assert.equal(command, "unshare"); + assert.deepEqual([options.uid, options.gid], [65534, 65534]); + assert.deepEqual(args.slice(0, 5), ["--user", "--map-current-user", "--net", "--keep-caps", "--"]); + // Execute the real launcher shell with fixture tools. macOS has no Linux namespaces. + const child = spawnSync(args[5], args.slice(6), { cwd: options.cwd, env: options.env, encoding: "utf8" }); + assert.ifError(child.error); + return { exitCode: child.status, stdoutTail: child.stdout, stderrTail: child.stderr, diagnosis: "" }; + } }); + assert.equal(outcome.exitCode, scenario.exitCode, outcome.stderrTail); + assert.deepEqual(outcome.stdoutTail.trim().split("\n"), ["scope", ...scenario.trace]); + if (scenario.ipMode === 0o644) assert.match(outcome.stderrTail, /ip: Permission denied/i); + if (scenario.error) assert.match(outcome.stderrTail, scenario.error); + }); +} + test("host executes quoted literal filters and the root typecheck with cloud concurrency", t=>{ const calls=[]; const commands = ["pnpm turbo typecheck --filter=\"...[origin/main]\"","pnpm typecheck"]; diff --git a/plugins/vibe/lib/vibe/scripts/cloud-validation-recovery.test.mjs b/plugins/vibe/lib/vibe/scripts/cloud-validation-recovery.test.mjs index d9e11b29..302741d6 100644 --- a/plugins/vibe/lib/vibe/scripts/cloud-validation-recovery.test.mjs +++ b/plugins/vibe/lib/vibe/scripts/cloud-validation-recovery.test.mjs @@ -118,25 +118,39 @@ for (const recovery of ["ledger","nonce"]) test("accepted provider dispatch surv finally{mock.mock.restore();syncBuiltinESMExports();} }); -test("two unpinned environments share one account reservation",async t=>{ - const f=runtime(t);let active=0,peak=0; - const run=index=>f.run({lanes:[{name:"version",command:"node --version"}],digest:"key"+index,file:f.file+index,env:{id:"env_"+index}, - start:async()=>{peak=Math.max(peak,++active);return {status:"running",taskId:String(index)};}, - poll:async row=>{await new Promise(res=>setTimeout(res,40));active--;return {...row,status:"completed"};},onReport:()=>{}}); - await Promise.all([run(1),run(2)]);assert.equal(peak,1); +test("distinct unpinned requests can launch in separate environments", async t => { + const f = runtime(t); + const first = Promise.withResolvers(); + const second = Promise.withResolvers(); + const submit = (index, started, peer) => f.run({ + lanes: [{ name: "version", command: "node --version" }], digest: "key" + index, file: f.file + index, env: { id: "env_" + index }, + start: async () => { started.resolve(); return { status: "running", taskId: String(index) }; }, + poll: async row => { await peer.promise; return { ...row, status: "completed" }; }, onReport: () => {}, + }); + const runs = [submit(1, first, second), submit(2, second, first)]; + try { + await Promise.race([Promise.all([first.promise, second.promise]), ...runs]); + } finally { + first.resolve(); + second.resolve(); + await Promise.all(runs); + } }); -test("first account pin waits for already-dispatched unbound validation",async t=>{ - const f=runtime(t); - let announce; - const entered=new Promise(resolve=>{announce=resolve;}); - let running=false,overlap=false; - const submit=(key)=>f.run({lanes:[{name:"version",command:"node --version"}],digest:key,file:f.file+key, - start:async()=>{if(running)overlap=true;running=true;announce();return {taskId:key,status:"running"};}, - poll:async row=>{await new Promise(done=>setTimeout(done,300));running=false;return {...row,status:"completed"};},onReport:()=>{}}); - const first=submit("before"); - await entered; - await recordEnvironmentPin({home:f.home,...pin}); - await Promise.all([first,submit("after")]); - assert.equal(overlap,false); +test("a pin leaves an already dispatched independent unbound request free to finish", async t => { + const f = runtime(t); + const started = Promise.withResolvers(); + const finish = Promise.withResolvers(); + const submit = (key) => f.run({ lanes: [{ name: "version", command: "node --version" }], digest: key, file: f.file + key, + start: async () => { if (key === "before") started.resolve(); return { taskId: key, status: "running" }; }, + poll: async row => { if (key === "before") await finish.promise; return { ...row, status: "completed" }; }, onReport: () => {} }); + const first = submit("before"); + try { + await Promise.race([first, started.promise]); + await recordEnvironmentPin({ home: f.home, ...pin }); + assert.equal((await submit("after")).taskId, "after"); + } finally { + finish.resolve(); + await first; + } }); diff --git a/plugins/vibe/lib/vibe/scripts/cloud-worker.mjs b/plugins/vibe/lib/vibe/scripts/cloud-worker.mjs index b9820388..c8920ccc 100644 --- a/plugins/vibe/lib/vibe/scripts/cloud-worker.mjs +++ b/plugins/vibe/lib/vibe/scripts/cloud-worker.mjs @@ -43,7 +43,7 @@ import { logText } from "./cloud-validation-log.mjs"; import { capturedJson, firstLine } from "./captured-json.mjs"; import { keepCreateStream, redactedLine, rejectedBeforeRun, remoteTriggerPrompt, remoteTriggerStream, TOOL_NOT_EXECUTED } from "./cloud-trigger-stream.mjs"; -import { MACHINE_OUTCOMES, measuredProbeTranscript, withCarriedFailures, outcomeArtifact, checkOutcomeArtifact, OUTCOME_LOG_LIMIT, outcomeTransportBytes, requireOutcomeCapacity, readOutcomeReport } from "./cloud-outcome-artifact.mjs"; +import { MACHINE_OUTCOMES, measuredProbeTranscript, withCarriedFailures, outcomeArtifact, checkOutcomeArtifact, OUTCOME_LOG_LIMIT, MISSING_RESULT_BRANCH, outcomeTransportBytes, requireOutcomeCapacity, readOutcomeReport } from "./cloud-outcome-artifact.mjs"; import { compactWorkflowBrief } from "./cloud-workflow-brief.mjs"; import { redactSecrets } from "./cloud-validation-host.mjs"; import { hostReporter, outcomeInstruction, LANE_DISCIPLINE } from "./cloud-outcome-instruction.mjs"; @@ -55,6 +55,7 @@ import { existsSync, lstatSync, readFileSync, realpathSync, renameSync, unlinkSy import os from "node:os"; import path from "node:path"; import { isDeepStrictEqual, parseArgs } from "node:util"; +import { setTimeout as delay } from "node:timers/promises"; import { recordCloudCheck } from "../../fleet-orchestrator/scripts/cloud-slot-routing.mjs"; import { resolveWorkDir } from "../../codex-fleet-monitor/scripts/work-dir.mjs"; import { decideCloudPlacement } from "../../fleet-orchestrator/scripts/cloud-placement.mjs"; @@ -349,7 +350,11 @@ function triggerAnswer(action, sent, result, timeout) { try { response = capturedJson(jsonLine); } catch { /* preserve the HTTP refusal without structured data */ } const codes = [response?.error, response?.code, response?.type, response?.error?.code, response?.error?.type, response]; if (status === 401 && codes.includes("github_token_missing")) throw githubTokenMissing(diagnostic); + const providerMessage = response?.error?.message ?? response?.message ?? (typeof response?.error === "string" ? response.error : jsonLine); const http = Number.isInteger(status) ? { httpStatus: status } : {}; + if (["create", "update", "run"].includes(action) && typeof providerMessage === "string") { + http.providerMessage = redactedLine(redactSecrets(providerMessage)).slice(0, 400); + } if (action === "create" && status === 400 && codes.includes("environment_not_found")) http.apiCode = "environment_not_found"; throw Object.assign(new Error(`RemoteTrigger ${action} failed: ${firstLine(body)}${details}`), http); } @@ -624,7 +629,7 @@ export async function abandonValidation(request, { confirm = false, home = os.ho ? boundProbeReceipt(base, validationLanes(withRepository(request)).lanes, readLedger(home), resolveClaudeEnvironment(request)) : base; const receipt = existsSync(file) ? JSON.parse(readFileSync(file, "utf8")) : null; const abandoned = receipt && (TERMINAL.has(receipt.status) ? receipt : { ...receipt, status: "abandoned", finishedAt: new Date().toISOString() }); - const result = await releaseValidationReservation({ home, key, confirm, unconfirmed: (plan) => unconfirmed("abandon", plan), markRun: (runId) => markRun(home, runId, "abandoned", DEFAULT_WALL_MS), + const result = await releaseValidationReservation({ home, key, receiptFile: file, confirm, unconfirmed: (plan) => unconfirmed("abandon", plan), markRun: (runId) => markRun(home, runId, "abandoned", DEFAULT_WALL_MS), receipt: abandoned && { plan: { receipt: file, from: receipt.status ?? null, to: abandoned.status, sweepsRoutines: true }, runId: abandoned.status === "abandoned" ? abandoned.runId ?? abandoned.taskId : null, write: () => writeFileSync(file, `${JSON.stringify(abandoned, null, 2)}\n`, { mode: 0o600 }) } }); if (!confirm || !abandoned) return result; @@ -771,6 +776,32 @@ export function validationLanes(request) { return { lanes: describeCloudLanes(lanes, { read, commit: request.commit }), laneSource: source }; } +/** Flag a hand-written command using the name of a job in the validated commit's CI workflow. */ +export function validationWorkflowWarnings(request) { + if (request.laneSource) return []; + const ci = ".github/workflows/ci.yml"; + let definitions; + try { + definitions = workflowLaneDefinitions(committedFile(request.worktree, request.commit, ci)); + } catch { + // A checkout without a readable, supported CI workflow can still run unrelated direct validation. + return []; + } + const normalize = (name) => name?.toLowerCase().replace(/[^a-z0-9]+/g, "-").replace(/^-|-$/g, ""); + const jobs = definitions.map(({ name, job, matrix, command }) => { + const recipe = JSON.parse(command).job; + const names = [name, job, recipe.name]; + if (matrix.shard !== undefined) names.push(`${job}-${matrix.shard}`, `${job}-shard-${matrix.shard}`); + const steps = recipe.steps.filter(({ run }) => typeof run === "string"); + return { names: new Set(names.filter(Boolean).map(normalize)), recipe: steps.map(({ run }) => run.trim()).join("\n") }; + }); + return request.lanes.flatMap(({ name, command }) => { + const matching = jobs.filter((job) => job.names.has(normalize(name))); + if (!matching.length || matching.every(({ recipe }) => recipe === command.trim())) return []; + return [`CLOUD_VALIDATION_WORKFLOW_MISMATCH: caller-written lane "${redactedLine(name)}" differs from its ${ci} job recipe; use laneSource for CI evidence`]; + }); +} + /** Check a validation-only request; Codex Cloud returns no task report to bind lane results to. */ export function validateValidationRequest(request) { if (!request || typeof request !== "object") throw new Error("structured validation request is required"); @@ -866,11 +897,16 @@ export function parseValidationResult(text, request, {managedHost = false, outco if (outcomeTransport && lane.capabilityProbe && result.passed) result.stdoutTail=measuredProbeTranscript(raw.stdoutTail,request.commit); withCarriedFailures(result,{probe:lane.capabilityProbe===true,index,sources:lane.capabilityProbe?[raw.stdoutTail,text]:[text],redact:redactSecrets}); + const diagnostic = machine?.diagnostics?.["lane" + index]; + if (diagnostic && !result.passed && Number.isInteger(result.exitCode)) { + result.stdoutTail ||= diagnostic[0]; + result.stderrTail ||= diagnostic[1]; + } return result; }); let artifact; if (machine) for (const [index,row] of machine.lanes.entries()) if(row.combinedOutput) lanes[index].combinedOutput=row.combinedOutput; - if (request.resultArtifact) { + if (request.resultArtifact && (!outcomeArtifact(request) || result.artifact)) { artifact = result.artifact; if (artifact?.path !== request.resultArtifact.path || artifact?.branch !== request.resultArtifact.branch || !/^[0-9a-f]{40}$/.test(artifact?.commit ?? "") || !/^[0-9a-f]{64}$/.test(artifact?.sha256 ?? "")) { @@ -917,7 +953,14 @@ function reportedLane(lane, reported, structured,index,managedHost) { export function readValidationArtifact(request, artifact, { run = runCommand, gitRead = git } = {}) { const ref = `refs/vibe/cloud-validation/${sha256(`${request.commit}:${artifact.branch}`)}`; const fetched = run("git", ["-C", request.worktree, "fetch", "--force", "origin", `refs/heads/${artifact.branch}:${ref}`], { cwd: request.worktree, timeout: COMMAND_MS }); - if (fetched.status !== 0) throw new Error(`cloud validation result branch fetch failed: ${firstLine(fetched.stderr || fetched.error?.message)}`); + if (fetched.status !== 0) { + const reason = fetched.stderr || fetched.error?.message || "unknown error"; + if (/^fatal: couldn't find remote ref\b/im.test(reason)) { + throw Object.assign(new Error(`cloud validation result branch ${artifact.branch} is missing; the cloud session did not leave a published result`), + { code: MISSING_RESULT_BRANCH }); + } + throw new Error(`cloud validation result branch fetch failed: ${redactedLine(firstLine(reason))}`); + } const commit = gitRead(request.worktree, ["rev-parse", ref]); const discover = outcomeArtifact(request) && artifact.commit === undefined && artifact.sha256 === undefined; if ((!discover && commit !== artifact.commit) || gitRead(request.worktree, ["rev-parse", `${commit}^`]) !== request.commit) { @@ -952,7 +995,8 @@ const PERMISSION_DENIAL = /Permission for this action (?:has been denied|was den /** A result that never arrived because the session was denied permission names that denial as the cause. */ function deniedResult(log, error) { - const denial = /result branch fetch failed|requires machine outcome evidence/.test(error.message) && PERMISSION_DENIAL.exec(log)?.[0]; + const missing = error.code === MISSING_RESULT_BRANCH || /result branch fetch failed|requires machine outcome evidence/.test(error.message); + const denial = missing && PERMISSION_DENIAL.exec(log)?.[0]; return denial ? new Error(`cloud validation session was denied permission to run a command: ${redactedLine(denial).slice(0, DIAGNOSIS_CHARS)} (${error.message})`) : error; } @@ -969,6 +1013,36 @@ function withOverflowArtifact(request, count, digest) { function validationReceiptPath(request, digest) { return path.join(gitDir(request.worktree), validationReceiptName(request.commit, digest)); } +/** Retry only provider-proven refusals, outside the routine lock and inside the request's launch window. */ +export async function retryValidationLaunch(start, { launchRefused, timeoutMs, signal, now = Date.now, + sleep = (ms) => delay(ms, undefined, { signal }), report = (line) => process.stderr.write(line + "\n") }) { + const deadline = now() + timeoutMs; + const refusals = []; + let backoffMs = 30_000; + let lastError; + for (;;) { + signal?.throwIfAborted(); + if (lastError && now() >= deadline) throw lastError; + try { + const started = await start(); + return { ...started, ...(refusals.length ? { launchRefusals: refusals } : {}) }; + } catch (error) { + if (!error.validationLaunchRefusal || error.launchUncertain) throw error; + lastError = error; + const observed = now(); + const time = new Date(observed).toISOString(); + const message = redactedLine(redactSecrets(error.validationLaunchRefusal)).slice(0, 400); + refusals.push({ time, message }); + const waitMs = Math.min(backoffMs, deadline - observed); + report(`CLOUD_VALIDATION_LAUNCH_LIMIT ${time}: ${message}${waitMs > 0 ? `; retrying in ${Math.ceil(waitMs / 1000)}s` : "; the launch deadline expired"}`); + await launchRefused(); + if (waitMs <= 0) throw error; + await sleep(waitMs); + backoffMs = Math.min(backoffMs * 2, 120_000); + } + } +} + /** Start (or resume) a Claude cloud session on the commit, poll it, and return results bound to that commit. */ export async function validateCommit(request, { remote = cliRemote(request.worktree), sleep, now, home = os.homedir(), executor = chromeRemoval(), stderr, artifactReader = readValidationArtifact, signal, proofGit = git, currentAccount = currentClaudeAccount } = {}) { validateValidationRequest(request); @@ -977,6 +1051,9 @@ export async function validateCommit(request, { remote = cliRemote(request.workt const routed = withOverflowArtifact(verified, validationLanes(verified).lanes.length, digest); const file = validationReceiptPath(request, digest); const { lanes } = validationLanes(routed); + const warnings = validationWorkflowWarnings(routed); + const report = stderr ?? ((line) => process.stderr.write(line + "\n")); + for (const warning of warnings) report(warning); const laneKeys = lanes.map(({ command }) => validationCommandKey(command)); const env = resolveClaudeEnvironment(routed); const ledger = () => readLedger(home); @@ -984,8 +1061,8 @@ export async function validateCommit(request, { remote = cliRemote(request.workt const selected = boundProbeReceipt(file, lanes, ledger(), env); if (!existsSync(selected)) validationBrief(routed, admission(), null, digest); // Before the hold and proof push: a refused brief takes no slot. const resume = `run the same cloud-worker.mjs validate --request again; its receipt ${selected} resumes this poll`; - return executeCloudValidation({ file, digest, request: routed, env, lanes, laneKeys, home, ledger, currentAccount, remote, signal, timeoutMs: DEFAULT_WALL_MS, - async start(launching) { + return executeCloudValidation({ file, digest, request: routed, env, lanes, laneKeys, home, ledger, currentAccount, remote, signal, warnings, timeoutMs: DEFAULT_WALL_MS, + async start(launching, launchRefused) { if (!routed.resultArtifact || outcomeArtifact(routed)) requireOutcomeCapacity(lanes,outcomeArtifact(routed)); if (outcomeArtifact(routed) && proofGit(request.worktree,["ls-remote","--refs","origin","refs/heads/"+routed.resultArtifact.branch])) throw new Error("outcome proof branch already exists; supply a fresh resultArtifact branch before dispatch"); const managedHost = admission(); @@ -993,8 +1070,10 @@ export async function validateCommit(request, { remote = cliRemote(request.workt const proof = request.cloudProof ? prepareCloudcheckProof({ worktree: request.worktree, commit: request.commit, key: digest, gitDir: path.dirname(file), git: proofGit }) : null; await sweepRemovals({ home, remote, worktree: request.worktree, executor, account: currentAccount, ...(stderr ? { stderr } : {}) }); const subject = proof ? { ...routed, branch: proof.branch } : routed; - const started = await startClaude({ ...subject, connectorAllowlist: [] }, validationBrief(routed, managedHost, proof?.branch,digest), { remote, home, - account: currentAccount, requestKey: digest, beforeRun: launch => launching(launch,{managedHost:Boolean(managedHost),outcomeTransport}), afterRun: launching, label: `validate ${request.commit.slice(0, 12)}` }); + const brief = validationBrief(routed, managedHost, proof?.branch, digest); + const started = await retryValidationLaunch(() => startClaude({ ...subject, connectorAllowlist: [] }, brief, { remote, home, + account: currentAccount, requestKey: digest, beforeRun: launch => launching(launch,{managedHost:Boolean(managedHost),outcomeTransport}), afterRun: launching, label: `validate ${request.commit.slice(0, 12)}` }), + { launchRefused, signal, sleep, now, timeoutMs: request.maxWallMs ?? DEFAULT_WALL_MS, report }); return { ...started, outcomeTransport, ...(managedHost ? {managedHost:true} : {}), ...(proof ? {proof} : {}) }; }, poll: (started) => pollTask(started, routed, { remote, resume, waitForVisibility: true, ...(sleep ? { sleep } : {}), ...(now ? { now } : {}) }), diff --git a/plugins/vibe/lib/vibe/scripts/cloud-worker.test.mjs b/plugins/vibe/lib/vibe/scripts/cloud-worker.test.mjs index ff355424..0fcc89b4 100644 --- a/plugins/vibe/lib/vibe/scripts/cloud-worker.test.mjs +++ b/plugins/vibe/lib/vibe/scripts/cloud-worker.test.mjs @@ -1027,10 +1027,12 @@ test('ISS-14116 item 24: a failed lane carries a short output tail and the worke assert.equal(Object.hasOwn(parsed.lanes[0], 'tail') || Object.hasOwn(parsed.lanes[0], 'diagnosis'), false, 'a lane reported without them has neither'); }); -test('ISS-14116 the validation brief keeps lanes waited for past the Bash ten-minute limit and keeps the final message to the result line', () => { +test('ISS-14116 the validation brief waits past the Bash ten-minute limit and keeps the final message bounded', () => { const brief = validationBrief(validationRequest()); for (const rule of ['moves a longer command to the background itself', 'never start the lane again', 'never after a pipe', - 'never infer one from the output', '"exitCode": null', '"notRun"', '"tail"', '"diagnosis"', 'Your final message is the result line alone, under 1,800 characters', + 'never infer one from the output', '"exitCode": null', '"notRun"', '"tail"', '"diagnosis"', + 'Your final message keeps the result line and any reporter-directed diagnostic lines under 1,800 characters', + 'Copy the reporter\'s complete result line, including any VIBE_VALIDATION_FAILURES or VIBE_OUTCOME_PUBLICATION suffix', 'a foreground `until` loop', 'shorten or drop tails to fit']) { assert.ok(brief.includes(rule), rule); } diff --git a/plugins/vibe/lib/vibe/scripts/cloud-workflow-brief.test.mjs b/plugins/vibe/lib/vibe/scripts/cloud-workflow-brief.test.mjs index 35df1b68..9aba65a5 100644 --- a/plugins/vibe/lib/vibe/scripts/cloud-workflow-brief.test.mjs +++ b/plugins/vibe/lib/vibe/scripts/cloud-workflow-brief.test.mjs @@ -7,7 +7,7 @@ import path from "node:path"; import { fileURLToPath, pathToFileURL } from "node:url"; import test from "node:test"; import { fakeDpkg, git, makeCheckout, makeHome, privateSudoers } from "../../../skills/vibe/scripts/test-fixtures.mjs"; -import { validateCommit, validationBrief, validationLanes } from "./cloud-worker.mjs"; +import { validationWorkflowWarnings, validateCommit, validationBrief, validationLanes } from "./cloud-worker.mjs"; import { workflowLaneDefinitions } from "./workflow-lane-definitions.mjs"; import { reporterFiles } from "./cloud-outcome-instruction.mjs"; import { compactWorkflowBrief, WORKFLOW_BRIEF_UNAVAILABLE } from "./cloud-workflow-brief.mjs"; @@ -20,6 +20,29 @@ const workflowPath=".github/workflows/ci.yml"; // The refusal's route to the managed pnpm lanes, as a pattern (team-lead ruling (b), 2026-11-25). const managedRoute="validate this commit through its managed pnpm lanes instead: lanes \\[\\{name, command\\}\\] whose command is a pnpm script, with no workflow file"; const root=fileURLToPath(new URL("../../../../../",import.meta.url)); + +test("caller-written jobs with different commands warn against the committed CI recipe", (t) => { + const f = makeHome("cloud-workflow-warning-"); + t.after(f.cleanup); + const worktree = path.join(f.root, "checkout"); + makeCheckout({ ...f, checkout: worktree, remoteUrl: "https://github.com/example/widgets.git", files: { + [workflowPath]: readFileSync(path.join(root, workflowPath), "utf8") + + "\n exact-command:\n runs-on: ubuntu-latest\n steps:\n - run: node --version\n", + } }); + const commit = git(worktree, ["rev-parse", "HEAD"], f.home); + const request = { worktree, commit, lanes: [ + { name: "node-tests", command: "node --test 'plugins/**/*.test.mjs'" }, + { name: "node-tests-shard-3", command: "node --test 'plugins/**/*.test.mjs'" }, + { name: "exact-command", command: "node --version" }, + { name: "focused", command: "node --test example.test.mjs" }, + ] }; + // Deliberately diverge the working copy. The warning must use the validated commit. + writeFileSync(path.join(worktree, workflowPath), "jobs: {}\n"); + const warnings = validationWorkflowWarnings(request); + assert.equal(warnings.length, 2); + assert.match(warnings[0], /node-tests.*ci\.yml.*recipe/); + assert.match(warnings[1], /node-tests-shard-3.*ci\.yml.*recipe/); +}); // The bootstrap's plan step runs the host's package repair, which runs dpkg as root: every bootstrap here runs with // dpkg and dpkg-query stubbed first on its PATH, so a root test run never configures a real package. const stubbed=dpkg=>({...process.env,PATH:dpkg.bin+path.delimiter+process.env.PATH}); diff --git a/plugins/vibe/lib/vibe/scripts/cloud-workflow-runner.test.mjs b/plugins/vibe/lib/vibe/scripts/cloud-workflow-runner.test.mjs index 894ce121..8f190735 100644 --- a/plugins/vibe/lib/vibe/scripts/cloud-workflow-runner.test.mjs +++ b/plugins/vibe/lib/vibe/scripts/cloud-workflow-runner.test.mjs @@ -334,7 +334,7 @@ test("AC-68 a fetch-depth 0 checkout refuses the lane when the cloud checkout is function runnerCommand(f, definitions, umask = null, env = {}) { const plan = path.join(f.checkout, ".git", "vibe-workflow-fixture"); mkdirSync(plan); - for (const name of ["cloud-workflow-runner.mjs", "cloud-validation-host.mjs"]) cpSync(path.join(here, name), path.join(plan, name)); + for (const name of ["cloud-workflow-runner.mjs", "cloud-validation-host.mjs", "cloud-redaction.mjs"]) cpSync(path.join(here, name), path.join(plan, name)); writeFileSync(path.join(plan, "lanes.json"), JSON.stringify(definitions.map((_, index) => `lane ${index}`))); for (const [index, definition] of definitions.entries()) writeFileSync(path.join(plan, `lane-${index}.json`), JSON.stringify({ version: 1, ...definition, matrix: {} })); writeFileSync(path.join(plan, "reporter-spec"), Buffer.from(JSON.stringify({ commit: f.commit })).toString("base64url")); diff --git a/plugins/vibe/skills/cl-sweep/scripts/app-server-worker-session.mjs b/plugins/vibe/skills/cl-sweep/scripts/app-server-worker-session.mjs index aa401ca1..b99bcd6e 100644 --- a/plugins/vibe/skills/cl-sweep/scripts/app-server-worker-session.mjs +++ b/plugins/vibe/skills/cl-sweep/scripts/app-server-worker-session.mjs @@ -1494,7 +1494,7 @@ async function superviseTurn(args, dependencies = {}) { try { await initializeClient(client); validateModelBinding(session); - collector = createTurnCollector(client, session.appServerThreadId); + collector = (dependencies.createTurnCollector ?? createTurnCollector)(client, session.appServerThreadId); const lifecycle = lifecycleView(session); const resumed = await ensureDurableThread( client, diff --git a/plugins/vibe/skills/cl-sweep/scripts/app-server-worker-session.test.mjs b/plugins/vibe/skills/cl-sweep/scripts/app-server-worker-session.test.mjs index 5c930e0a..6a612f36 100644 --- a/plugins/vibe/skills/cl-sweep/scripts/app-server-worker-session.test.mjs +++ b/plugins/vibe/skills/cl-sweep/scripts/app-server-worker-session.test.mjs @@ -12,7 +12,6 @@ import { symlinkSync, unlinkSync, writeFileSync, - watch, } from 'node:fs'; import { tmpdir } from 'node:os'; import { join } from 'node:path'; @@ -1779,8 +1778,14 @@ test('absent-turn recovery fails closed before mutation when authoritative state assert.equal(unchanged.state, 'RUNNING'); }); -test('supervision adopts the one authoritative live turn after a reconnect id mismatch', async () => { +const adoptionTest = 'supervision adopts the one authoritative live turn after a reconnect id mismatch'; +test(adoptionTest, async (t) => { + const forceExpiry = process.argv.includes('--force-adoption-timeout'); const fixture = initializeFixture(); + t.after(() => { + rmSync(fixture.directory, { recursive: true, force: true }); + rmSync(fixture.worktree, { recursive: true, force: true }); + }); const stored = JSON.parse(readFileSync(fixture.sessionFile, 'utf8')); stored.appServerThreadId = 'worker-thread'; stored.activeTurnId = 'stale-client-turn'; @@ -1793,29 +1798,48 @@ test('supervision adopts the one authoritative live turn after a reconnect id mi listedTurnId: 'live-server-turn', existingTurn: { id: 'live-server-turn', status: 'inProgress', items: [] }, }); - const adoption = new Promise((accept, reject) => { - const timer = setTimeout(() => { watcher.close(); reject(new Error('Authoritative turn adoption was not persisted')); }, 5000); - const watcher = watch(fixture.directory, () => { - const observed = JSON.parse(readFileSync(fixture.sessionFile, 'utf8')); - if (observed.activeTurnId !== 'live-server-turn') return; - watcher.close(); - clearTimeout(timer); - accept(); - }); - }); + const adoption = Promise.withResolvers(); + const observedCollector = (...args) => { + const collector = createTurnCollector(...args); + return { + ...collector, + wait(...waitArgs) { + const waiting = collector.wait(...waitArgs); + // Inject the old deadline's failure while the real collector holds an active timer. + if (forceExpiry) adoption.reject(new Error('Authoritative turn adoption was not persisted')); + else adoption.resolve(); + return waiting; + }, + }; + }; const supervision = superviseTurn({ 'session-file': fixture.sessionFile, 'events-file': fixture.eventsFile, - }, { client }); - await adoption; - const adopted = JSON.parse(readFileSync(fixture.sessionFile, 'utf8')); - assert.equal(adopted.activeTurnId, 'live-server-turn'); - assert.equal(adopted.state, 'RUNNING'); - assert.equal(adopted.lastFailure, undefined); - for (const handler of client.connections) handler('close', new Error('test complete')); + }, { client, createTurnCollector: observedCollector }); + try { + await Promise.race([adoption.promise, supervision]); + const adopted = JSON.parse(readFileSync(fixture.sessionFile, 'utf8')); + assert.equal(adopted.activeTurnId, 'live-server-turn'); + assert.equal(adopted.state, 'RUNNING'); + assert.equal(adopted.lastFailure, undefined); + } finally { + for (const handler of client.connections) handler('close', new Error('test complete')); + await supervision.catch(() => {}); + } await assert.rejects(supervision, /test complete/); }); +test('supervision releases its live handle when the adoption deadline expires', () => { + const { NODE_TEST_CONTEXT: _parentTest, ...env } = process.env; + const child = spawnSync(process.execPath, [ + `--test-name-pattern=^${adoptionTest}$`, fileURLToPath(import.meta.url), + '--force-adoption-timeout', + ], { encoding: 'utf8', timeout: 60_000, env }); + assert.ifError(child.error); + assert.equal(child.status, 1, child.stdout + child.stderr); + assert.match(child.stdout, /Authoritative turn adoption was not persisted/); +}); + test('rebinds an idle callback target without changing the ticket lease generation', async () => { const fixture = initializeFixture(); const rebound = await rebindParent({ diff --git a/plugins/vibe/skills/fleet-orchestrator/SKILL.md b/plugins/vibe/skills/fleet-orchestrator/SKILL.md index 576b60a0..d025aefa 100644 --- a/plugins/vibe/skills/fleet-orchestrator/SKILL.md +++ b/plugins/vibe/skills/fleet-orchestrator/SKILL.md @@ -193,6 +193,7 @@ For a publisher plugin version bump, attach the handoff run report with `board.m - A screenshot capture through a slot passes `--capture ` (`ticket`, `ref`, `pages`, `states`, optional `override`) after the worktree path; `scripts/fleet.sh` runs `../vibe/scripts/capture-guard.mjs` first and refuses it (exit 79) as `../vibe/references/quality-loop-visual-qa.md`, block `when-to-capture`, says; only an operator ruling recorded for that ticket in the program rulings, carrying `capture-guard override: baseline` or `capture-guard override: budget` for the refusal it lifts and quoted in the spec's `override`, lets it run. Before approving any capture, including after a compaction, read `../vibe/scripts/capture-guard.mjs status --ticket --ledger /captures`. - Before reporting or waiting on remaining work, identify true dependencies. Start independent repository selected integration, unit, typecheck and lint lanes at once through available heavy slots on allowed machines, even while e2e is queued or running elsewhere. A lane waiting only for a full slot or load moves to another allowed machine with capacity; report the move. With a passing cloud check, start those lanes in the cloud first (`CLOUD-VALIDATE` once the exact head is pushed); without one, route an eligible refused lane that way. Respect operator exclusions, machine load and slot limits, no dagger restrictions and the daily machine's no visible e2e rule. Keep the repository lane selector and `qa-impact.mjs` decision on which checks are needed. A lane runs the way its CI job runs: a proof harness never sets `umask 077` or exports `VITEST_MAX_WORKERS` above a tool's configured cap. - A shared e2e stack with fixed ports runs only under vibe's machine-wide e2e lock: `node ../vibe/scripts/e2e-lock.mjs run --head --source-hash --owner --label --ticket ` on the machine that runs it, where the machine slot reports the owner, label, ticket and compose project; receipts name HEAD plus diff/tree hashes, including dirty source. Each run gets its own compose project, so a teardown removes only its own stack; name a stack another tool started with `--foreign-compose `. Unit tests, typecheck, story runs and stand-in server tests run outside it. +- Submit independent cloud validations as soon as their inputs are ready. If the platform rate-limits a launch or reports that capacity is full, keep the other runs going. Validation reports the time and text of the refusal and waits before retrying that launch within its request timeout. - `scripts/slot-lock.sh --status ` on a machine lists slot holders. - Stop only owned processes with `fleet.sh local stop-owned `, even during plugin upgrades. `hooks/kill-guard.mjs` refuses the rest; its `tree ` prints that process and its descendants as pid, parent and elapsed time, so never list other command lines. Run signal tests on another machine and keep fleet guards trusted. - Stop an orphan on the heavy host with `fleet.sh remote stop-owned ` only when its slot record identifies the same owner and process. diff --git a/plugins/vibe/skills/fleet-orchestrator/scripts/slot-lock.sh b/plugins/vibe/skills/fleet-orchestrator/scripts/slot-lock.sh index c94e27da..b9bd19c0 100755 --- a/plugins/vibe/skills/fleet-orchestrator/scripts/slot-lock.sh +++ b/plugins/vibe/skills/fleet-orchestrator/scripts/slot-lock.sh @@ -157,7 +157,7 @@ until acquire; do if [ "$name" = heavy ] && [ -n "$queue_scope" ] && [ -z "$wait_dir" ] && [[ "$owner" != *$'\t'* && "$owner" != *$'\n'* ]]; then wait_dir=$(mktemp -d "$lock_root/$name-$$-XXXXXX") || exit 2 # The directory is published only after its identity and capacity are recorded. - cadence=$(awk -v poll="$poll" 'BEGIN { n = int(poll); print n >= 1 ? n + (n < poll) : 1 }') + cadence=$(awk -v poll="$poll" 'BEGIN { n = int(poll); print (n >= 1 ? n + (n < poll) : 1) }') printf '%s\t%s\t%s\t%s\t%s\t%s\t%s\n' "$$" "$slots" "$(start_of "$$")" "$queue_scope" "$(date +%s)" "$cadence" "$owner" >"$wait_dir/queue" mv "$wait_dir" "$wait_dir.wait" || exit 2 wait_dir=$wait_dir.wait diff --git a/plugins/vibe/skills/fleet-orchestrator/scripts/slot-lock.test.mjs b/plugins/vibe/skills/fleet-orchestrator/scripts/slot-lock.test.mjs index 990e22ed..0ecbd4fe 100644 --- a/plugins/vibe/skills/fleet-orchestrator/scripts/slot-lock.test.mjs +++ b/plugins/vibe/skills/fleet-orchestrator/scripts/slot-lock.test.mjs @@ -158,6 +158,17 @@ test('waits while every slot is held by a live process, then runs once one frees assert.equal(run.seen.stdout, 'ran\n'); }); +test('heavy wait computes the rounded cadence with the system awk', () => { + const program = readFileSync(SCRIPT, 'utf8').match(/cadence=\$\(awk -v poll="\$poll" '([^']+)'\)/)?.[1]; + assert.ok(program, 'the actual slot-lock cadence program'); + for (const [poll, expected] of [['2.5', '3'], ['2', '2'], ['0.1', '1']]) { + const result = spawnSync('/usr/bin/awk', ['-v', `poll=${poll}`, program], { encoding: 'utf8' }); + assert.equal(result.status, 0, result.stderr); + assert.equal(result.stderr, ''); + assert.equal(result.stdout, `${expected}\n`); + } +}); + test('SIGTERM stops the command and frees the slot', TIMEOUT, async () => { const root = lockRoot(); const marker = join(root, 'child-pid'); diff --git a/plugins/vibe/skills/vibe/scripts/e2e-requirement.mjs b/plugins/vibe/skills/vibe/scripts/e2e-requirement.mjs index 9223dad6..31d7f1cb 100644 --- a/plugins/vibe/skills/vibe/scripts/e2e-requirement.mjs +++ b/plugins/vibe/skills/vibe/scripts/e2e-requirement.mjs @@ -1,8 +1,9 @@ #!/usr/bin/env node // The e2e specs a change owes locally before its pull request opens, beyond what the graph test selector chose. The // repository's rule: an e2e lane is satisfied by the graph-selected specs, plus specs the branch's own changes newly -// reach, plus every spec the change adds or edits; without a graph result, by the CI changes job's changed-spec union, -// and by the whole lane wherever that union cannot narrow. A pull request once changed a shared e2e helper, six +// reach, plus every spec the change adds or edits; without a graph result, by the CI changes job's changed-spec union. +// Changes to shared suite inputs that the workflow cannot narrow require the whole lane even with a graph result. +// A pull request once changed a shared e2e helper, six // stories and one spec, ran two targeted specs, and broke main in a spec that opens one of those stories by its // Storybook URL. The graph selector cannot see that edge (a spec reaches its story through the id parameter of the iframe page, // not an import), so this module computes it: a changed story owes every suite spec that names the story's id, read @@ -26,9 +27,10 @@ import { isEntryPoint } from "../../../shared/plugin-roots.mjs"; import { containerizedIntent } from "../../../lib/vibe/scripts/docker-disk-admission.mjs"; import { LANE_RECORDS_FILE } from "./lane-outcomes.mjs"; +import { E2E_SELECTION_KEYS, laneRunCommit } from "./lane-run-witness.mjs"; import { witnessProblem } from "./lane-witness-check.mjs"; -const { git } = await vibeCore("lib/vibe/scripts/session-record.mjs"); +const { absoluteGitDir, git } = await vibeCore("lib/vibe/scripts/session-record.mjs"); const { boundWith, installedProviders } = await vibeCore("lib/vibe/scripts/provider.mjs"); export const E2eSurface = Object.freeze({ Web: "web", Desktop: "desktop" }); @@ -63,8 +65,8 @@ const RAN_RESULTS = new Set(["pass", "env-skip", "main-preexisting"]); * What the change from `base` to `head` owes each e2e lane the provider declares: * `[{ surface, required, full, reasons, lane, specs }]`. `specs` are the specs owed beyond the graph selection (those a * changed story's id reaches, those that import a file the change adds, and the surface's changed specs). `full` is true - * only for a fallback: a changed story whose specs cannot be found completely, or, with no graph result for the surface - * (`graphSelection[surface]` not a list), a change the changes job's union cannot narrow. `reasons` name the story ids that + * for a changed story whose specs cannot be found completely, a shared input the workflow cannot narrow, + * or a change the changes job's union cannot narrow when there is no graph result. `reasons` name the story ids that * added specs, the incomplete story, or the missing graph and the paths the union could not narrow. * `binding` is the session's provider binding; with none (a row outside a vibe session) the installed provider serving * this repository's origin is read. `files` replaces the committed diff with the caller's changed-file set, read from @@ -132,10 +134,21 @@ export function laneSurface(command) { return null; } +/** A plain full-lane name is insufficient when the command or its witnessed environment filters the run. */ +function ranWholeE2e({ command, environment, targeted }) { + if (targeted || /\btest:web-smoke\b/.test(command)) return false; + const args = /(?:^|\s)(?:--(?:grep(?:-invert)?|project|shard|last-failed|only-changed|list)|-g)(?=\s|=|$)/; + if (args.test(command) || /\btest:e2e\b.*\s[^\s]*\.spec\.[cm]?[jt]sx?/.test(command)) return false; + return !E2E_SELECTION_KEYS.some((key) => { + const assignment = new RegExp(`(?:^|\\s)${key}=(?:"([^"]*)"|'([^']*)'|([^\\s]*))`).exec(command); + return Boolean(assignment ? (assignment[1] ?? assignment[2] ?? assignment[3]) : environment?.[key]); + }); +} + /** * The e2e evidence pre-pr-lanes.mjs recorded for `head` (default: the worktree's HEAD) in the session's lane records. * `receipts`: one per witnessed e2e lane run that `check` accepts as run (`pass`, `env-skip`, `main-preexisting`), `full` - * unless it was a targeted run, with the specs it ran. `notRun`: the e2e lanes recorded not-run, with the record's reason + * when it ran without a spec, tag, shard or project filter, with the known specs otherwise. `notRun`: the e2e lanes recorded not-run, with the record's reason * and the skip ruling it quotes (`{ id, source }`, else null); only a quoted ruling lets one stand in for a run. `graphSelection`: the union of the graph selections the targeted records carry, * null when none does. No records (a worktree outside a vibe session) is empty evidence; an unparseable file throws. */ @@ -149,9 +162,9 @@ export function recordedE2eEvidence(worktree, { head } = {}) { if (!Array.isArray(records)) throw new Error(`${file} is not a list of lane records`); const at = head ?? git(worktree, ["rev-parse", "HEAD"]); const current = records.filter((record) => record?.head === at && typeof record.command === "string" && laneSurface(record.command)); - const ran = current.filter((record) => RAN_RESULTS.has(record.result) && !witnessProblem(record)); + const ran = current.filter((record) => RAN_RESULTS.has(record.result) && laneRunCommit(record) === at && !witnessProblem(record)); const receipts = ran.map((record) => ({ surface: laneSurface(record.command), lane: record.command, result: record.result, - full: !record.targeted, specs: Array.isArray(record.targeted?.specs) ? [...record.targeted.specs] : [] })); + full: ranWholeE2e(record), specs: Array.isArray(record.targeted?.specs) ? [...record.targeted.specs] : [] })); const notRun = current.filter((record) => record.result === "not-run").map((record) => ({ surface: laneSurface(record.command), lane: record.command, reason: record.reason ?? null, ruling: quotedRuling(record) })); let graphSelection = null; @@ -224,8 +237,18 @@ function surfaceRequirement(context, surface, spec, graphSelection) { } const owed = (extra) => [...new Set([...stories.specs, ...reached, ...extra])].sort(); if (stories.incomplete.length) return row({ full: true, reasons: stories.incomplete, specs: owed(changedSpecs) }); - if (Array.isArray(graphSelection)) return row({ reasons: stories.ids, specs: owed(changedSpecs) }); const suite = changed.filter(inSuite); + if (Array.isArray(graphSelection)) { + const shared = suite.filter((file) => !SPEC.test(file)); + try { + if (shared.length && runClassifier(context, classifier, shared).length === 0) { + return row({ full: true, reasons: shared, specs: owed(changedSpecs) }); + } + } catch (error) { + return row({ full: true, reasons: [`${spec.classifier} could not check shared inputs (${error.message})`], specs: owed(changedSpecs) }); + } + return row({ reasons: stories.ids, specs: owed(changedSpecs) }); + } if (suite.length === 0) return row({ reasons: [NO_GRAPH, ...stories.ids], specs: owed([]) }); try { // The whole set decides, as in CI; each path is then asked alone so the reasons name only those it cannot narrow. @@ -379,13 +402,13 @@ function classifierInput(step) { } /** - * Runs the classifier step's own shell, as the changes job runs it on a pull request, in a scratch folder holding the - * changed suite files and every repository file its script names, as they are at `head`. Returns the specs it names. + * Runs the classifier step's own shell, as the changes job runs it on a pull request, in the worktree's private Git + * directory. Its scratch folder holds the changed suite files and every repository file its script names, as they are + * at `head`. Returns the specs it names and removes the scratch folder after execution. */ function runClassifier({ worktree, head, fromWorktree }, step, suite) { const input = classifierInput(step); - const gitDir = git(worktree, ["rev-parse", "--absolute-git-dir"]); - const scratch = mkdtempSync(path.join(gitDir, "vibe-e2e-classifier-")); + const scratch = mkdtempSync(path.join(absoluteGitDir(worktree), "vibe-e2e-classifier-")); try { const tree = path.join(scratch, "tree"); mkdirSync(tree); diff --git a/plugins/vibe/skills/vibe/scripts/e2e-requirement.test.mjs b/plugins/vibe/skills/vibe/scripts/e2e-requirement.test.mjs index 819ba957..e5b4cccf 100644 --- a/plugins/vibe/skills/vibe/scripts/e2e-requirement.test.mjs +++ b/plugins/vibe/skills/vibe/scripts/e2e-requirement.test.mjs @@ -201,26 +201,28 @@ function commit(worktree, home, message) { const surface = (rows, name) => rows.find((row) => row.surface === name); -/** The pull request that broke main: a shared e2e helper, six stories and one new spec. */ -function brokeMainChange() { +/** The stories and spec alone exercise selection by Storybook id. */ +function storyChange() { return { - [HELPER]: "export const pinnedNameStrip = () => 1;\n", [NEW_SPEC]: "import { pinnedNameStrip } from \"./helpers/pinned-name-strip\";\ntest(\"cap\", () => pinnedNameStrip());\n", ...Object.fromEntries(Object.entries(STORIES).map(([file, title]) => [file, story(title, "Narrower")])), }; } +/** The pull request that broke main also edited an existing shared E2E helper. */ +const brokeMainChange = () => ({ ...storyChange(), [HELPER]: "export const pinnedNameStrip = () => 1;\n" }); + test("a changed story owes every spec that opens it by its Storybook id, which the graph cannot select", (t) => { const repo = repository(t, "e2e-req-story-"); - const head = repo.change(brokeMainChange()); + const head = repo.change(storyChange()); const rows = e2eLaneRequirement(repo.worktree, { base: repo.base, head, providers: PROVIDERS, graphSelection: { web: [], desktop: [] } }); const web = surface(rows, "web"); assert.equal(web.required, true); - assert.equal(web.full, false, "with a graph result the change is narrowed, never forced to the whole lane"); + assert.equal(web.full, false, "the graph can narrow when the suite inputs are unchanged"); assert.deepEqual(web.specs, [NARROW_LIST_SPEC, NEW_SPEC].sort()); assert.deepEqual(web.reasons, ["surfaces-artifacts-sessions-sessions-list"]); assert.equal(web.lane, WEB_LANE); - assert.deepEqual(surface(rows, "desktop"), { surface: "desktop", required: true, full: false, reasons: [], lane: DESKTOP_LANE, specs: [] }); + assert.deepEqual(surface(rows, "desktop"), { surface: "desktop", required: false, full: false, reasons: [], lane: DESKTOP_LANE, specs: [] }); }); test("without a graph result the changes job's own classifier decides: a helper forces the whole lane, a spec narrows", (t) => { @@ -308,8 +310,8 @@ test("a story whose title is not a literal, or whose id only a helper no spec im test("a spec importing a file the change adds is owed, since the trunk graph cannot have seen it", (t) => { const repo = repository(t, "e2e-req-added-"); - const head = repo.change({ "e2e/helpers/new-flow.ts": "export const flow = 1;\n", - "e2e/existing.spec.ts": "import { flow } from \"./helpers/new-flow\";\ntest(\"existing\", () => flow);\n" }); + const head = repo.change({ "apps/web/new-flow.ts": "export const flow = 1;\n", + "e2e/existing.spec.ts": "import { flow } from \"../apps/web/new-flow\";\ntest(\"existing\", () => flow);\n" }); const web = surface(e2eLaneRequirement(repo.worktree, { base: repo.base, head, providers: PROVIDERS, graphSelection: { web: [] } }), "web"); assert.deepEqual([web.full, web.specs], [false, ["e2e/existing.spec.ts"]]); }); @@ -340,7 +342,7 @@ test("uncommitted changes are read from the worktree when the caller passes its test("missingE2eSpecs names each owed spec or the whole lane, and a passing run covers it", (t) => { const repo = repository(t, "e2e-req-missing-"); - const head = repo.change(brokeMainChange()); + const head = repo.change(storyChange()); const options = { base: repo.base, head, providers: PROVIDERS, graphSelection: { web: ["e2e/existing.spec.ts"], desktop: [] } }; assert.deepEqual(missingE2eSpecs(repo.worktree, { ...options, receipts: [{ surface: "web", full: false, specs: [NEW_SPEC, "e2e/existing.spec.ts"] }] }), [{ surface: "web", spec: NARROW_LIST_SPEC, reason: "changed, reached by an added file, or naming a changed story (surfaces-artifacts-sessions-sessions-list)" }]); @@ -349,10 +351,11 @@ test("missingE2eSpecs names each owed spec or the whole lane, and a passing run assert.deepEqual(missingE2eSpecs(repo.worktree, { ...options, receipts: [{ surface: "web", full: true, specs: [] }] }), []); // A row outside a vibe session: a provider serves the repository and no graph result exists. - const fallback = missingE2eSpecs(repo.worktree, { base: repo.base, head, providers: PROVIDERS }); + const sharedHead = repo.change(brokeMainChange()); + const fallback = missingE2eSpecs(repo.worktree, { base: repo.base, head: sharedHead, providers: PROVIDERS }); assert.deepEqual(fallback.map(({ surface: name, spec }) => [name, spec]), [["web", "full"], ["desktop", "full"]]); assert.match(fallback[0].reason, new RegExp(`${NO_GRAPH}; ${HELPER}$`)); - assert.deepEqual(missingE2eSpecs(repo.worktree, { base: repo.base, head, providers: PROVIDERS, + assert.deepEqual(missingE2eSpecs(repo.worktree, { base: repo.base, head: sharedHead, providers: PROVIDERS, receipts: [{ surface: "web", full: true }, { surface: "desktop", full: true }] }), []); }); @@ -363,7 +366,7 @@ test("a lane recorded not-run satisfies nothing unless its record quotes the ski const desktopLane = "DESKTOP_E2E_SMOKE_TAG='' DESKTOP_E2E_CHANGED_SPECS='' pnpm --dir apps/desktop test:e2e"; const left = { surface: "desktop", lane: desktopLane, reason: "no displayless Linux Electron harness on this machine", ruling: null }; const owed = missingE2eSpecs(repo.worktree, { ...options, notRun: [left] }).filter((item) => item.surface === "desktop"); - assert.deepEqual(owed.map((item) => item.spec), ["apps/desktop/test/e2e/home.spec.ts"], "a not-run lane is still owed"); + assert.deepEqual(owed.map((item) => item.spec), ["full"], "a not-run lane is still owed"); assert.match(owed[0].reason, /recorded not-run here, which satisfies nothing: run it in cloud validation, which runs the whole Desktop suite, or on the heavy host/); assert.doesNotMatch(owed[0].reason, /harness/, "the reason names where the lane runs, not what this machine lacks"); const full = missingE2eSpecs(repo.worktree, { base: repo.base, head, providers: PROVIDERS, notRun: [left] }).find((item) => item.surface === "desktop"); @@ -409,7 +412,7 @@ test("check recommends targeted E2E only for lanes that can satisfy PR create wi test("recordedE2eEvidence reads the lane records pre-pr-lanes writes, and none is empty evidence", async (t) => { const repo = repository(t, "e2e-req-evidence-"); - const head = repo.change(brokeMainChange()); + const head = repo.change(storyChange()); assert.deepEqual(recordedE2eEvidence(repo.worktree), { graphSelection: null, receipts: [], notRun: [] }); // Witnessed passes recorded through the script itself, for the web lane and the Desktop lane. @@ -461,7 +464,7 @@ test("recordedE2eEvidence reads the lane records pre-pr-lanes writes, and none i test("pre-pr-lanes warns about the story-driven spec and keeps targeted evidence usable in flight", async (t) => { bindProviderInProcess((cleanup) => t.after(cleanup)); const repo = repository(t, "e2e-req-guard-"); - const head = repo.change(brokeMainChange()); + const head = repo.change(storyChange()); const changed = git(repo.worktree, ["diff", "--name-only", repo.base, head], repo.home).split("\n").sort(); const repoName = SYMPHONY_REMOTE.replace(/\.git$/, "").split("/").at(-1); const graphItem = { type: "mcpToolCall", id: "graph-call-1", server: "graph", tool: "code_tests_for_changes", status: "completed", @@ -507,3 +510,39 @@ test("ids, titles and globs follow Storybook and the paths-filter action", () => assert.equal(globMatcher("apps/*").test("apps/web/x.ts"), false); assert.throws(() => globMatcher("e2e/{a,b}.ts"), /unsupported glob/); }); + +test("the graph cannot replace the whole browser lane when an existing shared helper changes", (t) => { + const repo = repository(t, "e2e-req-graph-helper-"); + const head = repo.change(brokeMainChange()); + const options = { base: repo.base, head, providers: PROVIDERS, graphSelection: { web: [NARROW_LIST_SPEC, NEW_SPEC] } }; + const receipt = { surface: "web", full: false, specs: [NARROW_LIST_SPEC, NEW_SPEC] }; + const web = missingE2eSpecs(repo.worktree, { ...options, receipts: [receipt] }).find((item) => item.surface === "web"); + assert.equal(web?.spec, "full"); + assert.match(web.reason, /pinned-name-strip\.ts/); + assert.equal(missingE2eSpecs(repo.worktree, { ...options, receipts: [{ ...receipt, full: true }] }) + .some((item) => item.surface === "web"), false); +}); + +test("a smoke E2E run does not count as a whole surface even without targeted metadata", (t) => { + const repo = repository(t, "e2e-req-smoke-"); + const head = repo.change(brokeMainChange()); + const dir = git(repo.worktree, ["rev-parse", "--absolute-git-dir"], repo.home); + writeFileSync(path.join(dir, "vibe-lane-results.json"), JSON.stringify([ + { command: "E2E_SMOKE_TAG='@smoke' E2E_CHANGED_SPECS='' e2e/run-containerized.sh", head, result: "pass" }, + { command: "pnpm test:e2e", head, result: "pass", environment: { E2E_CHANGED_SPECS: NEW_SPEC } }, + { command: "pnpm test:e2e --grep narrow", head, result: "pass" }, + { command: "E2E_SMOKE_TAG='' E2E_CHANGED_SPECS='' e2e/run-containerized.sh", head, result: "pass" }, + ])); + assert.deepEqual(recordedE2eEvidence(repo.worktree, { head }).receipts.map(({ full }) => full), [false, false, false, true]); +}); + +test("an E2E receipt cannot relabel an older remote proof commit as the PR head", (t) => { + const repo = repository(t, "e2e-req-old-proof-"); + const head = repo.change(storyChange()); + const dir = git(repo.worktree, ["rev-parse", "--absolute-git-dir"], repo.home); + const receipt = { command: "pnpm test:e2e", head, result: "pass" }; + writeFileSync(path.join(dir, "vibe-lane-results.json"), JSON.stringify([{ ...receipt, ranOn: { proofCommit: repo.base } }])); + assert.deepEqual(recordedE2eEvidence(repo.worktree, { head }).receipts, []); + writeFileSync(path.join(dir, "vibe-lane-results.json"), JSON.stringify([{ ...receipt, ranOn: { proofCommit: head } }])); + assert.equal(recordedE2eEvidence(repo.worktree, { head }).receipts[0]?.full, true); +}); diff --git a/plugins/vibe/skills/vibe/scripts/lane-run-witness.mjs b/plugins/vibe/skills/vibe/scripts/lane-run-witness.mjs index ee5d4843..681f4ddc 100644 --- a/plugins/vibe/skills/vibe/scripts/lane-run-witness.mjs +++ b/plugins/vibe/skills/vibe/scripts/lane-run-witness.mjs @@ -18,6 +18,18 @@ import { RUNNER_HOST } from "../../handoff/scripts/e2e-tier.mjs"; const COMMIT = /^[a-f0-9]{40}$/; const NO_DIFF = createHash("sha256").digest("hex"); +/** Controls that turn a whole E2E command into a subset without changing its argv. */ +export const E2E_SELECTION_KEYS = Object.freeze([ + "E2E_CHANGED_SPECS", "E2E_SMOKE_TAG", "E2E_SHARD", + "DESKTOP_E2E_CHANGED_SPECS", "DESKTOP_E2E_SMOKE_TAG", "DESKTOP_E2E_SHARD", + "DESKTOP_E2E_SPECS", "DESKTOP_E2E_PROJECTS", +]); + +/** The actual tested commit, including an external proof commit when the local record names a same-tree head. */ +export function laneRunCommit(record) { + return record?.ranOn ? record.ranOn.proofCommit : record?.head; +} + /** A unique private directory even when multiple lanes start together. */ function witnessDirectory(worktree) { const root = path.join(absoluteGitDir(worktree), "vibe-lane-witnesses"); @@ -26,9 +38,8 @@ function witnessDirectory(worktree) { } /** The values of the named environment keys this run sees, sorted by key; an unset key is null. */ -function witnessEnvironment(keys, env = process.env) { - // These existing controls can turn a full E2E lane into a subset without changing the command. - const selectors = ["E2E_CHANGED_SPECS", "E2E_SMOKE_TAG", "E2E_QUARANTINE_TAG", "E2E_SHARD", "DESKTOP_E2E_SPECS", "DESKTOP_E2E_PROJECTS"]; +export function witnessEnvironment(keys, env = process.env) { + const selectors = [...E2E_SELECTION_KEYS, "E2E_QUARANTINE_TAG"]; return Object.fromEntries([...new Set([...keys, ...selectors.filter((key) => env[key] !== undefined)])] .sort().map((key) => [key, env[key] ?? null])); } @@ -46,6 +57,11 @@ export function declaredEnvironment(pairs) { /** Runs the lane command in the worktree and keeps its log, source, command, environment and exit code beside the records. */ export function witnessRun(values, source) { + return witnessedLaneRun(values, source).status ?? 1; +} + +/** Execute a local lane and return the evidence the lane recorder can attach directly. */ +export function witnessedLaneRun(values, source) { const command = values.command.trim(); const outcomes = values.outcomes && path.resolve(values.outcomes); if (outcomes && existsSync(outcomes)) throw new Error(`--outcomes ${outcomes} already exists; move an earlier run's report away, so the file is the one this run writes`); @@ -54,18 +70,19 @@ export function witnessRun(values, source) { const environment = witnessEnvironment(values.env ?? []); const gitTree = git(values.worktree, ["rev-parse", "--verify", `${source.head}^{tree}`]); const log = openSync(`${stem}.log`, "wx", 0o600); - let exitCode; + let result; + process.stdout.write(`witness ${stem}.json\n`); try { - exitCode = withStableSource(values.worktree, (current) => { + result = withStableSource(values.worktree, (current) => { if (!sameSource(source, current)) throw new Error("SOURCE-MOVED before lane startup"); - return { status: spawnSync(command, { cwd: values.worktree, shell: true, stdio: ["ignore", log, log] }).status ?? 1 }; - }, { head: source.head }).status; + return spawnSync(command, { cwd: values.worktree, shell: true, stdio: ["ignore", log, log] }); + }, { head: source.head }); } finally { closeSync(log); } - const witness = { command, head: source.head, gitTree, source, environment, exitCode, log: evidenceFingerprint(`${stem}.log`, LANE_LOG_MAX_BYTES), + if (result.error) throw result.error; + const witness = { command, head: source.head, gitTree, source, environment, exitCode: result.status ?? 1, log: evidenceFingerprint(`${stem}.log`, LANE_LOG_MAX_BYTES), ...(outcomes && existsSync(outcomes) ? { outcomes: evidenceFingerprint(outcomes) } : {}), startedAt, finishedAt: new Date().toISOString() }; writeFileSync(`${stem}.json`, `${JSON.stringify(witness, null, 2)}\n`, { mode: 0o600, flag: "wx" }); - process.stdout.write(`witness ${stem}.json\n`); - return exitCode; + return { status: result.status, signal: result.signal, recorded: { witness: evidenceFingerprint(`${stem}.json`), environment } }; } /** Stream the heavy-host output to the caller and retain the exact bytes beside the runner's completion facts. */ diff --git a/plugins/vibe/skills/vibe/scripts/pre-pr-lanes.mjs b/plugins/vibe/skills/vibe/scripts/pre-pr-lanes.mjs index 4a5286d2..754c9260 100644 --- a/plugins/vibe/skills/vibe/scripts/pre-pr-lanes.mjs +++ b/plugins/vibe/skills/vibe/scripts/pre-pr-lanes.mjs @@ -132,8 +132,9 @@ import { CACHED_RESULT, cachedRecord, findReusable, laneKeyFor, Provenance } fro import { storyTypecheckLane } from "./story-typecheck.mjs"; import { launchedReviewerOrVerifier } from "./agent-models.mjs"; import { E2E_SPEC, observedGraphSelection, relativePath } from "./lane-graph.mjs"; -import { E2eSurface, FULL_LANE, isDesktopE2eLane, isWebE2eLane, missingE2eSpecs, RUN_ELSEWHERE } from "./e2e-requirement.mjs"; -import { declaredEnvironment, remoteRun, remoteRunLog, witnessProblem, witnessRun, witnessWorkflowRun } from "./lane-run-witness.mjs"; +import { E2eSurface, FULL_LANE, isDesktopE2eLane, isWebE2eLane, laneSurface, missingE2eSpecs, RUN_ELSEWHERE } from "./e2e-requirement.mjs"; +import { declaredEnvironment, remoteRun, remoteRunLog, witnessedLaneRun, witnessEnvironment, witnessProblem, witnessRun, witnessWorkflowRun } from "./lane-run-witness.mjs"; +import { fullPackageLaneCommand, packageLaneNotice } from "../../../lib/handoff/scripts/full-ci-check.mjs"; export { witnessProblem }; import { environmentalSkipProblem, interruptedRuns, LANE_RECORDS_FILE, laneRunOutcome, readLaneOutcomes, rerunOf, runningRecord, startLaneInBackground } from "./lane-outcomes.mjs"; import { vibeCore } from "../../../shared/vibe-core.mjs"; @@ -607,7 +608,7 @@ function sameStringList(left, right) { } /** Valid targeted E2E receipts for the current source and changed-file scope. */ -export async function targetedE2eCoverage(values, lanes, records, selected, readTurn) { +export async function targetedE2eCoverage(values, lanes, records, selected, readTurn, warn = () => {}) { if (!allowsTargetedE2e(values.worktree)) return []; const scope = targetedScope(values); const covered = []; @@ -630,7 +631,10 @@ export async function targetedE2eCoverage(values, lanes, records, selected, read || (current.runtime === "claude" && JSON.stringify(current.evidence) !== JSON.stringify(record.targeted.graph?.evidence))) continue; let requirement; try { requirement = targetedSpecRequirements(values, current, scope, lane, record.targeted.specs); } catch { continue; } - if (requirement.accepted) covered.push({ lane, specs: record.targeted.specs }); + if (requirement.accepted) { + if (requirement.warning) warn(requirement.warning); + covered.push({ lane, specs: record.targeted.specs }); + } } return covered; } @@ -764,16 +768,22 @@ async function main(argv) { if (mainSource && mainSource.diffSha256 !== createHash('sha256').digest('hex')) throw new Error('captured main must be clean to establish a main-preexisting failure'); if (command === "run") { const ticket = containerizedIntent("sh", ["-c", values.command],values.worktree) ? originatingStackTicket(values.worktree) : null; - const execute = (tree, expected) => withStableSource(tree, async (current) => { - if (!sameSource(expected, current)) throw new Error('SOURCE-MOVED before lane startup'); + const wholePackage = fullPackageLaneCommand(values.command.trim()); + const execute = async (tree, expected) => { const preflight = lanePreflightProblem(values.command); if (preflight) throw new Error(preflight); const fleet = fleetLaneInvocation(values, expected, tree, ticket); - const run = values.recipe ? await witnessWorkflowRun(fleet, tree, expected, values.command.trim()) - : fleet ? spawnSync(fleet.bin, fleet.args, { cwd: tree, stdio: 'inherit' }) - : spawnSync(values.command, { cwd: tree, shell: true, stdio: 'inherit' }); - return { status: run.status, recorded: run.recorded, outcome: laneRunOutcome(run, { fleet: Boolean(fleet?.receipt) && !run.recorded }), fleet: fleet?.receipt }; - }, { head: expected.head }); + const run = !fleet && wholePackage ? witnessedLaneRun({ ...values, worktree: tree }, expected) + : await withStableSource(tree, (current) => { + if (!sameSource(expected, current)) throw new Error('SOURCE-MOVED before lane startup'); + if (values.recipe) return witnessWorkflowRun(fleet, tree, expected, values.command.trim()); + if (fleet) return spawnSync(fleet.bin, fleet.args, { cwd: tree, stdio: 'inherit' }); + return spawnSync(values.command, { cwd: tree, shell: true, stdio: 'inherit' }); + }, { head: expected.head }); + const environment = !fleet && !run.recorded && laneSurface(values.command) ? witnessEnvironment([]) : null; + return { status: run.status, recorded: run.recorded ?? (environment && { environment }), + outcome: laneRunOutcome(run, { fleet: Boolean(fleet?.receipt) && !run.recorded }), fleet: fleet?.receipt }; + }; const lane = { command: values.command.trim(), head: tested, source, laneKey: selected.laneKey }; // A run killed with its process leaves this record, which check reports as interrupted. withRecordsLock(values.worktree, () => writeRecords(values.worktree, [...readRecords(values.worktree), runningRecord(lane)])); @@ -809,6 +819,9 @@ async function main(argv) { process.stderr.write(`Both runs failed at ${tested} and main ${mainTested}. Record matching test ids and assertions with record --result main-preexisting --main-sha --failures .\n`); } values.fleetReceipt = fleetReceipt; + if (result === "pass" && wholePackage && !witnessed) { + process.stderr.write("CI-NOT-RUN: this full package lane needs a run witness at PR create. Use witness on the runner and record its evidence.\n"); + } } const cacheKey = source.diffSha256 === createHash("sha256").digest("hex") ? laneKeyFor(values.worktree, { command: values.command, base: values.base, config: values.config }) : null; // Two lanes of one pool finish close together: the read, the change and the write happen under one lock so neither record is lost. @@ -845,7 +858,8 @@ async function main(argv) { } const witnessedRecords = records.filter((record) => !unwitnessed.has(record)); const targeted = targetedLaneDecision(values, named); - const targetedRuns = await targetedE2eCoverage(values, named, witnessedRecords, selected); + const targetedRuns = await targetedE2eCoverage(values, named, witnessedRecords, selected, undefined, + (warning) => process.stdout.write(`${warning}\n`)); const targetedRunLanes = targetedRuns.map((item) => item.lane); const left = notRunLanes(named.filter((lane) => !skip?.test(lane) && !targeted.left.includes(lane) && !targetedRunLanes.includes(lane)), witnessedRecords, selected, { identity: hasStagingE2eIdentity(values.worktree), harness: hasDisplaylessElectronHarness(), worktree: values.worktree }); @@ -906,6 +920,13 @@ async function main(argv) { for (const line of hints.full) process.stdout.write(`${line}\n`); if (hints.targetable.length > 0) process.stdout.write(`TARGETED-E2E: this repository allows a targeted E2E lane in place of the full one for ${hints.targetable.join(", ")}; ${TARGETED_RECORD}\n`); } + // An impact report can still drive focused work. The new whole-package policy applies at PR create. + try { + const notice = packageLaneNotice(values.worktree, head); + if (notice) process.stdout.write(`CI-NOT-RUN ${notice}\n`); + } catch (error) { + process.stdout.write(`CI-NOT-RUN could not check full package lanes: ${error.message}\n`); + } process.stdout.write(`pre-pr lanes: ${lanes.length} lanes, ${missing.length} missing${notRun.length ? `, ${notRun.length} not run locally` : ""}${values["reuse-cache"] || values["reuse-unaffected"] ? `, ${covered.length + unaffected.length} cached` : ""} for changed-file scope ${selected.laneKey ?? "none"}\n`); return { exitCode: missing.length === 0 ? 0 : 1 }; })(); diff --git a/plugins/vibe/tools/python/test_pr_takeover_skill_contract.py b/plugins/vibe/tools/python/test_pr_takeover_skill_contract.py index 53464014..8e411d5e 100644 --- a/plugins/vibe/tools/python/test_pr_takeover_skill_contract.py +++ b/plugins/vibe/tools/python/test_pr_takeover_skill_contract.py @@ -25,7 +25,7 @@ def _section(text: str, heading: str) -> str: def test_both_manifests_publish_the_same_new_skill_version() -> None: claude = json.loads(skill_split.read(PLUGIN / ".claude-plugin" / "plugin.json")) codex = json.loads(skill_split.read(PLUGIN / ".codex-plugin" / "plugin.json")) - assert claude["version"] == codex["version"] == "1.1.122" + assert claude["version"] == codex["version"] == "1.1.123" assert codex["skills"] == "./skills/" assert skill_split.read(SKILL).startswith("---\nname: pr-takeover\n") diff --git a/plugins/vibe/tools/python/test_vibe_ws8_load_contract.py b/plugins/vibe/tools/python/test_vibe_ws8_load_contract.py index dd87f05a..245abc08 100644 --- a/plugins/vibe/tools/python/test_vibe_ws8_load_contract.py +++ b/plugins/vibe/tools/python/test_vibe_ws8_load_contract.py @@ -150,8 +150,8 @@ def test_the_flags_the_skill_uses_exist_in_verify_run_and_the_worker_can_join() def test_current_version_and_prior_release_notes() -> None: for manifest in (".claude-plugin", ".codex-plugin"): - assert json.loads(skill_split.read(PLUGIN_ROOT / manifest / "plugin.json"))["version"] == "1.1.122", manifest - assert "Version `1.1.122`" in skill_split.read(PLUGIN_ROOT / "README.md") + assert json.loads(skill_split.read(PLUGIN_ROOT / manifest / "plugin.json"))["version"] == "1.1.123", manifest + assert "Version `1.1.123`" in skill_split.read(PLUGIN_ROOT / "README.md") changelog = skill_split.read(PLUGIN_ROOT.parents[1] / "CHANGELOG.md") assert "### vibe v1.1.121" in changelog assert "### vibe v1.1.76" in changelog