From adc206c7a18c5b184c3f78ed86adcec2162494c3 Mon Sep 17 00:00:00 2001 From: Daniel Ochoa Date: Wed, 2 Dec 2026 15:45:53 -0600 Subject: [PATCH 1/8] ISS-15030: Fix cloud check false reds, the 100-file merge refusal and the fleet launch guard --- CHANGELOG.md | 12 ++ .../.claude-plugin/plugin.json | 2 +- .../vibe-closedloop/.codex-plugin/plugin.json | 2 +- plugins/vibe-closedloop/README.md | 2 +- plugins/vibe-closedloop/hooks/agent-guard.mjs | 51 +++++++-- plugins/vibe-closedloop/hooks/merge-guard.mjs | 25 ++++- .../lib/vibe/scripts/cloud-environment.mjs | 47 ++++++-- .../scripts/cloud-validation-environment.mjs | 14 ++- .../lib/vibe/scripts/cloud-worker.mjs | 20 +++- .../skills/handoff/scripts/rulings-check.mjs | 12 ++ plugins/vibe/.claude-plugin/plugin.json | 2 +- plugins/vibe/.codex-plugin/plugin.json | 2 +- plugins/vibe/README.md | 2 +- plugins/vibe/hooks/agent-guard.mjs | 51 +++++++-- plugins/vibe/hooks/agent-guard.test.mjs | 54 ++++++++- plugins/vibe/hooks/merge-guard.mjs | 25 ++++- plugins/vibe/hooks/merge-guard.test.mjs | 32 ++++++ .../scripts/cloud-capability-probe.test.mjs | 27 +++++ .../vibe/scripts/cloud-check-rows.test.mjs | 104 ++++++++++++++++++ .../lib/vibe/scripts/cloud-environment.mjs | 47 ++++++-- .../vibe/scripts/cloud-environment.test.mjs | 2 +- .../vibe/scripts/cloud-setup-proof.test.mjs | 10 +- .../scripts/cloud-validation-environment.mjs | 14 ++- .../cloud-validation-recovery.test.mjs | 5 +- .../vibe/lib/vibe/scripts/cloud-worker.mjs | 20 +++- .../skills/handoff/scripts/rulings-check.mjs | 12 ++ .../python/test_pr_takeover_skill_contract.py | 2 +- .../python/test_vibe_ws8_load_contract.py | 4 +- 28 files changed, 523 insertions(+), 79 deletions(-) create mode 100644 plugins/vibe/lib/vibe/scripts/cloud-check-rows.test.mjs diff --git a/CHANGELOG.md b/CHANGELOG.md index 89354071..0ed38043 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -4,6 +4,18 @@ All notable changes to the claude-plugins project will be documented in this fil The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.1.0/). Entries are listed newest-first; each plugin section is treated as released when merged to `main`. +### vibe v1.1.119 + +#### Fixed + +- ISS-15030: `cloud-worker.mjs check` no longer fails lane-tools only because the last capability proof is older than 30 minutes. A stale proof that measured every tool present asks only for a fresh capability run. The setup script is printed only when a tool was measured missing or there was never a proof. +- The environment-setup row passes after a run that succeeded, and the api row names the error a failed `claude -p` reports instead of "result success". +- A cloud-capabilities validate request without `repository` takes it from the worktree's origin. +- A new chrome-account row says a script cannot verify the Chrome and Claude in Chrome extension account, and names the manual check. +- The merge guard reads a pull request's full paginated file list when GitHub's view stops at 100 files. Only a failed listing is treated as changing UI. +- The fleet launch guard lets a fleet chat start read-only and operational workers. A plain code-writing worker starts only when the program's rulings.md quotes an operator ruling naming each of its tickets. The brief declares `Worker role:` and `Tickets:`; a brief with no role is a writer. +- Across all plugin Markdown, including eval prompts and graders, the release is about 0 words longer than v1.1.118. The count covers the source files in `plugins/vibe` and excludes the generated ClosedLoop edition. + ### vibe v1.1.118 #### Added diff --git a/plugins/vibe-closedloop/.claude-plugin/plugin.json b/plugins/vibe-closedloop/.claude-plugin/plugin.json index b0c614c5..be87bfd2 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.118", + "version": "1.1.119", "dependencies": [ "closedloop-core", "vibe-core" diff --git a/plugins/vibe-closedloop/.codex-plugin/plugin.json b/plugins/vibe-closedloop/.codex-plugin/plugin.json index d53fb815..434c4a81 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.118", + "version": "1.1.119", "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 6b3103b1..6b7da1ab 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.118` contains 17 skills and 17 agents, and no hook manifest: the +Version `1.1.119` contains 17 skills and 17 agents, and no hook manifest: the `vibe-core` plugin, which vibe declares as a dependency, registers the hooks and runs `hooks/runtime.mjs` from the vibe a session uses. Skill commands forward to guards in `hooks/` and runtime modules in `lib/`. The package has no standalone commands, root shell scripts or production Python tools. Tests sit beside their owners; Python contract helpers and the generic scan live in `tools/python/`. diff --git a/plugins/vibe-closedloop/hooks/agent-guard.mjs b/plugins/vibe-closedloop/hooks/agent-guard.mjs index f2a203c3..85c59b80 100644 --- a/plugins/vibe-closedloop/hooks/agent-guard.mjs +++ b/plugins/vibe-closedloop/hooks/agent-guard.mjs @@ -11,6 +11,9 @@ import { vibeSkillOf } from "../shared/plugin-roots.mjs"; import { vibeScriptPath, vibeSkill } from "../shared/vibe-install.mjs"; import { briefProviderProblem } from "../lib/vibe/scripts/provider-brief.mjs"; import { recordedBinding } from "../lib/vibe/scripts/provider.mjs"; +import { chatProgramDir, defaultHome } from "../lib/fleet-orchestrator/scripts/fleet-home.mjs"; +import { validChat } from "../lib/fleet-orchestrator/scripts/chat-binding.mjs"; +import { operatorTicketRuling } from "../skills/handoff/scripts/rulings-check.mjs"; // Roles are agent names qualified by either vibe plugin. const VIBE_WORKER = /^vibe-[a-z0-9-]+-worker$/; @@ -41,19 +44,53 @@ function rawCodexLaunch(words) { return ["exec", "e", "review"].includes(words[i]); } -/** Fleet-only launch policy. Managed launchers start their child internally and never issue a raw parent tool call. */ -export function fleetLaunchGuard(event, home) { +/** + * Fleet-only launch policy. Managed launchers start their child internally and never issue a raw parent tool call. A + * native Agent brief declares `Worker role: read-only | operational | writer` and `Tickets: `; a brief with no + * role is a writer. A writer that is neither a vibe start nor a helper needs a quoted operator ruling naming each of its + * tickets in the program's rulings.md (operator ruling 2026-12-02). + */ +export function fleetLaunchGuard(event, home, env = process.env) { const input = event?.tool_input; const native = event.tool_name === "Agent"; + const prompt = String(input?.prompt ?? ""); + const lines = prompt.split("\n"); const candidate = native - ? !/^(?:\$vibe\b|\/(?:vibe|vibe-generic):vibe\b)/.test(input?.prompt?.trim() ?? "") + ? !/^(?:\$vibe\b|\/(?:vibe|vibe-generic):vibe\b)/.test(prompt.trim()) && !["Ticket writer:", "Helper branch and worktree:", "Exclusive file allowlist:", "Assignment:", "Test authority:", "Return:"] - .every(field => String(input?.prompt ?? "").split("\n").some(line => line.startsWith(field) && line.slice(field.length).trim())) + .every(field => lines.some(line => line.startsWith(field) && line.slice(field.length).trim())) : typeof input?.command === "string"; if (!candidate || conversationSkill(event, home) !== "fleet-orchestrator") return null; - if (!native && !commandCalls(input.command, eventCwd(event)).some(({ words, value }) => rawCodexLaunch(words.map(word => value(word) ?? word)))) return null; - return deny("Fleet ticket analysis uses dist/claude-worker.mjs with vibe-requirements-worker in sessionless startup mode. " - + "Use dist/codex-reviewer.mjs for review, dist/codex-reviewer.mjs run --role visual-qa-critic --agent-definition for visual QA, or fleet.sh session turn for assigned worker work."); + if (native) { + const problem = plainWriterProblem(lines, event, env); + return problem ? deny(`${problem} ${FLEET_ROUTES}`) : null; + } + if (!commandCalls(input.command, eventCwd(event)).some(({ words, value }) => rawCodexLaunch(words.map(word => value(word) ?? word)))) return null; + return deny(FLEET_ROUTES); +} + +const FLEET_ROUTES = "Fleet ticket analysis uses dist/claude-worker.mjs with vibe-requirements-worker in sessionless startup mode. " + + "Use dist/codex-reviewer.mjs for review, dist/codex-reviewer.mjs run --role visual-qa-critic --agent-definition for visual QA, or fleet.sh session turn for assigned worker work."; +const NON_WRITER_ROLES = new Set(["read-only", "operational"]); + +/** Why a fleet chat may not launch this brief as a plain worker, or null: decided from its declared lines only. */ +function plainWriterProblem(lines, event, env) { + const declared = (field) => lines.find((line) => line.startsWith(field))?.slice(field.length).trim() ?? ""; + if (NON_WRITER_ROLES.has(declared("Worker role:").toLowerCase())) return null; + const tickets = declared("Tickets:").split(/[\s,]+/).filter(Boolean); + const declare = "Declare `Worker role: read-only` or `Worker role: operational` for a worker that writes no code."; + if (tickets.length === 0) { + return `A worker brief with no read-only or operational role is a writer, and a writer names its tickets on a \`Tickets: \` line. ${declare}`; + } + let rulings = ""; + try { + const chat = validChat(event?.session_id); + rulings = readFileSync(path.join(chatProgramDir(defaultHome(env, chat), chat, env).dir, "rulings.md"), "utf8"); + } catch { /* No program or no rulings file: no ticket has a ruling. */ } + const missing = tickets.filter((ticket) => !operatorTicketRuling(rulings, ticket)); + if (missing.length === 0) return null; + return `A plain worker that writes code for ${missing.join(", ")} outside vibe needs the operator's ruling naming that ticket in the program's rulings.md, ` + + `quoted with its source: \`- Ruling YYYY-MM-DD (operator message: ): "" \`. ${declare}`; } /** The refusal for a direct internal vibe-worker launch, or null. */ diff --git a/plugins/vibe-closedloop/hooks/merge-guard.mjs b/plugins/vibe-closedloop/hooks/merge-guard.mjs index ccf78b34..d5e40446 100644 --- a/plugins/vibe-closedloop/hooks/merge-guard.mjs +++ b/plugins/vibe-closedloop/hooks/merge-guard.mjs @@ -104,7 +104,7 @@ export function mergeProblem(command, gh, { cwd, environment = process.env, bind /** * Why `call` would merge a pull request that changes the repository's UI paths without visual QA findings for its - * current head, or null. A file list GitHub cut short is treated as changing UI. + * current head, or null. A file list that stays short after reading every page is treated as changing UI. */ function mergeVisualQaProblem(call, gh, binding, headBranch, environment, readRemote) { const { checkout, unresolved, remote } = headBranchCheckout(call, headBranch, environment); @@ -119,8 +119,13 @@ function mergeVisualQaProblem(call, gh, binding, headBranch, environment, readRe try { view = capturedJson(gh(args, { cwd: call.cwd })); } catch (error) { return `${name} refused: visual QA cannot be checked because gh could not list the pull request's files (${String(error?.message ?? error).split("\n")[0]}); rerun when gh can answer`; } const { files, changedFiles, headRefOid, body } = view ?? {}; - const paths = Array.isArray(files) ? files.map((file) => file?.path).filter((file) => typeof file === "string") : []; - const complete = Array.isArray(files) && Number.isInteger(changedFiles) && paths.length >= changedFiles; + let paths = Array.isArray(files) ? files.map((file) => file?.path).filter((file) => typeof file === "string") : []; + let complete = Array.isArray(files) && Number.isInteger(changedFiles) && paths.length >= changedFiles; + // gh pr view lists at most 100 files; a larger pull request is read page by page before it is judged. + if (!complete && Number.isInteger(changedFiles)) { + const listed = pagedFiles(call, gh, changedFiles); + if (listed) [paths, complete] = [listed, true]; + } let gateWitness = checkout ? () => readFileSync(gatePath(checkout), "utf8") : null; let expected = checkout ? undefined : null; if (remote) { @@ -155,6 +160,20 @@ function mergeVisualQaProblem(call, gh, binding, headBranch, environment, readRe return null; } +/** Every changed file of the pull request from the paginated files API, or null when that listing fails or comes up short. */ +function pagedFiles(call, gh, changedFiles) { + try { + const { url } = capturedJson(gh(["pr", "view", ...(call.target ? [call.target] : []), ...(call.repo ? ["-R", call.repo] : []), "--json", "url"], { cwd: call.cwd })) ?? {}; + const pr = /^https:\/\/github\.com\/([^/]+)\/([^/]+)\/pull\/(\d+)$/.exec(url ?? ""); + if (!pr) return null; + const listed = String(gh(["api", "--paginate", `repos/${pr[1]}/${pr[2]}/pulls/${pr[3]}/files`, "--jq", ".[].filename"], { cwd: call.cwd })) + .split("\n").filter(Boolean); + return listed.length >= changedFiles ? listed : null; + } catch { + return null; + } +} + /** Whichever of the session's binding and the head's recorded one declare UI paths, or the refusal when either cannot be read. */ function declaringSides(name, binding, recorded) { try { return { declaring: [binding, recorded()].filter(declaresUiPaths) }; } catch (error) { diff --git a/plugins/vibe-closedloop/lib/vibe/scripts/cloud-environment.mjs b/plugins/vibe-closedloop/lib/vibe/scripts/cloud-environment.mjs index 579d3a89..edac0ad2 100644 --- a/plugins/vibe-closedloop/lib/vibe/scripts/cloud-environment.mjs +++ b/plugins/vibe-closedloop/lib/vibe/scripts/cloud-environment.mjs @@ -18,7 +18,7 @@ import { existsSync, readFileSync } from "node:fs"; import path from "node:path"; import os from "node:os"; import { fileURLToPath } from "node:url"; -import { measuredSetupTools } from "./cloud-validation-environment.mjs"; +import { lastSetupMeasurement } from "./cloud-validation-environment.mjs"; import { cloudRecipe } from "./cloud-validation-recipes.mjs"; import { parseConfig } from "../../codex-fleet-monitor/scripts/work-dir.mjs"; import { defaultHome } from "../../fleet-orchestrator/scripts/fleet-home.mjs"; @@ -52,6 +52,8 @@ export function cloudSetupScript({ recipe = cloudRecipe, root = VIBE_ROOT } = {} export const CLAUDE_ENV_VAR = "VIBE_CLOUD_CLAUDE_ENV"; export const CLAUDE_ENV_CONFIG_KEY = "CLOUD_CLAUDE_ENV"; +// No script can read which Claude account Chrome or its extension is signed in to (extension storage and encrypted cookies). +const CHROME_ACCOUNT = "cannot verify by script which Claude account Chrome and the Claude in Chrome extension are signed in to. Check by hand on each machine that launches cloud workers: Chrome is signed in to the same account on every such machine, and claude.ai in Chrome and the Claude in Chrome extension both show the Claude account that `claude auth status` shows."; const NOTHING_RECORDED = "no vibe cloud worker routine is recorded on this machine yet; the first cloud run creates it"; export const CloudSetupError = Object.freeze({ EnvMissing: "CLOUD_ENV_MISSING", @@ -180,6 +182,9 @@ function environmentSetupCheck(routine) { if (!last) return { check: "environment-setup", ok: null, detail: "not exercised: the recorded routine has no run yet, so check did not run the environment setup script" }; const status = String(last.status ?? "").toLowerCase(); + // A run that finished got past the environment setup, which archives the session when it fails. + if (status.includes("succeed")) return { check: "environment-setup", ok: true, + detail: `the last run finished with status ${last.status}, so the environment setup script completed` }; const turns = last.turn_count ?? last.turns_count ?? last.num_turns; if (status.includes("archiv") && (!Number.isInteger(turns) || turns === 0)) { return { check: "environment-setup", ok: false, code: "CLOUD_ENV_SETUP_FAILED", @@ -193,9 +198,9 @@ function environmentSetupCheck(routine) { /** * The setup check: environment configured, the account pin, API reachable, the environment this machine's standing - * routine (`standing`, from the routine ledger) runs in, the GitHub connection, and the lane tools (zsh, uv, Python - * 3.13, Node 24, pnpm and Chromium headless shell 1254) a current measured run on this account and environment - * verified; `pending` is the routine-removal line when routines vibe created are still recorded for removal. + * routine (`standing`, from the routine ledger) runs in, the GitHub connection, the lane tools the setup script installs + * as the last measured run on this account and environment found them, and the Chrome account check this script + * cannot make; `pending` is the routine-removal line when routines vibe created are still recorded for removal. */ export function checkCloudSetup(request, { remote, env = process.env, home = os.homedir(), standing = null, pending = null, ledgerProblem = null, githubTokenMissingAt = null, account, environmentPin = null } = {}) { const checks = []; @@ -249,14 +254,32 @@ export function checkCloudSetup(request, { remote, env = process.env, home = os. detail: `The routine API reported github_token_missing${refusedAt ? ` on ${refusedAt}` : ""}. ${CONNECT_GITHUB}` } : { check: "github", ok: null, detail: "No GitHub connection refusal is recorded. This read-only check does not create a task to test repository access." }); const ownsEnvironment = checks.some((row) => row.check === "environment-use" && row.ok === true); - const observed = ownsEnvironment && !accountProblem && account?.uuid && environment - ? measuredSetupTools(home, environmentPin, account.uuid, environment.id) : null; - const setup = cloudSetupScript(); - const missing = setup.checks.filter((key) => observed?.[key] !== true); - checks.push(missing.length ? { check: "lane-tools", ok: false, code: "CLOUD_SETUP_UNVERIFIED", - detail: `Missing current account/environment measurements for ${missing.join(", ")}. At https://claude.ai/code open the environment selector, select the cloud environment's settings (or New environment), paste the setup script below (from ${setup.file}) into Setup script and save. Set CLOUD_CLAUDE_ENV= in ${path.join(defaultHome(env), "config.env")}. Re-pin with cloud-worker.mjs pin, run the cloud-capabilities lane on a pushed tooling head, then run check.`, - setupScript: setup.text } - : { check: "lane-tools", ok: true, detail: `A current measured run on this account and environment verified ${setup.checks.map((key) => MEASURED_NAMES[key]).join(", ")}.` }); + const measured = ownsEnvironment && !accountProblem && account?.uuid && environment + ? lastSetupMeasurement(home, environmentPin, account.uuid, environment.id) : null; + checks.push(laneToolsCheck(measured, cloudSetupScript(), env)); + checks.push({ check: "chrome-account", ok: null, detail: CHROME_ACCOUNT }); if (pending) checks.push({ check: "routine-removal", ok: null, detail: pending }); return { ok: checks.every((entry) => entry.ok !== false), environment, checks }; } + +/** + * The lane-tools row. Paste advice only when a tool was measured false or this account and environment were never + * measured; a proof older than admission allows that measured every tool true needs only a fresh capability run. + */ +function laneToolsCheck(measured, setup, env) { + const names = (keys) => keys.map((key) => MEASURED_NAMES[key]).join(", "); + const failed = setup.checks.filter((key) => measured?.checks[key] === false); + if (!measured || failed.length) { + const what = failed.length ? `The last capability run on this account and environment measured ${names(failed)} missing.` + : `Missing current account/environment measurements for ${setup.checks.join(", ")}.`; + return { check: "lane-tools", ok: false, code: "CLOUD_SETUP_UNVERIFIED", + detail: `${what} At https://claude.ai/code open the environment selector, select the cloud environment's settings (or New environment), paste the setup script below (from ${setup.file}) into Setup script and save. Set CLOUD_CLAUDE_ENV= in ${path.join(defaultHome(env), "config.env")}. Re-pin with cloud-worker.mjs pin, run the cloud-capabilities lane on a pushed tooling head, then run check.`, + setupScript: setup.text }; + } + const unmeasured = setup.checks.filter((key) => measured.checks[key] !== true); + if (!measured.fresh || unmeasured.length) { + const seen = setup.checks.filter((key) => measured.checks[key] === true); + return { check: "lane-tools", ok: null, detail: `The last capability run on this account and environment (${new Date(measured.at).toISOString()}) measured ${seen.length ? names(seen) : "none of the setup's tools"} present${unmeasured.length ? ` and did not measure ${names(unmeasured)}` : ""}. It needs a fresh capability run before capability lanes: run the cloud-capabilities lane on a pushed tooling head, then run check.` }; + } + return { check: "lane-tools", ok: true, detail: `A current measured run on this account and environment verified ${names(setup.checks)}.` }; +} 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 b3b6d555..d3c05398 100644 --- a/plugins/vibe-closedloop/lib/vibe/scripts/cloud-validation-environment.mjs +++ b/plugins/vibe-closedloop/lib/vibe/scripts/cloud-validation-environment.mjs @@ -44,21 +44,25 @@ function validTool(tool) { !tool.ref.includes("..") && !tool.ref.includes("//") && !tool.ref.endsWith(".lock"); } -function matchingProof(home, pin, tool, now) { +function matchingProof(home, pin, tool, now, maxAge = PROOF_MAX_MS) { const file = proofPath(home, pin); if (!existsSync(file)) return null; let record; try { record = regularJson(file); } catch { return null; } if (record?.schema !== PROOF_SCHEMA || record.environmentId !== pin.environmentId || record.accountUuid !== pin.accountUuid || !validTool(record.tool) || (tool && (record.tool.commit !== tool.commit || record.tool.ref !== tool.ref)) || typeof record.sessionId !== "string" || !record.sessionId || - !Number.isFinite(record.at) || record.at > now || now - record.at > PROOF_MAX_MS) return null; + !Number.isFinite(record.at) || record.at > now || now - record.at > maxAge) return null; return record; } -/** Read a fresh capability measurement for this exact environment and signed-in account. */ -export function measuredSetupTools(home, pin, accountUuid, environmentId, now = Date.now()) { +/** + * The last capability measurement for this exact environment and signed-in account at any age, and whether it is still + * fresh enough for admission. Only admission needs a fresh one; a stale one still shows which tools the setup installed. + */ +export function lastSetupMeasurement(home, pin, accountUuid, environmentId, now = Date.now()) { if (!pin || pin.environmentId !== environmentId || pin.accountUuid !== accountUuid) return null; - return matchingProof(home, pin, null, now)?.checks ?? null; + const proof = matchingProof(home, pin, null, now, Infinity); + return proof ? { checks: proof.checks ?? {}, at: proof.at, fresh: now - proof.at <= PROOF_MAX_MS } : null; } function laneCommands(lane) { diff --git a/plugins/vibe-closedloop/lib/vibe/scripts/cloud-worker.mjs b/plugins/vibe-closedloop/lib/vibe/scripts/cloud-worker.mjs index 95a45ff1..b2220823 100644 --- a/plugins/vibe-closedloop/lib/vibe/scripts/cloud-worker.mjs +++ b/plugins/vibe-closedloop/lib/vibe/scripts/cloud-worker.mjs @@ -266,7 +266,11 @@ function toolResultText(body, structured) { function triggerDiagnostic(result, terminal, last) { const clean = (value) => redactedLine(value).slice(0, 400); const errors = Array.isArray(terminal?.errors) ? terminal.errors.slice(0, 3).map((error) => clean(error?.message ?? error)).filter(Boolean) : []; - const end = [clean(terminal?.subtype), ...errors].filter(Boolean).join(": "); + // A failed `claude -p` (an OAuth refresh that failed over ssh) can end with subtype "success" and the cause in `result`. + const failed = terminal?.is_error === true || (Number.isInteger(result.status) && result.status !== 0); + const cause = failed && typeof terminal?.result === "string" ? clean(terminal.result) : ""; + const subtype = clean(terminal?.subtype); + const end = [cause && subtype === "success" ? "" : subtype, cause, ...errors].filter(Boolean).join(": "); const tool = clean(last?.raw); const stderr = clean(result.stderr); const spawn = clean(result.error?.message); @@ -546,6 +550,11 @@ export function verifyRepository(worktree, repository) { return resolveRepository(repository, origin); } +/** The request with its repository filled from the worktree's origin when it names none (the field is optional). */ +function withRepository(request) { + return request.repository === undefined ? { ...request, repository: verifyRepository(request.worktree) } : request; +} + /** A request's resolved repository; every cloud call runs after verifyRepository named it. */ function requireRepository(request) { if (!request.repository) throw new Error("the cloud repository was not resolved from the request or the worktree's origin"); @@ -609,7 +618,7 @@ export async function abandonValidation(request, { confirm = false, home = os.ho validateValidationRequest(request); const key = sha256(JSON.stringify(request)), base = validationReceiptPath(request, key); const file = request.lanes?.some(lane => lane.name === "cloud-capabilities") - ? boundProbeReceipt(base, validationLanes(request).lanes, readLedger(home), resolveClaudeEnvironment(request)) : base; + ? boundProbeReceipt(base, validationLanes(withRepository(request)).lanes, readLedger(home), resolveClaudeEnvironment(request)) : base; const receipt = existsSync(file) ? JSON.parse(readFileSync(file, "utf8")) : null; const abandoned = receipt && (TERMINAL.has(receipt.status) ? receipt : { ...receipt, status: "abandoned", finishedAt: new Date().toISOString() }); const result = await releaseValidationReservation({ home, key, confirm, unconfirmed: (plan) => unconfirmed("abandon", plan), markRun: (runId) => markRun(home, runId, "abandoned", DEFAULT_WALL_MS), @@ -773,7 +782,7 @@ export function validateValidationRequest(request) { if (Object.hasOwn(request, "env") || Object.hasOwn(request, "envValues")) throw new Error("caller test environment values are refused"); if (!Array.isArray(request.lanes) || request.lanes.length === 0) throw new Error("at least one lane is required"); if (new Set(request.lanes.map((lane) => lane.name)).size !== request.lanes.length) throw new Error("lane names must be unique"); - validationLanes(request); + validationLanes(withRepository(request)); if (request.resultArtifact !== undefined) { const artifact = request.resultArtifact; if (!artifact || typeof artifact !== "object" || typeof artifact.path !== "string" @@ -790,8 +799,9 @@ export function validateValidationRequest(request) { } /** The validation-only brief: exact checkout, install, lanes, no changes, one bound result line. */ -export function validationBrief(request, managedHost = null, provedBranch = null, requestKey = sha256(JSON.stringify(request))) { - validateValidationRequest(request); +export function validationBrief(raw, managedHost = null, provedBranch = null, requestKey = sha256(JSON.stringify(raw))) { + validateValidationRequest(raw); + const request = withRepository(raw); const resolved = validationLanes(request); const artifact = request.resultArtifact; const branch = provedBranch ?? request.branch; diff --git a/plugins/vibe-closedloop/skills/handoff/scripts/rulings-check.mjs b/plugins/vibe-closedloop/skills/handoff/scripts/rulings-check.mjs index 96649fdf..31063deb 100644 --- a/plugins/vibe-closedloop/skills/handoff/scripts/rulings-check.mjs +++ b/plugins/vibe-closedloop/skills/handoff/scripts/rulings-check.mjs @@ -244,6 +244,18 @@ export function separationRuling(program, reason, tickets) { return null; } +/** + * The program's quoted operator ruling, with its source, whose decision names `ticket` by its whole id, or null. A ruling + * copied from a ticket (`ticket:` channel) or one with no quoted words is never the operator's authority for a worker. + */ +export function operatorTicketRuling(program, ticket) { + for (const match of String(program ?? "").matchAll(PROGRAM_RULING)) { + const [, date, channel, source, decision] = match; + if (channel !== "ticket" && /"[^"\n]+"|“[^”\n]+”/u.test(decision) && rulingNamesScope(decision, [ticket], { exact: true })) return { date, channel, source, decision }; + } + return null; +} + /** A dated operator ruling line: its channel, its optional source after a colon, and its decision. */ const OPERATOR_RULING = /^\s*[-*]\s*Ruling\s+(\d{4}-\d{2}-\d{2})\s+\((operator message|AskUserQuestion)(?::\s*([^)]*?))?\s*\):\s*(\S.*)$/; const LOCATOR_CHANNELS = new Set(["chat", "slack", "dm", "email", "call", "meeting"]); diff --git a/plugins/vibe/.claude-plugin/plugin.json b/plugins/vibe/.claude-plugin/plugin.json index 930939fe..fe122a14 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.118", + "version": "1.1.119", "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 59bf8267..deb261a4 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.118", + "version": "1.1.119", "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 df8e9bd0..43a58196 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.118` contains 17 skills and 17 agents, and no hook manifest: the +Version `1.1.119` contains 17 skills and 17 agents, and no hook manifest: the `vibe-core` plugin, which vibe declares as a dependency, registers the hooks and runs `hooks/runtime.mjs` from the vibe a session uses. Skill commands forward to guards in `hooks/` and runtime modules in `lib/`. The package has no standalone commands, root shell scripts or production Python tools. Tests sit beside their owners; Python contract helpers and the generic scan live in `tools/python/`. diff --git a/plugins/vibe/hooks/agent-guard.mjs b/plugins/vibe/hooks/agent-guard.mjs index f2a203c3..85c59b80 100644 --- a/plugins/vibe/hooks/agent-guard.mjs +++ b/plugins/vibe/hooks/agent-guard.mjs @@ -11,6 +11,9 @@ import { vibeSkillOf } from "../shared/plugin-roots.mjs"; import { vibeScriptPath, vibeSkill } from "../shared/vibe-install.mjs"; import { briefProviderProblem } from "../lib/vibe/scripts/provider-brief.mjs"; import { recordedBinding } from "../lib/vibe/scripts/provider.mjs"; +import { chatProgramDir, defaultHome } from "../lib/fleet-orchestrator/scripts/fleet-home.mjs"; +import { validChat } from "../lib/fleet-orchestrator/scripts/chat-binding.mjs"; +import { operatorTicketRuling } from "../skills/handoff/scripts/rulings-check.mjs"; // Roles are agent names qualified by either vibe plugin. const VIBE_WORKER = /^vibe-[a-z0-9-]+-worker$/; @@ -41,19 +44,53 @@ function rawCodexLaunch(words) { return ["exec", "e", "review"].includes(words[i]); } -/** Fleet-only launch policy. Managed launchers start their child internally and never issue a raw parent tool call. */ -export function fleetLaunchGuard(event, home) { +/** + * Fleet-only launch policy. Managed launchers start their child internally and never issue a raw parent tool call. A + * native Agent brief declares `Worker role: read-only | operational | writer` and `Tickets: `; a brief with no + * role is a writer. A writer that is neither a vibe start nor a helper needs a quoted operator ruling naming each of its + * tickets in the program's rulings.md (operator ruling 2026-12-02). + */ +export function fleetLaunchGuard(event, home, env = process.env) { const input = event?.tool_input; const native = event.tool_name === "Agent"; + const prompt = String(input?.prompt ?? ""); + const lines = prompt.split("\n"); const candidate = native - ? !/^(?:\$vibe\b|\/(?:vibe|vibe-generic):vibe\b)/.test(input?.prompt?.trim() ?? "") + ? !/^(?:\$vibe\b|\/(?:vibe|vibe-generic):vibe\b)/.test(prompt.trim()) && !["Ticket writer:", "Helper branch and worktree:", "Exclusive file allowlist:", "Assignment:", "Test authority:", "Return:"] - .every(field => String(input?.prompt ?? "").split("\n").some(line => line.startsWith(field) && line.slice(field.length).trim())) + .every(field => lines.some(line => line.startsWith(field) && line.slice(field.length).trim())) : typeof input?.command === "string"; if (!candidate || conversationSkill(event, home) !== "fleet-orchestrator") return null; - if (!native && !commandCalls(input.command, eventCwd(event)).some(({ words, value }) => rawCodexLaunch(words.map(word => value(word) ?? word)))) return null; - return deny("Fleet ticket analysis uses dist/claude-worker.mjs with vibe-requirements-worker in sessionless startup mode. " - + "Use dist/codex-reviewer.mjs for review, dist/codex-reviewer.mjs run --role visual-qa-critic --agent-definition for visual QA, or fleet.sh session turn for assigned worker work."); + if (native) { + const problem = plainWriterProblem(lines, event, env); + return problem ? deny(`${problem} ${FLEET_ROUTES}`) : null; + } + if (!commandCalls(input.command, eventCwd(event)).some(({ words, value }) => rawCodexLaunch(words.map(word => value(word) ?? word)))) return null; + return deny(FLEET_ROUTES); +} + +const FLEET_ROUTES = "Fleet ticket analysis uses dist/claude-worker.mjs with vibe-requirements-worker in sessionless startup mode. " + + "Use dist/codex-reviewer.mjs for review, dist/codex-reviewer.mjs run --role visual-qa-critic --agent-definition for visual QA, or fleet.sh session turn for assigned worker work."; +const NON_WRITER_ROLES = new Set(["read-only", "operational"]); + +/** Why a fleet chat may not launch this brief as a plain worker, or null: decided from its declared lines only. */ +function plainWriterProblem(lines, event, env) { + const declared = (field) => lines.find((line) => line.startsWith(field))?.slice(field.length).trim() ?? ""; + if (NON_WRITER_ROLES.has(declared("Worker role:").toLowerCase())) return null; + const tickets = declared("Tickets:").split(/[\s,]+/).filter(Boolean); + const declare = "Declare `Worker role: read-only` or `Worker role: operational` for a worker that writes no code."; + if (tickets.length === 0) { + return `A worker brief with no read-only or operational role is a writer, and a writer names its tickets on a \`Tickets: \` line. ${declare}`; + } + let rulings = ""; + try { + const chat = validChat(event?.session_id); + rulings = readFileSync(path.join(chatProgramDir(defaultHome(env, chat), chat, env).dir, "rulings.md"), "utf8"); + } catch { /* No program or no rulings file: no ticket has a ruling. */ } + const missing = tickets.filter((ticket) => !operatorTicketRuling(rulings, ticket)); + if (missing.length === 0) return null; + return `A plain worker that writes code for ${missing.join(", ")} outside vibe needs the operator's ruling naming that ticket in the program's rulings.md, ` + + `quoted with its source: \`- Ruling YYYY-MM-DD (operator message: ): "" \`. ${declare}`; } /** The refusal for a direct internal vibe-worker launch, or null. */ diff --git a/plugins/vibe/hooks/agent-guard.test.mjs b/plugins/vibe/hooks/agent-guard.test.mjs index 19f7b1f5..3d152b2e 100644 --- a/plugins/vibe/hooks/agent-guard.test.mjs +++ b/plugins/vibe/hooks/agent-guard.test.mjs @@ -5,7 +5,7 @@ import os from "node:os"; import path from "node:path"; import test from "node:test"; import { fileURLToPath } from "node:url"; -import { agentGuard, agentLaunchProblem, paneLaunchProblem, writerBindingProblem } from "./agent-guard.mjs"; +import { agentGuard, agentLaunchProblem, fleetLaunchGuard, paneLaunchProblem, writerBindingProblem } from "./agent-guard.mjs"; import { PRE_TOOL_USE_ROUTES } from "./pre-tool-use.mjs"; import { vibeRoot } from "../shared/vibe-install.mjs"; import { activatedChat } from "./activation-test-support.mjs"; @@ -148,3 +148,55 @@ test("a named launch into a terminal pane is refused when its name can push the assert.match(problem("audit-1114-mesh", { TMUX: "/tmp/tmux,1,0" }) ?? "", /never starts/); assert.equal(problem("audit-1114-mesh", {}), null, "automatic mode outside tmux and iTerm stays in process"); }); + +test("ISS-15030 AC-8 a fleet chat launches read-only and operational workers, and a plain writer only with a quoted operator ruling naming its ticket", (t) => { + const root = mkdtempSync(path.join(os.tmpdir(), "fleet-launch-guard-")); + t.after(() => rmSync(root, { recursive: true, force: true })); + const fleetHome = path.join(root, "fleet"); + mkdirSync(path.join(fleetHome, "programs", "bugs"), { recursive: true }); + writeFileSync(path.join(fleetHome, "current"), "bugs\n"); + const rulings = path.join(fleetHome, "programs", "bugs", "rulings.md"); + const transcript = path.join(root, "transcript.jsonl"); + writeFileSync(transcript, JSON.stringify({ type: "user", message: { content: "Base directory for this skill: /cache/vibe/1.1.119/skills/fleet-orchestrator" } }) + "\n"); + const env = { FLEET_HOME: fleetHome, HOME: root }; + const launch = (prompt) => fleetLaunchGuard({ tool_name: "Agent", session_id: "chat-fixture", transcript_path: transcript, cwd: root, + tool_input: { subagent_type: "general-purpose", prompt } }, root, env); + const denied = (result) => result?.decision === "deny"; + writeFileSync(rulings, [ + "# Rulings", + "- Ruling 2026-12-02 (operator message: chat 3:20 PM): \"yes, plain workers for the next two PRs\" ISS-15030 is finished outside vibe.", + "- Ruling 2026-12-02 (ticket: ISS-15022): \"plain worker\" ISS-15022 copied from the ticket, not the operator.", + ].join("\n") + "\n"); + + assert.equal(launch("Worker role: read-only\nRun the node test lane on laptop 2 and report."), null, "a read-only lane worker passes"); + assert.equal(launch("Worker role: operational\nClean up the stale worktrees."), null, "an operational worker passes"); + assert.equal(launch("Worker role: writer\nTickets: ISS-15030\nFix the cloud check."), null, "a plain writer with a matching ruling passes"); + const without = launch("Worker role: writer\nTickets: ISS-15031\nFix the next thing."); + assert.ok(denied(without), "a plain writer without a ruling is refused"); + assert.match(without.reason, /rulings\.md/); + assert.match(without.reason, /ISS-15031/); + assert.ok(denied(launch("Worker role: writer\nTickets: ISS-15022\nFix it.")), "a ruling copied from a ticket is not the operator's"); + assert.ok(denied(launch("Worker role: writer\nTickets: ISS-15030, ISS-15031\nFix both.")), "every ticket needs its ruling"); + assert.ok(denied(launch("Worker role: writer\nFix the cloud check for ISS-15030.")), "a writer names its tickets on a Tickets line, never in free text"); + assert.ok(denied(launch("Tickets: ISS-15031\nThis is read-only research, it writes no code.")), "a brief with no declared role is a writer"); + assert.equal(launch("Tickets: ISS-15030\nFix the cloud check."), null, "a brief with no declared role and a matching ruling passes as a writer"); + + assert.equal(launch("/vibe:vibe ISS-15031"), null, "a vibe session start keeps passing"); + const helper = ["Ticket writer: w1", "Helper branch and worktree: h/1 at /tmp/h1", "Exclusive file allowlist: a.mjs", "Assignment: fix a", + "Test authority: focused", "Return: summary"].join("\n"); + assert.equal(launch(helper), null, "a helper brief keeps passing"); + // Through the hook entry, which calls the guard with the event alone and the process environment. + const hook = (prompt) => spawnSync(process.execPath, [GUARD], { encoding: "utf8", env: { ...process.env, ...env }, + input: JSON.stringify({ hook_event_name: "PreToolUse", tool_name: "Agent", session_id: "chat-fixture", transcript_path: transcript, cwd: root, + tool_input: { subagent_type: "general-purpose", prompt } }) }); + assert.equal(hook("Worker role: writer\nTickets: ISS-15030\nFix the cloud check.").stdout, "", "the hook lets a ruled writer start"); + assert.match(JSON.parse(hook("Worker role: writer\nTickets: ISS-15031\nFix it.").stdout).hookSpecificOutput.permissionDecisionReason, /ISS-15031 outside vibe/, + "the hook refuses a writer without a ruling"); + rmSync(rulings); + assert.ok(denied(launch("Worker role: writer\nTickets: ISS-15030\nFix the cloud check.")), "with no rulings.md no writer has a ruling"); + assert.equal(launch("Worker role: read-only\nRead the logs."), null, "a read-only worker needs no rulings.md"); + + const outside = fleetLaunchGuard({ tool_name: "Agent", session_id: "chat-fixture", transcript_path: path.join(root, "none.jsonl"), cwd: root, + tool_input: { subagent_type: "general-purpose", prompt: "Worker role: writer\nTickets: ISS-15031" } }, root, env); + assert.equal(outside, null, "outside a fleet-orchestrator chat the guard does nothing"); +}); diff --git a/plugins/vibe/hooks/merge-guard.mjs b/plugins/vibe/hooks/merge-guard.mjs index ccf78b34..d5e40446 100644 --- a/plugins/vibe/hooks/merge-guard.mjs +++ b/plugins/vibe/hooks/merge-guard.mjs @@ -104,7 +104,7 @@ export function mergeProblem(command, gh, { cwd, environment = process.env, bind /** * Why `call` would merge a pull request that changes the repository's UI paths without visual QA findings for its - * current head, or null. A file list GitHub cut short is treated as changing UI. + * current head, or null. A file list that stays short after reading every page is treated as changing UI. */ function mergeVisualQaProblem(call, gh, binding, headBranch, environment, readRemote) { const { checkout, unresolved, remote } = headBranchCheckout(call, headBranch, environment); @@ -119,8 +119,13 @@ function mergeVisualQaProblem(call, gh, binding, headBranch, environment, readRe try { view = capturedJson(gh(args, { cwd: call.cwd })); } catch (error) { return `${name} refused: visual QA cannot be checked because gh could not list the pull request's files (${String(error?.message ?? error).split("\n")[0]}); rerun when gh can answer`; } const { files, changedFiles, headRefOid, body } = view ?? {}; - const paths = Array.isArray(files) ? files.map((file) => file?.path).filter((file) => typeof file === "string") : []; - const complete = Array.isArray(files) && Number.isInteger(changedFiles) && paths.length >= changedFiles; + let paths = Array.isArray(files) ? files.map((file) => file?.path).filter((file) => typeof file === "string") : []; + let complete = Array.isArray(files) && Number.isInteger(changedFiles) && paths.length >= changedFiles; + // gh pr view lists at most 100 files; a larger pull request is read page by page before it is judged. + if (!complete && Number.isInteger(changedFiles)) { + const listed = pagedFiles(call, gh, changedFiles); + if (listed) [paths, complete] = [listed, true]; + } let gateWitness = checkout ? () => readFileSync(gatePath(checkout), "utf8") : null; let expected = checkout ? undefined : null; if (remote) { @@ -155,6 +160,20 @@ function mergeVisualQaProblem(call, gh, binding, headBranch, environment, readRe return null; } +/** Every changed file of the pull request from the paginated files API, or null when that listing fails or comes up short. */ +function pagedFiles(call, gh, changedFiles) { + try { + const { url } = capturedJson(gh(["pr", "view", ...(call.target ? [call.target] : []), ...(call.repo ? ["-R", call.repo] : []), "--json", "url"], { cwd: call.cwd })) ?? {}; + const pr = /^https:\/\/github\.com\/([^/]+)\/([^/]+)\/pull\/(\d+)$/.exec(url ?? ""); + if (!pr) return null; + const listed = String(gh(["api", "--paginate", `repos/${pr[1]}/${pr[2]}/pulls/${pr[3]}/files`, "--jq", ".[].filename"], { cwd: call.cwd })) + .split("\n").filter(Boolean); + return listed.length >= changedFiles ? listed : null; + } catch { + return null; + } +} + /** Whichever of the session's binding and the head's recorded one declare UI paths, or the refusal when either cannot be read. */ function declaringSides(name, binding, recorded) { try { return { declaring: [binding, recorded()].filter(declaresUiPaths) }; } catch (error) { diff --git a/plugins/vibe/hooks/merge-guard.test.mjs b/plugins/vibe/hooks/merge-guard.test.mjs index 5058628e..3ba2cc6f 100644 --- a/plugins/vibe/hooks/merge-guard.test.mjs +++ b/plugins/vibe/hooks/merge-guard.test.mjs @@ -314,3 +314,35 @@ echo '{"author":{"login":"operator"},"headRefName":"vibe/ui"}' assert.equal(output.permissionDecision, "deny"); assert.match(output.permissionDecisionReason, /visual QA is required/); }); + +test("ISS-15030 AC-7 a pull request over GitHub's 100-file view is judged on its full paginated file list", (t) => { + const { worktree, binding } = uiBinding(t); + const head = "c".repeat(40); + const docs = Array.from({ length: 101 }, (_, index) => `docs/page-${index}.md`); + const prs = { 454: docs, 455: [...docs.slice(0, 100), "apps/app/header.tsx"] }; + const calls = []; + const gh = (args, { paginationFails = false } = {}) => { + calls.push(args.join(" ")); + if (args[0] === "api" && args[1] === "user") return "operator\n"; + if (args[0] === "api") { + const number = /^repos\/acme\/app\/pulls\/(\d+)\/files$/.exec(args[2])?.[1]; + assert.ok(args.includes("--paginate"), "every page is read"); + if (paginationFails || !number) throw new Error("HTTP 502"); + return prs[number].join("\n") + "\n"; + } + if (args.includes("files,changedFiles,headRefOid,body")) { + // gh pr view lists at most 100 files. + return JSON.stringify({ files: prs[args[2]].slice(0, 100).map((file) => ({ path: file })), changedFiles: prs[args[2]].length, headRefOid: head, body: "" }); + } + if (args.includes("url")) return JSON.stringify({ url: `https://github.com/acme/app/pull/${args[2]}` }); + return JSON.stringify({ author: { login: "operator" }, headRefName: "vibe/ui" }); + }; + const problem = (command, options) => mergeProblem(command, (args) => gh(args, options), { cwd: worktree, environment: {}, binding }); + assert.equal(problem("gh pr merge 454 --squash --auto"), null, "101 non-UI files merge without visual QA"); + assert.ok(calls.includes("api --paginate repos/acme/app/pulls/454/files --jq .[].filename")); + const ui = problem("gh pr merge 455 --squash --auto") ?? ""; + assert.match(ui, /visual QA is required \(1 changed file\(s\)[^)]*apps\/app\/header\.tsx\)/, "the 101st file is UI"); + assert.doesNotMatch(ui, /listed only part/); + assert.match(problem("gh pr merge 454 --squash --auto", { paginationFails: true }) ?? "", /listed only part of its changed files/, + "a failed pagination is still treated as partial"); +}); diff --git a/plugins/vibe/lib/vibe/scripts/cloud-capability-probe.test.mjs b/plugins/vibe/lib/vibe/scripts/cloud-capability-probe.test.mjs index aa6df77e..89833e87 100644 --- a/plugins/vibe/lib/vibe/scripts/cloud-capability-probe.test.mjs +++ b/plugins/vibe/lib/vibe/scripts/cloud-capability-probe.test.mjs @@ -423,3 +423,30 @@ test("ISS-14874 a megabyte of one repeated text is redacted, and the credential assert.ok(redactUserinfo(text) === `${filler}\nPASSWORD=s3cret https://@proxy.internal`, form); } }); + +test("ISS-15030 AC-3 a cloud-capabilities validate request without repository takes it from the worktree's origin", async (t) => { + const { validateValidationRequest, validationBrief } = await import("./cloud-worker.mjs"); + const { git, makeCheckout } = await import("../../../skills/vibe/scripts/test-fixtures.mjs"); + const f = makeHome("probe-origin-repository-"); + t.after(f.cleanup); + const { repository, ...base } = canonicalRequest(); + const worktree = path.join(f.root, "checkout"), probe = CLOUD_CAPABILITIES_COMMAND.slice(5); + // `git remote get-url` applies the fixture's insteadOf, so drop it: these checks read only local objects. + const checkout = (dir, remoteUrl) => { + const { origin } = makeCheckout({ ...f, checkout: dir, remoteUrl, files: { [probe]: "export {};", [probe.replace("probe.mjs", "electron.cjs")]: "" } }); + git(dir, ["config", "--remove-section", `url.${origin}`], f.home); + }; + checkout(worktree, "https://github.com/" + repository); + const request = { ...base, provider: "claude", model: "claude-sonnet-5-5", commit: git(worktree, ["rev-parse", "HEAD"], f.home), worktree, branch: "main" }; + assert.equal(Object.hasOwn(request, "repository"), false); + assert.doesNotThrow(() => validateValidationRequest(request), "the header says repository is optional"); + assert.match(validationBrief(request), /cloud-capability-probe\.mjs/); + const { abandonValidation } = await import("./cloud-worker.mjs"); + // Abandoning the same request resolves its repository the same way and reaches the pin check, not the lane refusal. + await assert.rejects(abandonValidation({ ...request, claudeEnvironment: "env_01Fixture" }, { home: f.home, remote: () => { throw new Error("no remote call expected"); } }), + /requires a verified account and environment pin/); + const other = path.join(f.root, "other"); + checkout(other, "https://github.com/example-org/other-repo"); + assert.throws(() => validateValidationRequest({ ...request, worktree: other, commit: git(other, ["rev-parse", "HEAD"], f.home) }), + /CLOUD_CAPABILITY_UNAVAILABLE/, "an origin that is not the tooling repository is still refused"); +}); diff --git a/plugins/vibe/lib/vibe/scripts/cloud-check-rows.test.mjs b/plugins/vibe/lib/vibe/scripts/cloud-check-rows.test.mjs new file mode 100644 index 00000000..8ea661e1 --- /dev/null +++ b/plugins/vibe/lib/vibe/scripts/cloud-check-rows.test.mjs @@ -0,0 +1,104 @@ +import assert from "node:assert/strict"; +import test from "node:test"; +import { checkCloudSetup, cloudSetupScript } from "./cloud-environment.mjs"; +// The ClosedLoop build, whose recipe names its own setup script. +import { checkCloudSetup as providerCheckSetup, cloudSetupScript as providerSetup } from "../../../../vibe-closedloop/lib/vibe/scripts/cloud-environment.mjs"; +import { remoteTrigger } from "./cloud-worker.mjs"; +import { confirmCloudEnvironment } from "./cloud-validation-environment.mjs"; +import { makeHome } from "../../../../vibe/skills/vibe/scripts/test-fixtures.mjs"; + +const PIN = { accountUuid: "a0a01111-1111-4111-a111-111111111111", environmentId: "env_Fixture" }; +const TOOL = { commit: "a".repeat(40), ref: "refs/heads/proof" }; +const STALE = 31 * 60_000; +const FRESH_RUN = /needs a fresh capability run before capability lanes/; +const owning = () => ({ data: [{ id: "standing", job_config: { ccr: { environment_id: PIN.environmentId } } }] }); +const row = (result, name) => result.checks.find((entry) => entry.check === name); + +function proofFixture(t, check, setup) { + const f = makeHome("vibe-cloud-rows-"); + t.after(f.cleanup); + const allTrue = { workspace: true, nonRoot: true, ports: true, chromium: true, gitUtc: true, ...Object.fromEntries(setup.checks.map((key) => [key, true])) }; + const record = (flags, at = Date.now()) => confirmCloudEnvironment({ home: f.home, pin: PIN, environmentId: PIN.environmentId, + tool: TOOL, sessionId: "session-fixture", completed: true, now: at, outcome: { name: "cloud-capabilities", exitCode: 0, + stdoutTail: "CLOUD_HOST_RUNTIME " + JSON.stringify({ commit: TOOL.commit, checks: flags }) } }); + const run = () => check({ claudeEnvironment: PIN.environmentId }, { home: f.home, account: { uuid: PIN.accountUuid }, environmentPin: PIN, remote: owning }); + return { allTrue, record, run }; +} + +for (const [edition, check, setupOf] of [["generic", checkCloudSetup, cloudSetupScript], ["provider", providerCheckSetup, providerSetup]]) { + test(`ISS-15030 AC-1 AC-2 (${edition}) lane-tools fails only for a tool measured false or no proof, and prints this edition's script`, (t) => { + const setup = setupOf(); + const { allTrue, record, run } = proofFixture(t, check, setup); + + const never = row(run(), "lane-tools"); + assert.equal(never.ok, false, "there was never a proof"); + assert.equal(never.setupScript, setup.text, "the advice prints the script cloudSetupScript returns for this edition"); + + record(allTrue); + const fresh = run(); + assert.equal(row(fresh, "lane-tools").ok, true, "a fresh all-true proof passes"); + assert.equal(row(fresh, "lane-tools").setupScript, undefined); + + record(allTrue, Date.now() - STALE); + const stale = run(); + const staleRow = row(stale, "lane-tools"); + assert.notEqual(staleRow.ok, false, "a stale proof that measured every tool true does not fail lane-tools"); + assert.equal(stale.ok, true); + assert.match(staleRow.detail, FRESH_RUN); + assert.equal(staleRow.setupScript, undefined, "no setup script to paste"); + assert.doesNotMatch(staleRow.detail, /paste|Setup script/i); + + const [first] = setup.checks; + for (const at of [Date.now(), Date.now() - STALE]) { + record({ ...allTrue, [first]: false }, at); + const missing = row(run(), "lane-tools"); + assert.equal(missing.ok, false, "a tool measured false fails, fresh or stale"); + assert.equal(missing.setupScript, setup.text); + assert.match(missing.detail, /Setup script/); + } + }); +} + +test("ISS-15030 AC-2 the generic edition's script differs from the provider's, so each edition's advice is its own", () => { + assert.notEqual(cloudSetupScript().text, providerSetup().text); + assert.match(providerSetup().file, /cloud-env-setup-closedloop\.md$/); +}); + +// The stream shape is inferred from the reported message ("RemoteTrigger get failed: result success"); no failing stream was captured. +test("ISS-15030 AC-4 the api row names the claude -p failure, never a bare \"result success\"", () => { + for (const [status, isError] of [[1, true], [1, false], [0, true]]) { + const failing = () => ({ status, stderr: "", stdout: [ + JSON.stringify({ type: "system", subtype: "init" }), + JSON.stringify({ type: "result", subtype: "success", is_error: isError, result: "OAuth session expired and could not be refreshed. Please run /login." }), + ].join("\n") }); + const remote = (action, payload) => remoteTrigger(action, payload, { run: failing }); + assert.throws(() => remote("get", { trigger_id: "standing" }), /OAuth session expired and could not be refreshed/); + const api = row(checkCloudSetup({ claudeEnvironment: PIN.environmentId }, { remote, standing: { id: "standing" } }), "api"); + assert.equal(api.ok, false); + assert.match(api.detail, /OAuth session expired and could not be refreshed/, `exit ${status}, is_error ${isError}`); + assert.doesNotMatch(api.detail, /result success\b(?!:)/); + } +}); + +test("ISS-15030 AC-5 environment-setup passes after a completed run in that environment", () => { + const setupRow = (last) => row(checkCloudSetup({ claudeEnvironment: PIN.environmentId }, { standing: { id: "standing" }, + remote: () => ({ trigger: { id: "standing", job_config: { ccr: { environment_id: PIN.environmentId } }, last_run: last } }) }), "environment-setup"); + const done = setupRow({ status: "ROUTINE_RUN_STATUS_SUCCEEDED" }); + assert.equal(done.ok, true); + assert.doesNotMatch(done.detail, /not exercised/); + assert.equal(setupRow({ status: "ROUTINE_RUN_STATUS_RUNNING" }).ok, null, "a run still going proves nothing yet"); + assert.equal(setupRow({ status: "ROUTINE_RUN_STATUS_ARCHIVED", turn_count: 0 }).ok, false, "an archived run with no turn still fails"); +}); + +test("ISS-15030 AC-6 one named row says the Chrome and extension account cannot be verified by a script and names the manual check", () => { + for (const account of [{ uuid: PIN.accountUuid }, { error: Object.assign(new Error("CLOUD_ACCOUNT_UNVERIFIED: x"), { code: "CLOUD_ACCOUNT_UNVERIFIED" }) }, undefined]) { + const result = checkCloudSetup({ claudeEnvironment: PIN.environmentId }, { remote: owning, account, environmentPin: PIN }); + const rows = result.checks.filter((entry) => entry.check === "chrome-account"); + assert.equal(rows.length, 1); + assert.equal(rows[0].ok, null, "unverified, never a pass"); + assert.match(rows[0].detail, /cannot verify/); + assert.match(rows[0].detail, /Claude in Chrome extension/); + assert.match(rows[0].detail, /claude auth status/); + assert.match(rows[0].detail, /each machine that launches cloud workers/); + } +}); diff --git a/plugins/vibe/lib/vibe/scripts/cloud-environment.mjs b/plugins/vibe/lib/vibe/scripts/cloud-environment.mjs index 579d3a89..edac0ad2 100644 --- a/plugins/vibe/lib/vibe/scripts/cloud-environment.mjs +++ b/plugins/vibe/lib/vibe/scripts/cloud-environment.mjs @@ -18,7 +18,7 @@ import { existsSync, readFileSync } from "node:fs"; import path from "node:path"; import os from "node:os"; import { fileURLToPath } from "node:url"; -import { measuredSetupTools } from "./cloud-validation-environment.mjs"; +import { lastSetupMeasurement } from "./cloud-validation-environment.mjs"; import { cloudRecipe } from "./cloud-validation-recipes.mjs"; import { parseConfig } from "../../codex-fleet-monitor/scripts/work-dir.mjs"; import { defaultHome } from "../../fleet-orchestrator/scripts/fleet-home.mjs"; @@ -52,6 +52,8 @@ export function cloudSetupScript({ recipe = cloudRecipe, root = VIBE_ROOT } = {} export const CLAUDE_ENV_VAR = "VIBE_CLOUD_CLAUDE_ENV"; export const CLAUDE_ENV_CONFIG_KEY = "CLOUD_CLAUDE_ENV"; +// No script can read which Claude account Chrome or its extension is signed in to (extension storage and encrypted cookies). +const CHROME_ACCOUNT = "cannot verify by script which Claude account Chrome and the Claude in Chrome extension are signed in to. Check by hand on each machine that launches cloud workers: Chrome is signed in to the same account on every such machine, and claude.ai in Chrome and the Claude in Chrome extension both show the Claude account that `claude auth status` shows."; const NOTHING_RECORDED = "no vibe cloud worker routine is recorded on this machine yet; the first cloud run creates it"; export const CloudSetupError = Object.freeze({ EnvMissing: "CLOUD_ENV_MISSING", @@ -180,6 +182,9 @@ function environmentSetupCheck(routine) { if (!last) return { check: "environment-setup", ok: null, detail: "not exercised: the recorded routine has no run yet, so check did not run the environment setup script" }; const status = String(last.status ?? "").toLowerCase(); + // A run that finished got past the environment setup, which archives the session when it fails. + if (status.includes("succeed")) return { check: "environment-setup", ok: true, + detail: `the last run finished with status ${last.status}, so the environment setup script completed` }; const turns = last.turn_count ?? last.turns_count ?? last.num_turns; if (status.includes("archiv") && (!Number.isInteger(turns) || turns === 0)) { return { check: "environment-setup", ok: false, code: "CLOUD_ENV_SETUP_FAILED", @@ -193,9 +198,9 @@ function environmentSetupCheck(routine) { /** * The setup check: environment configured, the account pin, API reachable, the environment this machine's standing - * routine (`standing`, from the routine ledger) runs in, the GitHub connection, and the lane tools (zsh, uv, Python - * 3.13, Node 24, pnpm and Chromium headless shell 1254) a current measured run on this account and environment - * verified; `pending` is the routine-removal line when routines vibe created are still recorded for removal. + * routine (`standing`, from the routine ledger) runs in, the GitHub connection, the lane tools the setup script installs + * as the last measured run on this account and environment found them, and the Chrome account check this script + * cannot make; `pending` is the routine-removal line when routines vibe created are still recorded for removal. */ export function checkCloudSetup(request, { remote, env = process.env, home = os.homedir(), standing = null, pending = null, ledgerProblem = null, githubTokenMissingAt = null, account, environmentPin = null } = {}) { const checks = []; @@ -249,14 +254,32 @@ export function checkCloudSetup(request, { remote, env = process.env, home = os. detail: `The routine API reported github_token_missing${refusedAt ? ` on ${refusedAt}` : ""}. ${CONNECT_GITHUB}` } : { check: "github", ok: null, detail: "No GitHub connection refusal is recorded. This read-only check does not create a task to test repository access." }); const ownsEnvironment = checks.some((row) => row.check === "environment-use" && row.ok === true); - const observed = ownsEnvironment && !accountProblem && account?.uuid && environment - ? measuredSetupTools(home, environmentPin, account.uuid, environment.id) : null; - const setup = cloudSetupScript(); - const missing = setup.checks.filter((key) => observed?.[key] !== true); - checks.push(missing.length ? { check: "lane-tools", ok: false, code: "CLOUD_SETUP_UNVERIFIED", - detail: `Missing current account/environment measurements for ${missing.join(", ")}. At https://claude.ai/code open the environment selector, select the cloud environment's settings (or New environment), paste the setup script below (from ${setup.file}) into Setup script and save. Set CLOUD_CLAUDE_ENV= in ${path.join(defaultHome(env), "config.env")}. Re-pin with cloud-worker.mjs pin, run the cloud-capabilities lane on a pushed tooling head, then run check.`, - setupScript: setup.text } - : { check: "lane-tools", ok: true, detail: `A current measured run on this account and environment verified ${setup.checks.map((key) => MEASURED_NAMES[key]).join(", ")}.` }); + const measured = ownsEnvironment && !accountProblem && account?.uuid && environment + ? lastSetupMeasurement(home, environmentPin, account.uuid, environment.id) : null; + checks.push(laneToolsCheck(measured, cloudSetupScript(), env)); + checks.push({ check: "chrome-account", ok: null, detail: CHROME_ACCOUNT }); if (pending) checks.push({ check: "routine-removal", ok: null, detail: pending }); return { ok: checks.every((entry) => entry.ok !== false), environment, checks }; } + +/** + * The lane-tools row. Paste advice only when a tool was measured false or this account and environment were never + * measured; a proof older than admission allows that measured every tool true needs only a fresh capability run. + */ +function laneToolsCheck(measured, setup, env) { + const names = (keys) => keys.map((key) => MEASURED_NAMES[key]).join(", "); + const failed = setup.checks.filter((key) => measured?.checks[key] === false); + if (!measured || failed.length) { + const what = failed.length ? `The last capability run on this account and environment measured ${names(failed)} missing.` + : `Missing current account/environment measurements for ${setup.checks.join(", ")}.`; + return { check: "lane-tools", ok: false, code: "CLOUD_SETUP_UNVERIFIED", + detail: `${what} At https://claude.ai/code open the environment selector, select the cloud environment's settings (or New environment), paste the setup script below (from ${setup.file}) into Setup script and save. Set CLOUD_CLAUDE_ENV= in ${path.join(defaultHome(env), "config.env")}. Re-pin with cloud-worker.mjs pin, run the cloud-capabilities lane on a pushed tooling head, then run check.`, + setupScript: setup.text }; + } + const unmeasured = setup.checks.filter((key) => measured.checks[key] !== true); + if (!measured.fresh || unmeasured.length) { + const seen = setup.checks.filter((key) => measured.checks[key] === true); + return { check: "lane-tools", ok: null, detail: `The last capability run on this account and environment (${new Date(measured.at).toISOString()}) measured ${seen.length ? names(seen) : "none of the setup's tools"} present${unmeasured.length ? ` and did not measure ${names(unmeasured)}` : ""}. It needs a fresh capability run before capability lanes: run the cloud-capabilities lane on a pushed tooling head, then run check.` }; + } + return { check: "lane-tools", ok: true, detail: `A current measured run on this account and environment verified ${names(setup.checks)}.` }; +} diff --git a/plugins/vibe/lib/vibe/scripts/cloud-environment.test.mjs b/plugins/vibe/lib/vibe/scripts/cloud-environment.test.mjs index 15ffb6e4..01b726f6 100644 --- a/plugins/vibe/lib/vibe/scripts/cloud-environment.test.mjs +++ b/plugins/vibe/lib/vibe/scripts/cloud-environment.test.mjs @@ -131,7 +131,7 @@ test('the setup check reports each environment and API result with its fix, and const gone = { get: () => { throw httpError(404); }, list: () => used }; const ok = checkCloudSetup({ claudeEnvironment: REQUEST_ENV }, { remote: fakeRemote(recorded).remote, standing, env: { FLEET_HOME: fleetHome(t) } }); assert.equal(ok.ok, false, "an account-free routine read cannot prove the lane tools"); - assert.deepEqual(ok.checks.map(({ check, ok: passed }) => [check, passed]), [['environment', true], ['api', true], ['environment-setup', null], ['environment-use', true], ['github', null], ['lane-tools', false]]); + assert.deepEqual(ok.checks.map(({ check, ok: passed }) => [check, passed]), [['environment', true], ['api', true], ['environment-setup', null], ['environment-use', true], ['github', null], ['lane-tools', false], ['chrome-account', null]]); assert.match(ok.checks[2].detail, /not exercised.*did not run the environment setup script/); assert.match(ok.checks[3].detail, /routine trig_a on this account runs in env_01FromRequest/); assert.match(ok.checks[4].detail, /No GitHub connection refusal is recorded.*read-only check/); diff --git a/plugins/vibe/lib/vibe/scripts/cloud-setup-proof.test.mjs b/plugins/vibe/lib/vibe/scripts/cloud-setup-proof.test.mjs index 442a4105..81bea642 100644 --- a/plugins/vibe/lib/vibe/scripts/cloud-setup-proof.test.mjs +++ b/plugins/vibe/lib/vibe/scripts/cloud-setup-proof.test.mjs @@ -7,7 +7,7 @@ import { checkCloudSetup, cloudSetupScript } from "./cloud-environment.mjs"; // The ClosedLoop build's own setup script, which carries the repository tools vibe's generic template leaves out. import { checkCloudSetup as providerCheckSetup, cloudSetupScript as providerSetup } from "../../../../vibe-closedloop/lib/vibe/scripts/cloud-environment.mjs"; import { CLOUD_CAPABILITIES_COMMAND } from "./cloud-check-command.mjs"; -import { confirmCloudEnvironment, recordRuntimeFromValidation, measuredSetupTools } from "./cloud-validation-environment.mjs"; +import { confirmCloudEnvironment, recordRuntimeFromValidation, lastSetupMeasurement } from "./cloud-validation-environment.mjs"; import { PACKAGE_REPAIR, repairHostPackages } from "./cloud-validation-host.mjs"; import { makeHome } from "../../../../vibe/skills/vibe/scripts/test-fixtures.mjs"; @@ -50,7 +50,13 @@ test("AC-102 check requires current measured account, environment and every chec assert.equal(providerCheck().ok, true); record({ ...own, chromium1254: false }); assert.equal(providerCheck().ok, false, "a previous browser revision cannot satisfy the canonical setup"); + // ISS-15030 AC-1 (operator ruling): a stale proof whose tools were all measured present no longer fails lane-tools or + // asks for the setup script; it asks only for a fresh capability run. A stale proof with a tool measured false still refuses. record(checks, Date.now() - 31 * 60_000); + const stale = check().checks.find((entry) => entry.check === "lane-tools"); + assert.equal(stale.ok, null); + assert.match(stale.detail, /needs a fresh capability run before capability lanes/); + record({ ...checks, [setup.checks[0]]: false }, Date.now() - 31 * 60_000); refused(check()); }); @@ -137,7 +143,7 @@ test("AC-102 completion cannot rebind an unpinned, repinned or old run", (t) => const commit = "a".repeat(40); const outcome = { name: "cloud-capabilities", exitCode: 0, stdoutTail: "CLOUD_HOST_RUNTIME " + JSON.stringify({ commit, checks }) }; const run = { runId: "run", routineId: "routine", sessionId: "session", startedAt: new Date().toISOString() }; - const measured = () => measuredSetupTools(f.home, pin, pin.accountUuid, pin.environmentId)?.node24; + const measured = () => { const last = lastSetupMeasurement(f.home, pin, pin.accountUuid, pin.environmentId); return last?.fresh ? last.checks.node24 : undefined; }; const canonical = [{name:outcome.name,command:CLOUD_CAPABILITIES_COMMAND,capabilityProbe:true}]; const capture = (fields, lanes=canonical) => recordRuntimeFromValidation({ lanes, home: f.home, branch: "main", currentAccount: () => pin.accountUuid, ledger: () => ({ environmentPin: pin, runs: [{ ...run, ...fields }] }) }, { commit, lanes: [outcome] }, diff --git a/plugins/vibe/lib/vibe/scripts/cloud-validation-environment.mjs b/plugins/vibe/lib/vibe/scripts/cloud-validation-environment.mjs index b3b6d555..d3c05398 100644 --- a/plugins/vibe/lib/vibe/scripts/cloud-validation-environment.mjs +++ b/plugins/vibe/lib/vibe/scripts/cloud-validation-environment.mjs @@ -44,21 +44,25 @@ function validTool(tool) { !tool.ref.includes("..") && !tool.ref.includes("//") && !tool.ref.endsWith(".lock"); } -function matchingProof(home, pin, tool, now) { +function matchingProof(home, pin, tool, now, maxAge = PROOF_MAX_MS) { const file = proofPath(home, pin); if (!existsSync(file)) return null; let record; try { record = regularJson(file); } catch { return null; } if (record?.schema !== PROOF_SCHEMA || record.environmentId !== pin.environmentId || record.accountUuid !== pin.accountUuid || !validTool(record.tool) || (tool && (record.tool.commit !== tool.commit || record.tool.ref !== tool.ref)) || typeof record.sessionId !== "string" || !record.sessionId || - !Number.isFinite(record.at) || record.at > now || now - record.at > PROOF_MAX_MS) return null; + !Number.isFinite(record.at) || record.at > now || now - record.at > maxAge) return null; return record; } -/** Read a fresh capability measurement for this exact environment and signed-in account. */ -export function measuredSetupTools(home, pin, accountUuid, environmentId, now = Date.now()) { +/** + * The last capability measurement for this exact environment and signed-in account at any age, and whether it is still + * fresh enough for admission. Only admission needs a fresh one; a stale one still shows which tools the setup installed. + */ +export function lastSetupMeasurement(home, pin, accountUuid, environmentId, now = Date.now()) { if (!pin || pin.environmentId !== environmentId || pin.accountUuid !== accountUuid) return null; - return matchingProof(home, pin, null, now)?.checks ?? null; + const proof = matchingProof(home, pin, null, now, Infinity); + return proof ? { checks: proof.checks ?? {}, at: proof.at, fresh: now - proof.at <= PROOF_MAX_MS } : null; } function laneCommands(lane) { diff --git a/plugins/vibe/lib/vibe/scripts/cloud-validation-recovery.test.mjs b/plugins/vibe/lib/vibe/scripts/cloud-validation-recovery.test.mjs index d5c96f36..d9e11b29 100644 --- a/plugins/vibe/lib/vibe/scripts/cloud-validation-recovery.test.mjs +++ b/plugins/vibe/lib/vibe/scripts/cloud-validation-recovery.test.mjs @@ -3,7 +3,7 @@ import path from "node:path"; import test from "node:test"; import { makeHome } from "../../../../vibe/skills/vibe/scripts/test-fixtures.mjs"; import { recordEnvironmentPin, readLedger, runOnStanding } from "./cloud-routines.mjs"; -import { executeCloudValidation, measuredSetupTools, recordRuntimeFromValidation } from "./cloud-validation-environment.mjs"; +import { executeCloudValidation, lastSetupMeasurement, recordRuntimeFromValidation } from "./cloud-validation-environment.mjs"; import { CLOUD_CAPABILITIES_COMMAND } from "./cloud-check-command.mjs"; import { remoteTrigger } from "./cloud-worker.mjs"; import { regularJson, writeAtomic } from "./owned-state.mjs"; @@ -53,7 +53,8 @@ for(const variant of ["nonzero CLI","trailing frame"]) test("uncertain provider await f.run({start,remote}); assert.equal(starts,1); assert.equal(f.ledger().runs.filter(r=>r.accountUuid===accountUuid && r.environmentId===environmentId && r.runId==="run").length,1); - assert.equal(measuredSetupTools(f.home,pin,accountUuid,environmentId)?.node24,true); + const last = lastSetupMeasurement(f.home,pin,accountUuid,environmentId); + assert.equal(last?.fresh && last.checks.node24,true); }); test("expired completed capability request runs afresh while an in-flight receipt resumes",async t=>{ diff --git a/plugins/vibe/lib/vibe/scripts/cloud-worker.mjs b/plugins/vibe/lib/vibe/scripts/cloud-worker.mjs index 95a45ff1..b2220823 100644 --- a/plugins/vibe/lib/vibe/scripts/cloud-worker.mjs +++ b/plugins/vibe/lib/vibe/scripts/cloud-worker.mjs @@ -266,7 +266,11 @@ function toolResultText(body, structured) { function triggerDiagnostic(result, terminal, last) { const clean = (value) => redactedLine(value).slice(0, 400); const errors = Array.isArray(terminal?.errors) ? terminal.errors.slice(0, 3).map((error) => clean(error?.message ?? error)).filter(Boolean) : []; - const end = [clean(terminal?.subtype), ...errors].filter(Boolean).join(": "); + // A failed `claude -p` (an OAuth refresh that failed over ssh) can end with subtype "success" and the cause in `result`. + const failed = terminal?.is_error === true || (Number.isInteger(result.status) && result.status !== 0); + const cause = failed && typeof terminal?.result === "string" ? clean(terminal.result) : ""; + const subtype = clean(terminal?.subtype); + const end = [cause && subtype === "success" ? "" : subtype, cause, ...errors].filter(Boolean).join(": "); const tool = clean(last?.raw); const stderr = clean(result.stderr); const spawn = clean(result.error?.message); @@ -546,6 +550,11 @@ export function verifyRepository(worktree, repository) { return resolveRepository(repository, origin); } +/** The request with its repository filled from the worktree's origin when it names none (the field is optional). */ +function withRepository(request) { + return request.repository === undefined ? { ...request, repository: verifyRepository(request.worktree) } : request; +} + /** A request's resolved repository; every cloud call runs after verifyRepository named it. */ function requireRepository(request) { if (!request.repository) throw new Error("the cloud repository was not resolved from the request or the worktree's origin"); @@ -609,7 +618,7 @@ export async function abandonValidation(request, { confirm = false, home = os.ho validateValidationRequest(request); const key = sha256(JSON.stringify(request)), base = validationReceiptPath(request, key); const file = request.lanes?.some(lane => lane.name === "cloud-capabilities") - ? boundProbeReceipt(base, validationLanes(request).lanes, readLedger(home), resolveClaudeEnvironment(request)) : base; + ? boundProbeReceipt(base, validationLanes(withRepository(request)).lanes, readLedger(home), resolveClaudeEnvironment(request)) : base; const receipt = existsSync(file) ? JSON.parse(readFileSync(file, "utf8")) : null; const abandoned = receipt && (TERMINAL.has(receipt.status) ? receipt : { ...receipt, status: "abandoned", finishedAt: new Date().toISOString() }); const result = await releaseValidationReservation({ home, key, confirm, unconfirmed: (plan) => unconfirmed("abandon", plan), markRun: (runId) => markRun(home, runId, "abandoned", DEFAULT_WALL_MS), @@ -773,7 +782,7 @@ export function validateValidationRequest(request) { if (Object.hasOwn(request, "env") || Object.hasOwn(request, "envValues")) throw new Error("caller test environment values are refused"); if (!Array.isArray(request.lanes) || request.lanes.length === 0) throw new Error("at least one lane is required"); if (new Set(request.lanes.map((lane) => lane.name)).size !== request.lanes.length) throw new Error("lane names must be unique"); - validationLanes(request); + validationLanes(withRepository(request)); if (request.resultArtifact !== undefined) { const artifact = request.resultArtifact; if (!artifact || typeof artifact !== "object" || typeof artifact.path !== "string" @@ -790,8 +799,9 @@ export function validateValidationRequest(request) { } /** The validation-only brief: exact checkout, install, lanes, no changes, one bound result line. */ -export function validationBrief(request, managedHost = null, provedBranch = null, requestKey = sha256(JSON.stringify(request))) { - validateValidationRequest(request); +export function validationBrief(raw, managedHost = null, provedBranch = null, requestKey = sha256(JSON.stringify(raw))) { + validateValidationRequest(raw); + const request = withRepository(raw); const resolved = validationLanes(request); const artifact = request.resultArtifact; const branch = provedBranch ?? request.branch; diff --git a/plugins/vibe/skills/handoff/scripts/rulings-check.mjs b/plugins/vibe/skills/handoff/scripts/rulings-check.mjs index 96649fdf..31063deb 100644 --- a/plugins/vibe/skills/handoff/scripts/rulings-check.mjs +++ b/plugins/vibe/skills/handoff/scripts/rulings-check.mjs @@ -244,6 +244,18 @@ export function separationRuling(program, reason, tickets) { return null; } +/** + * The program's quoted operator ruling, with its source, whose decision names `ticket` by its whole id, or null. A ruling + * copied from a ticket (`ticket:` channel) or one with no quoted words is never the operator's authority for a worker. + */ +export function operatorTicketRuling(program, ticket) { + for (const match of String(program ?? "").matchAll(PROGRAM_RULING)) { + const [, date, channel, source, decision] = match; + if (channel !== "ticket" && /"[^"\n]+"|“[^”\n]+”/u.test(decision) && rulingNamesScope(decision, [ticket], { exact: true })) return { date, channel, source, decision }; + } + return null; +} + /** A dated operator ruling line: its channel, its optional source after a colon, and its decision. */ const OPERATOR_RULING = /^\s*[-*]\s*Ruling\s+(\d{4}-\d{2}-\d{2})\s+\((operator message|AskUserQuestion)(?::\s*([^)]*?))?\s*\):\s*(\S.*)$/; const LOCATOR_CHANNELS = new Set(["chat", "slack", "dm", "email", "call", "meeting"]); 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 c0f96470..f0d4345c 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.118" + assert claude["version"] == codex["version"] == "1.1.119" 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 1615cd76..9c272536 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.118", manifest - assert "Version `1.1.118`" in skill_split.read(PLUGIN_ROOT / "README.md") + assert json.loads(skill_split.read(PLUGIN_ROOT / manifest / "plugin.json"))["version"] == "1.1.119", manifest + assert "Version `1.1.119`" 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 From c3925837276a6fcf2c3e38419e88854ff5f2ec1d Mon Sep 17 00:00:00 2001 From: Daniel Ochoa Date: Wed, 2 Dec 2026 17:52:46 -0600 Subject: [PATCH 2/8] ISS-15038: Run Claude cloud validation at fleet scale Queued validations wait for the queue lock until their own deadline, one account runs up to seven validations at once, and a standing routine keeps under its 30 runs an hour. The outcome reporter installs from a short fetch of its tooling commit, the managed record is read in its own call, an overflowing request gets an outcomes branch, and API test lanes run with the CI step's environment instead of a committed fixture. --- CHANGELOG.md | 14 ++ .../vibe-closedloop-provider/provider.json | 9 +- .../.claude-plugin/plugin.json | 2 +- .../vibe-closedloop/.codex-plugin/plugin.json | 2 +- plugins/vibe-closedloop/README.md | 2 +- .../vibe/scripts/cloud-outcome-artifact.mjs | 2 + .../scripts/cloud-outcome-instruction.mjs | 43 ++++- .../lib/vibe/scripts/cloud-routines.mjs | 28 ++- .../scripts/cloud-validation-admission.mjs | 58 +++++-- .../scripts/cloud-validation-environment.mjs | 18 +- .../vibe/scripts/cloud-validation-host.mjs | 81 +++------ .../lib/vibe/scripts/cloud-worker.mjs | 22 ++- .../vibe-closedloop/provider/provider.json | 12 +- plugins/vibe/.claude-plugin/plugin.json | 2 +- plugins/vibe/.codex-plugin/plugin.json | 2 +- plugins/vibe/README.md | 2 +- .../cloud-creation-prevention.test.mjs | 36 ++++ .../vibe/scripts/cloud-outcome-artifact.mjs | 2 + .../scripts/cloud-outcome-instruction.mjs | 43 ++++- .../scripts/cloud-outcome-transport.test.mjs | 109 ++++++++++++ .../vibe/lib/vibe/scripts/cloud-routines.mjs | 28 ++- .../cloud-validation-admission-kill.test.mjs | 7 +- .../scripts/cloud-validation-admission.mjs | 58 +++++-- .../cloud-validation-admission.test.mjs | 117 ++++++++++++- .../scripts/cloud-validation-environment.mjs | 18 +- .../cloud-validation-environment.test.mjs | 159 ++++++++---------- .../vibe/scripts/cloud-validation-host.mjs | 81 +++------ .../scripts/cloud-validation-host.test.mjs | 89 ++++++++-- .../vibe/lib/vibe/scripts/cloud-worker.mjs | 22 ++- .../python/test_pr_takeover_skill_contract.py | 2 +- .../python/test_vibe_ws8_load_contract.py | 4 +- 31 files changed, 773 insertions(+), 301 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 0ed38043..9e320bdf 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -4,6 +4,20 @@ All notable changes to the claude-plugins project will be documented in this fil The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.1.0/). Entries are listed newest-first; each plugin section is treated as released when merged to `main`. +### vibe v1.1.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 standing routine starts at most 30 runs an hour, the documented per-routine limit. The next launch waits for the window, or refuses with that limit named when the wait would pass its deadline. +- 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), 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 neither commit 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. +- Across all plugin Markdown, including eval prompts and graders, the release is about 0 words longer than v1.1.119. The count covers the source files in `plugins/vibe` and excludes the generated ClosedLoop edition. + ### vibe v1.1.119 #### Fixed 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 be87bfd2..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.119", + "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 434c4a81..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.119", + "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 6b7da1ab..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.119` 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..dd9c38cc 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,14 @@ 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 +41,38 @@ 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; + 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; +} + +/** + * 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 +107,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..f1e2209b 100644 --- a/plugins/vibe-closedloop/lib/vibe/scripts/cloud-routines.mjs +++ b/plugins/vibe-closedloop/lib/vibe/scripts/cloud-routines.mjs @@ -26,6 +26,7 @@ import { existsSync, lstatSync, readdirSync, readFileSync } from "node:fs"; import os from "node:os"; import path from "node:path"; import { spawnSync } from "node:child_process"; +import { setTimeout as delay } from "node:timers/promises"; import { acquire, release } from "./e2e-lock.mjs"; import { legacyRoutineName, RECEIPT_NAME, TERMINAL } from "./cloud-receipts.mjs"; import { regularJson, writeAtomic } from "./owned-state.mjs"; @@ -41,6 +42,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; +/** + * Runs one routine may start in an hour: "Run now", API fires and re-running a one-off task share 30 per hour per + * routine, and the action fails until the window resets (https://code.claude.com/docs/en/routines, "Usage and + * limits"). Every launch on this machine goes through its one standing routine, so this is the machine's launch rate. + */ +export const ROUTINE_RUNS_PER_HOUR = 30; +const HOUR_MS = 60 * 60 * 1000; const ROUTINE_ID = /^[\w-]+$/; const RECEIPT_BYTES = 1024 * 1024; const LOCK_POLL_MS = 1000; @@ -232,7 +240,9 @@ function confirmConnectors(updated, allowlist) { * run it, and record the run's session id in the ledger before the lock is released. `afterRun` receives the * launch with the acknowledged run and session ids before the ledger is written. */ -export async function runOnStanding({ remote, home = os.homedir(), environment, ccr, brief, allowlist = [], label, waitMs, refusal, account = currentClaudeAccount, requestKey, beforeRun, afterRun }) { +export async function runOnStanding({ remote, home = os.homedir(), environment, ccr, brief, allowlist = [], label, waitMs, refusal, account = currentClaudeAccount, requestKey, beforeRun, afterRun, + now = Date.now, sleep = (ms) => delay(ms), report = (line) => process.stderr.write(`${line}\n`) }) { + const deadline = now() + (waitMs ?? 0); return withRoutineLock(home, waitMs, async () => { const ledger = readLedger(home); requireLedgerPin(ledger, environment, home, account); @@ -249,6 +259,7 @@ export async function runOnStanding({ remote, home = os.homedir(), environment, standing = null; } standing ??= createStanding(ledger, { home, remote, ccr, environment, refusal }); + await withinHourlyRuns(ledger, standing.id, { now, sleep, report, deadline }); // An allow-listed connector is set on the same routine through update; one a fresh create did not attach is refused. const connectorsFor = (routine) => { if (allowlist.length === 0) return []; @@ -569,3 +580,18 @@ export async function adoptStanding({ home = os.homedir(), remote, id, waitMs = return ledger; }); } + +/** + * Wait, holding the routine lock, until the standing routine is under its hourly run limit, or refuse with the limit + * named when the wait would pass the request's deadline. The provider would fail the run itself; this says why first. + */ +async function withinHourlyRuns(ledger, routineId, { now, sleep, report, deadline }) { + const started = ledger.runs.filter((run) => run.routineId === routineId).map((run) => Date.parse(run.startedAt ?? "")) + .filter((at) => Number.isFinite(at) && now() - at < HOUR_MS).sort((a, b) => a - b); + if (started.length < ROUTINE_RUNS_PER_HOUR) return; + const opens = started[started.length - ROUTINE_RUNS_PER_HOUR] + HOUR_MS; + const limit = `CLOUD_ROUTINE_HOURLY_LIMIT: this machine's standing routine started ${started.length} runs in the last hour, and a routine may start ${ROUTINE_RUNS_PER_HOUR} an hour (https://code.claude.com/docs/en/routines, "Usage and limits")`; + if (opens > deadline) throw Object.assign(new Error(`${limit}; the next run can start at ${new Date(opens).toISOString()}, past this request's deadline. Retry the same request then`), { code: "CLOUD_ROUTINE_HOURLY_LIMIT" }); + report(`${limit}; waiting until ${new Date(opens).toISOString()} to launch`); + await sleep(Math.max(0, opens - now())); +} 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-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 2fa27165..b1d9bc38 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; @@ -18,63 +17,17 @@ const HOST_TIMEOUT = 15 * 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 +601,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 +630,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..18ffd8a3 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"; @@ -953,13 +953,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 +983,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 fe122a14..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.119", + "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 deb261a4..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.119", + "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 43a58196..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.119` 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..3f931cb1 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,38 @@ 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 the standing routine's thirty-first run in an hour waits for the window or refuses naming the limit", async (t) => { + const { ROUTINE_RUNS_PER_HOUR } = await import("./cloud-routines.mjs"); + const fixture = makeHome("vibe-routine-hourly-"); + t.after(fixture.cleanup); + const { home } = fixture; + await recordEnvironmentPin({ home, environmentId: ENV, accountUuid: ACCOUNT }); + let clock = Date.parse("2026-12-02T23:00:00Z"), runs = 0; + const actions = []; + 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 lines = [], slept = []; + const start = (waitMs) => runOnStanding({ home, remote, account: () => ACCOUNT, environment: { id: ENV }, ccr: { environment_id: ENV }, + brief: "harmless fixture", waitMs, now: () => clock, sleep: async (ms) => { slept.push(ms); clock += ms; }, report: (line) => lines.push(line) }); + for (let index = 0; index < ROUTINE_RUNS_PER_HOUR; index++) await start(1000); + const ledger = readLedger(home); + // The ledger stamps real start times; place the thirty runs one minute apart inside the fixture's hour. + ledger.runs.forEach((run, index) => { run.startedAt = new Date(clock - (ROUTINE_RUNS_PER_HOUR - index) * 60_000).toISOString(); }); + writeAtomic(ledgerPath(home), ledger); + actions.length = 0; + await assert.rejects(start(60_000), (error) => error.code === "CLOUD_ROUTINE_HOURLY_LIMIT" + && /started 30 runs in the last hour, and a routine may start 30 an hour \(https:\/\/code\.claude\.com\/docs\/en\/routines/.test(error.message) + && /past this request's deadline\. Retry the same request then$/.test(error.message)); + assert.deepEqual(actions, [], "nothing is sent past the limit"); + await start(31 * 60_000); + assert.deepEqual(slept, [30 * 60_000], "the oldest run of the hour leaves the window after thirty minutes"); + assert.match(lines[0], /^CLOUD_ROUTINE_HOURLY_LIMIT: .* waiting until 2026-12-02T23:30:00\.000Z to launch$/); + assert.deepEqual(actions, ["update", "run"]); +}); 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..dd9c38cc 100644 --- a/plugins/vibe/lib/vibe/scripts/cloud-outcome-instruction.mjs +++ b/plugins/vibe/lib/vibe/scripts/cloud-outcome-instruction.mjs @@ -1,7 +1,14 @@ 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 +41,38 @@ 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; + 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; +} + +/** + * 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 +107,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..89e6522e 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,112 @@ 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 }) { + 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); + const repository = "example/widgets"; + const 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); + const 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); + 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: { [`${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 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..f1e2209b 100644 --- a/plugins/vibe/lib/vibe/scripts/cloud-routines.mjs +++ b/plugins/vibe/lib/vibe/scripts/cloud-routines.mjs @@ -26,6 +26,7 @@ import { existsSync, lstatSync, readdirSync, readFileSync } from "node:fs"; import os from "node:os"; import path from "node:path"; import { spawnSync } from "node:child_process"; +import { setTimeout as delay } from "node:timers/promises"; import { acquire, release } from "./e2e-lock.mjs"; import { legacyRoutineName, RECEIPT_NAME, TERMINAL } from "./cloud-receipts.mjs"; import { regularJson, writeAtomic } from "./owned-state.mjs"; @@ -41,6 +42,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; +/** + * Runs one routine may start in an hour: "Run now", API fires and re-running a one-off task share 30 per hour per + * routine, and the action fails until the window resets (https://code.claude.com/docs/en/routines, "Usage and + * limits"). Every launch on this machine goes through its one standing routine, so this is the machine's launch rate. + */ +export const ROUTINE_RUNS_PER_HOUR = 30; +const HOUR_MS = 60 * 60 * 1000; const ROUTINE_ID = /^[\w-]+$/; const RECEIPT_BYTES = 1024 * 1024; const LOCK_POLL_MS = 1000; @@ -232,7 +240,9 @@ function confirmConnectors(updated, allowlist) { * run it, and record the run's session id in the ledger before the lock is released. `afterRun` receives the * launch with the acknowledged run and session ids before the ledger is written. */ -export async function runOnStanding({ remote, home = os.homedir(), environment, ccr, brief, allowlist = [], label, waitMs, refusal, account = currentClaudeAccount, requestKey, beforeRun, afterRun }) { +export async function runOnStanding({ remote, home = os.homedir(), environment, ccr, brief, allowlist = [], label, waitMs, refusal, account = currentClaudeAccount, requestKey, beforeRun, afterRun, + now = Date.now, sleep = (ms) => delay(ms), report = (line) => process.stderr.write(`${line}\n`) }) { + const deadline = now() + (waitMs ?? 0); return withRoutineLock(home, waitMs, async () => { const ledger = readLedger(home); requireLedgerPin(ledger, environment, home, account); @@ -249,6 +259,7 @@ export async function runOnStanding({ remote, home = os.homedir(), environment, standing = null; } standing ??= createStanding(ledger, { home, remote, ccr, environment, refusal }); + await withinHourlyRuns(ledger, standing.id, { now, sleep, report, deadline }); // An allow-listed connector is set on the same routine through update; one a fresh create did not attach is refused. const connectorsFor = (routine) => { if (allowlist.length === 0) return []; @@ -569,3 +580,18 @@ export async function adoptStanding({ home = os.homedir(), remote, id, waitMs = return ledger; }); } + +/** + * Wait, holding the routine lock, until the standing routine is under its hourly run limit, or refuse with the limit + * named when the wait would pass the request's deadline. The provider would fail the run itself; this says why first. + */ +async function withinHourlyRuns(ledger, routineId, { now, sleep, report, deadline }) { + const started = ledger.runs.filter((run) => run.routineId === routineId).map((run) => Date.parse(run.startedAt ?? "")) + .filter((at) => Number.isFinite(at) && now() - at < HOUR_MS).sort((a, b) => a - b); + if (started.length < ROUTINE_RUNS_PER_HOUR) return; + const opens = started[started.length - ROUTINE_RUNS_PER_HOUR] + HOUR_MS; + const limit = `CLOUD_ROUTINE_HOURLY_LIMIT: this machine's standing routine started ${started.length} runs in the last hour, and a routine may start ${ROUTINE_RUNS_PER_HOUR} an hour (https://code.claude.com/docs/en/routines, "Usage and limits")`; + if (opens > deadline) throw Object.assign(new Error(`${limit}; the next run can start at ${new Date(opens).toISOString()}, past this request's deadline. Retry the same request then`), { code: "CLOUD_ROUTINE_HOURLY_LIMIT" }); + report(`${limit}; waiting until ${new Date(opens).toISOString()} to launch`); + await sleep(Math.max(0, opens - now())); +} 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-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 2fa27165..b1d9bc38 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; @@ -18,63 +17,17 @@ const HOST_TIMEOUT = 15 * 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 +601,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 +630,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..18ffd8a3 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"; @@ -953,13 +953,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 +983,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/tools/python/test_pr_takeover_skill_contract.py b/plugins/vibe/tools/python/test_pr_takeover_skill_contract.py index f0d4345c..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.119" + 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 9c272536..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.119", manifest - assert "Version `1.1.119`" 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 From f9061da2006d0bba0fa7a8c815cfa20dc31f60ea Mon Sep 17 00:00:00 2001 From: Daniel Ochoa Date: Wed, 2 Dec 2026 19:39:02 -0600 Subject: [PATCH 3/8] ISS-15038: Raise cloud time limits, reporter fetch for the tool repo, shard Node Tests A cloud run may now last 100 minutes and one lane 60, from a session measured running 117 minutes with no cutoff and a full Desktop e2e suite that takes 15 minutes on CI's 8 cores. The reporter installs from the commit under test when the tooling repository validates itself and that commit holds the same reporter bytes. The Node Tests job runs as three shards of the same discovered files so it stays under its 20-minute timeout. --- .github/workflows/ci.yml | 18 ++++++++++++---- CHANGELOG.md | 5 +++-- .../scripts/cloud-outcome-instruction.mjs | 16 ++++++++++++++ .../lib/vibe/scripts/cloud-routines.mjs | 4 ++-- .../vibe/scripts/cloud-validation-host.mjs | 4 +++- .../lib/vibe/scripts/cloud-worker.mjs | 9 +++++--- .../scripts/cloud-outcome-instruction.mjs | 16 ++++++++++++++ .../scripts/cloud-outcome-transport.test.mjs | 21 ++++++++++++++----- .../vibe/lib/vibe/scripts/cloud-routines.mjs | 4 ++-- .../vibe/scripts/cloud-validation-host.mjs | 4 +++- .../vibe/lib/vibe/scripts/cloud-worker.mjs | 9 +++++--- .../lib/vibe/scripts/cloud-worker.test.mjs | 12 +++++++++++ 12 files changed, 99 insertions(+), 23 deletions(-) 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 5faeb7a8..f938d8ee 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -11,12 +11,13 @@ The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.1.0/). - 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 standing routine starts at most 30 runs an hour, the documented per-routine limit. The next launch waits for the window, or refuses with that limit named when the wait would pass its deadline. -- 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), 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 neither commit is known. +- 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. -- Across all plugin Markdown, including eval prompts and graders, the release is about 0 words longer than v1.1.119. The count covers the source files in `plugins/vibe` and excludes the generated ClosedLoop edition. +- 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. +- 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 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 dd9c38cc..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,3 +1,4 @@ +import { spawnSync } from "node:child_process"; import { createHash } from "node:crypto"; import { brotliCompressSync } from "node:zlib"; import { readFileSync } from "node:fs"; @@ -48,6 +49,10 @@ export function hostReporter(request, lanes, key) { */ 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; @@ -57,6 +62,17 @@ function reporterCommit(request) { 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 diff --git a/plugins/vibe-closedloop/lib/vibe/scripts/cloud-routines.mjs b/plugins/vibe-closedloop/lib/vibe/scripts/cloud-routines.mjs index f1e2209b..a2b37a52 100644 --- a/plugins/vibe-closedloop/lib/vibe/scripts/cloud-routines.mjs +++ b/plugins/vibe-closedloop/lib/vibe/scripts/cloud-routines.mjs @@ -64,8 +64,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 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 37b7ef5f..3ac24b40 100644 --- a/plugins/vibe-closedloop/lib/vibe/scripts/cloud-validation-host.mjs +++ b/plugins/vibe-closedloop/lib/vibe/scripts/cloud-validation-host.mjs @@ -13,7 +13,9 @@ 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. A full Desktop e2e suite took 14.9 to 15.4 min in the provider's CI on 8 cores +// with 4 workers (2026-12-01 and 12-02); the cloud lane runs it with the suite's default 2 workers. +const HOST_TIMEOUT = 60 * 60_000; function digest(bytes) { return createHash("sha256").update(bytes).digest("hex"); } diff --git a/plugins/vibe-closedloop/lib/vibe/scripts/cloud-worker.mjs b/plugins/vibe-closedloop/lib/vibe/scripts/cloud-worker.mjs index 18ffd8a3..b9820388 100644 --- a/plugins/vibe-closedloop/lib/vibe/scripts/cloud-worker.mjs +++ b/plugins/vibe-closedloop/lib/vibe/scripts/cloud-worker.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"); } diff --git a/plugins/vibe/lib/vibe/scripts/cloud-outcome-instruction.mjs b/plugins/vibe/lib/vibe/scripts/cloud-outcome-instruction.mjs index dd9c38cc..606cb4cf 100644 --- a/plugins/vibe/lib/vibe/scripts/cloud-outcome-instruction.mjs +++ b/plugins/vibe/lib/vibe/scripts/cloud-outcome-instruction.mjs @@ -1,3 +1,4 @@ +import { spawnSync } from "node:child_process"; import { createHash } from "node:crypto"; import { brotliCompressSync } from "node:zlib"; import { readFileSync } from "node:fs"; @@ -48,6 +49,10 @@ export function hostReporter(request, lanes, key) { */ 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; @@ -57,6 +62,17 @@ function reporterCommit(request) { 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 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 89e6522e..17fefee3 100644 --- a/plugins/vibe/lib/vibe/scripts/cloud-outcome-transport.test.mjs +++ b/plugins/vibe/lib/vibe/scripts/cloud-outcome-transport.test.mjs @@ -398,7 +398,7 @@ test("AC-65 a prose word after the artifact marker is not a second pointer, whil // 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 }) { +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"); @@ -411,12 +411,12 @@ async function fetchedReporterRun(t, { pinned }) { const { pluginInstall, pluginMarketplace } = await import("../../../shared/plugin-roots.mjs"); const fixture = makeHome("outcome-fetched-reporter-"); t.after(fixture.cleanup); - const repository = "example/widgets"; - const worktree = path.join(fixture.root, "checkout"); + 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); - const commit = git(worktree, ["rev-parse", "HEAD"], 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); @@ -430,6 +430,13 @@ async function fetchedReporterRun(t, { pinned }) { 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" } } : {}) }; @@ -438,7 +445,7 @@ async function fetchedReporterRun(t, { pinned }) { 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: { [`${self.name}@${pluginMarketplace(self)}`]: [{ scope: "user", version: self.version, gitCommitSha: toolCommit }] } })); + 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; @@ -473,6 +480,10 @@ test("ISS-15038 a pinned runtime tool's reporter installs from a short fetch, an 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) => { diff --git a/plugins/vibe/lib/vibe/scripts/cloud-routines.mjs b/plugins/vibe/lib/vibe/scripts/cloud-routines.mjs index f1e2209b..a2b37a52 100644 --- a/plugins/vibe/lib/vibe/scripts/cloud-routines.mjs +++ b/plugins/vibe/lib/vibe/scripts/cloud-routines.mjs @@ -64,8 +64,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 diff --git a/plugins/vibe/lib/vibe/scripts/cloud-validation-host.mjs b/plugins/vibe/lib/vibe/scripts/cloud-validation-host.mjs index 37b7ef5f..3ac24b40 100644 --- a/plugins/vibe/lib/vibe/scripts/cloud-validation-host.mjs +++ b/plugins/vibe/lib/vibe/scripts/cloud-validation-host.mjs @@ -13,7 +13,9 @@ 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. A full Desktop e2e suite took 14.9 to 15.4 min in the provider's CI on 8 cores +// with 4 workers (2026-12-01 and 12-02); the cloud lane runs it with the suite's default 2 workers. +const HOST_TIMEOUT = 60 * 60_000; function digest(bytes) { return createHash("sha256").update(bytes).digest("hex"); } diff --git a/plugins/vibe/lib/vibe/scripts/cloud-worker.mjs b/plugins/vibe/lib/vibe/scripts/cloud-worker.mjs index 18ffd8a3..b9820388 100644 --- a/plugins/vibe/lib/vibe/scripts/cloud-worker.mjs +++ b/plugins/vibe/lib/vibe/scripts/cloud-worker.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"); } 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$/); +}); From 078e0e59de855cf4866d15e0d3e941f85ea643b9 Mon Sep 17 00:00:00 2001 From: Daniel Ochoa Date: Wed, 2 Dec 2026 19:46:55 -0600 Subject: [PATCH 4/8] ISS-15038: Run the whole Desktop e2e suite as one cloud lane The bare Desktop test:e2e command now resolves to CI's own suite step, with its pre-suite steps, D-Bus and keyring wrapper and result check, and with the shard arguments dropped so the whole suite runs. A lane argument must still name exactly one spec. --- CHANGELOG.md | 1 + .../lib/vibe/scripts/cloud-validation-e2e.mjs | 24 ++++++++++++------- .../lib/vibe/scripts/cloud-validation-e2e.mjs | 24 ++++++++++++------- .../scripts/cloud-validation-e2e.test.mjs | 20 ++++++++++++++++ 4 files changed, 53 insertions(+), 16 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index f938d8ee..153b704d 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -17,6 +17,7 @@ The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.1.0/). - 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 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/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"); From 70b3f04df0ff700471e5538b0dd56f86a054f0f0 Mon Sep 17 00:00:00 2001 From: Daniel Ochoa Date: Wed, 2 Dec 2026 20:19:30 -0600 Subject: [PATCH 5/8] ISS-15038: Cite the measured full Desktop suite at the lane limit The whole Desktop e2e suite ran as one cloud lane in 22.8 minutes on a 4-core VM, build included, so the 60-minute lane limit now cites that run instead of CI's 8-core timing. --- .../lib/vibe/scripts/cloud-validation-host.mjs | 5 +++-- plugins/vibe/lib/vibe/scripts/cloud-validation-host.mjs | 5 +++-- 2 files changed, 6 insertions(+), 4 deletions(-) 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 3ac24b40..5ca9d06f 100644 --- a/plugins/vibe-closedloop/lib/vibe/scripts/cloud-validation-host.mjs +++ b/plugins/vibe-closedloop/lib/vibe/scripts/cloud-validation-host.mjs @@ -13,8 +13,9 @@ 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"); -// One lane's process group ends here. A full Desktop e2e suite took 14.9 to 15.4 min in the provider's CI on 8 cores -// with 4 workers (2026-12-01 and 12-02); the cloud lane runs it with the suite's default 2 workers. +// 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"); } diff --git a/plugins/vibe/lib/vibe/scripts/cloud-validation-host.mjs b/plugins/vibe/lib/vibe/scripts/cloud-validation-host.mjs index 3ac24b40..5ca9d06f 100644 --- a/plugins/vibe/lib/vibe/scripts/cloud-validation-host.mjs +++ b/plugins/vibe/lib/vibe/scripts/cloud-validation-host.mjs @@ -13,8 +13,9 @@ 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"); -// One lane's process group ends here. A full Desktop e2e suite took 14.9 to 15.4 min in the provider's CI on 8 cores -// with 4 workers (2026-12-01 and 12-02); the cloud lane runs it with the suite's default 2 workers. +// 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"); } From 7398c3c5e2068939d43e93c70294334934a2f180 Mon Sep 17 00:00:00 2001 From: Daniel Ochoa Date: Wed, 2 Dec 2026 20:31:47 -0600 Subject: [PATCH 6/8] ISS-15038: Bump vibe-closedloop-provider to 1.0.11 The provider recipe changed in this branch (the API test environment in place of the committed fixture), so its plugin version moves with it. --- CHANGELOG.md | 4 ++++ plugins/vibe-closedloop-provider/.claude-plugin/plugin.json | 2 +- plugins/vibe-closedloop-provider/.codex-plugin/plugin.json | 2 +- 3 files changed, 6 insertions(+), 2 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 153b704d..76a517b5 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -4,6 +4,10 @@ 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 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", From 4c87e443b30af36baa6ecffe6fdc552d1730460b Mon Sep 17 00:00:00 2001 From: Daniel Ochoa Date: Wed, 2 Dec 2026 20:35:32 -0600 Subject: [PATCH 7/8] ISS-15038: Count the three Node Tests shards in the workflow job tests The repository's ci.yml now declares fifteen lanes: Node Tests is three matrix rows. The lane definition test pins each row's shard number and that the rows differ only in it, and the multi-proof carry fixture carries all three shards with the other scoped lane. --- .../handoff/scripts/ci-job-shape.test.mjs | 11 +++++--- .../skills/handoff/scripts/pr-facts.test.mjs | 27 ++++++++++--------- 2 files changed, 22 insertions(+), 16 deletions(-) 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) }); From 3ad93474215a546790c06f4882c37f6073f2ef70 Mon Sep 17 00:00:00 2001 From: Daniel Ochoa Date: Wed, 2 Dec 2026 21:17:39 -0600 Subject: [PATCH 8/8] ISS-15038: Leave the hourly run limit to Claude vibe no longer counts a routine's runs before a launch. This machine's ledger held 41 runs started on one routine in one hour with no refusal, so the count would have held back work Claude accepted. A run Claude refuses as rate-limited (HTTP 429) now fails with CLOUD_ROUTINE_HOURLY_LIMIT, naming the documented cap and when to retry, and is never recorded as started. --- CHANGELOG.md | 2 +- .../lib/vibe/scripts/cloud-routines.mjs | 33 ++++--------- .../cloud-creation-prevention.test.mjs | 46 ++++++++++++------- .../vibe/lib/vibe/scripts/cloud-routines.mjs | 33 ++++--------- 4 files changed, 50 insertions(+), 64 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 76a517b5..2dc1f426 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -14,7 +14,7 @@ The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.1.0/). - 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 standing routine starts at most 30 runs an hour, the documented per-routine limit. The next launch waits for the window, or refuses with that limit named when the wait would pass its deadline. +- 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. diff --git a/plugins/vibe-closedloop/lib/vibe/scripts/cloud-routines.mjs b/plugins/vibe-closedloop/lib/vibe/scripts/cloud-routines.mjs index a2b37a52..fcb0ca8c 100644 --- a/plugins/vibe-closedloop/lib/vibe/scripts/cloud-routines.mjs +++ b/plugins/vibe-closedloop/lib/vibe/scripts/cloud-routines.mjs @@ -26,7 +26,6 @@ import { existsSync, lstatSync, readdirSync, readFileSync } from "node:fs"; import os from "node:os"; import path from "node:path"; import { spawnSync } from "node:child_process"; -import { setTimeout as delay } from "node:timers/promises"; import { acquire, release } from "./e2e-lock.mjs"; import { legacyRoutineName, RECEIPT_NAME, TERMINAL } from "./cloud-receipts.mjs"; import { regularJson, writeAtomic } from "./owned-state.mjs"; @@ -43,12 +42,12 @@ 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; /** - * Runs one routine may start in an hour: "Run now", API fires and re-running a one-off task share 30 per hour per - * routine, and the action fails until the window resets (https://code.claude.com/docs/en/routines, "Usage and - * limits"). Every launch on this machine goes through its one standing routine, so this is the machine's launch rate. + * 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. */ -export const ROUTINE_RUNS_PER_HOUR = 30; -const HOUR_MS = 60 * 60 * 1000; +const ROUTINE_RUNS_PER_HOUR = 30; +const RATE_LIMITED = 429; const ROUTINE_ID = /^[\w-]+$/; const RECEIPT_BYTES = 1024 * 1024; const LOCK_POLL_MS = 1000; @@ -240,9 +239,7 @@ function confirmConnectors(updated, allowlist) { * run it, and record the run's session id in the ledger before the lock is released. `afterRun` receives the * launch with the acknowledged run and session ids before the ledger is written. */ -export async function runOnStanding({ remote, home = os.homedir(), environment, ccr, brief, allowlist = [], label, waitMs, refusal, account = currentClaudeAccount, requestKey, beforeRun, afterRun, - now = Date.now, sleep = (ms) => delay(ms), report = (line) => process.stderr.write(`${line}\n`) }) { - const deadline = now() + (waitMs ?? 0); +export async function runOnStanding({ remote, home = os.homedir(), environment, ccr, brief, allowlist = [], label, waitMs, refusal, account = currentClaudeAccount, requestKey, beforeRun, afterRun }) { return withRoutineLock(home, waitMs, async () => { const ledger = readLedger(home); requireLedgerPin(ledger, environment, home, account); @@ -259,7 +256,6 @@ export async function runOnStanding({ remote, home = os.homedir(), environment, standing = null; } standing ??= createStanding(ledger, { home, remote, ccr, environment, refusal }); - await withinHourlyRuns(ledger, standing.id, { now, sleep, report, deadline }); // An allow-listed connector is set on the same routine through update; one a fresh create did not attach is refused. const connectorsFor = (routine) => { if (allowlist.length === 0) return []; @@ -289,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; } @@ -581,17 +578,7 @@ export async function adoptStanding({ home = os.homedir(), remote, id, waitMs = }); } -/** - * Wait, holding the routine lock, until the standing routine is under its hourly run limit, or refuse with the limit - * named when the wait would pass the request's deadline. The provider would fail the run itself; this says why first. - */ -async function withinHourlyRuns(ledger, routineId, { now, sleep, report, deadline }) { - const started = ledger.runs.filter((run) => run.routineId === routineId).map((run) => Date.parse(run.startedAt ?? "")) - .filter((at) => Number.isFinite(at) && now() - at < HOUR_MS).sort((a, b) => a - b); - if (started.length < ROUTINE_RUNS_PER_HOUR) return; - const opens = started[started.length - ROUTINE_RUNS_PER_HOUR] + HOUR_MS; - const limit = `CLOUD_ROUTINE_HOURLY_LIMIT: this machine's standing routine started ${started.length} runs in the last hour, and a routine may start ${ROUTINE_RUNS_PER_HOUR} an hour (https://code.claude.com/docs/en/routines, "Usage and limits")`; - if (opens > deadline) throw Object.assign(new Error(`${limit}; the next run can start at ${new Date(opens).toISOString()}, past this request's deadline. Retry the same request then`), { code: "CLOUD_ROUTINE_HOURLY_LIMIT" }); - report(`${limit}; waiting until ${new Date(opens).toISOString()} to launch`); - await sleep(Math.max(0, opens - now())); +/** 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-creation-prevention.test.mjs b/plugins/vibe/lib/vibe/scripts/cloud-creation-prevention.test.mjs index 3f931cb1..c81a017d 100644 --- a/plugins/vibe/lib/vibe/scripts/cloud-creation-prevention.test.mjs +++ b/plugins/vibe/lib/vibe/scripts/cloud-creation-prevention.test.mjs @@ -325,35 +325,47 @@ test("the check command derives the live account itself and fails a changed or u // 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 the standing routine's thirty-first run in an hour waits for the window or refuses naming the limit", async (t) => { - const { ROUTINE_RUNS_PER_HOUR } = await import("./cloud-routines.mjs"); +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 }); - let clock = Date.parse("2026-12-02T23:00:00Z"), runs = 0; - const actions = []; + 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 lines = [], slept = []; - const start = (waitMs) => runOnStanding({ home, remote, account: () => ACCOUNT, environment: { id: ENV }, ccr: { environment_id: ENV }, - brief: "harmless fixture", waitMs, now: () => clock, sleep: async (ms) => { slept.push(ms); clock += ms; }, report: (line) => lines.push(line) }); - for (let index = 0; index < ROUTINE_RUNS_PER_HOUR; index++) await start(1000); + 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); - // The ledger stamps real start times; place the thirty runs one minute apart inside the fixture's hour. - ledger.runs.forEach((run, index) => { run.startedAt = new Date(clock - (ROUTINE_RUNS_PER_HOUR - index) * 60_000).toISOString(); }); + // 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; - await assert.rejects(start(60_000), (error) => error.code === "CLOUD_ROUTINE_HOURLY_LIMIT" - && /started 30 runs in the last hour, and a routine may start 30 an hour \(https:\/\/code\.claude\.com\/docs\/en\/routines/.test(error.message) - && /past this request's deadline\. Retry the same request then$/.test(error.message)); - assert.deepEqual(actions, [], "nothing is sent past the limit"); - await start(31 * 60_000); - assert.deepEqual(slept, [30 * 60_000], "the oldest run of the hour leaves the window after thirty minutes"); - assert.match(lines[0], /^CLOUD_ROUTINE_HOURLY_LIMIT: .* waiting until 2026-12-02T23:30:00\.000Z to launch$/); + 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-routines.mjs b/plugins/vibe/lib/vibe/scripts/cloud-routines.mjs index a2b37a52..fcb0ca8c 100644 --- a/plugins/vibe/lib/vibe/scripts/cloud-routines.mjs +++ b/plugins/vibe/lib/vibe/scripts/cloud-routines.mjs @@ -26,7 +26,6 @@ import { existsSync, lstatSync, readdirSync, readFileSync } from "node:fs"; import os from "node:os"; import path from "node:path"; import { spawnSync } from "node:child_process"; -import { setTimeout as delay } from "node:timers/promises"; import { acquire, release } from "./e2e-lock.mjs"; import { legacyRoutineName, RECEIPT_NAME, TERMINAL } from "./cloud-receipts.mjs"; import { regularJson, writeAtomic } from "./owned-state.mjs"; @@ -43,12 +42,12 @@ 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; /** - * Runs one routine may start in an hour: "Run now", API fires and re-running a one-off task share 30 per hour per - * routine, and the action fails until the window resets (https://code.claude.com/docs/en/routines, "Usage and - * limits"). Every launch on this machine goes through its one standing routine, so this is the machine's launch rate. + * 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. */ -export const ROUTINE_RUNS_PER_HOUR = 30; -const HOUR_MS = 60 * 60 * 1000; +const ROUTINE_RUNS_PER_HOUR = 30; +const RATE_LIMITED = 429; const ROUTINE_ID = /^[\w-]+$/; const RECEIPT_BYTES = 1024 * 1024; const LOCK_POLL_MS = 1000; @@ -240,9 +239,7 @@ function confirmConnectors(updated, allowlist) { * run it, and record the run's session id in the ledger before the lock is released. `afterRun` receives the * launch with the acknowledged run and session ids before the ledger is written. */ -export async function runOnStanding({ remote, home = os.homedir(), environment, ccr, brief, allowlist = [], label, waitMs, refusal, account = currentClaudeAccount, requestKey, beforeRun, afterRun, - now = Date.now, sleep = (ms) => delay(ms), report = (line) => process.stderr.write(`${line}\n`) }) { - const deadline = now() + (waitMs ?? 0); +export async function runOnStanding({ remote, home = os.homedir(), environment, ccr, brief, allowlist = [], label, waitMs, refusal, account = currentClaudeAccount, requestKey, beforeRun, afterRun }) { return withRoutineLock(home, waitMs, async () => { const ledger = readLedger(home); requireLedgerPin(ledger, environment, home, account); @@ -259,7 +256,6 @@ export async function runOnStanding({ remote, home = os.homedir(), environment, standing = null; } standing ??= createStanding(ledger, { home, remote, ccr, environment, refusal }); - await withinHourlyRuns(ledger, standing.id, { now, sleep, report, deadline }); // An allow-listed connector is set on the same routine through update; one a fresh create did not attach is refused. const connectorsFor = (routine) => { if (allowlist.length === 0) return []; @@ -289,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; } @@ -581,17 +578,7 @@ export async function adoptStanding({ home = os.homedir(), remote, id, waitMs = }); } -/** - * Wait, holding the routine lock, until the standing routine is under its hourly run limit, or refuse with the limit - * named when the wait would pass the request's deadline. The provider would fail the run itself; this says why first. - */ -async function withinHourlyRuns(ledger, routineId, { now, sleep, report, deadline }) { - const started = ledger.runs.filter((run) => run.routineId === routineId).map((run) => Date.parse(run.startedAt ?? "")) - .filter((at) => Number.isFinite(at) && now() - at < HOUR_MS).sort((a, b) => a - b); - if (started.length < ROUTINE_RUNS_PER_HOUR) return; - const opens = started[started.length - ROUTINE_RUNS_PER_HOUR] + HOUR_MS; - const limit = `CLOUD_ROUTINE_HOURLY_LIMIT: this machine's standing routine started ${started.length} runs in the last hour, and a routine may start ${ROUTINE_RUNS_PER_HOUR} an hour (https://code.claude.com/docs/en/routines, "Usage and limits")`; - if (opens > deadline) throw Object.assign(new Error(`${limit}; the next run can start at ${new Date(opens).toISOString()}, past this request's deadline. Retry the same request then`), { code: "CLOUD_ROUTINE_HOURLY_LIMIT" }); - report(`${limit}; waiting until ${new Date(opens).toISOString()} to launch`); - await sleep(Math.max(0, opens - now())); +/** 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 }); }