diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 3c218f33..77d4c7d5 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -133,9 +133,19 @@ jobs: - run: uv run pytest plugins/ node-tests: - name: Node Tests (skill scripts) + name: Node Tests (skill scripts) ${{ matrix.shard }}/3 runs-on: ubuntu-latest timeout-minutes: 20 + # ISS-15038: one job took 14.4 to 17.5 min on main and hit its 20-minute + # timeout on pull requests. Each shard runs every third discovered file + # (node's --test-shard keeps index % 3), so together they run the same set. + strategy: + fail-fast: false + matrix: + include: + - shard: 1 + - shard: 2 + - shard: 3 steps: - uses: actions/checkout@v4 - uses: actions/setup-node@v4 @@ -157,9 +167,9 @@ jobs: echo "::error::no *.test.{mjs,cjs,js} files found under plugins/; the discovery glob is broken." exit 1 fi - echo "Running ${#files[@]} test files:" - printf ' %s\n' "${files[@]}" - node --test --test-reporter=spec "${files[@]}" + echo "Discovered ${#files[@]} test files; this job runs shard ${{ matrix.shard }}/3 of them:" + printf ' %s\n' "${files[@]}" | awk -v shard=${{ matrix.shard }} '(NR - 1) % 3 == shard - 1' + node --test --test-shard=${{ matrix.shard }}/3 --test-reporter=spec "${files[@]}" vibe-eval-t0: name: Vibe Eval T0 diff --git a/CHANGELOG.md b/CHANGELOG.md index a803a8da..2dc1f426 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -4,6 +4,26 @@ 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-closedloop-provider v1.0.11 + +- ISS-15038: The cloud validation recipe names the environment of the CI step that runs the API tests (`AWS_REGION` and `AWS_EXECUTION_ENV` blank, every other `AWS_` setting removed) in place of a committed API test fixture. + +### vibe v1.1.121 + +#### 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. +- 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. +- A validation whose lanes overflow the run log's outcome record gets a fresh outcomes result branch automatically, so one Desktop spec with its setup lanes is no longer refused before launch. +- An API test lane needs no committed fixture. It runs with the environment the provider's CI step gives the same tests: `AWS_REGION` and `AWS_EXECUTION_ENV` blank and every other `AWS_` setting removed. The old fixture demanded test AWS keys that CI never sets and the repository's key schema rejects. +- A setup lane receives the Claude cloud marker, so the repository's own bootstrap knows it runs in the cloud. +- A cloud run may last up to 100 minutes instead of 35, under the 117 minutes one cloud session was measured to run, and one lane up to 60 minutes instead of 15, so a full Desktop e2e suite is no longer ended partway. +- A cloud Desktop lane may name no spec: the bare Desktop `test:e2e` command runs CI's whole suite step, unsharded, after the same pre-suite steps. +- Across all plugin Markdown, including eval prompts and graders, the release is about 0 words longer than v1.1.120. The count covers the source files in `plugins/vibe` and excludes the generated ClosedLoop edition. + ### vibe v1.1.120 #### Added diff --git a/plugins/vibe-closedloop-provider/.claude-plugin/plugin.json b/plugins/vibe-closedloop-provider/.claude-plugin/plugin.json index e1b2b2e0..b4438bb8 100644 --- a/plugins/vibe-closedloop-provider/.claude-plugin/plugin.json +++ b/plugins/vibe-closedloop-provider/.claude-plugin/plugin.json @@ -1,6 +1,6 @@ { "name": "vibe-closedloop-provider", "description": "ClosedLoop and symphony-alpha knowledge for vibe and fleet-orchestrator: tickets, plans, the code graph, repository memory and the symphony-alpha recipes. Build input for the vibe plugin: tools/vibe-closedloop-build assembles it into plugins/vibe-closedloop", - "version": "1.0.10", + "version": "1.0.11", "author": {"name": "ClosedLoop", "email": "support@closedloop.ai"} } diff --git a/plugins/vibe-closedloop-provider/.codex-plugin/plugin.json b/plugins/vibe-closedloop-provider/.codex-plugin/plugin.json index b1bf0014..e2277aa4 100644 --- a/plugins/vibe-closedloop-provider/.codex-plugin/plugin.json +++ b/plugins/vibe-closedloop-provider/.codex-plugin/plugin.json @@ -1,6 +1,6 @@ { "name": "vibe-closedloop-provider", - "version": "1.0.10", + "version": "1.0.11", "description": "ClosedLoop and symphony-alpha knowledge for vibe and fleet-orchestrator: tickets, plans, the code graph, repository memory and the symphony-alpha recipes. Build input for the vibe plugin: tools/vibe-closedloop-build assembles it into plugins/vibe-closedloop", "author": {"name": "ClosedLoop", "email": "support@closedloop.ai"}, "homepage": "https://github.com/closedloop-ai/claude-plugins", diff --git a/plugins/vibe-closedloop-provider/provider.json b/plugins/vibe-closedloop-provider/provider.json index b64cfdd8..718a7202 100644 --- a/plugins/vibe-closedloop-provider/provider.json +++ b/plugins/vibe-closedloop-provider/provider.json @@ -668,11 +668,12 @@ "desktopRoot": "apps/desktop", "apiDirectory": "apps/api", "apiTestPattern": "(?:^|[\\s;&|])pnpm(?: +--silent)? +(?:(?:--filter|-F)(?:=| +)[\"']?(?:api|@repo/api|\\.?/?apps/api)[\"']?|(?:--dir|-C)(?:=| +)[\"']?\\.?/?apps/api[\"']?) +(?:run +)?test(?:\\s|$)", - "apiFixture": "apps/api/.env.test", - "apiSetup": "apps/api/__tests__/setup.ts", - "apiWorkflow": ".github/workflows/pr-test.yml", + "apiEnvironment": { + "source": ".github/workflows/pr-test.yml Run tests", + "clear": "^AWS_", + "values": { "AWS_REGION": "", "AWS_EXECUTION_ENV": "" } + }, "rootServices": ["postgresql", "redis-server"], - "apiWorkflowPattern": "^\\s*run:\\s+pnpm\\s+--(?:filter(?:=| )api|dir(?:=| )apps/api)\\s+[^\\n]*--env-file(?:=| )apps/api/\\.env\\.test(?:\\s|$)", "setupScript": { "file": "skills/fleet-orchestrator/templates/cloud-env-setup-closedloop.md", "checks": ["zsh", "uv", "python313", "node24", "pnpm", "chromium1254", "display"] diff --git a/plugins/vibe-closedloop/.claude-plugin/plugin.json b/plugins/vibe-closedloop/.claude-plugin/plugin.json index 58750184..8ac02d85 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.120", + "version": "1.1.121", "dependencies": [ "closedloop-core", "vibe-core" diff --git a/plugins/vibe-closedloop/.codex-plugin/plugin.json b/plugins/vibe-closedloop/.codex-plugin/plugin.json index dd47f4a4..b42f5b2f 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.120", + "version": "1.1.121", "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 7a5b6755..9d53c6e7 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.120` contains 17 skills and 17 agents, and no hook manifest: the +Version `1.1.121` 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/lib/vibe/scripts/cloud-outcome-artifact.mjs b/plugins/vibe-closedloop/lib/vibe/scripts/cloud-outcome-artifact.mjs index 85321e19..474ba8c8 100644 --- a/plugins/vibe-closedloop/lib/vibe/scripts/cloud-outcome-artifact.mjs +++ b/plugins/vibe-closedloop/lib/vibe/scripts/cloud-outcome-artifact.mjs @@ -2,7 +2,9 @@ import { createHash } from "node:crypto"; import { capturedJson, jsonValueAt } from "./captured-json.mjs"; const MARKER = "VIBE_OUTCOMES_V1 "; +export const OUTCOMES_MARKER = MARKER.trim(); const LIMIT = 400; +export const OUTCOME_LOG_LIMIT = LIMIT; const HEX = /^[a-f0-9]{64}$/; const DIRECTORY = /^\/tmp\/vibe-lane-results-([a-zA-Z0-9]{6})$/; const CHECKS = [ 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 13504ad6..606cb4cf 100644 --- a/plugins/vibe-closedloop/lib/vibe/scripts/cloud-outcome-instruction.mjs +++ b/plugins/vibe-closedloop/lib/vibe/scripts/cloud-outcome-instruction.mjs @@ -1,7 +1,15 @@ +import { spawnSync } from "node:child_process"; import { createHash } from "node:crypto"; import { brotliCompressSync } from "node:zlib"; 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 { TOOL_REPO, validTool } from "./cloud-validation-environment.mjs"; +import { toolingRoot } from "./cloud-validation-recipes.mjs"; + +const SHA = /^[a-f0-9]{40}$/; /** Files required to execute the shipped outcome writer in a private directory. */ export const reporterFiles = Object.freeze([ @@ -34,6 +42,53 @@ export function hostReporter(request, lanes, key) { return { files: [...reporterFiles], key: outcomeKey, repository, probe, frozen, artifact }; } +/** + * The tooling commit that holds the installed reporter: the request's pinned runtime tool, else the commit Claude Code + * recorded when it installed this plugin's name and version (a Codex install of the same version has the same files). + * Null when neither exists; the in-cloud hash check refuses a commit whose reporter bytes differ. + */ +function reporterCommit(request) { + if (validTool(request.runtimeTool)) return request.runtimeTool.commit; + return recordedCommit() ?? commitUnderTest(request); +} + +function recordedCommit() { + let self; + try { self = pluginInstall(import.meta.url); } catch { return null; } + let registry; + try { registry = JSON.parse(readFileSync(path.join(os.homedir(), ".claude", "plugins", "installed_plugins.json"), "utf8")); } catch { return null; } + const records = registry?.plugins?.[`${self.name}@${pluginMarketplace(self)}`]; + const record = Array.isArray(records) ? records.find((entry) => entry?.version === self.version && SHA.test(entry?.gitCommitSha ?? "")) : null; + return record?.gitCommitSha ?? null; +} + +/** Validating the tooling repository itself: its commit under test serves when it holds exactly these reporter bytes. */ +function commitUnderTest(request) { + const commit = request.commit; + if (`https://github.com/${request.repository}.git` !== TOOL_REPO || !SHA.test(commit ?? "") || typeof request.worktree !== "string") return null; + const same = reporterFiles.every((name) => { + const shown = spawnSync("git", ["-C", request.worktree, "show", `${commit}:${toolingRoot}/lib/vibe/scripts/${name}`], { timeout: 30_000 }); + return shown.status === 0 && Buffer.compare(shown.stdout, readFileSync(new URL(name, import.meta.url))) === 0; + }); + return same ? commit : null; +} + +/** + * The reporter comes from its tooling commit by a short fetch the agent copies exactly, checked against the installed + * bytes. The inline payload (about 20 KB of base64) was one Sonnet could not copy, so a Desktop run whose five lanes + * all exited 0 returned no result (session cse_01H58iagT4c64SNRaKLqBbgw). + */ +function fetchedReporter(spec, commit) { + const root = toolingRoot + "/lib/vibe/scripts"; + const sha = createHash("sha256").update(Buffer.concat(reporterFiles.map((name) => readFileSync(new URL(name, import.meta.url))))).digest("hex"); + const dir = ".git/vibe-outcomes-" + commit.slice(0, 16); + const files = reporterFiles.join(" "); + const install = `(umask 077 && mkdir -p ${dir} && git fetch --no-tags ${TOOL_REPO} ${commit} && ` + + `for f in ${files}; do git show ${commit}:${root}/$f > ${dir}/$f || exit 1; done && test "$(cd ${dir} && cat ${files} | sha256sum | cut -c1-64)" = ${sha})`; + const packed = Buffer.from(JSON.stringify(spec)).toString("base64url"); + return { install, reporter: "node " + dir + "/cloud-outcome-writer.mjs " + packed + ' "$d"' }; +} + function portableReporter(spec) { const sources = Object.fromEntries( reporterFiles.map((name) => [name, readFileSync(new URL(name, import.meta.url), "utf8")]), @@ -68,7 +123,9 @@ export function outcomeInstruction(request, lanes, key, managedHost, compact = n : "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"); - const reporter=compact ?? portableReporter(outcomeSpec(request,lanes,key,managedHost)); + const spec = () => outcomeSpec(request,lanes,key,managedHost); + const commit = compact ? null : reporterCommit(request); + 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.", diff --git a/plugins/vibe-closedloop/lib/vibe/scripts/cloud-routines.mjs b/plugins/vibe-closedloop/lib/vibe/scripts/cloud-routines.mjs index a6134a81..fcb0ca8c 100644 --- a/plugins/vibe-closedloop/lib/vibe/scripts/cloud-routines.mjs +++ b/plugins/vibe-closedloop/lib/vibe/scripts/cloud-routines.mjs @@ -41,6 +41,13 @@ const STANDING_CRON = "0 0 1 1 *"; const TOKEN_LINE = "VIBE_ROUTINE_TOKEN"; /** Run records kept; proved removals are all kept (ids and times only), so an old receipt is never re-queued. */ const KEEP_RUNS = 200; +/** + * The documented cap on runs one routine may start in an hour (https://code.claude.com/docs/en/routines, "Usage and + * limits"). Only Claude enforces it: this machine's ledger held 41 runs started on one routine in one hour + * (2026-11-24), so nothing here counts runs before a launch; a run Claude refuses as rate-limited names this cap. + */ +const ROUTINE_RUNS_PER_HOUR = 30; +const RATE_LIMITED = 429; const ROUTINE_ID = /^[\w-]+$/; const RECEIPT_BYTES = 1024 * 1024; const LOCK_POLL_MS = 1000; @@ -56,8 +63,8 @@ const INTENT_LOOKUPS = 5; const SETTLED_INTENT_MS = 10 * 60 * 1000; /** Sends of one standing create: the first, and one fresh create when Claude Code refused the first before running it. */ const CREATE_ATTEMPTS = 2; -/** A run still marked started past this wall time ended without a mark (its poll gave up); the run limit is 35 minutes. */ -const RUN_WALL_MS = 35 * 60 * 1000; +/** A run still marked started past this wall time ended without a mark (its poll gave up); the run limit is 100 minutes (cloud-worker.mjs MAX_WALL_MS). */ +const RUN_WALL_MS = 100 * 60 * 1000; /** * The removal run's confinement, from Claude Code 2.1.323 (`claude --help` and its bundle): `--chrome` wires the * Claude in Chrome server into the dynamic MCP config, which `--strict-mcp-config` keeps while dropping every @@ -278,6 +285,7 @@ export async function runOnStanding({ remote, home = os.homedir(), environment, let started; try { started = remote("run", { trigger_id: standing.id }); } catch (error) { + if (error.httpStatus === RATE_LIMITED) throw hourlyLimit(error); if (![400,401,403,404].includes(error.httpStatus)) error.launchUncertain = true; throw error; } @@ -569,3 +577,8 @@ export async function adoptStanding({ home = os.homedir(), remote, id, waitMs = return ledger; }); } + +/** 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 }); +} 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 a34e05d3..b2d279ed 100644 --- a/plugins/vibe-closedloop/lib/vibe/scripts/cloud-validation-admission.mjs +++ b/plugins/vibe-closedloop/lib/vibe/scripts/cloud-validation-admission.mjs @@ -6,12 +6,19 @@ import { processIdentityStatus, readProcessIdentity } from "../../../shared/proc import { acquire, release } from "./e2e-lock.mjs"; import { regularJson, writeAtomic } from "./owned-state.mjs"; -// A standing routine owns its configuration and its current provider run until the run is terminal. -export const CLOUD_VALIDATION_CAPACITY = 1; +// 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. 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. +const LOCK_WAIT_FLOOR_MS = 5_000; const TERMINAL = new Set(["completed", "failed", "canceled", "cancelled", "archived"]); // Recovery's answers when the provider proves nothing: every read succeeded, or a read threw. const UNPROVEN = new Set(["unknown", "unreadable"]); @@ -29,11 +36,16 @@ function readQueue(file) { return state; } -/** Change one account's queue under its lock. */ -async function updateQueue(file, change) { +/** + * Change one account's queue under its lock, waiting for the lock up to `waitMs`. A queued request passes the time + * left before its own deadline: a fixed 5-second wait failed queued requests under contention while their deadlines + * had minutes left (two queued requests failed after 591 s and 32 s). + */ +async function updateQueue(file, change, waitMs = LOCK_WAIT_FLOOR_MS) { + mkdirSync(path.dirname(file), { recursive: true, mode: 0o700 }); const lock = path.join(path.dirname(file), "queue.lock"); const holder = { pid: process.pid, token: randomUUID(), purpose: "cloud-validation-queue" }; - const locked = await acquire(lock, holder, { waitSeconds: 5, pollMs: 10 }); + const locked = await acquire(lock, holder, { waitSeconds: Math.max(LOCK_WAIT_FLOOR_MS, waitMs) / 1000, pollMs: 10 }); if (!locked.acquired) throw new Error("cloud validation queue state is busy; retry the exact request"); try { const current = readQueue(file); @@ -56,6 +68,7 @@ function abandonedRecord(entry, reason) { export async function withCloudValidationAdmission({ home, account, 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, }, action) { const queues = queuesDir(home); // The first verified pin must wait for any earlier unbound provider run, including an interrupted launch. @@ -63,15 +76,24 @@ export async function withCloudValidationAdmission({ home, account, key, receipt await withCloudValidationAdmission({home, account:"unbound-validation", key:"drain:"+account+":"+key, receipt, metadata, timeoutMs,signal,recover,now,wait,sleepMs,report,identityOf,launchWindowMs,drainUnbound:true},async()=>{}); } - const dir = path.join(queues,identityKey(account)); - mkdirSync(dir, { recursive: true, mode: 0o700 }); - const file = path.join(dir, "queue.json"); + // 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 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 ${CLOUD_VALIDATION_CAPACITY}: one active validation per account; excess requests wait in order`); + 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); - const update = (change) => updateQueue(file, change); + 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, + // and still gets the request's whole queue budget so a busy lock never replaces the run's result. + const update = (change) => updateQueue(file, change, selected ? timeoutMs : deadline - now()); await update((state) => { const previous = state.queued.find((entry) => entry.key === key); @@ -79,15 +101,17 @@ export async function withCloudValidationAdmission({ home, account, key, receipt if (previous) Object.assign(previous, owner); else state.queued.push(owner); }); - let selected = false; let unresolved = false; // Admitted onto a receipt the person already abandoned: such a request refuses before any launch, so it holds nothing. let abandonedBefore = false; try { while (!selected) { signal?.throwIfAborted(); + // Each liveness check runs ps, so it reads an unlocked snapshot: run under the lock, every waiter's poll held it + // for one ps per queued entry. The atomic rename keeps the snapshot whole; only tokens it proved gone are dropped. + const goneTokens = new Set(readQueue(file).queued.filter((entry) => entry.token !== owner.token && !alive(entry)).map(({ token }) => token)); const active = await update((state) => { - const gone = state.queued.filter((entry) => entry.token !== owner.token && !alive(entry)); + const gone = state.queued.filter((entry) => goneTokens.has(entry.token)); state.queued = state.queued.filter((entry) => !gone.includes(entry)); state.abandoned = [...state.abandoned, ...gone.map(({ key: queuedKey }) => ({ key: queuedKey, reason: "owner exited before launch" }))].slice(-200); if (!state.active && state.queued[0]?.token === owner.token) { @@ -124,7 +148,15 @@ export async function withCloudValidationAdmission({ home, account, key, receipt }); } if (selected) break; - if (now() >= deadline) throw Object.assign(new Error(`${BUSY}: this request did not launch; retry the same request after the active reservation settles`), { code: BUSY }); + // 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 }); 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. diff --git a/plugins/vibe-closedloop/lib/vibe/scripts/cloud-validation-e2e.mjs b/plugins/vibe-closedloop/lib/vibe/scripts/cloud-validation-e2e.mjs index 26258d95..47552bd2 100644 --- a/plugins/vibe-closedloop/lib/vibe/scripts/cloud-validation-e2e.mjs +++ b/plugins/vibe-closedloop/lib/vibe/scripts/cloud-validation-e2e.mjs @@ -44,7 +44,7 @@ export function dockerStartCommand(recipe = cloudRecipe) { } /** - * The committed Desktop workflow's own pre-suite steps and suite wrapper, run for one spec: every + * The committed Desktop workflow's own pre-suite steps and suite wrapper, run for one spec or the whole suite: every * `run` step before the suite step in its job (for example verifying the Electron binary and building Desktop), each in * its working directory with its literal env, then the suite step itself with its test command narrowed to the spec, * so a D-Bus session and an unlocked keyring the suite step sets up are kept. A step the cloud cannot run as committed @@ -61,7 +61,8 @@ export function desktopSuiteCommand(workflow, directory, spec) { if (plan.suite.skip && !/expressions or secrets/.test(plan.suite.skip)) throw new Error(`CLOUD_E2E_UNAVAILABLE: the Desktop suite step cannot run in the cloud: ${plan.suite.skip}`); const calls = plan.suite.run.match(/pnpm test:e2e\b[^\n'";&|)]*/g) ?? []; if (calls.length !== 1) throw new Error("CLOUD_E2E_UNAVAILABLE: the Desktop suite step does not run exactly one pnpm test:e2e"); - const suite = plan.suite.run.replace(/pnpm test:e2e\b[^\n'";&|)]*/, `pnpm test:e2e ${spec}`); + // The test arguments (CI's shard selection) are replaced by the one spec, or dropped to run the whole suite. + const suite = plan.suite.run.replace(/pnpm test:e2e\b[^\n'";&|)]*/, spec ? `pnpm test:e2e ${spec}` : "pnpm test:e2e"); if (/\$\{\{/.test(suite)) throw new Error("CLOUD_E2E_UNAVAILABLE: the Desktop suite step needs GitHub expressions or secrets beyond its test arguments"); const step = ({ name, run, directory: dir, env }) => { const exports = Object.entries(env).filter(([key]) => /^[A-Za-z_][A-Za-z0-9_]*$/.test(key)).map(([key, value]) => `${key}=${quoted(value)}`); @@ -124,15 +125,22 @@ export function resolveCloudE2ELane(command, readCommitted) { return `(${dockerStartCommand()}; ${WEB_LIST})`; } const directory = cloudRecipe.desktopRoot; - const prefix = `pnpm --dir ${directory} test:e2e `; - if (!directory || typeof command !== "string" || !command.startsWith(prefix)) return null; - const argument = command.slice(prefix.length); - const spec = argument.startsWith(directory + "/") ? argument.slice(directory.length + 1) : argument; - if (!SPEC.test(spec) || spec.split("/").some((segment) => !segment || segment === "." || segment === "..")) return null; - committed(`${directory}/${spec}`); + const suite = `pnpm --dir ${directory} test:e2e`; + const prefix = `${suite} `; + if (!directory || typeof command !== "string" || (command !== suite && !command.startsWith(prefix))) return null; + // The bare command is CI's whole suite step, run as committed; any argument must name one spec. + const spec = command === suite ? null : specArgument(command.slice(prefix.length), directory); + if (spec === undefined) return null; + if (spec) committed(`${directory}/${spec}`); const workflow = committed(DESKTOP_WORKFLOW).toString("utf8"); if (!workflow.includes(DESKTOP_SUITE)) { throw new Error("CLOUD_E2E_UNAVAILABLE: the exact commit does not name the supported displayless Desktop workflow"); } return `(test "$(uname -s)" = Linux && command -v Xvfb >/dev/null && command -v xvfb-run >/dev/null && command -v xauth >/dev/null || ${unavailable("Desktop E2E requires the repository-supported Linux Xvfb and xauth harness.")}; ${desktopSuiteCommand(workflow, directory, spec)})`; } + +/** The one spec a Desktop lane argument names, relative to the Desktop root, or undefined when it names none. */ +function specArgument(argument, directory) { + const spec = argument.startsWith(directory + "/") ? argument.slice(directory.length + 1) : argument; + return SPEC.test(spec) && !spec.split("/").some((segment) => !segment || segment === "." || segment === "..") ? spec : undefined; +} 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 d3c05398..af7ce31e 100644 --- a/plugins/vibe-closedloop/lib/vibe/scripts/cloud-validation-environment.mjs +++ b/plugins/vibe-closedloop/lib/vibe/scripts/cloud-validation-environment.mjs @@ -1,12 +1,13 @@ 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 { createHash } from "node:crypto"; import { existsSync, renameSync } from "node:fs"; import path from "node:path"; import { recoverValidationReservation, withCloudValidationAdmission } from "./cloud-validation-admission.mjs"; import { withValidationReportLock } from "./cloud-validation-report.mjs"; import { TERMINAL } from "./cloud-receipts.mjs"; -import { canonicalCloudArgv, cloudTurboTasks, cloudTypecheckArgv, cloudApiEnvironment, routeArgv } from "./cloud-validation-host.mjs"; +import { canonicalCloudArgv, cloudTurboTasks, cloudTypecheckArgv, routeArgv } from "./cloud-validation-host.mjs"; import { restoreValidationRun } from "./cloud-routines.mjs"; import { CLOUD_CAPABILITIES_LANE, CLOUD_CAPABILITIES_COMMAND } from "./cloud-check-command.mjs"; import { checkEnvironmentPin } from "./cloud-account-pin.mjs"; @@ -19,7 +20,7 @@ const SHA = /^[a-f0-9]{40}$/; const PROOF_KEYS = ["workspace", "nonRoot", "ports", "chromium", "gitUtc"]; const OPTIONAL_PROOF_KEYS = ["controlNamespace", "chromium1254", "docker", "dockerBootstrap", "display", "zsh", "uv", "python313", "node24", "pnpm"]; const API_TEST = cloudRecipe.apiTestPattern ? new RegExp(cloudRecipe.apiTestPattern) : null; -const TOOL_REPO = "https://github.com/closedloop-ai/claude-plugins.git"; +export const TOOL_REPO = "https://github.com/closedloop-ai/claude-plugins.git"; const RUNNER = `${toolingRoot}/lib/vibe/scripts/cloud-validation-host.mjs`; 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; @@ -39,7 +40,7 @@ function proofPath(home, pin) { return path.join(home, ".codex", "vibe", "cloud", "runtime-proof", `${digest(`${pin.environmentId}\0${pin.accountUuid}`)}.json`); } -function validTool(tool) { +export function validTool(tool) { return SHA.test(tool?.commit ?? "") && SAFE_REF.test(tool?.ref ?? "") && !tool.ref.includes("..") && !tool.ref.includes("//") && !tool.ref.endsWith(".lock"); } @@ -135,7 +136,7 @@ export function describeCloudLanes(lanes, { read, commit } = {}) { const needsEnv = ordinary && commands.some((command) => API_TEST?.test(command)); if (needsEnv) capabilities.push("nonRoot"); return { ...lane, prerequisites: { packages: ordinary ? packages : [], capabilities: [...new Set(capabilities)], - env: needsEnv ? { kind: "api-test", source: typeof read === "function" ? cloudApiEnvironment(read, commit, cloudRecipe) : null } : null } }; + env: needsEnv ? { kind: "api-test" } : null } }; }); } @@ -152,9 +153,8 @@ export function admitCloudEnvironment(lanes, { home, environmentId, pin, current 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 problems = affected.flatMap(({ name, capabilities, env }) => { + const problems = affected.flatMap(({ name, capabilities }) => { const missing = capabilities.filter((key) => proof?.checks?.[key] !== true); - if (env && !env.source) missing.unshift("approved committed non-secret API test fixture"); const lane = lanes.find((entry) => entry.name === name); if (lane.workflow) missing.unshift("non-root workflow step execution"); return missing.length ? [`${name} (${missing.join(", ")})`] : []; @@ -232,7 +232,7 @@ export function cloudHostInstruction({ tool, affected }, { lanes, commit, report const plan = { commit, lanes: lanes.map((lane) => ({ name: lane.name, command: lane.command, prerequisite: lane.prerequisite === true, - browser: capability(lane.name, "chromium"), isolateControlPorts: capability(lane.name,"controlNamespace"), envSource: affected.find(({ name }) => name === lane.name)?.env?.source ?? null })), + browser: capability(lane.name, "chromium"), isolateControlPorts: capability(lane.name,"controlNamespace"), apiTest: affected.some(({ name, env }) => name === lane.name && env?.kind === "api-test") })), ...(reporter ? { reporter: { tool: tool.commit, root: toolingRoot, ...reporter } } : {}), }; const target = `.git/vibe-validation-host-${tool.commit}.mjs`; @@ -246,6 +246,10 @@ export function cloudHostInstruction({ tool, affected }, { lanes, commit, report `node ${target} ${quoted(JSON.stringify(plan))}`, `node ${target} lanes`, `Run each command above as its own Bash call, in order. The first runner call sets up the environment and writes ${target}.setup.out, then its exit code to ${target}.setup.exit; the second runs the requested lanes from the saved plan and writes ${target}.out, then ${target}.exit. When the Bash tool moves a runner call to the background, keep waiting in this turn: poll that call's exit file with a foreground \`until\` loop in later calls until it exists, then read its output file. Start the second call only after ${target}.setup.exit exists. Never end the turn, rerun a runner call or report lanes unrun while an exit file is missing. If a runner call is stopped before its exit file appears, read ${target}.progress, which holds each finished step's wall time, and report it.`, + // 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.`] : []), "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"); } 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 938b9382..5ca9d06f 100644 --- a/plugins/vibe-closedloop/lib/vibe/scripts/cloud-validation-host.mjs +++ b/plugins/vibe-closedloop/lib/vibe/scripts/cloud-validation-host.mjs @@ -4,7 +4,6 @@ import { appendFileSync, chmodSync, closeSync, copyFileSync, existsSync, fstatSy import os from "node:os"; import path from "node:path"; import { fileURLToPath } from "node:url"; -import { isDeepStrictEqual } from "node:util"; const NO_INPUT = "ignore"; const UNPRIVILEGED_FALLBACK = 65534; @@ -14,67 +13,24 @@ const WORKSPACE = /^[A-Za-z0-9_@./: +%=\[\]-]+$/; const BROWSER_VERSION = "1.65.0"; const BROWSER_STORE = "/opt/pw-browsers"; const HEADLESS_SHELL = path.join(BROWSER_STORE, "chromium_headless_shell-1254/chrome-headless-shell-linux64/chrome-headless-shell"); -const HOST_TIMEOUT = 15 * 60_000; +// One lane's process group ends here. The full Desktop e2e suite, run as the provider's CI step runs it (4 workers), +// took 22.8 min as one lane on a 4-core cloud VM, build included (cse_01H58iag4UozkuYjYfbQj9Pe, 2026-12-02), against +// 15.3 min on CI's 8 cores. 60 minutes leaves that suite room to grow and stays under the 100-minute run limit. +const HOST_TIMEOUT = 60 * 60_000; function digest(bytes) { return createHash("sha256").update(bytes).digest("hex"); } -const API_VALUES = { - AWS_ACCESS_KEY_ID: /^test-(?:aws-)?(?:access-)?key(?:-id)?$/, - AWS_SECRET_ACCESS_KEY: /^test-(?:aws-)?(?:secret-)?key$/, - AWS_REGION: /^(?:us|eu|ap|ca|sa|af|me|il|mx)-[a-z]+-[1-9]$/, -}; - -function optional(read, file) { - try { return read(file); } catch { return null; } -} - -function apiFixture(read, recipe) { - if (!recipe?.apiFixture || !recipe.apiWorkflowPattern) return null; - const { apiFixture: fixturePath, apiSetup: setupPath, apiWorkflow: workflowPath } = recipe; - const bytes = optional(read, fixturePath); - if (typeof bytes !== "string" || bytes.length > 512) return null; - const setup = optional(read, setupPath); - const workflow = optional(read, workflowPath); - const source = /^\s*(?:dotenv\.config|dotenvConfig)\s*\(\s*\{[^;]*["']\.env\.test["']/m.test(setup ?? "") ? setupPath - : new RegExp(recipe.apiWorkflowPattern, "m").test(workflow ?? "") ? workflowPath : null; - if (!source) return null; - const values = {}; - for (const raw of bytes.split(/\r?\n/)) { - const line = raw.trim(); - if (!line || line.startsWith("#")) continue; - const match = /^([A-Z_]+)=([a-z0-9-]+)$/.exec(line); - if (!match || Object.hasOwn(values, match[1]) || !Object.hasOwn(API_VALUES, match[1]) || !API_VALUES[match[1]].test(match[2])) return null; - values[match[1]] = match[2]; - } - const keys = Object.keys(values).sort(); - if (keys.length !== Object.keys(API_VALUES).length) return null; - return { metadata: { path: fixturePath, source, sha256: digest(bytes), sourceSha256: digest(source === setupPath ? setup : workflow), keys }, values }; -} - -/** Bind API test fixture metadata to exact committed bytes. Keep its values out of requests and receipts. */ -export function cloudApiEnvironment(read, commit, recipe) { - const fixture = apiFixture(read, recipe); - return fixture ? { ...fixture.metadata, commit } : null; -} - -function hostApiEnvironment(root, declaration, run, recipe, options) { - const read = (file) => { - const result = run("git", ["show", `HEAD:${file}`], options); - if (result.exitCode !== 0) throw new Error("approved fixture file is missing"); - return result.stdoutTail; - }; - const head = run("git", ["rev-parse", "HEAD"], options); - const fixture = apiFixture(read, recipe); - if (!fixture || head.exitCode !== 0 || declaration.commit !== head.stdoutTail.trim() || - !isDeepStrictEqual(declaration, { ...fixture.metadata, commit: declaration.commit })) return null; - return fixture.values; -} - -function redactFixture(result, values) { - for (const field of ["stdoutTail", "stderrTail", "diagnosis"]) { - for (const value of Object.values(values ?? {})) result[field] = String(result[field] ?? "").replaceAll(value, "[test fixture]"); - } - return result; +/** + * An API test lane runs with exactly the environment the provider's CI step gives the same tests: every key matching + * the recipe's `apiEnvironment.clear` pattern is removed from the lane, then its `values` are set. A committed fixture + * of test credentials contradicted that step, which sets no credentials, and the repository's own key schema. + */ +export function apiTestEnvironment(env, recipe) { + const contract = recipe?.apiEnvironment; + if (!contract || typeof contract.clear !== "string" || !contract.values || typeof contract.values !== "object") + throw new Error("the provider recipe declares no API test environment"); + const clear = new RegExp(contract.clear); + return { ...Object.fromEntries(Object.entries(env).filter(([key]) => !clear.test(key))), ...contract.values }; } /** Reserve an exclusive per-lane range in the cloud host's private state and release it only by exact owner. */ @@ -648,13 +604,17 @@ export function runCloudHostPlan({ checkout, directory, lanes, uid, gid, environ args.push("--concurrency=1",...forwarded); } if (command === "pnpm" && program === "typecheck") env.TURBO_TYPECHECK_CONCURRENCY = "1"; - const values = lane.envSource ? hostApiEnvironment(root, lane.envSource, run, contract?.data?.recipes?.cloudValidation,{cwd:root,env,...actor}) : null; - if (lane.envSource && !values) return skipped(lane.name, "approved committed non-secret test fixture differs; run on L2 (remote slot heavy)"); + let laneEnv = env; + try { if (lane.apiTest === true) laneEnv = apiTestEnvironment(env, contract?.data?.recipes?.cloudValidation); } + catch (error) { return skipped(lane.name, `${error.message}; run on L2 (remote slot heavy)`); } + // A setup lane runs the repository's own bootstrap, which tells a Claude cloud session from a local checkout by + // this marker; without it the bootstrap wrote local stub settings that the API lanes refuse. + if (lane.prerequisite === true && environment.CLAUDE_CODE_REMOTE === "true") laneEnv = { ...laneEnv, CLAUDE_CODE_REMOTE: "true" }; // Environment setup (the repository bootstrap and the workspace builds the lanes depend on) runs as root, and the // actor then owns what it wrote. As the actor, a workspace build's pnpm self-install of the pinned version stalled // with no CPU for 39 minutes while the same bootstrap finished in 37 s as root (r17). const rootSetup = asRoot && lane.prerequisite === true; - const options = rootSetup ? { cwd: root, env: rootSetupEnvironment({ ...env, ...values }, environment, root) } : { cwd: root, env: { ...env, ...values }, ...actor }; + const options = rootSetup ? { cwd: root, env: rootSetupEnvironment(laneEnv, environment, root) } : { cwd: root, env: laneEnv, ...actor }; if (command === "pnpm" && args.slice(0, 3).join(" ") === "control up web") { args.push("--app-port", String(ports.first), "--api-port", String(ports.first + 1)); } @@ -673,7 +633,7 @@ export function runCloudHostPlan({ checkout, directory, lanes, uid, gid, environ } if (rootSetup) { provision(root, actor); provision(home, actor); } if (lane.prerequisite && includingBrowser.exitCode !== 0) prerequisiteFailure = lane.name; - return { name: lane.name, ...redactFixture(includingBrowser, values), runtime: { uid: rootSetup ? 0 : actor.uid, ports: [ports.first, ports.last] } }; + return { name: lane.name, ...includingBrowser, runtime: { uid: rootSetup ? 0 : actor.uid, ports: [ports.first, ports.last] } }; }; // Each lane reports its own wall time as it ends, so a run cut off by a host limit still shows where the time went. return lanes.map((lane, index) => { diff --git a/plugins/vibe-closedloop/lib/vibe/scripts/cloud-worker.mjs b/plugins/vibe-closedloop/lib/vibe/scripts/cloud-worker.mjs index b2220823..b9820388 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, requireOutcomeCapacity, readOutcomeReport } from "./cloud-outcome-artifact.mjs"; +import { MACHINE_OUTCOMES, measuredProbeTranscript, withCarriedFailures, outcomeArtifact, checkOutcomeArtifact, OUTCOME_LOG_LIMIT, 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"; @@ -78,8 +78,11 @@ import { isEntryPoint } from "../../../shared/plugin-roots.mjs"; import { checkCloudcheckRequest, prepareCloudcheckProof } from "./cloudcheck-proof.mjs"; import { cloudPrProblem, completeFromCommit, importFromGit, importResult, readyForPr, refreshImportWitness, unconfirmed } from "./cloud-import.mjs"; -const MAX_WALL_MS = 35 * 60 * 1000; -const DEFAULT_WALL_MS = 35 * 60 * 1000; +// One Sonnet session on the pinned environment ran 117 minutes with no cutoff (cse_01H58iagWGazkKdUCDGCUQEh, +// 2026-12-02, 13 nine-minute tool calls, stopped by request); no longer session was tried, so 117 is a floor, not the +// platform's limit. A run, and a validation's queue wait, stay under it. +const MAX_WALL_MS = 100 * 60 * 1000; +const DEFAULT_WALL_MS = MAX_WALL_MS; const DEFAULT_POLL_MS = 30 * 1000; export const COMMAND_MS = 90 * 1000; /** @@ -194,7 +197,7 @@ export function validateRequest(request, rules = requestRules(request)) { } function checkPollingBounds(request) { - if (!Number.isInteger(request.maxWallMs ?? DEFAULT_WALL_MS) || (request.maxWallMs ?? DEFAULT_WALL_MS) < 1000 || (request.maxWallMs ?? DEFAULT_WALL_MS) > MAX_WALL_MS) throw new Error("maxWallMs must be between 1 second and 35 minutes"); + if (!Number.isInteger(request.maxWallMs ?? DEFAULT_WALL_MS) || (request.maxWallMs ?? DEFAULT_WALL_MS) < 1000 || (request.maxWallMs ?? DEFAULT_WALL_MS) > MAX_WALL_MS) throw new Error(`maxWallMs must be between 1 second and ${MAX_WALL_MS / 60_000} minutes`); if (!Number.isInteger(request.pollMs ?? DEFAULT_POLL_MS) || (request.pollMs ?? DEFAULT_POLL_MS) < 1000 || (request.pollMs ?? DEFAULT_POLL_MS) > 60_000) throw new Error("pollMs must be between 1 and 60 seconds"); } @@ -953,13 +956,25 @@ function deniedResult(log, error) { return denial ? new Error(`cloud validation session was denied permission to run a command: ${redactedLine(denial).slice(0, DIAGNOSIS_CHARS)} (${error.message})`) : error; } +/** + * A request whose resolved lanes, setup lanes validate adds included, overflow the run log's record gets a fresh + * outcomes artifact named from its commit and request digest, so the same request resumes the same branch. One + * Desktop spec resolves to five lanes and the log holds two, so every such request was refused before launch. + */ +function withOverflowArtifact(request, count, digest) { + if (request.resultArtifact !== undefined || outcomeTransportBytes(count) <= OUTCOME_LOG_LIMIT) return request; + return { ...request, resultArtifact: { kind: "validation-outcomes", path: `.vibe-validation-outcomes-${digest.slice(0, 16)}.json`, + branch: `vibe-validation-results/${request.commit.slice(0, 12)}-${digest.slice(0, 12)}` } }; +} + function validationReceiptPath(request, digest) { return path.join(gitDir(request.worktree), validationReceiptName(request.commit, digest)); } /** 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); - const routed = { ...request, repository: verifyRepository(request.worktree, request.repository) }; const digest = sha256(JSON.stringify(request)); + const verified = { ...request, repository: verifyRepository(request.worktree, request.repository) }; + const routed = withOverflowArtifact(verified, validationLanes(verified).lanes.length, digest); const file = validationReceiptPath(request, digest); const { lanes } = validationLanes(routed); const laneKeys = lanes.map(({ command }) => validationCommandKey(command)); @@ -971,10 +986,10 @@ export async function validateCommit(request, { remote = cliRemote(request.workt 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) { - if (!request.resultArtifact || outcomeArtifact(request)) requireOutcomeCapacity(lanes,outcomeArtifact(request)); - if (outcomeArtifact(request) && proofGit(request.worktree,["ls-remote","--refs","origin","refs/heads/"+request.resultArtifact.branch])) throw new Error("outcome proof branch already exists; supply a fresh resultArtifact branch before dispatch"); + 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(); - const outcomeTransport=request.resultArtifact && !outcomeArtifact(request) ? "eval-artifact" : MACHINE_OUTCOMES; + const outcomeTransport=routed.resultArtifact && !outcomeArtifact(routed) ? "eval-artifact" : MACHINE_OUTCOMES; 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; diff --git a/plugins/vibe-closedloop/provider/provider.json b/plugins/vibe-closedloop/provider/provider.json index 8c1e94c1..01c873c2 100644 --- a/plugins/vibe-closedloop/provider/provider.json +++ b/plugins/vibe-closedloop/provider/provider.json @@ -681,14 +681,18 @@ "desktopRoot": "apps/desktop", "apiDirectory": "apps/api", "apiTestPattern": "(?:^|[\\s;&|])pnpm(?: +--silent)? +(?:(?:--filter|-F)(?:=| +)[\"']?(?:api|@repo/api|\\.?/?apps/api)[\"']?|(?:--dir|-C)(?:=| +)[\"']?\\.?/?apps/api[\"']?) +(?:run +)?test(?:\\s|$)", - "apiFixture": "apps/api/.env.test", - "apiSetup": "apps/api/__tests__/setup.ts", - "apiWorkflow": ".github/workflows/pr-test.yml", + "apiEnvironment": { + "source": ".github/workflows/pr-test.yml Run tests", + "clear": "^AWS_", + "values": { + "AWS_REGION": "", + "AWS_EXECUTION_ENV": "" + } + }, "rootServices": [ "postgresql", "redis-server" ], - "apiWorkflowPattern": "^\\s*run:\\s+pnpm\\s+--(?:filter(?:=| )api|dir(?:=| )apps/api)\\s+[^\\n]*--env-file(?:=| )apps/api/\\.env\\.test(?:\\s|$)", "setupScript": { "file": "skills/fleet-orchestrator/templates/cloud-env-setup-closedloop.md", "checks": [ diff --git a/plugins/vibe/.claude-plugin/plugin.json b/plugins/vibe/.claude-plugin/plugin.json index 430957e4..cf5b195c 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.120", + "version": "1.1.121", "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 3208f5ee..2751095f 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.120", + "version": "1.1.121", "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 e4619f10..b9d73989 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.120` contains 17 skills and 17 agents, and no hook manifest: the +Version `1.1.121` 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/lib/vibe/scripts/cloud-creation-prevention.test.mjs b/plugins/vibe/lib/vibe/scripts/cloud-creation-prevention.test.mjs index 3c0d0cfb..c81a017d 100644 --- a/plugins/vibe/lib/vibe/scripts/cloud-creation-prevention.test.mjs +++ b/plugins/vibe/lib/vibe/scripts/cloud-creation-prevention.test.mjs @@ -8,6 +8,7 @@ import { confirmCloudEnvironment } from "./cloud-validation-environment.mjs"; import { checkCloudSetup } from "./cloud-environment.mjs"; import { ledgerPath, NO_EXECUTOR, readLedger, recordEnvironmentPin, runOnStanding } from "./cloud-routines.mjs"; import { createStreamDir, remoteTriggerPrompt } from "./cloud-trigger-stream.mjs"; +import { writeAtomic } from "./owned-state.mjs"; import { remoteTrigger, validateCommit } from "./cloud-worker.mjs"; import { git, makeCheckout, makeHome } from "../../../../vibe/skills/vibe/scripts/test-fixtures.mjs"; @@ -321,3 +322,50 @@ test("the check command derives the live account itself and fails a changed or u fake(`printf '%s' '{"loggedIn":true,"authMethod":"claude.ai","storedClaudeAiLogin":true,"accountUuid":"${PINNED}"}'; exit 0`); assert.equal(check().row?.ok, true, "the pinned account and environment match"); }); + +// ISS-15038: every launch on a machine runs its one standing routine, and a routine may start 30 runs an hour; past that +// the provider fails the run. The thirty-first launch waits for the window when it can, and otherwise says why. +test("ISS-15038 a routine that started 41 runs in the last hour still launches: the platform's own refusal is the only limit", async (t) => { + const fixture = makeHome("vibe-routine-hourly-"); + t.after(fixture.cleanup); + const { home } = fixture; + await recordEnvironmentPin({ home, environmentId: ENV, accountUuid: ACCOUNT }); + const clock = Date.parse("2026-11-24T03:18:20Z"); + let runs = 0; + const actions = [], slept = []; + const remote = (action) => { + actions.push(action); + if (action === "create" || action === "update") return { trigger: { id: "standing", mcp_connections: [] } }; + if (action === "run") return { run_id: `run-${++runs}` }; + assert.fail("unexpected remote operation " + action); + }; + const start = () => runOnStanding({ home, remote, account: () => ACCOUNT, environment: { id: ENV }, ccr: { environment_id: ENV }, + brief: "harmless fixture", waitMs: 60_000, now: () => clock, sleep: async (ms) => { slept.push(ms); } }); + await start(); + const ledger = readLedger(home); + // A real ledger hour: 41 runs on one standing routine between 02:18 and 03:18Z on 2026-11-24, 37 of them completed. + ledger.runs = Array.from({ length: 41 }, (_, index) => ({ ...ledger.runs[0], runId: `past-${index}`, sessionId: `past-${index}`, + startedAt: new Date(clock - (41 - index) * 87_000).toISOString(), status: index < 37 ? "completed" : "started" })); + writeAtomic(ledgerPath(home), ledger); + actions.length = 0; + const started = await start(); + assert.equal(started.runId, "run-2"); + assert.deepEqual(actions, ["update", "run"]); + assert.deepEqual(slept, [], "no launch waits on a count of earlier runs"); +}); + +test("ISS-15038 a run the platform refuses as rate-limited surfaces the documented hourly cap and when to retry", async (t) => { + const fixture = makeHome("vibe-routine-rate-"); + t.after(fixture.cleanup); + const { home } = fixture; + await recordEnvironmentPin({ home, environmentId: ENV, accountUuid: ACCOUNT }); + const remote = (action) => { + if (action === "create" || action === "update") return { trigger: { id: "standing", mcp_connections: [] } }; + if (action === "run") throw Object.assign(new Error("RemoteTrigger run failed: HTTP 429 Too Many Requests"), { httpStatus: 429 }); + assert.fail("unexpected remote operation " + action); + }; + await assert.rejects(runOnStanding({ home, remote, account: () => ACCOUNT, environment: { id: ENV }, ccr: { environment_id: ENV }, + brief: "harmless fixture", waitMs: 60_000 }), (error) => error.code === "CLOUD_ROUTINE_HOURLY_LIMIT" && error.launchUncertain !== true + && /^CLOUD_ROUTINE_HOURLY_LIMIT: Claude refused the run as rate-limited \(HTTP 429\)\. A routine may start 30 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$/.test(error.message)); + assert.equal(readLedger(home).runs.length, 0, "a refused run is never recorded as started"); +}); diff --git a/plugins/vibe/lib/vibe/scripts/cloud-outcome-artifact.mjs b/plugins/vibe/lib/vibe/scripts/cloud-outcome-artifact.mjs index 85321e19..474ba8c8 100644 --- a/plugins/vibe/lib/vibe/scripts/cloud-outcome-artifact.mjs +++ b/plugins/vibe/lib/vibe/scripts/cloud-outcome-artifact.mjs @@ -2,7 +2,9 @@ import { createHash } from "node:crypto"; import { capturedJson, jsonValueAt } from "./captured-json.mjs"; const MARKER = "VIBE_OUTCOMES_V1 "; +export const OUTCOMES_MARKER = MARKER.trim(); const LIMIT = 400; +export const OUTCOME_LOG_LIMIT = LIMIT; const HEX = /^[a-f0-9]{64}$/; const DIRECTORY = /^\/tmp\/vibe-lane-results-([a-zA-Z0-9]{6})$/; const CHECKS = [ diff --git a/plugins/vibe/lib/vibe/scripts/cloud-outcome-instruction.mjs b/plugins/vibe/lib/vibe/scripts/cloud-outcome-instruction.mjs index 13504ad6..606cb4cf 100644 --- a/plugins/vibe/lib/vibe/scripts/cloud-outcome-instruction.mjs +++ b/plugins/vibe/lib/vibe/scripts/cloud-outcome-instruction.mjs @@ -1,7 +1,15 @@ +import { spawnSync } from "node:child_process"; import { createHash } from "node:crypto"; import { brotliCompressSync } from "node:zlib"; 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 { TOOL_REPO, validTool } from "./cloud-validation-environment.mjs"; +import { toolingRoot } from "./cloud-validation-recipes.mjs"; + +const SHA = /^[a-f0-9]{40}$/; /** Files required to execute the shipped outcome writer in a private directory. */ export const reporterFiles = Object.freeze([ @@ -34,6 +42,53 @@ export function hostReporter(request, lanes, key) { return { files: [...reporterFiles], key: outcomeKey, repository, probe, frozen, artifact }; } +/** + * The tooling commit that holds the installed reporter: the request's pinned runtime tool, else the commit Claude Code + * recorded when it installed this plugin's name and version (a Codex install of the same version has the same files). + * Null when neither exists; the in-cloud hash check refuses a commit whose reporter bytes differ. + */ +function reporterCommit(request) { + if (validTool(request.runtimeTool)) return request.runtimeTool.commit; + return recordedCommit() ?? commitUnderTest(request); +} + +function recordedCommit() { + let self; + try { self = pluginInstall(import.meta.url); } catch { return null; } + let registry; + try { registry = JSON.parse(readFileSync(path.join(os.homedir(), ".claude", "plugins", "installed_plugins.json"), "utf8")); } catch { return null; } + const records = registry?.plugins?.[`${self.name}@${pluginMarketplace(self)}`]; + const record = Array.isArray(records) ? records.find((entry) => entry?.version === self.version && SHA.test(entry?.gitCommitSha ?? "")) : null; + return record?.gitCommitSha ?? null; +} + +/** Validating the tooling repository itself: its commit under test serves when it holds exactly these reporter bytes. */ +function commitUnderTest(request) { + const commit = request.commit; + if (`https://github.com/${request.repository}.git` !== TOOL_REPO || !SHA.test(commit ?? "") || typeof request.worktree !== "string") return null; + const same = reporterFiles.every((name) => { + const shown = spawnSync("git", ["-C", request.worktree, "show", `${commit}:${toolingRoot}/lib/vibe/scripts/${name}`], { timeout: 30_000 }); + return shown.status === 0 && Buffer.compare(shown.stdout, readFileSync(new URL(name, import.meta.url))) === 0; + }); + return same ? commit : null; +} + +/** + * The reporter comes from its tooling commit by a short fetch the agent copies exactly, checked against the installed + * bytes. The inline payload (about 20 KB of base64) was one Sonnet could not copy, so a Desktop run whose five lanes + * all exited 0 returned no result (session cse_01H58iagT4c64SNRaKLqBbgw). + */ +function fetchedReporter(spec, commit) { + const root = toolingRoot + "/lib/vibe/scripts"; + const sha = createHash("sha256").update(Buffer.concat(reporterFiles.map((name) => readFileSync(new URL(name, import.meta.url))))).digest("hex"); + const dir = ".git/vibe-outcomes-" + commit.slice(0, 16); + const files = reporterFiles.join(" "); + const install = `(umask 077 && mkdir -p ${dir} && git fetch --no-tags ${TOOL_REPO} ${commit} && ` + + `for f in ${files}; do git show ${commit}:${root}/$f > ${dir}/$f || exit 1; done && test "$(cd ${dir} && cat ${files} | sha256sum | cut -c1-64)" = ${sha})`; + const packed = Buffer.from(JSON.stringify(spec)).toString("base64url"); + return { install, reporter: "node " + dir + "/cloud-outcome-writer.mjs " + packed + ' "$d"' }; +} + function portableReporter(spec) { const sources = Object.fromEntries( reporterFiles.map((name) => [name, readFileSync(new URL(name, import.meta.url), "utf8")]), @@ -68,7 +123,9 @@ export function outcomeInstruction(request, lanes, key, managedHost, compact = n : "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"); - const reporter=compact ?? portableReporter(outcomeSpec(request,lanes,key,managedHost)); + const spec = () => outcomeSpec(request,lanes,key,managedHost); + const commit = compact ? null : reporterCommit(request); + 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.", 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 24e9d232..17fefee3 100644 --- a/plugins/vibe/lib/vibe/scripts/cloud-outcome-transport.test.mjs +++ b/plugins/vibe/lib/vibe/scripts/cloud-outcome-transport.test.mjs @@ -395,3 +395,123 @@ test("AC-65 a prose word after the artifact marker is not a second pointer, whil { path: ".vibe-validation-outcomes-12345678.json", branch: "vibe-validation-results/fixture", commit: "a".repeat(40), sha256: "b".repeat(64) }); assert.throws(() => artifactPointer(`VIBE_OUTCOME_ARTIFACT ${pointer}\nVIBE_OUTCOME_ARTIFACT ${"c".repeat(40)}:${"d".repeat(63)}`, request), /no unique complete result artifact pointer/); }); + +// ISS-15038: Desktop lanes in session cse_01H58iagT4c64SNRaKLqBbgw all exited 0, yet the Sonnet agent could not copy +// the ~20 KB inline reporter payload ("about 20 KB of base64 that I can't reproduce exactly"), so no result arrived. +async function fetchedReporterRun(t, { pinned, underTest = false }) { + const { execFileSync } = await import("node:child_process"); + const { mkdirSync, mkdtempSync, readFileSync, realpathSync, rmSync, writeFileSync } = await import("node:fs"); + const { tmpdir } = await import("node:os"); + const path = (await import("node:path")).default; + const { git, makeCheckout, makeHome } = await import("../../../skills/vibe/scripts/test-fixtures.mjs"); + const { reporterFiles } = await import("./cloud-outcome-instruction.mjs"); + const { TOOL_REPO } = await import("./cloud-validation-environment.mjs"); + const { toolingRoot } = await import("./cloud-validation-recipes.mjs"); + const { MACHINE_OUTCOMES } = await import("./cloud-outcome-artifact.mjs"); + const { pluginInstall, pluginMarketplace } = await import("../../../shared/plugin-roots.mjs"); + const fixture = makeHome("outcome-fetched-reporter-"); + t.after(fixture.cleanup); + let repository = "example/widgets"; + let worktree = path.join(fixture.root, "checkout"); + makeCheckout({ ...fixture, checkout: worktree, remoteUrl: `https://github.com/${repository}.git` }); + const rewrite = git(worktree, ["config", "--name-only", "--get-regexp", "^url\\..*\\.insteadof$"], fixture.home); + git(worktree, ["config", "--unset", rewrite], fixture.home); + let commit = git(worktree, ["rev-parse", "HEAD"], fixture.home); + // The tooling repository at the pinned commit holds the installed reporter bytes; insteadOf keeps the network out. + const tools = path.join(fixture.root, "tools"); + git(fixture.root, ["init", "--quiet", "--initial-branch=main", tools], fixture.home); + git(tools, ["config", "uploadpack.allowAnySHA1InWant", "true"], fixture.home); + for (const name of reporterFiles) { + const file = path.join(tools, toolingRoot, "lib/vibe/scripts", name); + mkdirSync(path.dirname(file), { recursive: true }); + writeFileSync(file, readFileSync(new URL(name, import.meta.url))); + } + git(tools, ["add", "-A"], fixture.home); + git(tools, ["commit", "--quiet", "-m", "tools"], fixture.home); + const toolCommit = git(tools, ["rev-parse", "HEAD"], fixture.home); + git(worktree, ["config", `url.${tools}.insteadOf`, TOOL_REPO], fixture.home); + // Validating the tooling repository itself: the commit under test is the one that holds the reporter. + if (underTest) { + [repository, worktree, commit] = ["closedloop-ai/claude-plugins", tools, toolCommit]; + // The SSH form: the HTTPS one would be rewritten to the local fixture by the insteadOf above. + git(worktree, ["remote", "add", "origin", "git@github.com:closedloop-ai/claude-plugins.git"], fixture.home); + git(worktree, ["config", `url.${tools}.insteadOf`, TOOL_REPO], fixture.home); + } + const request = { worktree, repository, provider: "claude", branch: "main", commit, model: "claude-sonnet-5-5", + lanes: [{ name: "desktop-spec", command: "node --test desktop.test.mjs" }], + ...(pinned ? { runtimeTool: { commit: toolCommit, ref: "refs/heads/main" } } : {}) }; + const key = createHash("sha256").update(JSON.stringify(request)).digest("hex"); + // Without a runtime tool, the commit is the one Claude Code recorded installing this plugin's name and version. + const self = pluginInstall(new URL("./cloud-outcome-instruction.mjs", import.meta.url)); + mkdirSync(path.join(fixture.home, ".claude", "plugins"), { recursive: true }); + writeFileSync(path.join(fixture.home, ".claude", "plugins", "installed_plugins.json"), JSON.stringify({ version: 2, + plugins: underTest ? {} : { [`${self.name}@${pluginMarketplace(self)}`]: [{ scope: "user", version: self.version, gitCommitSha: toolCommit }] } })); + const home = process.env.HOME; + process.env.HOME = fixture.home; + let paragraphs; + try { paragraphs = validationBrief(request, null, null, key).split("\n\n"); } + finally { process.env.HOME = home; } + const install = paragraphs[paragraphs.indexOf("Install the shipped machine reporter:") + 1]; + const reporter = paragraphs.find((paragraph) => /^node \.git\/vibe-outcomes-[a-f0-9]{16}\/cloud-outcome-writer\.mjs /.test(paragraph)); + for (const command of [install, reporter]) assert.ok(command.length < 1_000, `a ${command.length}-character command is not one an agent copies by hand`); + // The agent copies each command verbatim, as Sonnet did every short one in that session. + const bash = (script, env = {}) => execFileSync("bash", ["-c", script], { cwd: worktree, encoding: "utf8", + env: { ...process.env, HOME: fixture.home, CLAUDE_CODE_REMOTE: "true", ...env }, stdio: ["ignore", "pipe", "pipe"] }); + bash(install); + // The brief's `mktemp -d /tmp/vibe-lane-results-XXXXXX`, in this machine's real temporary folder. + const d = mkdtempSync(path.join(realpathSync(tmpdir()), "vibe-lane-results-")); + t.after(() => rmSync(d, { recursive: true, force: true })); + writeFileSync(path.join(d, "0.stdout"), "1 passing\n"); + writeFileSync(path.join(d, "0.stderr"), ""); + writeFileSync(path.join(d, "0.json"), JSON.stringify({ name: "desktop-spec", exitCode: 0 })); + const record = bash(reporter, { d }).split("\n")[0]; + const transcript = [ + "[2026-12-02T21:58:12.573896Z] tool_use Bash: {\"command\":\"cd /home/user/widgets; d=$(cat /tmp/vibe_d)\"}", + `[2026-12-02T21:58:12.929780Z] tool_result: ${record}`, + `[2026-12-02T21:58:18.068176Z] assistant: ${record}`, + `[2026-12-02T21:58:18.210003Z] result: success is_error=false turns=7 duration=192s — ${record}`, + ].join("\n"); + const result = parseValidationResult(transcript, request, { outcomeTransport: MACHINE_OUTCOMES, requestKey: key }); + assert.deepEqual(result.lanes.map(({ name, exitCode, passed }) => ({ name, exitCode, passed })), [{ name: "desktop-spec", exitCode: 0, passed: true }]); + assert.equal(result.passed, true); +} + +test("ISS-15038 a pinned runtime tool's reporter installs from a short fetch, and a Sonnet-shaped run of the brief's commands records the exit-0 lane passed", (t) => fetchedReporterRun(t, { pinned: true })); + +test("ISS-15038 without a runtime tool the reporter installs from the commit Claude Code recorded for this plugin version", (t) => fetchedReporterRun(t, { pinned: false })); + +// ISS-15038: a capabilities run validates the tooling repository and names no runtime tool; on a version Claude Code +// had not recorded, Sonnet could not copy the inline payload (session cse_01H58iag7KD1LBPagjEP3oA5). +test("ISS-15038 validating the tooling repository itself installs the reporter from the commit under test", (t) => fetchedReporterRun(t, { pinned: false, underTest: true })); + +// ISS-15038: a single Desktop spec resolves to five lanes once validate adds its setup lanes, past the run log's two, +// so every fleet Desktop request without a hand-picked resultArtifact was refused before launch. +test("ISS-15038 validate picks a fresh outcomes artifact itself when the resolved lanes overflow the run log", async (t) => { + const path = (await import("node:path")).default; + const { git, makeCheckout, makeHome } = await import("../../../skills/vibe/scripts/test-fixtures.mjs"); + const { validateCommit } = await import("./cloud-worker.mjs"); + const { NO_EXECUTOR } = await import("./cloud-routines.mjs"); + const f = makeHome("vibe-auto-outcomes-artifact-"); + t.after(f.cleanup); + const repository = "example/widgets"; + const worktree = path.join(f.root, "checkout"); + makeCheckout({ ...f, checkout: worktree, remoteUrl: `https://github.com/${repository}.git` }); + const commit = git(worktree, ["rev-parse", "HEAD"], f.home); + const request = { commit, worktree, repository, provider: "claude", model: "claude-sonnet-5-5", branch: "main", + claudeEnvironment: "env_01AutoArtifactFixture", lanes: ["one", "two", "three"].map((name) => ({ name, command: `node --test ${name}.test.mjs` })) }; + const stop = new Error("stopped at the provider boundary"); + let brief; + const remote = (action, payload) => { + if (action === "create") return { trigger: { id: "standing", mcp_connections: [] } }; + if (action === "update") { brief = payload.body.job_config.ccr.events[0].data.message.content; throw stop; } + assert.fail(action); + }; + const lsRemote = []; + const proofGit = (_worktree, args) => { lsRemote.push(args); return ""; }; + await assert.rejects(validateCommit(request, { remote, home: f.home, executor: NO_EXECUTOR, proofGit }), (error) => error === stop); + await assert.rejects(validateCommit(request, { remote, home: f.home, executor: NO_EXECUTOR, proofGit }), (error) => error === stop); + 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/); +}); diff --git a/plugins/vibe/lib/vibe/scripts/cloud-routines.mjs b/plugins/vibe/lib/vibe/scripts/cloud-routines.mjs index a6134a81..fcb0ca8c 100644 --- a/plugins/vibe/lib/vibe/scripts/cloud-routines.mjs +++ b/plugins/vibe/lib/vibe/scripts/cloud-routines.mjs @@ -41,6 +41,13 @@ const STANDING_CRON = "0 0 1 1 *"; const TOKEN_LINE = "VIBE_ROUTINE_TOKEN"; /** Run records kept; proved removals are all kept (ids and times only), so an old receipt is never re-queued. */ const KEEP_RUNS = 200; +/** + * The documented cap on runs one routine may start in an hour (https://code.claude.com/docs/en/routines, "Usage and + * limits"). Only Claude enforces it: this machine's ledger held 41 runs started on one routine in one hour + * (2026-11-24), so nothing here counts runs before a launch; a run Claude refuses as rate-limited names this cap. + */ +const ROUTINE_RUNS_PER_HOUR = 30; +const RATE_LIMITED = 429; const ROUTINE_ID = /^[\w-]+$/; const RECEIPT_BYTES = 1024 * 1024; const LOCK_POLL_MS = 1000; @@ -56,8 +63,8 @@ const INTENT_LOOKUPS = 5; const SETTLED_INTENT_MS = 10 * 60 * 1000; /** Sends of one standing create: the first, and one fresh create when Claude Code refused the first before running it. */ const CREATE_ATTEMPTS = 2; -/** A run still marked started past this wall time ended without a mark (its poll gave up); the run limit is 35 minutes. */ -const RUN_WALL_MS = 35 * 60 * 1000; +/** A run still marked started past this wall time ended without a mark (its poll gave up); the run limit is 100 minutes (cloud-worker.mjs MAX_WALL_MS). */ +const RUN_WALL_MS = 100 * 60 * 1000; /** * The removal run's confinement, from Claude Code 2.1.323 (`claude --help` and its bundle): `--chrome` wires the * Claude in Chrome server into the dynamic MCP config, which `--strict-mcp-config` keeps while dropping every @@ -278,6 +285,7 @@ export async function runOnStanding({ remote, home = os.homedir(), environment, let started; try { started = remote("run", { trigger_id: standing.id }); } catch (error) { + if (error.httpStatus === RATE_LIMITED) throw hourlyLimit(error); if (![400,401,403,404].includes(error.httpStatus)) error.launchUncertain = true; throw error; } @@ -569,3 +577,8 @@ export async function adoptStanding({ home = os.homedir(), remote, id, waitMs = return ledger; }); } + +/** 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 }); +} 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 7c972d8b..43f87476 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 @@ -56,8 +56,11 @@ async function killedLauncher(t, signal, acknowledged) { return { ...f, receipt, held }; } -/** Request `key` asking for admission 15 minutes after the launch, past LAUNCH_WINDOW_MS, with `remote` as the provider. */ -const admitLater = (f, key, receipt, remote, action) => withCloudValidationAdmission({ home: f.home, account: ACCOUNT, key, receipt, metadata: {}, timeoutMs: 300, sleepMs: 20, +/** + * 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. + */ +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 BUSY = { code: "CLOUD_VALIDATION_QUEUE_TIMEOUT" }; diff --git a/plugins/vibe/lib/vibe/scripts/cloud-validation-admission.mjs b/plugins/vibe/lib/vibe/scripts/cloud-validation-admission.mjs index a34e05d3..b2d279ed 100644 --- a/plugins/vibe/lib/vibe/scripts/cloud-validation-admission.mjs +++ b/plugins/vibe/lib/vibe/scripts/cloud-validation-admission.mjs @@ -6,12 +6,19 @@ import { processIdentityStatus, readProcessIdentity } from "../../../shared/proc import { acquire, release } from "./e2e-lock.mjs"; import { regularJson, writeAtomic } from "./owned-state.mjs"; -// A standing routine owns its configuration and its current provider run until the run is terminal. -export const CLOUD_VALIDATION_CAPACITY = 1; +// 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. 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. +const LOCK_WAIT_FLOOR_MS = 5_000; const TERMINAL = new Set(["completed", "failed", "canceled", "cancelled", "archived"]); // Recovery's answers when the provider proves nothing: every read succeeded, or a read threw. const UNPROVEN = new Set(["unknown", "unreadable"]); @@ -29,11 +36,16 @@ function readQueue(file) { return state; } -/** Change one account's queue under its lock. */ -async function updateQueue(file, change) { +/** + * Change one account's queue under its lock, waiting for the lock up to `waitMs`. A queued request passes the time + * left before its own deadline: a fixed 5-second wait failed queued requests under contention while their deadlines + * had minutes left (two queued requests failed after 591 s and 32 s). + */ +async function updateQueue(file, change, waitMs = LOCK_WAIT_FLOOR_MS) { + mkdirSync(path.dirname(file), { recursive: true, mode: 0o700 }); const lock = path.join(path.dirname(file), "queue.lock"); const holder = { pid: process.pid, token: randomUUID(), purpose: "cloud-validation-queue" }; - const locked = await acquire(lock, holder, { waitSeconds: 5, pollMs: 10 }); + const locked = await acquire(lock, holder, { waitSeconds: Math.max(LOCK_WAIT_FLOOR_MS, waitMs) / 1000, pollMs: 10 }); if (!locked.acquired) throw new Error("cloud validation queue state is busy; retry the exact request"); try { const current = readQueue(file); @@ -56,6 +68,7 @@ function abandonedRecord(entry, reason) { export async function withCloudValidationAdmission({ home, account, 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, }, action) { const queues = queuesDir(home); // The first verified pin must wait for any earlier unbound provider run, including an interrupted launch. @@ -63,15 +76,24 @@ export async function withCloudValidationAdmission({ home, account, key, receipt await withCloudValidationAdmission({home, account:"unbound-validation", key:"drain:"+account+":"+key, receipt, metadata, timeoutMs,signal,recover,now,wait,sleepMs,report,identityOf,launchWindowMs,drainUnbound:true},async()=>{}); } - const dir = path.join(queues,identityKey(account)); - mkdirSync(dir, { recursive: true, mode: 0o700 }); - const file = path.join(dir, "queue.json"); + // 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 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 ${CLOUD_VALIDATION_CAPACITY}: one active validation per account; excess requests wait in order`); + 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); - const update = (change) => updateQueue(file, change); + 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, + // and still gets the request's whole queue budget so a busy lock never replaces the run's result. + const update = (change) => updateQueue(file, change, selected ? timeoutMs : deadline - now()); await update((state) => { const previous = state.queued.find((entry) => entry.key === key); @@ -79,15 +101,17 @@ export async function withCloudValidationAdmission({ home, account, key, receipt if (previous) Object.assign(previous, owner); else state.queued.push(owner); }); - let selected = false; let unresolved = false; // Admitted onto a receipt the person already abandoned: such a request refuses before any launch, so it holds nothing. let abandonedBefore = false; try { while (!selected) { signal?.throwIfAborted(); + // Each liveness check runs ps, so it reads an unlocked snapshot: run under the lock, every waiter's poll held it + // for one ps per queued entry. The atomic rename keeps the snapshot whole; only tokens it proved gone are dropped. + const goneTokens = new Set(readQueue(file).queued.filter((entry) => entry.token !== owner.token && !alive(entry)).map(({ token }) => token)); const active = await update((state) => { - const gone = state.queued.filter((entry) => entry.token !== owner.token && !alive(entry)); + const gone = state.queued.filter((entry) => goneTokens.has(entry.token)); state.queued = state.queued.filter((entry) => !gone.includes(entry)); state.abandoned = [...state.abandoned, ...gone.map(({ key: queuedKey }) => ({ key: queuedKey, reason: "owner exited before launch" }))].slice(-200); if (!state.active && state.queued[0]?.token === owner.token) { @@ -124,7 +148,15 @@ export async function withCloudValidationAdmission({ home, account, key, receipt }); } if (selected) break; - if (now() >= deadline) throw Object.assign(new Error(`${BUSY}: this request did not launch; retry the same request after the active reservation settles`), { code: BUSY }); + // 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 }); 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. 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 af2bc3f2..f1f97933 100644 --- a/plugins/vibe/lib/vibe/scripts/cloud-validation-admission.test.mjs +++ b/plugins/vibe/lib/vibe/scripts/cloud-validation-admission.test.mjs @@ -1,5 +1,5 @@ import assert from "node:assert/strict"; -import { existsSync, mkdirSync, readFileSync, realpathSync, rmSync, writeFileSync } from "node:fs"; +import { existsSync, mkdirSync, readdirSync, readFileSync, realpathSync, rmSync, writeFileSync } from "node:fs"; import path from "node:path"; import test from "node:test"; import { capturedJson } from "./captured-json.mjs"; @@ -7,12 +7,14 @@ import { setTimeout as sleep } from "node:timers/promises"; import { git, makeCheckout, makeHome } from "../../../../vibe/skills/vibe/scripts/test-fixtures.mjs"; 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 {machineTestReport} from "./cloud-outcome-test-fixture.mjs"; import { abandonValidation, pollTask, remoteTrigger, 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); @@ -20,7 +22,7 @@ function fixture(t) { 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), ...options, + identityOf: () => "mock-process-start", recover: () => "terminal", report: (line) => lines.push(line), capacity: 1, ...options, }, action); return { home: f.home, receipt, lines, execute }; } @@ -55,6 +57,43 @@ test("ISS-14476 ten concurrent cloud requests each fire once at declared one-run 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"); + 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 }) => { + 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) => { + 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 f = fixture(t); let begin; @@ -279,6 +318,80 @@ test("queued validations launch in the order they arrived once the active one re 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"); + // Each liveness check runs ps in production; under the lock it serialized every waiter's poll behind them. Only the + // one waiting request polls while counting, so a lock present during a check is that request's own. + let counting = false; + let checks = 0; + let underLock = 0; + const identityOf = () => { + if (counting) { checks++; if (existsSync(lock())) underLock++; } + return "mock-process-start"; + }; + let release; + const held = new Promise((resolve) => { release = resolve; }); + 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 }); + 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" }; + assert.equal((await acquire(lock(), peer, { waitSeconds: 5, pollMs: 1 })).acquired, true); + writeAtomic(queueFile(f.home), { ...queueState(f.home), queued: [...queueState(f.home).queued, + { token: "live-peer", pid: process.pid, identity: "mock-process-start", key: "live-peer", receipt: f.receipt("live-peer") }] }); + releaseLock(lock(), peer); + counting = true; + await sleep(100); + counting = false; + release(); + assert.deepEqual(await Promise.all([first, waiter]), [undefined, "launched"]); + assert.ok(checks > 0); + assert.equal(underLock, 0); +}); + +test("ISS-15038 a launched request past its queue deadline still releases the account 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" }; + // The run outlasts its 8 s queue budget, then a peer holds the lock longer than the 5 s floor. + const run = f.execute("long-run", async ({ launching }) => { + await launching(); + await sleep(9_000); + assert.equal((await acquire(lock(), peer, { waitSeconds: 5, pollMs: 1 })).acquired, true); + setTimeout(() => releaseLock(lock(), peer), 6_000); + return "finished"; + }, { timeoutMs: 8_000 }); + assert.equal(await run, "finished"); + assert.equal(queueState(f.home).active, null); +}); + const LAUNCH = { routineId: "standing", launchToken: "93383742-95da-42d3-9ace-2d1fcf6dbf8e" }; const lostLaunch = (message) => Object.assign(new Error(message), { code: "CLOUD_CALL_TIMEOUT" }); diff --git a/plugins/vibe/lib/vibe/scripts/cloud-validation-e2e.mjs b/plugins/vibe/lib/vibe/scripts/cloud-validation-e2e.mjs index 26258d95..47552bd2 100644 --- a/plugins/vibe/lib/vibe/scripts/cloud-validation-e2e.mjs +++ b/plugins/vibe/lib/vibe/scripts/cloud-validation-e2e.mjs @@ -44,7 +44,7 @@ export function dockerStartCommand(recipe = cloudRecipe) { } /** - * The committed Desktop workflow's own pre-suite steps and suite wrapper, run for one spec: every + * The committed Desktop workflow's own pre-suite steps and suite wrapper, run for one spec or the whole suite: every * `run` step before the suite step in its job (for example verifying the Electron binary and building Desktop), each in * its working directory with its literal env, then the suite step itself with its test command narrowed to the spec, * so a D-Bus session and an unlocked keyring the suite step sets up are kept. A step the cloud cannot run as committed @@ -61,7 +61,8 @@ export function desktopSuiteCommand(workflow, directory, spec) { if (plan.suite.skip && !/expressions or secrets/.test(plan.suite.skip)) throw new Error(`CLOUD_E2E_UNAVAILABLE: the Desktop suite step cannot run in the cloud: ${plan.suite.skip}`); const calls = plan.suite.run.match(/pnpm test:e2e\b[^\n'";&|)]*/g) ?? []; if (calls.length !== 1) throw new Error("CLOUD_E2E_UNAVAILABLE: the Desktop suite step does not run exactly one pnpm test:e2e"); - const suite = plan.suite.run.replace(/pnpm test:e2e\b[^\n'";&|)]*/, `pnpm test:e2e ${spec}`); + // The test arguments (CI's shard selection) are replaced by the one spec, or dropped to run the whole suite. + const suite = plan.suite.run.replace(/pnpm test:e2e\b[^\n'";&|)]*/, spec ? `pnpm test:e2e ${spec}` : "pnpm test:e2e"); if (/\$\{\{/.test(suite)) throw new Error("CLOUD_E2E_UNAVAILABLE: the Desktop suite step needs GitHub expressions or secrets beyond its test arguments"); const step = ({ name, run, directory: dir, env }) => { const exports = Object.entries(env).filter(([key]) => /^[A-Za-z_][A-Za-z0-9_]*$/.test(key)).map(([key, value]) => `${key}=${quoted(value)}`); @@ -124,15 +125,22 @@ export function resolveCloudE2ELane(command, readCommitted) { return `(${dockerStartCommand()}; ${WEB_LIST})`; } const directory = cloudRecipe.desktopRoot; - const prefix = `pnpm --dir ${directory} test:e2e `; - if (!directory || typeof command !== "string" || !command.startsWith(prefix)) return null; - const argument = command.slice(prefix.length); - const spec = argument.startsWith(directory + "/") ? argument.slice(directory.length + 1) : argument; - if (!SPEC.test(spec) || spec.split("/").some((segment) => !segment || segment === "." || segment === "..")) return null; - committed(`${directory}/${spec}`); + const suite = `pnpm --dir ${directory} test:e2e`; + const prefix = `${suite} `; + if (!directory || typeof command !== "string" || (command !== suite && !command.startsWith(prefix))) return null; + // The bare command is CI's whole suite step, run as committed; any argument must name one spec. + const spec = command === suite ? null : specArgument(command.slice(prefix.length), directory); + if (spec === undefined) return null; + if (spec) committed(`${directory}/${spec}`); const workflow = committed(DESKTOP_WORKFLOW).toString("utf8"); if (!workflow.includes(DESKTOP_SUITE)) { throw new Error("CLOUD_E2E_UNAVAILABLE: the exact commit does not name the supported displayless Desktop workflow"); } return `(test "$(uname -s)" = Linux && command -v Xvfb >/dev/null && command -v xvfb-run >/dev/null && command -v xauth >/dev/null || ${unavailable("Desktop E2E requires the repository-supported Linux Xvfb and xauth harness.")}; ${desktopSuiteCommand(workflow, directory, spec)})`; } + +/** The one spec a Desktop lane argument names, relative to the Desktop root, or undefined when it names none. */ +function specArgument(argument, directory) { + const spec = argument.startsWith(directory + "/") ? argument.slice(directory.length + 1) : argument; + return SPEC.test(spec) && !spec.split("/").some((segment) => !segment || segment === "." || segment === "..") ? spec : undefined; +} diff --git a/plugins/vibe/lib/vibe/scripts/cloud-validation-e2e.test.mjs b/plugins/vibe/lib/vibe/scripts/cloud-validation-e2e.test.mjs index da88291a..0d1b2895 100644 --- a/plugins/vibe/lib/vibe/scripts/cloud-validation-e2e.test.mjs +++ b/plugins/vibe/lib/vibe/scripts/cloud-validation-e2e.test.mjs @@ -304,6 +304,26 @@ test("ISS-14874 AC-4 a Desktop lane runs the committed workflow's pre-suite step assert.doesNotMatch(failed.stdout, /test:e2e/); }); +test("ISS-15038 the bare Desktop suite command runs CI's whole suite step, unnarrowed, after the same pre-suite steps", (t) => { + const f = fixture(t); + for (const name of ["Xvfb", "xauth"]) f.command(name, "exit 0"); + f.command("uname", "printf '%s\\n' Linux"); + const lane = validationLanes(f.request("pnpm --dir apps/desktop test:e2e")).lanes[0]; + const run = f.run(lane.cloudE2E); + assert.equal(run.status, 0, run.stderr); + assert.deepEqual(run.stdout.trim().split("\n"), [ + "SAFE-DESKTOP-RUNNER electron-check BUILD_MODE= DIR=desktop", + "SAFE-DESKTOP-RUNNER build BUILD_MODE=e2e DIR=desktop", + "DBUS-SESSION", + "KEYRING-UNLOCKED", + "SAFE-DISPLAYLESS-RUNNER", + "SAFE-DESKTOP-RUNNER test:e2e BUILD_MODE= DIR=desktop", + ], "the suite step runs as CI wrote it, with no spec and no shard argument"); + for (const argv of ["pnpm --dir apps/desktop test:e2e ", "pnpm --dir apps/desktop test:e2e --workers=4"]) { + assert.throws(() => validateValidationRequest(f.request(argv)), /Cloud E2E lanes/); + } +}); + test("ISS-14874 AC-4 a Desktop lane from the real workflow layout skips its runner-file and multi-line apt steps and reaches the suite", (t) => { const f = fixture(t); const command = desktopSuiteCommand(REAL_DESKTOP_WORKFLOW, "apps/desktop", "test/e2e/approved.spec.ts"); diff --git a/plugins/vibe/lib/vibe/scripts/cloud-validation-environment.mjs b/plugins/vibe/lib/vibe/scripts/cloud-validation-environment.mjs index d3c05398..af7ce31e 100644 --- a/plugins/vibe/lib/vibe/scripts/cloud-validation-environment.mjs +++ b/plugins/vibe/lib/vibe/scripts/cloud-validation-environment.mjs @@ -1,12 +1,13 @@ 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 { createHash } from "node:crypto"; import { existsSync, renameSync } from "node:fs"; import path from "node:path"; import { recoverValidationReservation, withCloudValidationAdmission } from "./cloud-validation-admission.mjs"; import { withValidationReportLock } from "./cloud-validation-report.mjs"; import { TERMINAL } from "./cloud-receipts.mjs"; -import { canonicalCloudArgv, cloudTurboTasks, cloudTypecheckArgv, cloudApiEnvironment, routeArgv } from "./cloud-validation-host.mjs"; +import { canonicalCloudArgv, cloudTurboTasks, cloudTypecheckArgv, routeArgv } from "./cloud-validation-host.mjs"; import { restoreValidationRun } from "./cloud-routines.mjs"; import { CLOUD_CAPABILITIES_LANE, CLOUD_CAPABILITIES_COMMAND } from "./cloud-check-command.mjs"; import { checkEnvironmentPin } from "./cloud-account-pin.mjs"; @@ -19,7 +20,7 @@ const SHA = /^[a-f0-9]{40}$/; const PROOF_KEYS = ["workspace", "nonRoot", "ports", "chromium", "gitUtc"]; const OPTIONAL_PROOF_KEYS = ["controlNamespace", "chromium1254", "docker", "dockerBootstrap", "display", "zsh", "uv", "python313", "node24", "pnpm"]; const API_TEST = cloudRecipe.apiTestPattern ? new RegExp(cloudRecipe.apiTestPattern) : null; -const TOOL_REPO = "https://github.com/closedloop-ai/claude-plugins.git"; +export const TOOL_REPO = "https://github.com/closedloop-ai/claude-plugins.git"; const RUNNER = `${toolingRoot}/lib/vibe/scripts/cloud-validation-host.mjs`; 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; @@ -39,7 +40,7 @@ function proofPath(home, pin) { return path.join(home, ".codex", "vibe", "cloud", "runtime-proof", `${digest(`${pin.environmentId}\0${pin.accountUuid}`)}.json`); } -function validTool(tool) { +export function validTool(tool) { return SHA.test(tool?.commit ?? "") && SAFE_REF.test(tool?.ref ?? "") && !tool.ref.includes("..") && !tool.ref.includes("//") && !tool.ref.endsWith(".lock"); } @@ -135,7 +136,7 @@ export function describeCloudLanes(lanes, { read, commit } = {}) { const needsEnv = ordinary && commands.some((command) => API_TEST?.test(command)); if (needsEnv) capabilities.push("nonRoot"); return { ...lane, prerequisites: { packages: ordinary ? packages : [], capabilities: [...new Set(capabilities)], - env: needsEnv ? { kind: "api-test", source: typeof read === "function" ? cloudApiEnvironment(read, commit, cloudRecipe) : null } : null } }; + env: needsEnv ? { kind: "api-test" } : null } }; }); } @@ -152,9 +153,8 @@ export function admitCloudEnvironment(lanes, { home, environmentId, pin, current 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 problems = affected.flatMap(({ name, capabilities, env }) => { + const problems = affected.flatMap(({ name, capabilities }) => { const missing = capabilities.filter((key) => proof?.checks?.[key] !== true); - if (env && !env.source) missing.unshift("approved committed non-secret API test fixture"); const lane = lanes.find((entry) => entry.name === name); if (lane.workflow) missing.unshift("non-root workflow step execution"); return missing.length ? [`${name} (${missing.join(", ")})`] : []; @@ -232,7 +232,7 @@ export function cloudHostInstruction({ tool, affected }, { lanes, commit, report const plan = { commit, lanes: lanes.map((lane) => ({ name: lane.name, command: lane.command, prerequisite: lane.prerequisite === true, - browser: capability(lane.name, "chromium"), isolateControlPorts: capability(lane.name,"controlNamespace"), envSource: affected.find(({ name }) => name === lane.name)?.env?.source ?? null })), + browser: capability(lane.name, "chromium"), isolateControlPorts: capability(lane.name,"controlNamespace"), apiTest: affected.some(({ name, env }) => name === lane.name && env?.kind === "api-test") })), ...(reporter ? { reporter: { tool: tool.commit, root: toolingRoot, ...reporter } } : {}), }; const target = `.git/vibe-validation-host-${tool.commit}.mjs`; @@ -246,6 +246,10 @@ export function cloudHostInstruction({ tool, affected }, { lanes, commit, report `node ${target} ${quoted(JSON.stringify(plan))}`, `node ${target} lanes`, `Run each command above as its own Bash call, in order. The first runner call sets up the environment and writes ${target}.setup.out, then its exit code to ${target}.setup.exit; the second runs the requested lanes from the saved plan and writes ${target}.out, then ${target}.exit. When the Bash tool moves a runner call to the background, keep waiting in this turn: poll that call's exit file with a foreground \`until\` loop in later calls until it exists, then read its output file. Start the second call only after ${target}.setup.exit exists. Never end the turn, rerun a runner call or report lanes unrun while an exit file is missing. If a runner call is stopped before its exit file appears, read ${target}.progress, which holds each finished step's wall time, and report it.`, + // 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.`] : []), "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"); } 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 cbf38aed..ca385843 100644 --- a/plugins/vibe/lib/vibe/scripts/cloud-validation-environment.test.mjs +++ b/plugins/vibe/lib/vibe/scripts/cloud-validation-environment.test.mjs @@ -106,14 +106,14 @@ test("ISS-14476 validate names unsupported lanes before any cloud create, update assert.deepEqual(calls, []); }); -const API_FIXTURE = "apps/api/.env.test"; -const API_SETUP = "apps/api/__tests__/setup.ts"; const API_COMMAND = "pnpm --filter api test"; -const FIXTURE_REGION = "us-west-2"; -const FIXTURE = ["AWS_ACCESS_KEY_ID=test-access-key-id", "AWS_SECRET_ACCESS_KEY=test-secret-key", "AWS_REGION=" + FIXTURE_REGION].join("\n") + "\n"; -const USE_FIXTURE = "dotenv.config({ path: path.resolve(__dirname, '../', '.env.test') });\n"; +// What the provider CI step gives the API tests (pr-test.yml "Run tests"): both blank, and no AWS credential at all. +const CI_API_VALUES = { AWS_REGION: "", AWS_EXECUTION_ENV: "" }; +const STALE_FIXTURE = ["AWS_ACCESS_KEY_ID=test-access-key-id", "AWS_SECRET_ACCESS_KEY=test-secret-key", "AWS_REGION=us-west-2"].join("\n") + "\n"; -test("ISS-14476 API command refuses before provider creation unless committed test settings are approved", async (t) => { +// ISS-15038: the committed fixture contract demanded test AWS keys that the provider CI step never sets and the +// repository's key schema rejects, so every API test lane was refused for a missing fixture. +test("ISS-15038 an API test lane needs no committed fixture and is admitted on the capability proof alone", async (t) => { const f = makeHome("vibe-api-env-"); t.after(f.cleanup); const worktree = path.join(f.root, "checkout"); @@ -121,42 +121,24 @@ test("ISS-14476 API command refuses before provider creation unless committed te makeCheckout({ ...f, checkout: worktree, remoteUrl: `https://github.com/${repository}.git` }); const request = { worktree, commit: git(worktree, ["rev-parse", "HEAD"], f.home), branch: "proof", model: "claude-sonnet-5-5", provider: "claude", repository, claudeEnvironment: ENV, lanes: [{ name: "api-unit", command: API_COMMAND }], runtimeTool: TOOL }; - const calls = []; - const clients = { home: f.home, remote: (action) => { calls.push(action); throw new Error("unexpected provider call"); } }; - await assert.rejects(() => validateCommit(request, clients), /api-unit.*approved committed non-secret API test fixture.*run on L2 \(remote slot heavy\)/); - await assert.rejects(() => validateCommit({ ...request, env: {} }, clients), /caller test environment values are refused/); - assert.deepEqual(calls, []); - for (const [file, text] of [[API_FIXTURE, FIXTURE], [API_SETUP, USE_FIXTURE]]) { - mkdirSync(path.dirname(path.join(worktree, file)), { recursive: true }); - writeFileSync(path.join(worktree, file), text); - } - assert.equal(validationLanes(request).lanes[0].prerequisites.env.source, null, "worktree-only input cannot satisfy exact-commit admission"); - git(worktree, ["add", "--", API_FIXTURE, API_SETUP], f.home); - git(worktree, ["commit", "-qm", "test: add approved public API fixture"], f.home); - const commit = git(worktree, ["rev-parse", "HEAD"], f.home); - const lanes = validationLanes({ ...request, commit }).lanes; - assert.equal(lanes[0].prerequisites.env.source.commit, commit); - assert.equal(lanes[0].prerequisites.env.source.source, API_SETUP); - assert.deepEqual(lanes[0].prerequisites.env.source.keys, ["AWS_ACCESS_KEY_ID", "AWS_REGION", "AWS_SECRET_ACCESS_KEY"]); - assert.doesNotMatch(JSON.stringify(lanes), /test-secret-key|test-access-key-id|us-west-2/); + await assert.rejects(() => validateCommit({ ...request, env: {} }, { home: f.home, remote: () => assert.fail("provider call") }), + /caller test environment values are refused/); + const lanes = validationLanes(request).lanes; + assert.deepEqual(lanes[0].prerequisites.env, { kind: "api-test" }); assert.equal(confirmCloudEnvironment({ home: f.home, pin: PIN, environmentId: ENV, tool: TOOL, completed: true, sessionId: "session-exact-approved", now: NOW, outcome: { name: "cloud-capabilities", exitCode: 0, stdoutTail: `CLOUD_HOST_RUNTIME ${JSON.stringify({ commit: TOOL.commit, checks: CHECKS })}` } }), true); assert.equal(admitCloudEnvironment(lanes, { home: f.home, pin: PIN, tool: TOOL, environmentId: ENV, - currentAccount: PIN.accountUuid, now: NOW }).affected[0].env.source.commit, commit); + currentAccount: PIN.accountUuid, now: NOW }).affected[0].name, "api-unit"); + assert.throws(() => admitCloudEnvironment(lanes, { home: "/nonexistent", pin: PIN, tool: TOOL, environmentId: ENV, currentAccount: PIN.accountUuid, now: NOW }), + (error) => /api-unit \(nonRoot/.test(error.message) && !/fixture/.test(error.message), "without the proof only the measured capability is missing"); }); -test("ISS-14476 classifies each lane and refuses incomplete, excessive, credential-looking, and unrelated settings", () => { +test("ISS-14476 classifies each lane, and a committed fixture file never changes an API test lane", () => { const command = { name: "api-test", command: API_COMMAND }; - const describe = (fixture, setup) => describeCloudLanes([command], { commit: "c".repeat(40), - read: (file) => ({ [API_FIXTURE]: fixture, [API_SETUP]: setup })[file], - })[0].prerequisites; - for (const [fixture, setup] of [ - [null, USE_FIXTURE], [FIXTURE, "// " + USE_FIXTURE], [FIXTURE, USE_FIXTURE.replace(".env.test", ".env.local")], - [FIXTURE.replace(/^AWS_REGION=.*$/m, ""), USE_FIXTURE], [FIXTURE + "NEW_KEY=test-extra\n", USE_FIXTURE], - [FIXTURE + "AWS_REGION=us-east-1\n", USE_FIXTURE], [FIXTURE.replace("test-access-key-id", "AK" + "IA1111111111111111"), USE_FIXTURE], - ]) { - assert.deepEqual(describe(fixture, setup), { packages: [], capabilities: ["nonRoot"], env: { kind: "api-test", source: null } }); + for (const read of [undefined, () => STALE_FIXTURE, () => { throw new Error("absent"); }]) { + assert.deepEqual(describeCloudLanes([command], { commit: "c".repeat(40), read })[0].prerequisites, + { packages: [], capabilities: ["nonRoot"], env: { kind: "api-test" } }); } const classified = describeCloudLanes([ { name: "setup:build", command: "pnpm --filter @repo/required build", prerequisite: true }, @@ -173,82 +155,77 @@ test("ISS-14476 classifies each lane and refuses incomplete, excessive, credenti assert.equal(classified[4].prerequisites.env.kind, "api-test"); }); -test("ISS-14476 host imports exact approved bytes for the lane and redacts fixture values from evidence", (t) => { - const f = makeHome("vibe-approved-host-fixture-"); +test("ISS-15038 the host runs an API test lane with the CI step's environment and no AWS credential from anywhere", (t) => { + const f = makeHome("vibe-api-host-env-"); t.after(f.cleanup); const checkout = path.join(f.root, "checkout"); - const commit = "f".repeat(40); mkdirSync(checkout); - const fixtureFiles = { [API_FIXTURE]: FIXTURE, [API_SETUP]: USE_FIXTURE }; - const [{ prerequisites: { env } }] = describeCloudLanes([{ name: "api", command: API_COMMAND }], { - read: (file) => fixtureFiles[file], commit, - }); const calls = []; - let observedCommit = commit; - const run = (command, args, options) => { - if (command === "git") { - assert.equal(options.uid,1000); - assert.equal(options.gid,1000); - const stdoutTail = args[0] === "rev-parse" ? observedCommit + "\n" : fixtureFiles[args[1].slice(5)]; - return { exitCode: stdoutTail ? 0 : 1, stdoutTail }; - } - calls.push({ command, args, env: options.env }); - return { exitCode: 0, stdoutTail: options.env.AWS_ACCESS_KEY_ID, stderrTail: options.env.AWS_SECRET_ACCESS_KEY, diagnosis: options.env.AWS_REGION }; - }; - const execute = (directory, envSource) => { - const work = path.join(f.root, directory); - mkdirSync(work); - return runCloudHostPlan({ checkout, directory: work, contract: installedProviders()[0].contract, lanes: [{ name: "api", command: API_COMMAND, envSource }], - uid: 1000, gid: 1000, run, environment: { AWS_ACCESS_KEY_ID: "never-inherit" } })[0]; - }; - const passed = execute("accepted", env.source); - assert.equal(passed.exitCode, 0); - assert.deepEqual(calls.map(({ command, args }) => [command, ...args]), [["pnpm", "--filter", "api", "test"]]); - assert.equal(calls[0].env.AWS_REGION, FIXTURE_REGION); - assert.equal(calls[0].env.AWS_ACCESS_KEY_ID, "test-access-key-id"); - assert.doesNotMatch(JSON.stringify(passed), /test-secret-key|test-access-key-id|us-west-2|never-inherit/); - const wrongSource = execute("wrong-source", { ...env.source, source: ".env.local" }); - assert.equal(wrongSource.exitCode, null); - assert.match(wrongSource.notRun, /fixture differs.*run on L2/); - observedCommit = "b".repeat(40); - assert.equal(execute("stale-commit", env.source).exitCode, null); - observedCommit = commit; - fixtureFiles[API_FIXTURE] = FIXTURE.replace("us-west-2", "us-west-1"); - assert.equal(execute("mismatched-digest", env.source).exitCode, null); - assert.equal(calls.length, 1); + const run = (command, args, options) => { calls.push({ command, args, env: options.env }); return { exitCode: 0, stdoutTail: "", stderrTail: "" }; }; + const lanes = describeCloudLanes([{ name: "api", command: API_COMMAND }, { name: "web", command: "pnpm --filter app test" }]); + const instructions = cloudHostInstruction({ tool: TOOL, affected: lanes.map((l) => ({ name: l.name, ...l.prerequisites })) }, { lanes, commit: TOOL.commit }); + assert.match(instructions, /"name":"api","command":"pnpm --filter api test",[^}]*"apiTest":true/); + assert.match(instructions, /"name":"web","command":"pnpm --filter app test",[^}]*"apiTest":false/); + const plan = { lanes: [{ name: "api", command: API_COMMAND, apiTest: true }, { name: "web", command: "pnpm --filter app test", apiTest: false }] }; + const work = path.join(f.root, "work"); + mkdirSync(work); + const results = runCloudHostPlan({ checkout, directory: work, contract: installedProviders()[0].contract, lanes: plan.lanes, uid: 1000, gid: 1000, run, + environment: { AWS_ACCESS_KEY_ID: "AKIAHOSTKEY000000000", AWS_SECRET_ACCESS_KEY: "host-secret", AWS_SESSION_TOKEN: "host-token", AWS_PROFILE: "host", PATH: process.env.PATH, + HTTPS_PROXY: "http://proxy.invalid:3128" } }); + assert.deepEqual(results.map(({ exitCode }) => exitCode), [0, 0]); + const [api, web] = calls; + assert.deepEqual(Object.fromEntries(Object.entries(api.env).filter(([key]) => key.startsWith("AWS_"))), CI_API_VALUES); + assert.equal(api.env.HTTPS_PROXY, "http://proxy.invalid:3128", "the host network settings still reach the lane"); + assert.equal(Object.keys(web.env).some((key) => key.startsWith("AWS_")), false, "other lanes get no AWS setting either"); }); -test("both control filters and the pkgs-a group consume the measured namespace capability", ()=>{ - for(const [name,command] of [["control","pnpm -F @repo/control test"],["control","pnpm --filter @repo/control test"],["pkgs-a","pnpm test"]]){ - const lane = name === "pkgs-a" ? {name, workflow:{}, command:JSON.stringify({workflow:{}, job:{steps:[{run:command}]}})} : {name,command}; - const lanes=describeCloudLanes([lane]); - assert.ok(lanes[0].prerequisites.capabilities.includes("controlNamespace")); - const instructions=cloudHostInstruction({tool:TOOL,affected:lanes.map(l=>({name:l.name,...l.prerequisites}))},{lanes,commit:TOOL.commit}); - assert.match(instructions,/"isolateControlPorts":true/); +test("ISS-15038 only a setup lane receives the Claude cloud marker, so the repository bootstrap knows where it runs", (t) => { + const f = makeHome("vibe-setup-marker-"); + t.after(f.cleanup); + const checkout = path.join(f.root, "checkout"), work = path.join(f.root, "work"); + mkdirSync(checkout); + mkdirSync(work); + const seen = {}; + const run = (command, args, options) => { seen[args.at(-1)] = options.env.CLAUDE_CODE_REMOTE; return { exitCode: 0, stdoutTail: "", stderrTail: "" }; }; + const provider = installedProviders()[0].contract, recipes = provider.data.recipes; + const contract = { ...provider, data: { ...provider.data, recipes: { ...recipes, cloudValidation: { ...recipes.cloudValidation, rootServices: [] } } } }; + const lanes = [{ name: "setup:repo-bootstrap", command: "pnpm --filter @scope/setup build", prerequisite: true }, + { name: "api", command: API_COMMAND, apiTest: true }, { name: "unit", command: "pnpm --filter app test" }]; + for (const remote of ["true", undefined]) { + runCloudHostPlan({ checkout, directory: work, contract, lanes, uid: 1000, gid: 1000, run, provision: () => {}, + environment: { PATH: process.env.PATH, ...(remote ? { CLAUDE_CODE_REMOTE: remote } : {}) } }); + assert.deepEqual(seen, { build: remote, test: undefined }, `with the marker ${remote}`); } }); -test("committed API fixture Git reads run as the real checkout owner", t => { - const f = makeHome("vibe-actor-git-"); +test("an API test lane's real process sees blank AWS settings and no inherited credential", t => { + const f = makeHome("vibe-actor-api-env-"); t.after(f.cleanup); const checkout = path.join(f.root,"checkout"), directory = path.join(f.root,"work"); chmodSync(f.root,0o711); mkdirSync(directory,{mode:0o711}); - const files = {[API_FIXTURE]:FIXTURE,[API_SETUP]:USE_FIXTURE, - "verify.cjs":"process.exitCode=process.getuid() > 0 && process.env.AWS_REGION ? 0 : 1"}; + const files = {"apps/api/.env.test":STALE_FIXTURE, + "verify.cjs":"const aws=Object.keys(process.env).filter(k=>k.startsWith('AWS_')).sort().join(',');process.exitCode=aws==='AWS_EXECUTION_ENV,AWS_REGION'&&process.env.AWS_REGION===''&&process.env.AWS_EXECUTION_ENV===''?0:1"}; makeCheckout({...f,checkout,files}); - const commit = git(checkout,["rev-parse","HEAD"],f.home); - const [{prerequisites:{env}}] = describeCloudLanes([{name:"api",command:API_COMMAND}], - {read:file=>files[file],commit}); - // The fixture's lane needs no database: as root the runner would otherwise start the provider's real declared services. + // The lane needs no database: as root the runner would otherwise start the provider's real declared services. const provider = installedProviders()[0].contract, recipes = provider.data.recipes; const contract = {...provider,data:{...provider.data,recipes:{...recipes,cloudValidation:{...recipes.cloudValidation,rootServices:[]}}}}; - const [result] = runCloudHostPlan({checkout,directory,contract, - lanes:[{name:"api",command:"node verify.cjs",envSource:env.source}]}); + const [result] = runCloudHostPlan({checkout,directory,contract,lanes:[{name:"api",command:"node verify.cjs",apiTest:true}], + environment:{...process.env,AWS_ACCESS_KEY_ID:"AKIAHOSTKEY000000000",AWS_SECRET_ACCESS_KEY:"host-secret"}}); assert.equal(result.exitCode,0,result.diagnosis); assert.equal(result.runtime.uid,process.getuid() || 65534); }); +test("both control filters and the pkgs-a group consume the measured namespace capability", ()=>{ + for(const [name,command] of [["control","pnpm -F @repo/control test"],["control","pnpm --filter @repo/control test"],["pkgs-a","pnpm test"]]){ + const lane = name === "pkgs-a" ? {name, workflow:{}, command:JSON.stringify({workflow:{}, job:{steps:[{run:command}]}})} : {name,command}; + const lanes=describeCloudLanes([lane]); + assert.ok(lanes[0].prerequisites.capabilities.includes("controlNamespace")); + const instructions=cloudHostInstruction({tool:TOOL,affected:lanes.map(l=>({name:l.name,...l.prerequisites}))},{lanes,commit:TOOL.commit}); + assert.match(instructions,/"isolateControlPorts":true/); + } +}); + test("direct labels never change requirements and equivalent package commands share admission",()=>{ const describe=(name,command)=>describeCloudLanes([{name,command}])[0].prerequisites; assert.deepEqual(describe("desktop-version","node --version"),describe("version","node --version")); diff --git a/plugins/vibe/lib/vibe/scripts/cloud-validation-host.mjs b/plugins/vibe/lib/vibe/scripts/cloud-validation-host.mjs index 938b9382..5ca9d06f 100644 --- a/plugins/vibe/lib/vibe/scripts/cloud-validation-host.mjs +++ b/plugins/vibe/lib/vibe/scripts/cloud-validation-host.mjs @@ -4,7 +4,6 @@ import { appendFileSync, chmodSync, closeSync, copyFileSync, existsSync, fstatSy import os from "node:os"; import path from "node:path"; import { fileURLToPath } from "node:url"; -import { isDeepStrictEqual } from "node:util"; const NO_INPUT = "ignore"; const UNPRIVILEGED_FALLBACK = 65534; @@ -14,67 +13,24 @@ const WORKSPACE = /^[A-Za-z0-9_@./: +%=\[\]-]+$/; const BROWSER_VERSION = "1.65.0"; const BROWSER_STORE = "/opt/pw-browsers"; const HEADLESS_SHELL = path.join(BROWSER_STORE, "chromium_headless_shell-1254/chrome-headless-shell-linux64/chrome-headless-shell"); -const HOST_TIMEOUT = 15 * 60_000; +// One lane's process group ends here. The full Desktop e2e suite, run as the provider's CI step runs it (4 workers), +// took 22.8 min as one lane on a 4-core cloud VM, build included (cse_01H58iag4UozkuYjYfbQj9Pe, 2026-12-02), against +// 15.3 min on CI's 8 cores. 60 minutes leaves that suite room to grow and stays under the 100-minute run limit. +const HOST_TIMEOUT = 60 * 60_000; function digest(bytes) { return createHash("sha256").update(bytes).digest("hex"); } -const API_VALUES = { - AWS_ACCESS_KEY_ID: /^test-(?:aws-)?(?:access-)?key(?:-id)?$/, - AWS_SECRET_ACCESS_KEY: /^test-(?:aws-)?(?:secret-)?key$/, - AWS_REGION: /^(?:us|eu|ap|ca|sa|af|me|il|mx)-[a-z]+-[1-9]$/, -}; - -function optional(read, file) { - try { return read(file); } catch { return null; } -} - -function apiFixture(read, recipe) { - if (!recipe?.apiFixture || !recipe.apiWorkflowPattern) return null; - const { apiFixture: fixturePath, apiSetup: setupPath, apiWorkflow: workflowPath } = recipe; - const bytes = optional(read, fixturePath); - if (typeof bytes !== "string" || bytes.length > 512) return null; - const setup = optional(read, setupPath); - const workflow = optional(read, workflowPath); - const source = /^\s*(?:dotenv\.config|dotenvConfig)\s*\(\s*\{[^;]*["']\.env\.test["']/m.test(setup ?? "") ? setupPath - : new RegExp(recipe.apiWorkflowPattern, "m").test(workflow ?? "") ? workflowPath : null; - if (!source) return null; - const values = {}; - for (const raw of bytes.split(/\r?\n/)) { - const line = raw.trim(); - if (!line || line.startsWith("#")) continue; - const match = /^([A-Z_]+)=([a-z0-9-]+)$/.exec(line); - if (!match || Object.hasOwn(values, match[1]) || !Object.hasOwn(API_VALUES, match[1]) || !API_VALUES[match[1]].test(match[2])) return null; - values[match[1]] = match[2]; - } - const keys = Object.keys(values).sort(); - if (keys.length !== Object.keys(API_VALUES).length) return null; - return { metadata: { path: fixturePath, source, sha256: digest(bytes), sourceSha256: digest(source === setupPath ? setup : workflow), keys }, values }; -} - -/** Bind API test fixture metadata to exact committed bytes. Keep its values out of requests and receipts. */ -export function cloudApiEnvironment(read, commit, recipe) { - const fixture = apiFixture(read, recipe); - return fixture ? { ...fixture.metadata, commit } : null; -} - -function hostApiEnvironment(root, declaration, run, recipe, options) { - const read = (file) => { - const result = run("git", ["show", `HEAD:${file}`], options); - if (result.exitCode !== 0) throw new Error("approved fixture file is missing"); - return result.stdoutTail; - }; - const head = run("git", ["rev-parse", "HEAD"], options); - const fixture = apiFixture(read, recipe); - if (!fixture || head.exitCode !== 0 || declaration.commit !== head.stdoutTail.trim() || - !isDeepStrictEqual(declaration, { ...fixture.metadata, commit: declaration.commit })) return null; - return fixture.values; -} - -function redactFixture(result, values) { - for (const field of ["stdoutTail", "stderrTail", "diagnosis"]) { - for (const value of Object.values(values ?? {})) result[field] = String(result[field] ?? "").replaceAll(value, "[test fixture]"); - } - return result; +/** + * An API test lane runs with exactly the environment the provider's CI step gives the same tests: every key matching + * the recipe's `apiEnvironment.clear` pattern is removed from the lane, then its `values` are set. A committed fixture + * of test credentials contradicted that step, which sets no credentials, and the repository's own key schema. + */ +export function apiTestEnvironment(env, recipe) { + const contract = recipe?.apiEnvironment; + if (!contract || typeof contract.clear !== "string" || !contract.values || typeof contract.values !== "object") + throw new Error("the provider recipe declares no API test environment"); + const clear = new RegExp(contract.clear); + return { ...Object.fromEntries(Object.entries(env).filter(([key]) => !clear.test(key))), ...contract.values }; } /** Reserve an exclusive per-lane range in the cloud host's private state and release it only by exact owner. */ @@ -648,13 +604,17 @@ export function runCloudHostPlan({ checkout, directory, lanes, uid, gid, environ args.push("--concurrency=1",...forwarded); } if (command === "pnpm" && program === "typecheck") env.TURBO_TYPECHECK_CONCURRENCY = "1"; - const values = lane.envSource ? hostApiEnvironment(root, lane.envSource, run, contract?.data?.recipes?.cloudValidation,{cwd:root,env,...actor}) : null; - if (lane.envSource && !values) return skipped(lane.name, "approved committed non-secret test fixture differs; run on L2 (remote slot heavy)"); + let laneEnv = env; + try { if (lane.apiTest === true) laneEnv = apiTestEnvironment(env, contract?.data?.recipes?.cloudValidation); } + catch (error) { return skipped(lane.name, `${error.message}; run on L2 (remote slot heavy)`); } + // A setup lane runs the repository's own bootstrap, which tells a Claude cloud session from a local checkout by + // this marker; without it the bootstrap wrote local stub settings that the API lanes refuse. + if (lane.prerequisite === true && environment.CLAUDE_CODE_REMOTE === "true") laneEnv = { ...laneEnv, CLAUDE_CODE_REMOTE: "true" }; // Environment setup (the repository bootstrap and the workspace builds the lanes depend on) runs as root, and the // actor then owns what it wrote. As the actor, a workspace build's pnpm self-install of the pinned version stalled // with no CPU for 39 minutes while the same bootstrap finished in 37 s as root (r17). const rootSetup = asRoot && lane.prerequisite === true; - const options = rootSetup ? { cwd: root, env: rootSetupEnvironment({ ...env, ...values }, environment, root) } : { cwd: root, env: { ...env, ...values }, ...actor }; + const options = rootSetup ? { cwd: root, env: rootSetupEnvironment(laneEnv, environment, root) } : { cwd: root, env: laneEnv, ...actor }; if (command === "pnpm" && args.slice(0, 3).join(" ") === "control up web") { args.push("--app-port", String(ports.first), "--api-port", String(ports.first + 1)); } @@ -673,7 +633,7 @@ export function runCloudHostPlan({ checkout, directory, lanes, uid, gid, environ } if (rootSetup) { provision(root, actor); provision(home, actor); } if (lane.prerequisite && includingBrowser.exitCode !== 0) prerequisiteFailure = lane.name; - return { name: lane.name, ...redactFixture(includingBrowser, values), runtime: { uid: rootSetup ? 0 : actor.uid, ports: [ports.first, ports.last] } }; + return { name: lane.name, ...includingBrowser, runtime: { uid: rootSetup ? 0 : actor.uid, ports: [ports.first, ports.last] } }; }; // Each lane reports its own wall time as it ends, so a run cut off by a host limit still shows where the time went. return lanes.map((lane, index) => { 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 0087882e..e387d6a2 100644 --- a/plugins/vibe/lib/vibe/scripts/cloud-validation-host.test.mjs +++ b/plugins/vibe/lib/vibe/scripts/cloud-validation-host.test.mjs @@ -618,19 +618,25 @@ test("environment setup runs once as root before the lanes and every lane comman assert.ok(called.every(({ command, uid }) => !command.startsWith("service") && uid === 1000), "a non-root host account starts nothing as root"); }); -test("the API fixture is admitted when only the repository's CI workflow, not its test setup, references it", async () => { - const { cloudApiEnvironment } = await import("./cloud-validation-host.mjs"); +test("ISS-15038 the API test environment comes from the shipped recipe, and a recipe without one refuses the lane", async () => { + const { apiTestEnvironment } = await import("./cloud-validation-host.mjs"); const provider = JSON.parse(readFileSync(new URL("../../../../vibe-closedloop-provider/provider.json", import.meta.url), "utf8")); const recipe = provider.data.recipes.cloudValidation; - const fixtureBytes = "AWS_ACCESS_KEY_ID=test-key-id\nAWS_SECRET_ACCESS_KEY=test-secret-key\nAWS_REGION=us-east-1\n"; - const files = (workflow) => ({ [recipe.apiFixture]: fixtureBytes, [recipe.apiSetup]: "export default {};\n", [recipe.apiWorkflow]: workflow }); - const read = (workflow) => (file) => { const text = files(workflow)[file]; if (text === undefined) throw new Error("absent"); return text; }; - const referenced = "jobs:\n test:\n steps:\n - name: API tests\n run: pnpm --filter api test --env-file apps/api/.env.test\n"; - const bound = cloudApiEnvironment(read(referenced), "c".repeat(40), recipe); - assert.equal(bound?.source, recipe.apiWorkflow); - assert.deepEqual(bound?.keys, ["AWS_ACCESS_KEY_ID", "AWS_REGION", "AWS_SECRET_ACCESS_KEY"]); - assert.equal(cloudApiEnvironment(read("jobs:\n test:\n steps:\n - name: API tests\n run: pnpm --filter api test\n"), "c".repeat(40), recipe), null, - "a workflow that never names the fixture does not admit it"); + assert.deepEqual(apiTestEnvironment({ PATH: "/bin", AWS_ACCESS_KEY_ID: "AKIAHOSTKEY000000000", AWS_DEFAULT_REGION: "us-east-1" }, recipe), + { PATH: "/bin", AWS_REGION: "", AWS_EXECUTION_ENV: "" }); + assert.throws(() => apiTestEnvironment({ PATH: "/bin" }, { ...recipe, apiEnvironment: undefined }), /declares no API test environment/); + const { root, cleanup } = makeHome("vibe-api-recipe-"); + try { + const contract = { ...provider, data: { ...provider.data, recipes: { ...provider.data.recipes, cloudValidation: { ...recipe, apiEnvironment: undefined, rootServices: [] } } } }; + const ran = []; + mkdirSync(path.join(root, "c")); + mkdirSync(path.join(root, "w")); + const [lane] = runCloudHostPlan({ checkout: path.join(root, "c"), directory: path.join(root, "w"), contract, uid: 1000, gid: 1000, provision: () => {}, + lanes: [{ name: "api", command: "pnpm --filter api test", apiTest: true }], environment: { PATH: "/bin" }, run: (...call) => { ran.push(call); return { exitCode: 0 }; } }); + assert.equal(lane.exitCode, null); + assert.match(lane.notRun, /declares no API test environment; run on L2/); + assert.deepEqual(ran, []); + } finally { cleanup(); } }); test("ISS-14476 the host runner runs the shipped reporter from the exact tool commit on its own lane directory", (t) => { @@ -745,3 +751,64 @@ test("ISS-14476 root setup runs the package repair once before any lane: a failu assert.deepEqual(plan(null, { provisioned: true }), { calls: 0, timed: [], lanes: [[0, null]] }, "the lanes phase does not repair again"); assert.deepEqual(plan(null, { uid: 1000, gid: 1000 }), { calls: 0, timed: [], lanes: [[0, null]] }, "a non-root runner does not repair"); }); + +// ISS-15038: in session cse_01H58iaeEVzoR7WVfUQooHjt test-ci and its setup exited 0 and the runner printed its record, +// but behind its CLOUD_HOST_LANE_TIME lines, so the condensed log cut the record ("[+296 chars]"); the agent's final +// message held prose, not the record, and validate refused the result for lack of machine outcome evidence. +test("ISS-15038 the managed brief reads the runner's record in its own short call, so lane timing lines cannot push it past the run log's cut", async (t) => { + const { execFileSync } = await import("node:child_process"); + const { mkdtempSync, rmSync } = await import("node:fs"); + const { tmpdir } = await import("node:os"); + const { fileURLToPath } = await import("node:url"); + const { makeCheckout } = await import("../../../skills/vibe/scripts/test-fixtures.mjs"); + const { parseValidationResult } = await import("./cloud-worker.mjs"); + const { MACHINE_OUTCOMES } = await import("./cloud-outcome-artifact.mjs"); + const { hostReporter, outcomeInstruction } = await import("./cloud-outcome-instruction.mjs"); + const { cloudHostInstruction } = await import("./cloud-validation-environment.mjs"); + const { writeHostLaneFiles } = await import("./cloud-validation-host.mjs"); + const f = makeHome("vibe-host-record-read-"); + t.after(f.cleanup); + const repository = "closedloop-ai/claude-plugins", worktree = path.join(f.root, "checkout"); + makeCheckout({ ...f, checkout: worktree, remoteUrl: "https://github.com/" + repository }); + git(worktree, ["config", "--unset", git(worktree, ["config", "--name-only", "--get-regexp", "^url\\..*\\.insteadof$"], f.home)], f.home); + const commit = git(worktree, ["rev-parse", "HEAD"], f.home), key = "d".repeat(64); + const request = { worktree, provider: "claude", model: "claude-opus-5-5", repository, branch: "main", commit, + lanes: [{ name: "test-ci", command: "pnpm test:ci" }] }; + const host = fixture(t); + const lanes = request.lanes.map(({ name }) => { + const streams = { stdout: path.join(host.directory, name + ".stdout"), stderr: path.join(host.directory, name + ".stderr") }; + for (const file of Object.values(streams)) writeFileSync(file, "private lane output\n"); + return { name, exitCode: 0, stdoutTail: "", stderrTail: "", diagnosis: "", streamFiles: streams }; + }); + const directory = writeHostLaneFiles(realpathSync(tmpdir()), lanes); + t.after(() => rmSync(directory, { recursive: true, force: true })); + const spec = Buffer.from(JSON.stringify({ key, commit, repository, names: lanes.map(({ name }) => name), combined: [], probe: -1, frozen: [] })).toString("base64url"); + const record = execFileSync(process.execPath, [fileURLToPath(new URL("./cloud-outcome-writer.mjs", import.meta.url)), spec, directory], + { cwd: worktree, env: { ...process.env, HOME: f.home, CLAUDE_CODE_REMOTE: "true" }, encoding: "utf8", stdio: ["ignore", "pipe", "pipe"] }).trim(); + assert.match(record, /^VIBE_OUTCOMES_V1 \S+$/); + const tool = { commit: "2fc9d54e8c726c16a042eb129f8a1e99d0ecefbe", ref: "refs/heads/main" }; + const target = path.join(worktree, ".git", `vibe-validation-host-${tool.commit}.mjs`); + // The lanes call's output file as that session's runner wrote it: timing lines first, then the record. + writeFileSync(target + ".out", [ + 'CLOUD_HOST_LANE_TIME {"name":"root services","exitCode":0,"seconds":0}', + 'CLOUD_HOST_LANE_TIME {"name":"test-ci","exitCode":0,"seconds":77}', + record, `CLOUD_HOST_LANES ${directory} 1`].join("\n") + "\n"); + const brief = cloudHostInstruction({ tool, affected: [] }, { lanes: request.lanes, commit, reporter: hostReporter(request, request.lanes, key) }) + + "\n\n" + outcomeInstruction(request, request.lanes, key, true); + const read = /`(grep -m1 [^`]+)`/.exec(brief)?.[1]; + assert.ok(read, "the brief names its own call that prints only the record"); + const printed = execFileSync("bash", ["-c", read], { cwd: worktree, encoding: "utf8" }); + assert.equal(printed.trim(), record); + const cut = (line) => line.slice(0, 380) + ` [+${line.length - 380} chars]`; + const log = [ + `[2026-12-02T22:03:33.519538Z] tool_result: ${cut(readFileSync(target + ".out", "utf8").replaceAll("\n", " "))}`, + `[2026-12-02T22:03:36.000000Z] tool_result: ${printed.trim()}`, + "[2026-12-02T22:03:43.839311Z] assistant: Lanes: test-ci exit 0. git status --porcelain: empty.", + ].join("\n"); + const parse = (text) => parseValidationResult(text, request, { managedHost: true, outcomeTransport: MACHINE_OUTCOMES, requestKey: key }); + assert.throws(() => parse(log.split("\n").filter((line) => !line.includes(`tool_result: ${printed.trim()}`)).join("\n")), + /requires machine outcome evidence/, "without the short read, that session's log holds no whole record"); + const result = parse(log); + assert.deepEqual(result.lanes.map(({ name, passed }) => ({ name, passed })), [{ name: "test-ci", passed: true }]); + assert.equal(result.passed, true); +}); diff --git a/plugins/vibe/lib/vibe/scripts/cloud-worker.mjs b/plugins/vibe/lib/vibe/scripts/cloud-worker.mjs index b2220823..b9820388 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, requireOutcomeCapacity, readOutcomeReport } from "./cloud-outcome-artifact.mjs"; +import { MACHINE_OUTCOMES, measuredProbeTranscript, withCarriedFailures, outcomeArtifact, checkOutcomeArtifact, OUTCOME_LOG_LIMIT, 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"; @@ -78,8 +78,11 @@ import { isEntryPoint } from "../../../shared/plugin-roots.mjs"; import { checkCloudcheckRequest, prepareCloudcheckProof } from "./cloudcheck-proof.mjs"; import { cloudPrProblem, completeFromCommit, importFromGit, importResult, readyForPr, refreshImportWitness, unconfirmed } from "./cloud-import.mjs"; -const MAX_WALL_MS = 35 * 60 * 1000; -const DEFAULT_WALL_MS = 35 * 60 * 1000; +// One Sonnet session on the pinned environment ran 117 minutes with no cutoff (cse_01H58iagWGazkKdUCDGCUQEh, +// 2026-12-02, 13 nine-minute tool calls, stopped by request); no longer session was tried, so 117 is a floor, not the +// platform's limit. A run, and a validation's queue wait, stay under it. +const MAX_WALL_MS = 100 * 60 * 1000; +const DEFAULT_WALL_MS = MAX_WALL_MS; const DEFAULT_POLL_MS = 30 * 1000; export const COMMAND_MS = 90 * 1000; /** @@ -194,7 +197,7 @@ export function validateRequest(request, rules = requestRules(request)) { } function checkPollingBounds(request) { - if (!Number.isInteger(request.maxWallMs ?? DEFAULT_WALL_MS) || (request.maxWallMs ?? DEFAULT_WALL_MS) < 1000 || (request.maxWallMs ?? DEFAULT_WALL_MS) > MAX_WALL_MS) throw new Error("maxWallMs must be between 1 second and 35 minutes"); + if (!Number.isInteger(request.maxWallMs ?? DEFAULT_WALL_MS) || (request.maxWallMs ?? DEFAULT_WALL_MS) < 1000 || (request.maxWallMs ?? DEFAULT_WALL_MS) > MAX_WALL_MS) throw new Error(`maxWallMs must be between 1 second and ${MAX_WALL_MS / 60_000} minutes`); if (!Number.isInteger(request.pollMs ?? DEFAULT_POLL_MS) || (request.pollMs ?? DEFAULT_POLL_MS) < 1000 || (request.pollMs ?? DEFAULT_POLL_MS) > 60_000) throw new Error("pollMs must be between 1 and 60 seconds"); } @@ -953,13 +956,25 @@ function deniedResult(log, error) { return denial ? new Error(`cloud validation session was denied permission to run a command: ${redactedLine(denial).slice(0, DIAGNOSIS_CHARS)} (${error.message})`) : error; } +/** + * A request whose resolved lanes, setup lanes validate adds included, overflow the run log's record gets a fresh + * outcomes artifact named from its commit and request digest, so the same request resumes the same branch. One + * Desktop spec resolves to five lanes and the log holds two, so every such request was refused before launch. + */ +function withOverflowArtifact(request, count, digest) { + if (request.resultArtifact !== undefined || outcomeTransportBytes(count) <= OUTCOME_LOG_LIMIT) return request; + return { ...request, resultArtifact: { kind: "validation-outcomes", path: `.vibe-validation-outcomes-${digest.slice(0, 16)}.json`, + branch: `vibe-validation-results/${request.commit.slice(0, 12)}-${digest.slice(0, 12)}` } }; +} + function validationReceiptPath(request, digest) { return path.join(gitDir(request.worktree), validationReceiptName(request.commit, digest)); } /** 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); - const routed = { ...request, repository: verifyRepository(request.worktree, request.repository) }; const digest = sha256(JSON.stringify(request)); + const verified = { ...request, repository: verifyRepository(request.worktree, request.repository) }; + const routed = withOverflowArtifact(verified, validationLanes(verified).lanes.length, digest); const file = validationReceiptPath(request, digest); const { lanes } = validationLanes(routed); const laneKeys = lanes.map(({ command }) => validationCommandKey(command)); @@ -971,10 +986,10 @@ export async function validateCommit(request, { remote = cliRemote(request.workt 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) { - if (!request.resultArtifact || outcomeArtifact(request)) requireOutcomeCapacity(lanes,outcomeArtifact(request)); - if (outcomeArtifact(request) && proofGit(request.worktree,["ls-remote","--refs","origin","refs/heads/"+request.resultArtifact.branch])) throw new Error("outcome proof branch already exists; supply a fresh resultArtifact branch before dispatch"); + 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(); - const outcomeTransport=request.resultArtifact && !outcomeArtifact(request) ? "eval-artifact" : MACHINE_OUTCOMES; + const outcomeTransport=routed.resultArtifact && !outcomeArtifact(routed) ? "eval-artifact" : MACHINE_OUTCOMES; 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; diff --git a/plugins/vibe/lib/vibe/scripts/cloud-worker.test.mjs b/plugins/vibe/lib/vibe/scripts/cloud-worker.test.mjs index 72fa3d9c..ff355424 100644 --- a/plugins/vibe/lib/vibe/scripts/cloud-worker.test.mjs +++ b/plugins/vibe/lib/vibe/scripts/cloud-worker.test.mjs @@ -1116,3 +1116,15 @@ test('ISS-14116 item 24: an archived validation names its session and the init e await assert.rejects(validateCommit(validationRequest(other), { remote: archivedRemote(() => { throw new Error('log read failed'); }), sleep: async () => {}, home: homeOf(other) }), /^Error: cloud validation ended archived \(session session_v\)$/); }); + +test('ISS-15038 a run may poll for 100 minutes, under the 117 minutes one cloud session was measured to run, and no longer', () => { + const request = { + worktree: '/tmp/vibe-example', ticket: '#42', provider: 'claude', model: 'claude-sonnet-5-5', reservedVersion: '1.0.3', branch: 'cloud/widget-fix', + placement: { codeOnly: true, needsRunningApp: false, localEvidence: [] }, + criteria: [{ id: 'AC-1', source: 'the request', text: 'Fix the widget.' }], + validationCommands: ['node --test x.test.mjs'], connectorAllowlist: [], repository: 'acme/widgets', + }; + const rules = { ...cloudRules(null), ticket: /^#\d+$/ }; + assert.equal(validateRequest({ ...request, maxWallMs: 100 * 60_000 }, rules).maxWallMs, 100 * 60_000); + assert.throws(() => validateRequest({ ...request, maxWallMs: 100 * 60_000 + 1 }, rules), /^Error: maxWallMs must be between 1 second and 100 minutes$/); +}); diff --git a/plugins/vibe/skills/handoff/scripts/ci-job-shape.test.mjs b/plugins/vibe/skills/handoff/scripts/ci-job-shape.test.mjs index 88f76ba5..5b3e5d7f 100644 --- a/plugins/vibe/skills/handoff/scripts/ci-job-shape.test.mjs +++ b/plugins/vibe/skills/handoff/scripts/ci-job-shape.test.mjs @@ -62,12 +62,17 @@ test("the CLI prints each job shape and the needles no job runs", (t) => { }); -test("workflow lane definitions expand all thirteen repository jobs and preserve exact run recipes", () => { +test("workflow lane definitions expand all fifteen repository jobs and preserve exact run recipes", () => { const workflow = readFileSync(new URL("../../../../../.github/workflows/ci.yml", import.meta.url), "utf8"); const lanes = workflowLaneDefinitions(workflow); - assert.equal(lanes.length, 13); + assert.equal(lanes.length, 15); assert.deepEqual(lanes.filter(lane => lane.job !== "tools-ts").map(lane => lane.name), - ["plugin-version-bump", "plugin-manifest-versions", "lint", "typecheck", "test", "node-tests", "vibe-eval-t0"]); + ["plugin-version-bump", "plugin-manifest-versions", "lint", "typecheck", "test", + 'node-tests[{"shard":1}]', 'node-tests[{"shard":2}]', 'node-tests[{"shard":3}]', "vibe-eval-t0"]); + const shards = lanes.filter(lane => lane.job === "node-tests").map(lane => JSON.parse(lane.command).job.steps.at(-1).run); + assert.deepEqual(shards.map(run => run.match(/node --test --test-shard=(\d)\/3 --test-reporter=spec "\$\{files\[@\]\}"/)?.[1]), ["1", "2", "3"], + "each Node Tests row runs its own third of the same discovered files"); + assert.deepEqual(new Set(shards.map(run => run.replace(/\b[123](?=\/3\b)|shard=\d/g, "N"))).size, 1, "the rows differ only in the shard number"); const workers = lanes.find(lane => lane.job === "tools-ts" && lane.matrix.tool === "vibe-workers"); const recipe = JSON.parse(workers.command); const steps = recipe.job.steps.filter(step => step.run); diff --git a/plugins/vibe/skills/handoff/scripts/pr-facts.test.mjs b/plugins/vibe/skills/handoff/scripts/pr-facts.test.mjs index 2d82fb55..60877dd8 100644 --- a/plugins/vibe/skills/handoff/scripts/pr-facts.test.mjs +++ b/plugins/vibe/skills/handoff/scripts/pr-facts.test.mjs @@ -701,8 +701,9 @@ function multiProofCarry(t) { const f = makeHome("multi-proof-carry-"); t.after(f.cleanup); const wt = path.join(f.root, "wt"); const workflowPath = ".github/workflows/ci.yml"; const workflow = readFileSync(new URL("../../../../../.github/workflows/ci.yml", import.meta.url), "utf8"); - const lanes = workflowLaneDefinitions(workflow); assert.equal(lanes.length, 13); + const lanes = workflowLaneDefinitions(workflow); assert.equal(lanes.length, 15); const worker = lanes.find(lane => lane.job === "tools-ts" && lane.matrix.tool === "vibe-workers").name; + const nodeLanes = lanes.filter(lane => lane.job === "node-tests").map(lane => lane.name); assert.equal(nodeLanes.length, 3); makeCheckout({ ...f, checkout: wt, files: { [workflowPath]: workflow, "vibe-handoff-paths.json": JSON.stringify({ ...JSON.parse(SYMPHONY_PATH_POLICY), laneSource: { kind: "github-workflow", path: workflowPath } }), "node.mjs": "export const n=0;", "worker.ts": "export const w=0;", "contract.py": "value=0", "stable.txt": "stable" } }); @@ -719,17 +720,17 @@ function multiProofCarry(t) { const final = snapshot("final", interim); const published = g("commit-tree", g("write-tree"), "-p", interim, "-m", "final publication"); g("reset", "--hard", published); const point = (commit, ref) => ({ ref, commit, gitTree: g("rev-parse", `${commit}^{tree}`), source: committedSourceIdentity(wt, commit) }); - const finalLanes = ["lint", "typecheck", "test"]; const scopedLanes = ["node-tests", worker]; + const finalLanes = ["lint", "typecheck", "test"]; const scopedLanes = [...nodeLanes, worker]; const stableLanes = lanes.filter(lane => ![...finalLanes, ...scopedLanes].includes(lane.name)).map(lane => lane.name); assert.equal(stableLanes.length, 8); const request = { lastQa: { boundary: scoped }, evidence: { screens: [] }, featureMap: { entries: [] }, graphImporters: { importers: {} }, - laneSelections: { files: { "node.mjs": ["node-tests"], "worker.ts": [worker], "contract.py": finalLanes, "stable.txt": stableLanes } }, config: { docs: [] } }; + laneSelections: { files: { "node.mjs": nodeLanes, "worker.ts": [worker], "contract.py": finalLanes, "stable.txt": stableLanes } }, config: { docs: [] } }; const impact = qaImpact({ worktree: wt, since: scoped, ...request }); const run = (lane, commit, status = "passed") => ({ lane: lane.name, command: lane.command, commit, status, exitCode: status === "passed" ? 0 : 1, laneKey: "9".repeat(16) }); - const history = lanes.map(lane => run(lane, full, ["node-tests", "test"].includes(lane.name) ? "failed" : "passed")); - history.push(...lanes.filter(lane => ["node-tests", ...finalLanes].includes(lane.name)).map(lane => run(lane, repaired))); + const history = lanes.map(lane => run(lane, full, [...nodeLanes, "test"].includes(lane.name) ? "failed" : "passed")); + history.push(...lanes.filter(lane => [...nodeLanes, ...finalLanes].includes(lane.name)).map(lane => run(lane, repaired))); const records = lanes.map((lane, index) => { const origin = finalLanes.includes(lane.name) ? final : scopedLanes.includes(lane.name) ? scoped : full; - const result = run(lane, origin); const input = finalLanes.includes(lane.name) ? "contract.py" : lane.name === "node-tests" ? "node.mjs" : lane.name === worker ? "worker.ts" : "stable.txt"; + const result = run(lane, origin); const input = finalLanes.includes(lane.name) ? "contract.py" : nodeLanes.includes(lane.name) ? "node.mjs" : lane.name === worker ? "worker.ts" : "stable.txt"; const coveredFiles = [workflowPath, input].map(file => ({ path: file, sha256: createHash("sha256").update(readFileSync(path.join(wt, file))).digest("hex") })); const bytes = JSON.stringify({ version: 1, source: committedSourceIdentity(wt, origin), result, coveredFiles }); const receipt = { path: `lane-${index}.json`, sha256: createHash("sha256").update(bytes).digest("hex") }; @@ -741,18 +742,18 @@ function multiProofCarry(t) { const evidence = { source: sourceIdentity(wt), testSelection: [], qaImpact: impact, qaImpactRequest: request, treeEquivalentCarry: carry, targetedInventory: { actor: "read-only", source: "final-committed-diff", commit: published, impactKey: impact.laneKey, laneReport: { source: { kind: "github-workflow", path: workflowPath, commit: published, sha256: createHash("sha256").update(workflow).digest("hex") }, - matches: lanes.map(({ name, command }) => ({ name, command })) }, entries: [], noTestsReason: "all thirteen declared workflow recipes" }, + matches: lanes.map(({ name, command }) => ({ name, command })) }, entries: [], noTestsReason: "all fifteen declared workflow recipes" }, testRuns: [...history, ...records.map(record => record.result)], rerunCycles: [] }; - return { wt, g, evidence: JSON.parse(JSON.stringify(evidence)), published, full, repaired, scoped, final, finalLanes, scopedLanes, stableLanes }; + return { wt, g, evidence: JSON.parse(JSON.stringify(evidence)), published, full, repaired, scoped, final, finalLanes, scopedLanes, stableLanes, nodeLanes }; } -test("all thirteen recipes survive the real multi-proof sibling chain without another full sweep", t => { +test("all fifteen recipes survive the real multi-proof sibling chain without another full sweep", t => { const f = multiProofCarry(t); assert.throws(() => qaImpactRequest(f.wt, f.evidence.qaImpactRequest), /ancestor/); assert.deepEqual(targetedEvidenceProblems(f.evidence, f.published, f.wt), []); const origins = f.evidence.treeEquivalentCarry.runs.map(record => record.result.commit); assert.equal(origins.filter(commit => commit === f.full).length, 8); - assert.equal(origins.filter(commit => commit === f.scoped).length, 2); + assert.equal(origins.filter(commit => commit === f.scoped).length, 4); assert.equal(origins.filter(commit => commit === f.final).length, 3); }); @@ -770,7 +771,7 @@ for (const [name, mutate] of [ ["ordinary sibling evidence", f => { delete f.evidence.treeEquivalentCarry; }], ]) test(`multi-proof carry fails closed on ${name}`, t => { const f=multiProofCarry(t); - assert.deepEqual(targetedEvidenceProblems(f.evidence,f.published,f.wt),[],"all thirteen positive control"); + assert.deepEqual(targetedEvidenceProblems(f.evidence,f.published,f.wt),[],"all fifteen positive control"); mutate(f); assert.notDeepEqual(targetedEvidenceProblems(f.evidence,f.published,f.wt),[]); }); @@ -779,9 +780,9 @@ for (const [name, mutate] of [ test("direct sibling scope rejects an impacted older passing lane even with consistent unchanged covered hashes", t => { const f=multiProofCarry(t); const e=f.evidence; assert.deepEqual(targetedEvidenceProblems(e,f.published,f.wt),[]); - const old=e.testRuns.find(run=>run.lane==="node-tests"&&run.commit===f.repaired&&run.status==="passed"); + const old=e.testRuns.find(run=>run.lane===f.nodeLanes[0]&&run.commit===f.repaired&&run.status==="passed"); assert.ok(old, "actual earlier repair pass in fixture history"); - const record=e.treeEquivalentCarry.runs.find(item=>item.result.lane==="node-tests"); + const record=e.treeEquivalentCarry.runs.find(item=>item.result.lane===f.nodeLanes[0]); record.result=structuredClone(old); e.treeEquivalentCarry.proofs.push({ ref:"refs/heads/proof/repaired", commit:f.repaired, gitTree:f.g("rev-parse",`${f.repaired}^{tree}`), source:committedSourceIdentity(f.wt,f.repaired) }); 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 47bbcf50..e6f00117 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.120" + assert claude["version"] == codex["version"] == "1.1.121" 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 70c9a271..d774e431 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.120", manifest - assert "Version `1.1.120`" in skill_split.read(PLUGIN_ROOT / "README.md") + assert json.loads(skill_split.read(PLUGIN_ROOT / manifest / "plugin.json"))["version"] == "1.1.121", manifest + assert "Version `1.1.121`" in skill_split.read(PLUGIN_ROOT / "README.md") changelog = skill_split.read(PLUGIN_ROOT.parents[1] / "CHANGELOG.md") assert "### vibe v1.1.76" in changelog assert "### vibe v1.1.61" in changelog