diff --git a/CHANGELOG.md b/CHANGELOG.md index 9f80c1a3..89354071 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -4,6 +4,37 @@ 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.118 + +#### Added + +- ISS-14827: a barred host refuses a local heavy lane and names the remote route. A fleet refusal before the lane starts, or a run killed midway, is never recorded as a pass or a failure. Admission refuses only the same owner, tree and lane command, so different lanes of one commit run together. +- `pre-pr-lanes.mjs run --fleet-where remote` replays a workflow job on the heavy host. Test selection includes tests that read a changed file by path, and a change to a bundled module needs the build and the committed-dist check. +- `fleet-home.mjs start` and `resume` run a recurring worker check for the program, and a missing, stale or failing heartbeat is flagged. +- ISS-14882: on a barred host main-sync validation and the frozen render run on the heavy host against the exact committed tree, with the caller's provider binding. A report for another head, tree, recipe or transaction is refused. +- The session's writer can write its own decision table and local plan. A scratch lease and a proof worktree at the exact commit work on the heavy host, and `fleet.sh remote stop-owned` stops only a process that host's slot records name with the caller's owner. +- ISS-14881: `fleet.sh remote review` starts the Codex reviewer from the plugin installed on the other host. + +#### Changed + +- A lane pass needs its run's log and the HEAD and tree captured when it ran, and only the writer records lanes. The web lane requires the browser specs and the Desktop lane the Desktop specs. +- Proof receipts read the branch's own changes from its merge base with the base, so a base that moved on adds no proofs and hides none. +- The frozen render retries a base-only play failure with more time, writes evidence for every blocking story and takes a recorded base-broken story. It ignores type-only imports when it selects stories. +- The watcher reports each machine's free Docker disk and stays up through gaps the host's load explains. + +#### Fixed + +- ISS-14874: a cloud workflow lane step trusts only the checkout and the lane's clone for Git, even on a host whose system Git config trusts every directory, as GitHub's Ubuntu runner image does. +- A review receipt recorded before launchers wrote their worktree is accepted on its other bindings, and a recorded review keeps its own copy of the launcher output. +- The orphaned-type-member rule sees conditional spreads and shorthand properties, negated property, containment and call matchers count as absence assertions, and the Storybook version merge bumps past main when both chose the same version. +- Codex skill discovery skips the forced reload when the cached list is current, and a timeout names its stage. +- The sweep lists and reclaims an orphaned run-state directory. A sweep of one named record touches nothing else. +- Across all plugin Markdown, including eval prompts and graders, the release is about 998 words longer than v1.1.117. The count covers the source files in `plugins/vibe` and excludes the generated ClosedLoop edition. + +### vibe-closedloop-provider v1.0.10 + +- The verifier reference says the writer runs, witnesses and records lanes. + ### vibe v1.1.117 #### Added diff --git a/plugins/vibe-closedloop-provider/.claude-plugin/plugin.json b/plugins/vibe-closedloop-provider/.claude-plugin/plugin.json index eaa48394..e1b2b2e0 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.9", + "version": "1.0.10", "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 2c0cded2..b1bf0014 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.9", + "version": "1.0.10", "description": "ClosedLoop and symphony-alpha knowledge for vibe and fleet-orchestrator: tickets, plans, the code graph, repository memory and the symphony-alpha recipes. Build input for the vibe plugin: tools/vibe-closedloop-build assembles it into plugins/vibe-closedloop", "author": {"name": "ClosedLoop", "email": "support@closedloop.ai"}, "homepage": "https://github.com/closedloop-ai/claude-plugins", diff --git a/plugins/vibe-closedloop-provider/skills/closedloop-provider/references/agents/vibe-verify-worker.md b/plugins/vibe-closedloop-provider/skills/closedloop-provider/references/agents/vibe-verify-worker.md index 0cdd4919..175a9276 100644 --- a/plugins/vibe-closedloop-provider/skills/closedloop-provider/references/agents/vibe-verify-worker.md +++ b/plugins/vibe-closedloop-provider/skills/closedloop-provider/references/agents/vibe-verify-worker.md @@ -26,7 +26,9 @@ When `../skills/vibe/scripts/verify-run.mjs` exists, run once at the final head instead of running the bounded checks below by hand. It wraps the repository's own Biome, `pnpm check:source-gates`, `pnpm typecheck:affected`, the lanes `pnpm test:lanes` names (through -`pre-pr-lanes.mjs`) and the commands in your `--tests-file`, which is the +`pre-pr-lanes.mjs`; as the verifier it runs none, and each missing lane comes +back `not-run`, owned by the writer, who runs, witnesses and records it) and +the commands in your `--tests-file`, which is the `code_tests_for_changes` selection you make (it is an MCP tool the script cannot call). It writes one evidence JSON that keeps `passed`, `failed`, `blocked`, `cached`, `main-preexisting`, `no-op`, `skipped` and `not-run` apart: a skipped, no-op, @@ -99,9 +101,10 @@ script or workflow reruns in its job's shape from failure, refresh the inventory and rerun only that failed case and any target the fix newly reaches, never the whole set. `qa-impact.mjs` decides reuse and names any lanes or screens. A selected failure runs once more on captured main (the main-sync -`mainSha`; for a lane, `../skills/vibe/scripts/pre-pr-lanes.mjs run +`mainSha`; for a lane, the writer runs `../skills/vibe/scripts/pre-pr-lanes.mjs run --main-worktree --main-sha ` with the same `--report` -or `--impact` selection file). When it fails there +or `--impact` selection file, since lane records are the writer's and that +command refuses you). When it fails there too, record it `status: "main-preexisting"` with that `mainSha`: it does not block the pull request, and the body lists it under Known main failures. One that passes on main stays a failure for the writer. A @@ -211,8 +214,8 @@ Three more rules: limitation, never a pass. - Graph-selected local E2E: on `RUN_ALL`, use `code_tests_for_changes`'s `start_here` and direct-evidence specs plus every E2E spec the pull request - adds or edits, and record them as `pre-pr-lanes.mjs check`'s `TARGETED-E2E` - line says. In symphony-alpha the full lane runs after merge, not on the pull request. + adds or edits, and give them to the writer, who runs, witnesses and + records them as `pre-pr-lanes.mjs check`'s `TARGETED-E2E` line says. In symphony-alpha the full lane runs after merge, not on the pull request. - Before you claim that CI runs, or ran, a check or test, read `.github/pr-test-event-tiers.md` and cite the tier of the job that runs it. A `batch-only` job does not run on the pull request, and its `skipped` diff --git a/plugins/vibe-closedloop-provider/tests/fleet-shipment.test.mjs b/plugins/vibe-closedloop-provider/tests/fleet-shipment.test.mjs new file mode 100644 index 00000000..ba8c26c9 --- /dev/null +++ b/plugins/vibe-closedloop-provider/tests/fleet-shipment.test.mjs @@ -0,0 +1,12 @@ +import assert from "node:assert/strict"; +import test from "node:test"; +import { fileURLToPath } from "node:url"; +import { shippedFiles } from "../../vibe/shared/ship-plugins.mjs"; + +test("fleet shipment includes the generated provider contract and exact-tree inventory bundle", () => { + const built = fileURLToPath(new URL("../../vibe-closedloop", import.meta.url)); + assert.ok(shippedFiles(["skills/handoff/scripts/frozen-render-gate.mjs"], built).includes("plugins/vibe/provider/provider.json"), + "the shipped provider binding resolves its own contract on the heavy host"); + assert.ok(shippedFiles(["skills/handoff/scripts/handoff-inventory.mjs"], built) + .includes("plugins/vibe/skills/vibe/scripts/dist/main-sync.mjs"), "the inventory ships its bundle without treating embedded source as imports"); +}); diff --git a/plugins/vibe-closedloop/.claude-plugin/plugin.json b/plugins/vibe-closedloop/.claude-plugin/plugin.json index 6d0c89db..b0c614c5 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.117", + "version": "1.1.118", "dependencies": [ "closedloop-core", "vibe-core" diff --git a/plugins/vibe-closedloop/.codex-plugin/plugin.json b/plugins/vibe-closedloop/.codex-plugin/plugin.json index de7508b7..d53fb815 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.117", + "version": "1.1.118", "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 4e164c8c..6b3103b1 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.117` contains 17 skills and 17 agents, and no hook manifest: the +Version `1.1.118` 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/agents/vibe-change-worker.md b/plugins/vibe-closedloop/agents/vibe-change-worker.md index b6cdb4b4..5036e9d7 100644 --- a/plugins/vibe-closedloop/agents/vibe-change-worker.md +++ b/plugins/vibe-closedloop/agents/vibe-change-worker.md @@ -430,6 +430,28 @@ Throughout: `code_tests_for` is one-file only. Empty results add related tests; E2E uses lanes/behavior refs. A UI bug records each shell as `Owner test: : test ` or `Owner test: : missing tests `. +- Run each lane as a coordinator background job, never inside a worker + turn: `pre-pr-lanes.mjs run --background` starts it detached and it records + its own result. `pre-pr-lanes.mjs check` reports `RUNNING-LANE` until then, + and `INTERRUPTED-LANE` for a run killed mid-run, which is neither a pass nor + a failure: run it again. `REFUSED-LANE` is a fleet slot that refused before + the lane started; nothing was recorded. An environmental skip names the + exact timed-out test ids of a run under `pre-pr-lanes.mjs witness --outcomes` + (`record --result env-skip`), and every other test in that run passed. +- Classify the affected checks with + `pre-pr-lanes.mjs check --reuse-unaffected ` whose + `lastQa.boundary` identifies the source the passing lanes and clean reviews + covered. Run only its `MISSING-LANE`s + and ask for a new review only from the roles its `REVIEW-ROLES` line names; + a `CACHED-LANE` is reported as cached, never as a fresh pass. +- A workflow-recipe lane (a JSON lane report's job) can replay on the heavy + host: `pre-pr-lanes.mjs run --fleet-where remote` runs the job's steps + with its Node, `CI`, Python and `env` and records the result. +- Run `vibe-worker-bundle-impact.mjs --worktree --base ` + from the handoff skill's scripts when checking a change in a repository + that contains `tools/vibe-workers`. If it reports affected inputs, include + the repository's vibe-workers workflow job. Its `npm run build` and + committed-dist verification need a passing result on the tested source. - Never spawn unsafe browser/Electron automation: unsupported required scenarios remain named incomplete evidence. Publication-ready preview is not E2E PASS. diff --git a/plugins/vibe-closedloop/agents/vibe-verify-worker.md b/plugins/vibe-closedloop/agents/vibe-verify-worker.md index 8f3be97c..9e6e7571 100644 --- a/plugins/vibe-closedloop/agents/vibe-verify-worker.md +++ b/plugins/vibe-closedloop/agents/vibe-verify-worker.md @@ -23,8 +23,12 @@ source's verifier failures: `{id, blocking, evidence, premises}` entries, or clear handoff by reporting only a narrative summary. "Read-only" here means no product source, test, or live record mutations. The existing `pre-pr` procedure writes its owned private -`/vibe-pr-evidence.json` and `pre-pr-lanes.mjs` writes -`/vibe-lane-results.json`; these are required verification receipts. +`/vibe-pr-evidence.json`, a required verification receipt. Lane +records in `/vibe-lane-results.json` belong to the session's writer: +you run `pre-pr-lanes.mjs check` only, which reads them and writes nothing for +you, and `pre-pr-lanes.mjs run`, `witness` and `record` refuse you with a +message naming the writer. Report each missing lane to the writer, who runs, +witnesses and records it. Save the repository-declared lane report as `/vibe-lane-report.txt`. Command-based repositories default to `pnpm test:lanes`; their existing `pre-pr-lanes.mjs check --report` path is unchanged. @@ -73,7 +77,9 @@ When `../skills/vibe/scripts/verify-run.mjs` exists, run once at the final head instead of running the bounded checks below by hand. It wraps the repository's own Biome, `pnpm check:source-gates`, `pnpm typecheck:affected`, the lanes `pnpm test:lanes` names (through -`pre-pr-lanes.mjs`) and the commands in your `--tests-file`, which is the +`pre-pr-lanes.mjs`; as the verifier it runs none, and each missing lane comes +back `not-run`, owned by the writer, who runs, witnesses and records it) and +the commands in your `--tests-file`, which is the `code_tests_for_changes` selection you make (it is an MCP tool the script cannot call). It writes one evidence JSON that keeps `passed`, `failed`, `blocked`, `cached`, `main-preexisting`, `no-op`, `skipped` and `not-run` apart: a skipped, no-op, @@ -149,9 +155,10 @@ script or workflow reruns in its job's shape from failure, refresh the inventory and rerun only that failed case and any target the fix newly reaches, never the whole set. `qa-impact.mjs` decides reuse and names any lanes or screens. A selected failure runs once more on captured main (the main-sync -`mainSha`; for a lane, `../skills/vibe/scripts/pre-pr-lanes.mjs run +`mainSha`; for a lane, the writer runs `../skills/vibe/scripts/pre-pr-lanes.mjs run --main-worktree --main-sha ` with the same `--report` -or `--impact` selection file). When it fails there +or `--impact` selection file, since lane records are the writer's and that +command refuses you). When it fails there too, record it `status: "main-preexisting"` with that `mainSha`: it does not block the pull request, and the body lists it under Known main failures. One that passes on main stays a failure for the writer. A @@ -261,8 +268,8 @@ Three more rules: limitation, never a pass. - Graph-selected local E2E: on `RUN_ALL`, use `code_tests_for_changes`'s `start_here` and direct-evidence specs plus every E2E spec the pull request - adds or edits, and record them as `pre-pr-lanes.mjs check`'s `TARGETED-E2E` - line says. In symphony-alpha the full lane runs after merge, not on the pull request. + adds or edits, and give them to the writer, who runs, witnesses and + records them as `pre-pr-lanes.mjs check`'s `TARGETED-E2E` line says. In symphony-alpha the full lane runs after merge, not on the pull request. - Before you claim that CI runs, or ran, a check or test, read `.github/pr-test-event-tiers.md` and cite the tier of the job that runs it. A `batch-only` job does not run on the pull request, and its `skipped` diff --git a/plugins/vibe-closedloop/hooks/protected-write-guard.mjs b/plugins/vibe-closedloop/hooks/protected-write-guard.mjs index 86b493a0..4810966f 100644 --- a/plugins/vibe-closedloop/hooks/protected-write-guard.mjs +++ b/plugins/vibe-closedloop/hooks/protected-write-guard.mjs @@ -8,6 +8,8 @@ import { execFileSync } from "node:child_process"; import { existsSync, lstatSync, readFileSync, realpathSync } from "node:fs"; import path from "node:path"; import { isEntryPoint } from "../shared/plugin-roots.mjs"; +import { localPlanPaths } from "../lib/vibe/scripts/session-artifact-paths.mjs"; +import { localPlanArguments } from "../lib/vibe/scripts/local-plan-arguments.mjs"; const protectedDirectories = new Set([ ".git", ".claude", ".vscode", ".idea", ".husky", ".cargo", @@ -50,8 +52,23 @@ function targetPaths(root, cwd, raw) { return { lexical, effective, admitted }; } -/** Match the one private change log owned by this exact linked worktree. */ -function isOwnChangeLog(root, target) { +/** The exact file at `lexical` (its real path only `base` resolved), as a regular file or not yet created. */ +function exactPrivateFile(target, lexical, base) { + const effective = path.join(realpathSync(base), path.relative(base, lexical)); + if (target.lexical !== lexical || target.effective !== effective) return false; + try { + if (!lstatSync(target.lexical).isFile()) return false; + } catch (error) { + if (error?.code !== "ENOENT") return false; + } + return true; +} + +/** + * Match this exact linked worktree's own private session files: its change log, and, when the session keeps them in + * the git common dir (no provider recipe), the decision table and the request plans `local-plans.mjs paths` reports. + */ +function isOwnSessionFile(root, target) { try { let gitDir = gitDirectoryCache.get(root); if (!gitDir) { @@ -60,15 +77,13 @@ function isOwnChangeLog(root, target) { }).trim()); gitDirectoryCache.set(root, gitDir); } - const lexical = path.join(gitDir, "vibe-changes.md"); - const effective = path.join(realpathSync(gitDir), "vibe-changes.md"); - if (target.lexical !== lexical || target.effective !== effective) return false; - try { - if (!lstatSync(target.lexical).isFile()) return false; - } catch (error) { - if (error?.code !== "ENOENT") return false; - } - return true; + if (exactPrivateFile(target, path.join(gitDir, "vibe-changes.md"), gitDir)) return true; + if (!target.lexical.endsWith(".md")) return false; + const requestId = path.basename(target.lexical, ".md"); + const paths = localPlanPaths(root, { requestId }); + if (paths.inWorktree) return false; + const commonDir = path.dirname(path.dirname(paths.root)); + return exactPrivateFile(target, paths.decisionTable, commonDir) || exactPrivateFile(target, paths.plan, commonDir); } catch { return false; } @@ -83,9 +98,9 @@ function protectedPath(root, target) { || protectedFiles.has(part) || (part === "git" && parts[index - 1] === ".config")); } -function protectedWrite(root, cwd, raw, { allowOwnChangeLog = true } = {}) { +function protectedWrite(root, cwd, raw, { allowOwnSessionFiles = true } = {}) { const target = targetPaths(root, cwd, raw); - if (allowOwnChangeLog && isOwnChangeLog(root, target)) return false; + if (allowOwnSessionFiles && isOwnSessionFile(root, target)) return false; return protectedPath(root, target.lexical) || protectedPath(realpathSync(root), target.effective); } @@ -134,6 +149,34 @@ function scriptTargets(script) { return targets.filter((value) => typeof value === "string"); } +/** Whether `word` names local-plans.mjs in any case, or is a file whose real path does. */ +function runsLocalPlans(word, cwd, unresolvedCwd) { + const named = (file) => path.basename(file).toLowerCase() === "local-plans.mjs"; + if (named(word)) return true; + if (unresolvedCwd && !path.isAbsolute(word)) return false; + try { return named(realpathSync(path.resolve(cwd, word))); } catch { return false; } +} + +/** + * `local-plans.mjs write` replaces a session's table or plan at the worktree it is given, so it is admitted only when + * exactly one literal `--worktree` resolves to this session's own worktree; anything else fails closed. + */ +function foreignLocalPlansWrite(root, cwd, unresolvedCwd, words) { + const at = words.findIndex((word) => runsLocalPlans(word, cwd, unresolvedCwd)); + if (at < 0) return false; + try { + const { positionals, values, tokens } = localPlanArguments(words.slice(at + 1)); + if (positionals[0] !== "write") return false; + const value = values.worktree; + const count = tokens.filter((token) => token.kind === "option" && token.name === "worktree").length; + if (count !== 1 || !value || /[$*?`]/.test(value) || value.startsWith("~")) return true; + if (unresolvedCwd && !path.isAbsolute(value)) return true; + return realpathSync(path.resolve(cwd, value)) !== realpathSync(root); + } catch { + return true; + } +} + function bashProtectedWrite(root, cwd, command) { const commands = shellCommands(command); const protectedReason = "shell write to a protected target refused"; @@ -160,9 +203,12 @@ function bashProtectedWrite(root, cwd, command) { } continue; } - const decisionFor = (target, allowOwnChangeLog = true) => { + if (foreignLocalPlansWrite(root, currentCwd, unresolvedCwd, [program ?? "", ...args])) { + return "local-plans.mjs write must name this session's own worktree"; + } + const decisionFor = (target, allowOwnSessionFiles = true) => { if (unresolvedCwd && !path.isAbsolute(target)) return unresolvedReason; - return protectedWrite(root, currentCwd, target, { allowOwnChangeLog }) ? protectedReason : null; + return protectedWrite(root, currentCwd, target, { allowOwnSessionFiles }) ? protectedReason : null; }; if (writers.has(name)) { const inline = args.findIndex((arg) => ["-c", "-e", "--eval"].includes(arg)); @@ -207,7 +253,7 @@ export function protectedWriteDecision(event, root) { const cwd = path.resolve(event.cwd); if (tool === "Edit" || tool === "Write") { const target = targetPaths(root, cwd, event.tool_input?.file_path); - if (target.admitted || isOwnChangeLog(root, target)) { + if (target.admitted || isOwnSessionFile(root, target)) { return eventName === "PermissionRequest" ? { hookSpecificOutput: { hookEventName: "PermissionRequest", decision: { behavior: "allow" } } } : null; diff --git a/plugins/vibe-closedloop/hooks/shell-safety-guard.mjs b/plugins/vibe-closedloop/hooks/shell-safety-guard.mjs index cf68726e..448295eb 100644 --- a/plugins/vibe-closedloop/hooks/shell-safety-guard.mjs +++ b/plugins/vibe-closedloop/hooks/shell-safety-guard.mjs @@ -25,6 +25,7 @@ import { deny, eventCwd } from "./hook-dispatch.mjs"; import { scriptOperands, ScriptUse } from "./script-operands.mjs"; import { providerGuardRule, recordedBinding } from "../lib/vibe/scripts/provider.mjs"; import { launcherWorker } from "../lib/vibe/scripts/worker-scope.mjs"; +import { LAUNCHED_AGENT_ENV, launchedReviewerOrVerifier } from "../skills/vibe/scripts/agent-models.mjs"; const E2E_SCRIPT = /e2e/i; @@ -68,6 +69,10 @@ const FIND_EXEC = new Set(["-exec", "-execdir", "-ok", "-okdir"]); const FIND_MATCH = new Set(["-name", "-iname", "-path", "-ipath", "-wholename", "-iwholename", "-regex", "-iregex"]); const FIND_PATTERN = /[*?[]/; +const QUOTING = /\\\n|["'\\]/g; +// The spellings of `env -i` commandPrefix does not parse (`-`, a short cluster, an abbreviation); it leaves them as the first words. +const CLEARS_ENVIRONMENT = /^-(?:$|[A-Za-z]*i|-i)/; + /** The credential-safety refusal for a shell command, or null. */ export function credentialProblem(command) { if (!CREDENTIAL_ROUTE.test(command) || !TOKEN.test(command)) return null; @@ -180,6 +185,15 @@ function workerDeleteProblem(event, command) { return problem && launcherWorker(event?.session_id) ? problem : null; } +/** In a process the launcher started as a reviewer or verifier, the refusal for naming the variable that says so or running `env -i`, or null. */ +function launchedAgentProblem(command) { + const agent = launchedReviewerOrVerifier(); + if (!agent) return null; + const clears = ({ words, clearEnv }) => clearEnv || (words[0]?.startsWith("-") && words.some((word) => CLEARS_ENVIRONMENT.test(word))); + if (!command.replace(QUOTING, "").includes(LAUNCHED_AGENT_ENV) && !commandSegments(command, { expandShellPayloads: true }).some(clears)) return null; + return `launched agent ${agent} is a reviewer or verifier, so a command that names ${LAUNCHED_AGENT_ENV} or runs env -i is refused: run it without them; the session's writer keeps its records`; +} + /** The refusal for a fleet watcher launch that is not its own background tool call, or null. */ export function watcherLaunchProblem(input) { const command = typeof input?.command === "string" ? input.command.replace(REDIRECT_AMPERSAND, " ") : ""; @@ -365,7 +379,7 @@ export function shellSafetyGuard(event) { const rule = providerRules(event); const problem = credentialProblem(command) ?? forcePushProblem(command) ?? noVerifyProblem(command) ?? watcherLaunchProblem(event.tool_input) ?? wordSplitProblem(command) ?? equalsWordProblem(command) - ?? workerDeleteProblem(event, command) ?? e2eSlotProblem(command, rule("e2eSlot"), { cwd: eventCwd(event) }) ?? heavySlotProblem(command, rule("heavySlot")); + ?? workerDeleteProblem(event, command) ?? launchedAgentProblem(command) ?? e2eSlotProblem(command, rule("e2eSlot"), { cwd: eventCwd(event) }) ?? heavySlotProblem(command, rule("heavySlot")); return problem ? deny(problem) : null; } diff --git a/plugins/vibe-closedloop/lib/codex-fleet-monitor/scripts/watch-gap.mjs b/plugins/vibe-closedloop/lib/codex-fleet-monitor/scripts/watch-gap.mjs index 84cc91f0..9c66db4d 100644 --- a/plugins/vibe-closedloop/lib/codex-fleet-monitor/scripts/watch-gap.mjs +++ b/plugins/vibe-closedloop/lib/codex-fleet-monitor/scripts/watch-gap.mjs @@ -1,7 +1,9 @@ // The watcher publishes a gap in its snapshot; only a complete, in-window pmset pair can queue a sleep notice. +// A gap the host's load explains raises at most one WATCH-GAP an hour; the others are noted in the snapshot only. import { spawn } from "node:child_process"; import { createHash, randomUUID } from "node:crypto"; -import { lstatSync, readdirSync, readFileSync, readlinkSync, renameSync, symlinkSync, unlinkSync, writeFileSync } from "node:fs"; +import { lstatSync, readdirSync, readFileSync, readlinkSync, renameSync, rmSync, symlinkSync, unlinkSync, writeFileSync } from "node:fs"; +import os from "node:os"; import path from "node:path"; import { createInterface } from "node:readline"; import { canonicalHome, commandChat, programChats, validChat } from "../../fleet-orchestrator/scripts/chat-binding.mjs"; @@ -13,6 +15,9 @@ import { isEntryPoint } from "../../../shared/plugin-roots.mjs"; import { processIdentityStatus, readProcessIdentity } from "../../../shared/process-identity.mjs"; const DISPLAY_TIME = /^([01]\d|2[0-3]):[0-5]\d [A-Za-z0-9+:-]+$/; +// One WATCH-GAP an hour for a run of load-explained gaps (AC-15); the fleet's load ceiling defaults as load-check.sh does. +const LOAD_GAP_HOLD_SECONDS = 3600; +const DEFAULT_MAX_LOAD_PER_CORE = 1.5; const NOTICE_ID = /^(\d{1,10})-(\d{1,10})-[a-f0-9-]{36}$/; /** Bound owners use their program queue. Launching chats find their queue in private hook state. */ @@ -94,15 +99,63 @@ function publishGap(dir, line, pending) { } } +/** + * The host's load per core across a stalled tick, read at its end: the lower of the 5- and 15-minute averages, so a + * short spike cannot explain a long gap. Null when the reading is unusable. + */ +function hostLoad(env = process.env) { + const cores = typeof os.availableParallelism === "function" ? os.availableParallelism() : os.cpus().length; + const [, five, fifteen] = os.loadavg(); + const configured = Number(env.MAX_LOAD_PER_CORE); + const max = Number.isFinite(configured) && configured > 0 ? configured : DEFAULT_MAX_LOAD_PER_CORE; + if (!(cores > 0) || !Number.isFinite(five) || !Number.isFinite(fifteen)) return null; + return { perCore: Math.min(five, fifteen) / cores, max }; +} + +function readLoadState(dir) { + try { return regularJson(path.join(dir, "watch-gap-load.json")); } catch { return null; } +} + +/** + * Classify one late tick. A confirmed sleep pair is SLEPT; a gap whose load per core is over the fleet's ceiling + * raises `WATCH-GAP (load ...)` once an hour and is otherwise held as a note line for the snapshot; any other + * gap raises `WATCH-GAP ` at once. Returns `{ event, note }`: a null event is a held gap. + */ +export function classifyGap(dir, { start, end, pair = null, load = null }) { + if (pair) { + return { event: `SLEPT ${duration(pair.woke - pair.slept)} (sleep ${clock(pair.slept)}, wake ${clock(pair.woke)})`, note: null }; + } + const span = duration(end - start); + const notePath = path.join(dir, "watch-load-gap"); + if (!load || !(load.perCore > load.max)) { + rmSync(notePath, { force: true }); + return { event: `WATCH-GAP ${span}`, note: null }; + } + const shown = `${load.perCore.toFixed(2)}/core over ${load.max}`; + const last = Number(readLoadState(dir)?.lastEventAt); + if (Number.isSafeInteger(last) && end >= last && end - last < LOAD_GAP_HOLD_SECONDS) { + const note = `watch-load-gap ${start}-${end} ${span} load ${shown}; held, the next load event can raise after ${clock(last + LOAD_GAP_HOLD_SECONDS)}`; + writeFileSync(notePath, `${note}\n`, { mode: 0o600 }); + return { event: null, note }; + } + writeAtomic(path.join(dir, "watch-gap-load.json"), { lastEventAt: end }); + rmSync(notePath, { force: true }); + return { event: `WATCH-GAP ${span} (load ${shown})`, note: null }; +} + /** Capture the original owner together with confirmed endpoints before publishing the tick. */ async function recordGap(dir, start, end, platform, oldest, reported) { const pair = platform === "Darwin" ? await confirmedSleep(start, end) : null; + const { event } = classifyGap(dir, { start, end, pair, load: pair ? null : hostLoad() }); + if (event === null) { + // A held gap publishes nothing new, so the watcher keeps running; an older queued window still gets its retry. + if (oldest) retryWindow(dir, oldest, reported); + return; + } let notice = null; - let event = `WATCH-GAP ${duration(end - start)}`; if (pair) { const slept = clock(pair.slept); const woke = clock(pair.woke); - event = `SLEPT ${duration(pair.woke - pair.slept)} (sleep ${slept}, wake ${woke})`; const { home, program } = resolveWorkDir(canonicalHome(dir)); const holder = program && programChats(home, program)[0]; const owner = holder || commandChat(); diff --git a/plugins/vibe-closedloop/lib/codex-fleet-monitor/scripts/work-dir.mjs b/plugins/vibe-closedloop/lib/codex-fleet-monitor/scripts/work-dir.mjs index 754b01e4..629c1645 100644 --- a/plugins/vibe-closedloop/lib/codex-fleet-monitor/scripts/work-dir.mjs +++ b/plugins/vibe-closedloop/lib/codex-fleet-monitor/scripts/work-dir.mjs @@ -30,7 +30,7 @@ import { existsSync, readFileSync, statSync } from "node:fs"; import path from "node:path"; -import { ambiguousHome, canonicalHome, chatBinding, commandChat, takenOver } from "../../fleet-orchestrator/scripts/chat-binding.mjs"; +import { ambiguousHome, canonicalHome, chatBinding, commandChat, takenOver, worktreePrograms } from "../../fleet-orchestrator/scripts/chat-binding.mjs"; import { isEntryPoint } from "../../../shared/plugin-roots.mjs"; export const PER_PROGRAM_KEYS = ["LOCAL_STATE_DIR", "REQUESTS_DIR", "REMOTE_STATE_DIR", "REMOTE_REQUESTS_DIR"]; @@ -96,6 +96,24 @@ function configFiles(resolved) { .filter((file) => file && existsSync(file)); } +/** fleet.sh's exit, and the route it names, for heavy work on a machine whose fleet config bars it. */ +export const HEAVY_BAR_EXIT = 78; +export const HEAVY_BAR_MESSAGE = "LOCAL_HEAVY_BARRED=1 in config.env bars heavy work on this machine; run it with fleet.sh remote slot heavy "; + +/** + * This machine's heavy-work policy, read the way fleet.sh reads it: the fleet dir's config.env (FLEET_HOME, else the + * home this chat is bound to, else a program whose board registers `worktree` as a writer's) sourced over the + * environment, so a config value wins and the environment fills a key the config leaves out. `{ barred, config }`; barred only for exactly LOCAL_HEAVY_BARRED=1. A home that resolves to no + * single program throws, as fleet.sh stops there (`work-dir.mjs sh` exits 2). + */ +export function fleetHeavyPolicy(env = process.env, fleetDir = env.FLEET_HOME, worktree = null) { + fleetDir ??= chatBinding(commandChat(env), env)?.home; + const dirs = fleetDir ? [fleetDir] : worktree ? worktreePrograms(worktree, env) : []; + const configs = dirs.map((dir) => readConfig(resolveWorkDir(dir, { env }))); + const config = configs.find((found) => found.LOCAL_HEAVY_BARRED === "1") ?? configs[0] ?? {}; + return { barred: (config.LOCAL_HEAVY_BARRED ?? env.LOCAL_HEAVY_BARRED) === "1", config }; +} + /** The shell lines that set W, the home and program, source the config files and set the derived keys. */ export function shellLines(resolved) { const lines = [`W=${quote(resolved.dir)}`, `FLEET_HOME=${quote(resolved.home ?? "")}`, `FLEET_PROGRAM=${quote(resolved.program ?? "")}`]; diff --git a/plugins/vibe-closedloop/lib/fleet-orchestrator/scripts/chat-binding.mjs b/plugins/vibe-closedloop/lib/fleet-orchestrator/scripts/chat-binding.mjs index cf90ada8..9155260b 100644 --- a/plugins/vibe-closedloop/lib/fleet-orchestrator/scripts/chat-binding.mjs +++ b/plugins/vibe-closedloop/lib/fleet-orchestrator/scripts/chat-binding.mjs @@ -30,6 +30,7 @@ // program wins; else `current` when no other chat holds it, the // single-orchestrator behavior from before bindings; else no program. +import { execFileSync } from "node:child_process"; import { createHash, randomUUID } from "node:crypto"; import { existsSync, linkSync, lstatSync, mkdirSync, readdirSync, readFileSync, realpathSync, renameSync, statSync, unlinkSync, writeFileSync } from "node:fs"; import os from "node:os"; @@ -95,6 +96,56 @@ export function programWorktrees(chat, env = process.env) { } } +/** Writer registrations from known fleet programs (under FLEET_HOME or bound to a chat), with their program directory. */ +export function fleetWriterRegistrations(env = process.env) { + const listDir = (dir) => { + try { + return readdirSync(dir); + } catch { + return []; + } + }; + const programs = new Set(); + // One home, however it is spelled (a symlink or a relative FLEET_HOME), is one set of programs. + if (env.FLEET_HOME) { + const dir = path.join(canonicalHome(env.FLEET_HOME), "programs"); + for (const name of listDir(dir)) programs.add(path.join(dir, name)); + } + for (const name of listDir(bindingDir(env)).filter((file) => file.endsWith(".json"))) { + try { + const binding = JSON.parse(readFileSync(path.join(bindingDir(env), name), "utf8")); + if (typeof binding?.home === "string" && typeof binding.program === "string") { + programs.add(path.join(canonicalHome(binding.home), "programs", binding.program)); + } + } catch { /* A broken file is not a fleet binding. */ } + } + return [...programs].flatMap((program) => { + try { + const board = JSON.parse(readFileSync(path.join(program, "board.json"), "utf8")); + return Object.values(board?.writers ?? {}).map((writer) => ({ program, writer })); + } catch { + return []; + } + }); +} + +/** Every fleet program whose board registers the checkout. */ +export function worktreePrograms(worktree, env = process.env) { + let top; + try { + top = realpathSync(execFileSync("git", ["rev-parse", "--show-toplevel"], { cwd: worktree, encoding: "utf8", stdio: ["ignore", "pipe", "ignore"] }).trim()); + } catch { + return []; + } + const programs = new Set(); + for (const { program, writer } of fleetWriterRegistrations(env)) { + try { + if (realpathSync(writer.worktree) === top) programs.add(program); + } catch { /* A missing or remote-only path does not own this checkout. */ } + } + return [...programs]; +} + function takenFile(chat, env) { return path.join(bindingDir(env), "taken", `${chat}.json`); } diff --git a/plugins/vibe-closedloop/lib/fleet-orchestrator/scripts/fleet-home.mjs b/plugins/vibe-closedloop/lib/fleet-orchestrator/scripts/fleet-home.mjs index 8a2f7b0f..3c39033f 100644 --- a/plugins/vibe-closedloop/lib/fleet-orchestrator/scripts/fleet-home.mjs +++ b/plugins/vibe-closedloop/lib/fleet-orchestrator/scripts/fleet-home.mjs @@ -56,6 +56,11 @@ // choice, else the last result. Every new chat runs the check again. // `resume` also writes the default context-guard.json when the home has none // (vibe's compaction hooks; the operator's 2026-11-09 ruling). +// `start` and `resume`, run in a Claude Code or Codex chat, schedule the program's recurring worker check +// themselves (worker-check-schedule.mjs: a vibe-owned background loop, every 15 minutes by default) and print +// `WORKER-CHECK-SCHEDULED ` or `WORKER-CHECK-LIVE `; the reading list prints +// `WORKER-CHECK-MISSING()` while its heartbeat is missing or older than two intervals, +// and `WORKER-CHECK-FAILING()` while its last pass failed. // `check` prints, and exits 1 on, state outside the home or the program: // `FLAT ` (program state at the home's top), `OUTSIDE -> ` // (a symlink in the home resolving outside it), `CONFIG ` (a per-program @@ -84,6 +89,7 @@ import { bindChat, canonicalHome, canonicalProgram, chatBinding, chatHome, comma import { completeHandoff, HANDOVER_FILE, handoffProblems, recordCronDeleted, recordTold, startHandoff, stopRecordedWatcher, stopWatcher } from "./fleet-handoff.mjs"; import { migrate } from "./fleet-migrate.mjs"; import { skillFreshnessProblem } from "./skill-freshness.mjs"; +import { scheduleWorkerCheck, workerCheckHeartbeat } from "./worker-check-schedule.mjs"; import { vibeScriptPath } from "../../../shared/vibe-install.mjs"; import { isEntryPoint } from "../../../shared/plugin-roots.mjs"; @@ -205,6 +211,8 @@ export function resumeLines(home, { env = process.env, chat = commandChat(env) } } if (!resolved.program) return [...lines, `NO-ACTIVE-PROGRAM: start one with fleet-home.mjs start ; it reads no earlier program's state`]; lines.push(`ACTIVE ${resolved.program} ${resolved.dir}`, shapeLine(resolved.dir), pluginVersionLine(resolved.dir)); + const workerCheck = workerCheckHeartbeat(resolved.dir); + if (!workerCheck.ok) lines.push(workerCheck.line); // Each chat writes its own program's handover (fleet-handoff.mjs); the home's shared one is read only while a program has none. const handover = [path.join(resolved.dir, HANDOVER_FILE), path.join(home, HANDOVER_FILE)].find((file) => existsSync(file)); if (handover) lines.push(`READ ${handover}`); @@ -491,7 +499,20 @@ export function launcherLines(home, { install = false, bin, env = process.env } ...(onPath ? [] : [`NOT-ON-PATH ${dir}: add it to PATH, or run ${file} by its full path`])]; } -function main(argv, env = process.env) { +/** The worker-check schedule line for the program `chat` runs in `home`; none outside a chat, which runs no orchestrator. */ +function scheduleLines(home, chat, env, spawnLoop) { + if (!chat) return []; + let dir; + try { + ({ dir } = chatProgramDir(home, chat, env)); + } catch { + return []; + } + return existsSync(dir) ? [scheduleWorkerCheck(dir, { env, ...(spawnLoop ? { spawnLoop } : {}) })] : []; +} + +/** The command line; `spawnLoop` replaces the worker check's detached start (tests). */ +export function main(argv, env = process.env, { spawnLoop } = {}) { const [command, ...rest] = argv; const { values, positionals } = parseArgs({ args: rest, allowPositionals: true, options: { home: { type: "string" }, from: { type: "string" }, program: { type: "string" }, shape: { type: "string" }, "dry-run": { type: "boolean" }, settled: { type: "boolean" }, @@ -507,7 +528,7 @@ function main(argv, env = process.env) { if (!positionals[0]) throw new Error("Usage: fleet-home.mjs start --shape no-writer|one-writer|fleet [--home ]"); const { dir, takenFrom } = startProgram(home, positionals[0], values.shape, { env, chat, takeover: values.takeover }); print([`started ${dir}`, shapeLine(dir), ...takenFrom.map((other) => `TAKEOVER ${other}: that chat ran ${positionals[0]}; if it is still open, stop it there`), - ...(chat ? [`BOUND ${positionals[0]} ${chat}`] : [])]); + ...(chat ? [`BOUND ${positionals[0]} ${chat}`] : []), ...scheduleLines(home, chat, env, spawnLoop)]); return 0; } if (command === "shape") { @@ -523,7 +544,7 @@ function main(argv, env = process.env) { if (command === "resume") { const seeded = seedLines(home); const bound = positionals[0] ? resumeProgram(home, positionals[0], chat, env, values.takeover) : bindCurrent(home, chat, env); - print([...seeded, ...bound, ...resumeLines(home, { env, chat })]); + print([...seeded, ...bound, ...resumeLines(home, { env, chat }), ...scheduleLines(home, chat, env, spawnLoop)]); return 0; } if (command === "check") { diff --git a/plugins/vibe-closedloop/lib/fleet-orchestrator/scripts/helpers.mjs b/plugins/vibe-closedloop/lib/fleet-orchestrator/scripts/helpers.mjs index aaea1445..81b3810e 100644 --- a/plugins/vibe-closedloop/lib/fleet-orchestrator/scripts/helpers.mjs +++ b/plugins/vibe-closedloop/lib/fleet-orchestrator/scripts/helpers.mjs @@ -10,6 +10,8 @@ // --worker-id --role // --agent-definition --capabilities [--runtime claude|codex] // [--owner --ticket --repo --pr --ending pr-terminal] +// helpers.mjs proof-session --worktree prints its id, commit and tree. +// With --owner and --ticket , it also attests the live scratch lease for remote scratch-run. // helpers.mjs pid [--group] // helpers.mjs resources [--project ] [--container ]... // [--volume ]... [--network ]... @@ -74,8 +76,9 @@ import { promptProblems } from "./skill-freshness.mjs"; import { LoadBasis, loadedSkillEvidence } from "../../vibe/scripts/loaded-skill.mjs"; import { vibeRoot } from "../../../shared/vibe-install.mjs"; -import { prepareScratchLease, reconcileExpiredScratchHelpers, registerScratchProgram, runScratchStack, +import { exportScratchProof, prepareScratchLease, reconcileExpiredScratchHelpers, registerScratchProgram, runScratchStack, scratchLeaseTerminal } from './scratch-cleanup.mjs'; +import { exportProofSession } from '../../vibe/scripts/session-record.mjs'; import { failScript } from "../../vibe/scripts/provider.mjs"; import { isEntryPoint } from "../../../shared/plugin-roots.mjs"; @@ -560,7 +563,8 @@ function prepareTransition(action, entry, values, orchDir) { } else if (action === "start") { const reviewer = FINAL_KINDS.has(values.kind) ? prepareReviewerStart(orchDir, values, readInput, rememberVersion) : {}; if (values.project && values.worktree) requireEmptyProject(values.project); - if (values.kind === "scratch") readLease = prepareScratchLease(orchDir, values.owner, values.worktree); + if (values.kind === "scratch") readLease = prepareScratchLease(orchDir, values.owner, values.worktree, values.ticket, + values["carried-lease"] === undefined ? undefined : JSON.parse(values["carried-lease"])); result = { ...reviewer, ...(values.worktree ? { worktree: path.resolve(values.worktree), source: readSource(values.worktree) } : {}) }; } } catch (error) { @@ -661,20 +665,30 @@ async function main(argv) { deliverable: { type: "string" }, out: { type: "string" }, "session-id": { type: "string" }, "turn-id": { type: "string" }, "completion-event": { type: "string" }, findings: { type: "string" }, runtime: { type: "string" }, reason: { type: "string" }, "if-registration": { type: "string" }, + "carried-lease": { type: "string" }, container: { type: "string", multiple: true }, volume: { type: "string", multiple: true }, network: { type: "string", multiple: true }, }, }); - if (!workDir || !["start", "pid", "resources", "final", "accepted", "abandoned", "stopped", "hand", "unhand", "status", "scratch-run"].includes(action)) { + if (!workDir || !["start", "pid", "resources", "final", "accepted", "abandoned", "stopped", "hand", "unhand", "status", "scratch-run", "proof-session"].includes(action)) { throw new Error("Usage: helpers.mjs start [--kind reviewer|verifier|critic --brief --worktree --worker-id --role --agent-definition --capabilities [--runtime claude|codex]] | final|accepted|stopped|pid|resources|hand|unhand | status"); } const orchDir = resolveWorkDir(workDir).dir; + if (action === 'proof-session') { + if (!values.worktree) throw new Error('proof-session needs --worktree'); + const proof = values.owner || values.ticket + ? exportScratchProof(orchDir, { owner: values.owner, ticket: values.ticket, worktree: values.worktree }) + : exportProofSession(values.worktree); + process.stdout.write(JSON.stringify(proof) + '\n'); + return 0; + } if (action === 'scratch-run') { const name = positionals[0]; if (!name || !values.owner || !values.ticket || !values.worktree || !values["compose-file"]) { throw new Error('scratch-run needs name, owner, ticket, worktree, TTL and Compose file'); } const result = runScratchStack({ orchDir, name, owner: values.owner, ticket: values.ticket, - worktree: values.worktree, ttlSeconds: Number(values["ttl-seconds"]), composeFile: values["compose-file"] }); + worktree: values.worktree, ttlSeconds: Number(values["ttl-seconds"]), composeFile: values["compose-file"], + carriedLease: values["carried-lease"] }); process.stdout.write(JSON.stringify(result) + '\n'); return 0; } diff --git a/plugins/vibe-closedloop/lib/fleet-orchestrator/scripts/scratch-cleanup.mjs b/plugins/vibe-closedloop/lib/fleet-orchestrator/scripts/scratch-cleanup.mjs index 47b925ce..80cd4610 100644 --- a/plugins/vibe-closedloop/lib/fleet-orchestrator/scripts/scratch-cleanup.mjs +++ b/plugins/vibe-closedloop/lib/fleet-orchestrator/scripts/scratch-cleanup.mjs @@ -10,36 +10,57 @@ import path from 'node:path'; import { fileURLToPath } from 'node:url'; import { captureOwnedDockerResources, removeOwnedDockerResources } from '../../vibe/scripts/owned-docker.mjs'; import { defaultLockDir, sameWorktreeEntry } from '../../vibe/scripts/e2e-lock.mjs'; -import { git, readSessionRecord, readSessionRecordFile, sessionRecordPath } from '../../vibe/scripts/session-record.mjs'; +import { exportProofSession, git, proofSession, readSessionRecord, readSessionRecordFile, sessionLiveTicket, + sessionRecordPath } from '../../vibe/scripts/session-record.mjs'; import { acquireLedgerLock, helperEntries, isAlive, pendingRecordedProcess, read, readIdentity, write } from './helpers.mjs'; const HERE = path.dirname(fileURLToPath(import.meta.url)); /** Capture the exact live vibe or fleet writer lease that authorizes a scratch stack. */ -export function captureScratchLease(orchDir, owner, worktree) { - return readScratchLease(orchDir, owner, worktree, sessionRecordPath(worktree)); +export function captureScratchLease(orchDir, owner, worktree, ticket, carried) { + return readScratchLease(orchDir, owner, worktree, sessionRecordPath(worktree), ticket, carried); } /** Bind the lease reader to the prepared Git directory, and verify the live directory before reading. */ -export function prepareScratchLease(orchDir, owner, worktree) { +export function prepareScratchLease(orchDir, owner, worktree, ticket, carried) { const sessionFile = sessionRecordPath(worktree); return (currentGitDir = git(worktree, ['rev-parse', '--absolute-git-dir'], { timeout: 1000 })) => { if (currentGitDir !== path.dirname(sessionFile)) throw new Error('scratch worktree Git directory changed during verification'); - return readScratchLease(orchDir, owner, worktree, sessionFile); + return readScratchLease(orchDir, owner, worktree, sessionFile, ticket, carried); }; } -function readScratchLease(orchDir, owner, worktree, sessionFile) { +/** Confirm the lead's live scratch lease and export only its routing identity and proof tuple. */ +export function exportScratchProof(orchDir, { owner, ticket, worktree }, { host = os.hostname() } = {}) { + if (!owner || !ticket || !worktree) throw new Error('proof-session needs owner, ticket and worktree'); + if (!/^[a-zA-Z0-9_.-]+$/.test(owner)) throw new Error('proof-session owner is malformed'); + const record = readSessionRecord(worktree); + if (!record || sessionLiveTicket(record) !== ticket) throw new Error('proof-session ticket differs from the originating session'); + readScratchLease(orchDir, owner, worktree, sessionRecordPath(worktree), ticket, undefined, true); + return { binding: exportProofSession(worktree), host, owner, ticket }; +} + +function readScratchLease(orchDir, owner, worktree, sessionFile, ticket, carried, exporting = false) { + if (carried !== undefined) { + const { binding, host, owner: issuerOwner, ticket: issuerTicket } = carried ?? {}; + if (issuerOwner !== owner || issuerTicket !== ticket || typeof host !== 'string' || !host || host === os.hostname()) { + throw new Error(`scratch start refused: the carried lease is not a live ${owner} lease for ${ticket} held on another fleet host`); + } + const proof = proofSession(worktree, binding); + return { kind: 'carried', host, head: proof.head, sessionId: proof.sessionId, owner, ticket }; + } let session; try { session = readSessionRecordFile(sessionFile); } catch { /* Fleet state is checked below. */ } - if (session?.createdAt && session.status === 'active') return { kind: 'vibe', createdAt: session.createdAt }; + if (session?.createdAt && session.status === 'active' && (!exporting || session.slug === owner)) { + return { kind: 'vibe', createdAt: session.createdAt }; + } const file = path.join(process.env.LOCAL_STATE_DIR || path.join(orchDir, 'sessions'), owner + '.json'); let state; try { state = JSON.parse(readFileSync(file, 'utf8')); } catch { /* Missing proof refuses registration. */ } if (state?.cwd === path.resolve(worktree) && state.threadId && !state.ended) { return { kind: 'fleet', stateDir: path.dirname(file), name: owner, threadId: state.threadId }; } - throw new Error(`scratch start must run on the machine that holds the live writer lease: checked vibe session record ${sessionFile} and fleet state ${file}; neither contained an active lease for ${path.resolve(worktree)}`); + throw new Error(`scratch start must run on the machine that holds the live writer lease: checked vibe session record ${sessionFile} and fleet state ${file}; neither contained an active lease for ${path.resolve(worktree)}; a heavy host takes the lead's lease through fleet.sh remote scratch-run`); } /** Whether the scratch stack's recorded writer lease has reached its terminal handoff. */ @@ -58,10 +79,13 @@ export function scratchLeaseTerminal(helper) { && Boolean(current.ended && current.archivedAt); } catch { return false; } } + // A lease carried from another fleet host cannot be read here; the stack's own TTL is the only bound this host + // has, so it ends then and the registered program's sweep reclaims the stack. + if (lease?.kind === 'carried') return Date.now() >= Date.parse(helper.expiresAt ?? ''); return false; } -/** Reconcile expired, creation-labelled scratch stacks without touching active leases. */ +/** Reconcile creation-labelled stacks after TTL and local lease termination, or at the carried lease's TTL. */ export function reconcileExpiredScratchHelpers(ledger, now, { capture = captureOwnedDockerResources, cleanup = removeOwnedDockerResources, alive = isAlive, identityOf = readIdentity, leaseTerminal = scratchLeaseTerminal, explicit = false, @@ -126,7 +150,7 @@ export function registerScratchProgram(orchDir, home = os.homedir()) { renameSync(temp, file); } -/** One bounded scratch pass under the helper ledger lock; TTL never replaces terminal writer proof. */ +/** Run a bounded pass under the ledger lock. For carried leases, the recorded TTL is the terminal evidence. */ export async function sweepScratchHelpers(orchDir, { now = Date.now(), deadline = Date.now() + 30_000, clock = Date.now, maxRecords = 20, home = os.homedir(), ...checks } = {}) { if (clock() >= deadline || maxRecords <= 0) return { removed: [], leftover: [], visited: 0 }; @@ -217,7 +241,7 @@ export function scratchOverlay(config, ownerToken, project) { } /** Reserve, label, launch and capture one PostgreSQL/perf/seed scratch Compose project. */ -export function runScratchStack({ orchDir, name, owner, ticket, worktree, ttlSeconds, composeFile }, +export function runScratchStack({ orchDir, name, owner, ticket, worktree, ttlSeconds, composeFile, carriedLease }, { run = command, docker = process.env.VIBE_E2E_DOCKER || 'docker' } = {}) { if (!Number.isSafeInteger(ttlSeconds) || ttlSeconds < 60 || ttlSeconds > 86_400 || !existsSync(composeFile)) { throw new Error('Scratch stack needs an existing Compose file and TTL of 60 to 86400 seconds.'); @@ -226,7 +250,8 @@ export function runScratchStack({ orchDir, name, owner, ticket, worktree, ttlSec const project = `vibe-scratch-${token}`; const helper = path.join(HERE, 'helpers.mjs'); run(process.execPath, [helper, orchDir, 'start', name, '--kind', 'scratch', '--owner', owner, '--ticket', ticket, - '--worktree', worktree, '--project', project, '--ttl-seconds', String(ttlSeconds)]); + '--worktree', worktree, '--project', project, '--ttl-seconds', String(ttlSeconds), + ...(carriedLease === undefined ? [] : ['--carried-lease', carriedLease])]); const ledger = JSON.parse(readFileSync(path.join(orchDir, 'helpers.json'), 'utf8')); const ownerToken = ledger[name]?.ownerToken; if (!ownerToken || ledger[name]?.project !== project) throw new Error('Scratch owner was not recorded before Docker launch.'); diff --git a/plugins/vibe-closedloop/lib/fleet-orchestrator/scripts/worker-check-schedule.mjs b/plugins/vibe-closedloop/lib/fleet-orchestrator/scripts/worker-check-schedule.mjs new file mode 100644 index 00000000..aa0dc60c --- /dev/null +++ b/plugins/vibe-closedloop/lib/fleet-orchestrator/scripts/worker-check-schedule.mjs @@ -0,0 +1,104 @@ +// The recurring worker check's schedule and heartbeat. The check once lived only as a prose instruction to +// start a loop or cron while the operator was away; the harness schedule died with the chat, a reboot dropped +// it, and nothing noticed (2026-11-30: two writers planned full reruns and a filed ticket sat with no writer). +// Operator, 2026-11-30: "obviously should make its way into vibe as a bug fix so we don't rely on a cron we +// created in prose. it should happen even on new fleet-orchestrator sessions". +// +// No harness lets a command create a harness schedule (Claude Code's loop and cron are model tools, Codex has +// none), so the schedule is a vibe-owned background process, as setup-ctl.mjs and verify-background.mjs start +// theirs: `fleet-home.mjs start` and `resume` call scheduleWorkerCheck, which starts +// skills/fleet-orchestrator/scripts/worker-check.mjs `loop ` detached unless a live loop already +// holds the program's lock. The loop runs one pass every WORKER_CHECK_SECONDS (config.env, default 900), +// writes the timestamped heartbeat worker-check.json, and exits on its own once its program is closed. +// +// workerCheckHeartbeat reads that heartbeat for `fleet-home.mjs resume` (and the compaction hook through +// resumeLines) and for codex-fleet-monitor's watcher: no heartbeat, an unreadable one, or one older than two +// of its recorded intervals is `WORKER-CHECK-MISSING`; a fresh one whose pass failed is `WORKER-CHECK-FAILING`. + +import { spawn } from "node:child_process"; +import { closeSync, existsSync, mkdirSync, openSync, readFileSync } from "node:fs"; +import path from "node:path"; +import { fileURLToPath } from "node:url"; +import { processStartStatus } from "../../../shared/process-identity.mjs"; +import { readConfig, resolveWorkDir } from "../../codex-fleet-monitor/scripts/work-dir.mjs"; + +export const DEFAULT_WORKER_CHECK_SECONDS = 900; +export const WORKER_CHECK_HEARTBEAT = "worker-check.json"; +export const WORKER_CHECK_LOCK = "worker-check.lock"; +export const WORKER_CHECK_LOG = "worker-check.log"; +/** How a missing check is brought back: `resume` in the orchestrator chat schedules it again. */ +export const RECREATE = "re-create the schedule: run fleet-home.mjs resume in the orchestrator chat, which starts it again"; +const WORKER_CHECK_SCRIPT = fileURLToPath(new URL("../../../skills/fleet-orchestrator/scripts/worker-check.mjs", import.meta.url)); + +/** A positive whole number from config `key`, else `fallback`. */ +export function positiveConfig(config, key, fallback) { + const value = Number(config?.[key]); + return Number.isSafeInteger(value) && value > 0 ? value : fallback; +} + +/** The check's interval in seconds for `programDir` (WORKER_CHECK_SECONDS, default 900). */ +export function workerCheckSeconds(programDir) { + return positiveConfig(readConfig(resolveWorkDir(programDir)), "WORKER_CHECK_SECONDS", DEFAULT_WORKER_CHECK_SECONDS); +} + +/** + * The heartbeat state of `programDir`: `{ ok, why, line }`. `why` is `no heartbeat`, `unreadable heartbeat` or + * `stale heartbeat` (older than two of the intervals it recorded) or `failing` (the pass failed). `line` carries no age, so a snapshot holding + * it changes only when the state does. + */ +export function workerCheckHeartbeat(programDir, now = Date.now()) { + let beat; + try { + beat = JSON.parse(readFileSync(path.join(programDir, WORKER_CHECK_HEARTBEAT), "utf8")); + } catch (error) { + return missing(error?.code === "ENOENT" ? "no heartbeat" : "unreadable heartbeat"); + } + const at = Date.parse(beat?.at); + const interval = Number(beat?.intervalSeconds); + if (!Number.isFinite(at) || !(interval > 0)) return missing("unreadable heartbeat"); + if (now - at > 2 * interval * 1000) return missing("stale heartbeat"); + if (beat.lastError) { + const reason = String(beat.lastError).replace(/\s+/g, " "); + return { ok: false, why: "failing", line: `WORKER-CHECK-FAILING(${reason}): the last worker check pass failed and its earlier findings stand; fix the cause, then run worker-check.mjs run ` }; + } + return { ok: true, why: null, line: "WORKER-CHECK ok" }; +} + +function missing(why) { + return { ok: false, why, line: `WORKER-CHECK-MISSING(${why}): the recurring worker check is not running; ${RECREATE}` }; +} + +/** The live loop holding `programDir`'s lock: its pid, or null. A lock whose identity cannot be read counts as live. */ +export function workerCheckLoopPid(programDir, { status = processStartStatus } = {}) { + let lock; + try { + lock = JSON.parse(readFileSync(path.join(programDir, WORKER_CHECK_LOCK), "utf8")); + } catch { + return null; + } + return status(Number(lock?.pid), lock?.identity) === "dead" ? null : Number(lock?.pid) || null; +} + +/** Starts `worker-check.mjs loop ` detached, its output appended to worker-check.log; returns its pid. */ +export function spawnWorkerCheckLoop(programDir, env = process.env) { + mkdirSync(programDir, { recursive: true }); + const log = openSync(path.join(programDir, WORKER_CHECK_LOG), "a"); + try { + const child = spawn(process.execPath, [WORKER_CHECK_SCRIPT, "loop", programDir], { detached: true, stdio: ["ignore", log, log], env }); + child.unref(); + return child.pid; + } finally { + closeSync(log); + } +} + +/** Schedules the check for `programDir` unless a live loop holds it; returns the line `start` or `resume` prints. */ +export function scheduleWorkerCheck(programDir, { env = process.env, spawnLoop = spawnWorkerCheckLoop, status = processStartStatus } = {}) { + if (!existsSync(programDir)) throw new Error(`no program dir ${programDir} to schedule the worker check for`); + const seconds = workerCheckSeconds(programDir); + const every = seconds % 60 === 0 ? `${seconds / 60}m` : `${seconds}s`; + const live = workerCheckLoopPid(programDir, { status }); + if (live) return `WORKER-CHECK-LIVE ${live}: the recurring worker check already runs for this program every ${every}`; + const pid = spawnLoop(programDir, env); + return `WORKER-CHECK-SCHEDULED ${pid} every ${every}: it runs until this program is closed; its findings arrive as events/worker-check.md, which the watcher reports`; +} diff --git a/plugins/vibe-closedloop/lib/handoff/scripts/handoff-evidence.mjs b/plugins/vibe-closedloop/lib/handoff/scripts/handoff-evidence.mjs index 8c991bcb..ad5e3487 100644 --- a/plugins/vibe-closedloop/lib/handoff/scripts/handoff-evidence.mjs +++ b/plugins/vibe-closedloop/lib/handoff/scripts/handoff-evidence.mjs @@ -35,8 +35,8 @@ function inspectEvidence(file, retain, maxBytes = MAX_EVIDENCE_BYTES) { } /** Fingerprint a bounded regular file without retaining its contents. */ -export function evidenceFingerprint(file) { - return inspectEvidence(file, false).fingerprint; +export function evidenceFingerprint(file, maxBytes) { + return inspectEvidence(file, false, maxBytes).fingerprint; } /** Read the authenticated bytes once, optionally checking an independently saved fingerprint. */ diff --git a/plugins/vibe-closedloop/lib/handoff/scripts/proof-receipts.mjs b/plugins/vibe-closedloop/lib/handoff/scripts/proof-receipts.mjs index eb83adb7..9b2dd107 100644 --- a/plugins/vibe-closedloop/lib/handoff/scripts/proof-receipts.mjs +++ b/plugins/vibe-closedloop/lib/handoff/scripts/proof-receipts.mjs @@ -680,8 +680,9 @@ const quotedIn = (entry) => entry.in ?? "ticket"; * What keeps this source from opening or pushing a pull request: a missing flag-keys record, a bug fix (a recorded kind, * or a session plan that classifies the work as one) without a reproduction or accepted reason, an operator command * in the body, the ticket or a changed runbook without a matching passing run, and an added or changed test without a - * mutation proof. With `head` the committed tree of that commit is - * checked (fleet push-check); otherwise the worktree's current source. + * mutation proof. Diff-scoped checks start at the common ancestor with the base + * branch. With `head` the committed tree is checked (fleet push-check); + * otherwise the worktree's current source is checked. */ export function proofGateProblems(worktree, { base, head, bodyText = "", ticketText: suppliedTicket, runs = {} } = {}) { const record = readSessionRecord(worktree); @@ -689,7 +690,9 @@ export function proofGateProblems(worktree, { base, head, bodyText = "", ticketT const ticket = sessionLiveTicket(record ?? {}); if (suppliedTicket == null && ticket) problems.push(`the live ticket ${ticket}'s body was not supplied (--ticket ); its commands and bug-report signal cannot be checked`); const ticketText = suppliedTicket ?? ""; - const fullHead = head ? execFileSync("git", ["-C", worktree, "rev-parse", "--verify", "--end-of-options", `${head}^{commit}`], { encoding: "utf8" }).trim() : null; + const git = (...args) => execFileSync("git", ["-C", worktree, ...args], { encoding: "utf8" }).trim(); + const fullHead = head ? git("rev-parse", "--verify", "--end-of-options", `${head}^{commit}`) : null; + const comparisonBase = git("merge-base", "--", fullHead ?? "HEAD", base); const current = fullHead ? committedSourceIdentity(worktree, fullHead) : sourceIdentity(worktree); const receipt = readProofReceipt(worktree); const signal = BUG_REPORT.test(ticketText) || BUG_SUMMARY.test(record?.summary ?? ""); @@ -699,9 +702,9 @@ export function proofGateProblems(worktree, { base, head, bodyText = "", ticketT if (featureProblem) problems.push(`the work is recorded as a feature over the ticket's bug-report signal: ${featureProblem} (proof-receipts.mjs accept --for feature)`); if (kind === "bug-fix") problems.push(...reproductionProblems(receipt, current, ticketText, ticket)); problems.push(...commandProblems(receipt, [...found(operatorCommands(bodyText), "body"), ...found(operatorCommands(ticketText), "ticket"), - ...runbookCommands(worktree, base, fullHead)], current, ticket)); + ...runbookCommands(worktree, comparisonBase, fullHead)], current, ticket)); const view = sourceView(worktree, fullHead, current); - problems.push(...testProofProblems(worktree, base, fullHead, receipt, current, runs, view), ...mutantInventoryProblems(worktree, receipt, view)); + problems.push(...testProofProblems(worktree, comparisonBase, fullHead, receipt, current, runs, view), ...mutantInventoryProblems(worktree, receipt, view)); return problems; } diff --git a/plugins/vibe-closedloop/lib/handoff/scripts/review-receipts.mjs b/plugins/vibe-closedloop/lib/handoff/scripts/review-receipts.mjs index b4d407cc..954589dc 100644 --- a/plugins/vibe-closedloop/lib/handoff/scripts/review-receipts.mjs +++ b/plugins/vibe-closedloop/lib/handoff/scripts/review-receipts.mjs @@ -2,11 +2,13 @@ // Capture source-bound review receipts from the owned Claude launcher or a // managed Codex App Server thread plus its helper-owned FINAL artifact. import { capturedJson } from "../../vibe/scripts/captured-json.mjs"; -import { existsSync, realpathSync, writeFileSync } from "node:fs"; +import { createHash } from "node:crypto"; +import { chmodSync, constants, copyFileSync, existsSync, realpathSync, renameSync, rmSync, writeFileSync } from "node:fs"; import path from "node:path"; import { isDeepStrictEqual, parseArgs } from "node:util"; import { EVENT_PREFIX, parseGenericCallback } from "../../../skills/cl-sweep/scripts/native-app-server-orchestrator.mjs"; -import { evidenceArray, evidenceObject, readEvidence } from "./handoff-evidence.mjs"; +import { evidenceArray, evidenceFingerprint, evidenceObject, readEvidence } from "./handoff-evidence.mjs"; +import { absoluteGitDir } from "../../vibe/scripts/session-record.mjs"; import { sourceIdentity, validSourceIdentity } from "../../vibe/scripts/tested-head.mjs"; import { premiseProblems } from "./review-premises.mjs"; import { acquireLedgerLock, read as readHelpers, write as writeHelpers, verifiedFinalReport } from "../../fleet-orchestrator/scripts/helpers.mjs"; @@ -71,6 +73,9 @@ export function captureReviewReceipt({ worktree, resultFile, outFile, role, take if (!validSourceIdentity(result.source) || result.source.treeSha256 !== current.treeSha256) { throw new Error(`${role}: launcher source differs from captured worktree`); } + if (result.worktree === undefined) { + throw new Error(`${role}: launcher result has no worktree field, so an older launcher wrote it (version skew); relaunch the reviewer with the current launcher`); + } if (result.worktree !== realpathSync(worktree)) throw new Error(`${role}: launcher worktree differs from captured worktree`); const takeover = takeoverBinding(role, result, worktree, current, expected); const trace = readEvidence(result.tracePath); @@ -81,13 +86,38 @@ export function captureReviewReceipt({ worktree, resultFile, outFile, role, take const shape = findingShapeProblems(result.data?.findings, worktree); if (shape.length) throw new Error(`${role}: ${shape.join("; ")}`); const source = result.source; - const receipt = { role, runtime: result.runtime, worktree: realpathSync(worktree), source, result: resultEvidence.fingerprint, trace: trace.fingerprint, sessionId: result.sessionId, + // Launcher output usually lives in scratch the writer later deletes; the receipt verifies against copies kept with it. + const keptDir = keptEvidenceDir(worktree, outFile); + // Separate receipts can have the same basename. Recapture must also leave the earlier fingerprint's bytes intact. + const receiptKey = createHash("sha256").update(path.resolve(outFile)).digest("hex"); + const kept = (evidence, suffix) => keepEvidence(evidence, + path.join(keptDir, `review-${receiptKey}.${evidence.fingerprint.sha256}.${suffix}`)); + const receipt = { role, runtime: result.runtime, worktree: realpathSync(worktree), source, result: kept(resultEvidence, "result.json"), trace: kept(trace, "trace.jsonl"), sessionId: result.sessionId, requestId: result.requestId, graphStatus: result.graphToolAliases.length === 0 ? "unavailable" : "used", graphCalls: usedGraphCalls, findings: result.data.findings, ...(result.data.questions ? { questions: result.data.questions } : {}), model: facts.model, ...(takeover ? { takeover } : {}) }; writeFileSync(outFile, `${JSON.stringify(receipt)}\n`, { mode: 0o600 }); return receipt; } +/** Where a receipt's evidence copies live: beside the receipt inside the worktree's git directory, else in that directory. */ +function keptEvidenceDir(worktree, outFile) { + const gitDir = realpathSync(absoluteGitDir(worktree)); + const receiptDir = realpathSync(path.dirname(path.resolve(outFile))); + return receiptDir === gitDir || receiptDir.startsWith(gitDir + path.sep) ? receiptDir : gitDir; +} + +/** A private copy of authenticated evidence at `target`, refused unless its bytes still hash to the fingerprint read. */ +function keepEvidence(evidence, target) { + const temp = `${target}.${process.pid}.tmp`; + copyFileSync(evidence.fingerprint.path, temp, constants.COPYFILE_EXCL); + try { + chmodSync(temp, 0o600); + if (evidenceFingerprint(temp).sha256 !== evidence.fingerprint.sha256) throw new Error(`Evidence changed: ${evidence.fingerprint.path}`); + renameSync(temp, target); + } finally { rmSync(temp, { force: true }); } + return evidenceFingerprint(target); +} + /** * Parse a native deliverable's body lines, those before its exact FINAL line (finalBodyLines in helpers.mjs). * Native reviewers can include the managed completion event immediately before the helper FINAL. @@ -229,7 +259,8 @@ export function reviewReceiptProblems(receipts, source, { reusableRoles = new Se try { const result = evidenceObject(readEvidence(receipt.result.path, receipt.result)); const trace = reviewTraceFacts(readEvidence(receipt.trace.path, receipt.trace).text); - if (result.worktree !== receipt.worktree) problems.push(`${role}: launcher worktree differs from receipt`); + // A launcher older than the worktree field is held to the receipt's worktree by the identity checks below. + if (result.worktree !== undefined && result.worktree !== receipt.worktree) problems.push(`${role}: launcher worktree differs from receipt`); if (result.runtime !== receipt.runtime || result.agentName !== role || result.status !== "DONE" || result.source?.treeSha256 !== receipt.source?.treeSha256 || result.sessionId !== receipt.sessionId || result.requestId !== receipt.requestId || trace.sessionId !== receipt.sessionId) problems.push(`${role}: completion identity differs`); if (receipt.model !== undefined && receipt.model !== trace.model) problems.push(`${role}: recorded model differs from its trace`); diff --git a/plugins/vibe-closedloop/lib/vibe/scripts/capture-ledger.mjs b/plugins/vibe-closedloop/lib/vibe/scripts/capture-ledger.mjs index 0223ee5a..50a6c5aa 100644 --- a/plugins/vibe-closedloop/lib/vibe/scripts/capture-ledger.mjs +++ b/plugins/vibe-closedloop/lib/vibe/scripts/capture-ledger.mjs @@ -1,56 +1,16 @@ -import { lstatSync, readFileSync, readdirSync, realpathSync } from "node:fs"; -import os from "node:os"; +import { lstatSync, readFileSync } from "node:fs"; import path from "node:path"; -import { canonicalHome } from "../../fleet-orchestrator/scripts/chat-binding.mjs"; +import { fleetWriterRegistrations, worktreePrograms } from "../../fleet-orchestrator/scripts/chat-binding.mjs"; import { git, readSessionRecord, sessionLiveTicket } from "./session-record.mjs"; -function listDir(dir) { - try { return readdirSync(dir); } catch { return []; } -} - -/** Writer registrations from known fleet programs, with their program directory. */ -export function fleetWriterRegistrations(env = process.env) { - const programs = new Set(); - if (env.FLEET_HOME) { - const dir = path.join(canonicalHome(env.FLEET_HOME), "programs"); - for (const name of listDir(dir)) programs.add(path.join(dir, name)); - } - const bindings = path.join(env.HOME || os.homedir(), ".vibe-hook-scope", "fleet-binding"); - for (const name of listDir(bindings).filter((file) => file.endsWith(".json"))) { - try { - const binding = JSON.parse(readFileSync(path.join(bindings, name), "utf8")); - if (typeof binding?.home === "string" && typeof binding.program === "string") { - programs.add(path.join(canonicalHome(binding.home), "programs", binding.program)); - } - } catch { /* A broken file is not a fleet binding. */ } - } - return [...programs].flatMap((program) => { - try { - const board = JSON.parse(readFileSync(path.join(program, "board.json"), "utf8")); - return Object.values(board?.writers ?? {}).map((writer) => ({ program, writer })); - } catch { return []; } - }); -} +export { fleetWriterRegistrations, worktreePrograms as fleetProgramsFor }; /** Use a fleet's capture ledger only when exactly one program owns the checkout. */ export function fleetLedgerFor(worktree, env = process.env) { - const programs = fleetProgramsFor(worktree, env); + const programs = worktreePrograms(worktree, env); return programs.length === 1 ? path.join(programs[0], "captures") : null; } -/** Every fleet program whose board registers the checkout. */ -export function fleetProgramsFor(worktree, env = process.env) { - let top; - try { top = realpathSync(git(worktree, ["rev-parse", "--show-toplevel"])); } catch { return []; } - const programs = new Set(); - for (const { program, writer } of fleetWriterRegistrations(env)) { - try { - if (realpathSync(writer.worktree) === top) programs.add(program); - } catch { /* A missing or remote-only path does not own this checkout. */ } - } - return [...programs]; -} - /** Fallback for captures made directly in this clone. */ export function defaultLedgerDir(worktree) { return path.resolve(worktree, git(worktree, ["rev-parse", "--git-common-dir"]), "vibe-captures"); diff --git a/plugins/vibe-closedloop/lib/vibe/scripts/cloud-repository.mjs b/plugins/vibe-closedloop/lib/vibe/scripts/cloud-repository.mjs index d60b7438..6a8c1f20 100644 --- a/plugins/vibe-closedloop/lib/vibe/scripts/cloud-repository.mjs +++ b/plugins/vibe-closedloop/lib/vibe/scripts/cloud-repository.mjs @@ -78,7 +78,7 @@ export function codexEnvironment(request) { } /** Printed in the cloud before the lanes. A Claude cloud session sets CLAUDE_CODE_REMOTE; a local run leaves it unset. */ -export const PROVENANCE_COMMAND = 'echo "host=$(hostname)"; echo "remote=${CLAUDE_CODE_REMOTE:-}"; echo "origin=$(git remote get-url origin)"; echo "commit=$(git rev-parse HEAD)"'; +export const PROVENANCE_COMMAND = 'echo "host=$(hostname)"; echo "remote=${CLAUDE_CODE_REMOTE:-}"; echo "origin=$(git remote get-url origin)"; echo "commit=$(git rev-parse HEAD)"; echo "gitTree=$(git rev-parse HEAD^{tree})"'; /** Why a reported provenance does not prove a cloud run of this repository and commit, or null. */ export function provenanceProblem(provenance, { repository, commit }) { diff --git a/plugins/vibe-closedloop/lib/vibe/scripts/cloud-validation-report.mjs b/plugins/vibe-closedloop/lib/vibe/scripts/cloud-validation-report.mjs index 78e81ce5..2c1e5c9a 100644 --- a/plugins/vibe-closedloop/lib/vibe/scripts/cloud-validation-report.mjs +++ b/plugins/vibe-closedloop/lib/vibe/scripts/cloud-validation-report.mjs @@ -16,7 +16,7 @@ export function validationReportInstruction(artifact) { return [ "Record one lane object per requested lane in the given order. Each object has \"name\" and \"exitCode\". For failure or an unfinished lane, include \"stdoutTail\" and \"stderrTail\" (empty when the stream was empty), \"diagnosis\", and any combined \"tail\". An unfinished lane also needs \"notRun\".", `After the lanes finish, UTF-8 encode each lane's JSON with Node Buffer.from(JSON.stringify(lane), "utf8"). Split those bytes into chunks of at most ${CHUNK_BYTES}, base64-encode each chunk, and emit each chunk in a separate assistant text message as one line: ${LANE_MARKER} then a space and a JSON object with "commit" (the validated commit), "index" (zero-based lane position), "part" (zero-based chunk position), "parts" (chunk count for that lane) and "data" (base64 for that chunk). Include every chunk exactly once.`, - `Your final message ends with one line: ${RESULT_MARKER} then a space and a JSON object with "commit" (the validated commit, before any result commit), "provenance" ({"host", "remote", "origin", "commit"}, each the exact output value from its line of the provenance command), "laneCount" (the number of requested lanes), and "status" (the final git status --porcelain lines, an empty list when there are none)${artifact ? `, plus "artifact" ({"path":"${artifact.path}","branch":"${artifact.branch}","commit":"","sha256":""})` : ""}.`, + `Your final message ends with one line: ${RESULT_MARKER} then a space and a JSON object with "commit" (the validated commit, before any result commit), "provenance" ({"host", "remote", "origin", "commit", "gitTree"}, each the exact output value from its line of the provenance command), "laneCount" (the number of requested lanes), and "status" (the final git status --porcelain lines, an empty list when there are none)${artifact ? `, plus "artifact" ({"path":"${artifact.path}","branch":"${artifact.branch}","commit":"","sha256":""})` : ""}.`, ].join("\n\n"); } diff --git a/plugins/vibe-closedloop/lib/vibe/scripts/cloud-worker.mjs b/plugins/vibe-closedloop/lib/vibe/scripts/cloud-worker.mjs index c5bfbaca..95a45ff1 100644 --- a/plugins/vibe-closedloop/lib/vibe/scripts/cloud-worker.mjs +++ b/plugins/vibe-closedloop/lib/vibe/scripts/cloud-worker.mjs @@ -808,7 +808,7 @@ export function validationBrief(request, managedHost = null, provedBranch = null return [ `Validation only. Repository: ${requireRepository(request)}. Branch: ${branch}. Commit: ${request.commit}.`, `Check out the exact commit: run \`git fetch origin refs/heads/${branch}\`, then \`git checkout --detach ${request.commit}\`, then confirm \`git rev-parse HEAD\` prints ${request.commit}. If it does not, run no lane and report the commit you have.`, - `After checkout, run \`${PROVENANCE_COMMAND}\` as one call, exactly as written, and keep its four lines.`, + `After checkout, run \`${PROVENANCE_COMMAND}\` as one call, exactly as written, and keep its five lines.`, ...(managedHost || compact ? [] : [installInstruction(request)]), compact?.start ?? (managedHost ? cloudHostInstruction(managedHost, { lanes: resolved.lanes, commit: request.commit, reporter: legacyArtifact ? null : hostReporter(subject, resolved.lanes, requestKey) }) : "Run each lane once, in order, from the repository root, and record its exit code. A failing lane does not stop the others:\n" + resolved.lanes.map((lane) => `- ${lane.name}: ${lane.cloudFrozen ?? lane.cloudE2E ?? lane.command}`).join("\n")), @@ -866,8 +866,11 @@ export function parseValidationResult(text, request, {managedHost = false, outco } else if (result.artifact !== undefined) throw new Error("cloud validation returned an unrequested result artifact"); if (managedHost) checkStreamDirectories(lanes); validatePrerequisiteOutcomes(resolved.lanes, lanes); - const { host, remote, origin } = result.provenance; - return { commit: request.commit, branch: request.branch, repository: request.repository, provenance: { host, remote, origin, commit: request.commit }, lanes, + const { host, remote, origin, gitTree } = result.provenance; + const validatedTree = resolved.laneSource ? git(request.worktree, ["rev-parse", "--verify", `${request.commit}^{tree}`]) : null; + if (validatedTree && gitTree !== undefined && gitTree !== validatedTree) throw new Error("cloud validation reported a different Git tree; result refused"); + return { commit: request.commit, branch: request.branch, repository: request.repository, + provenance: { host, remote, origin, commit: request.commit, ...(validatedTree ? { gitTree: validatedTree } : {}) }, lanes, ...(resolved.laneSource ? { laneSource: resolved.laneSource } : {}), passed: lanes.every((lane) => lane.passed), ...(artifact ? { artifact } : {}) }; } diff --git a/plugins/vibe-closedloop/lib/vibe/scripts/cloud-workflow-runner.mjs b/plugins/vibe-closedloop/lib/vibe/scripts/cloud-workflow-runner.mjs index ea06815a..980924b0 100644 --- a/plugins/vibe-closedloop/lib/vibe/scripts/cloud-workflow-runner.mjs +++ b/plugins/vibe-closedloop/lib/vibe/scripts/cloud-workflow-runner.mjs @@ -195,14 +195,14 @@ function git(cwd, args) { /** * The actor's private copy of the exact commit, with the checkout's remote branches so a base-branch step finds them, - * its origin set to the checkout's own (laneOrigin), and whether it is shallow. The objects still come from the local + * its `origin` the checkout's own unless the caller names one (laneOrigin), and whether it is shallow. The objects still come from the local * checkout. Every read happens here, while the runner still owns the copy: once the actor owns it, Git refuses a root * caller there as dubious ownership (the r11 kit, as root). */ -export function laneCheckout(checkout, commit, target) { +export function laneCheckout(checkout, commit, target, origin = laneOrigin(checkout)) { git(checkout, ["clone", "--quiet", "--no-hardlinks", "--no-checkout", checkout, target]); git(target, ["fetch", "--quiet", "--no-tags", checkout, "+refs/remotes/origin/*:refs/remotes/origin/*"]); - git(target, ["remote", "set-url", "origin", laneOrigin(checkout)]); + git(target, ["remote", "set-url", "origin", origin]); git(target, ["checkout", "--quiet", "--detach", commit]); if (git(target, ["rev-parse", "HEAD"]).trim() !== commit) refuse("the lane checkout is not the validation commit"); return { shallow: git(target, ["rev-parse", "--is-shallow-repository"]).trim() !== "false" }; @@ -248,6 +248,11 @@ export function cloudLaneLimit(job) { return { minutes: Math.min(CLOUD_LANE_MAX_MINUTES, Math.max(JOB_MINUTES, budget * CLOUD_SLOWDOWN)), routed: null }; } +/** The limit on a host with no per-lane cap of its own, as the heavy host: the job's own budget. */ +export function jobLaneLimit(job) { + return { minutes: job["timeout-minutes"] ?? JOB_MINUTES, routed: null }; +} + /** The cloud limit for a resolved workflow lane's canonical command (its `{workflow, job}` JSON). */ export function workflowLaneLimit(command) { return cloudLaneLimit(JSON.parse(command).job); @@ -257,11 +262,13 @@ export function workflowLaneLimit(command) { * Git trust for every step: a step may run Git in the lane's clone or in the root-owned checkout, and Git refuses a * repository another uid owns as dubious ownership (2026-11-30: two tooling lanes exited 1 with "detected dubious * ownership in repository"). GitHub's runner runs every step as the checkout's owner, so no step there meets that - * refusal. The runner marks those two repositories safe, and no other, after the existing Git settings: each as given - * and by realpath, and with its .git, the path an older Git's upload-pack checks (measured on Ubuntu 24.04's 2.43.0). - * Git drops these GIT_CONFIG_* variables for the upload-pack it starts in a local remote, the root-owned checkout - * (2026-11-30, cloud run 1: tools-ts vibe-workers' release fetch), so runLane also writes the same trust into the lane - * home's .gitconfig (laneGitTrust). + * refusal. The runner marks those two repositories safe, and no other: each as given and by realpath, and with its + * .git, the path an older Git's upload-pack checks (measured on Ubuntu 24.04's 2.43.0). Git drops these GIT_CONFIG_* + * variables for the upload-pack it starts in a local remote, the root-owned checkout (2026-11-30, cloud run 1: tools-ts + * vibe-workers' release fetch), so runLane also writes the same trust into the lane home's .gitconfig (laneGitTrust). + * That file starts with an empty safe.directory, which clears every entry the system config added before it: GitHub's + * Ubuntu runner image sets `safe.directory = *` in /etc/gitconfig, and with it every step trusted every directory + * (2026-12-02, main's Node Tests run 46925693587). The variables come after the lane's .gitconfig, so they only add. */ export function stepGitEnvironment(env, trusted) { return trusted.reduce((settings, directory) => rootSetupGitEnvironment(settings, directory), env); @@ -270,7 +277,7 @@ export function stepGitEnvironment(env, trusted) { const trustedDirectories = (...repositories) => repositories.flatMap((directory) => [directory, realpathSync(directory)]) .flatMap((directory) => [directory, path.join(directory, ".git")]); -const laneGitTrust = (trusted) => `[safe]\n${trusted.map((directory) => `\tdirectory = ${JSON.stringify(directory)}\n`).join("")}`; +const laneGitTrust = (trusted) => `[safe]\n\tdirectory =\n${trusted.map((directory) => `\tdirectory = ${JSON.stringify(directory)}\n`).join("")}`; /** * Run one lane's job in declared order. Step output goes to `stdio`; each step's line names the identity it ran as. The @@ -286,11 +293,15 @@ export function runWorkflowLane(options) { try { return runLane(options); } finally { process.umask(previous); } } -function runLane({ checkout, commit, definition, work, base = null, uid, gid, environment = process.env, repaired = [], +/** Workflow and job environment inherited by every workflow step before its step-specific overrides. */ +export function workflowLaneEnvironment({ workflow, job }) { + return { ...strings(workflow?.env), ...strings(job?.env) }; +} + +function runLane({ checkout, commit, definition, work, base = null, uid, gid, environment = process.env, repaired = [], origin, limit = cloudLaneLimit(definition.job), run = runLaneGroup, provision = ownTree, sudo = grantActorSudo, stdio = ["ignore", "inherit", "inherit"], log = (line) => process.stdout.write(line + "\n"), now = Date.now }) { const { workflow = {}, job } = definition; const plan = workflowLanePlan(definition); - const limit = cloudLaneLimit(job); if (limit.routed) refuse(`${CLOUD_LANE_ROUTED}: ${limit.routed}; run it on another machine`); if (!conditionHolds(job.if, false)) refuse(`the job condition ${job.if} is false for a pull request`); if (!base && plan.some(({ step }) => step.run?.includes(BASE_REF))) refuse("a step names the pull request base branch, which the cloud checkout does not record"); @@ -304,7 +315,7 @@ function runLane({ checkout, commit, definition, work, base = null, uid, gid, en // Explicit modes: a umask can narrow the ones given at creation, and the actor reads every step script. mkdirSync(scripts); chmodSync(scripts, 0o755); - const { shallow } = laneCheckout(checkout, commit, clone); + const { shallow } = laneCheckout(checkout, commit, clone, origin); const trusted = trustedDirectories(checkout, clone); writeFileSync(path.join(home, ".gitconfig"), laneGitTrust(trusted)); const own = () => { if (asRoot) { provision(clone, actor); provision(home, actor); } }; @@ -315,7 +326,7 @@ function runLane({ checkout, commit, definition, work, base = null, uid, gid, en // settings, as GitHub's runner user does, its sudo keeps them, and a proxy URL's userinfo never reaches a step. A root // runner gives the actor a readable copy of each host CA path it cannot read (cloud-validation-host.mjs actorNetworkEnvironment). const host = stepGitEnvironment({ ...cloudHostEnvironment(environment, home, home), ...actorNetworkEnvironment(environment, path.join(work, "ca"), actor, asRoot) }, trusted); - const env = { ...strings(workflow.env), ...strings(job.env) }; + const env = workflowLaneEnvironment({ workflow, job }); const bins = []; const deadline = now() + limit.minutes * 60_000; const steps = []; diff --git a/plugins/vibe-closedloop/lib/vibe/scripts/docker-disk-admission.mjs b/plugins/vibe-closedloop/lib/vibe/scripts/docker-disk-admission.mjs index 1e4dce25..8544474b 100644 --- a/plugins/vibe-closedloop/lib/vibe/scripts/docker-disk-admission.mjs +++ b/plugins/vibe-closedloop/lib/vibe/scripts/docker-disk-admission.mjs @@ -7,7 +7,7 @@ import { existsSync, readFileSync, realpathSync, statSync } from 'node:fs'; import os from 'node:os'; import path from 'node:path'; -const MIN_FREE_BYTES = 64_000_000_000n; +export const MIN_FREE_BYTES = 64_000_000_000n; function systemRun(binary, args) { return spawnSync(binary, args, { encoding: 'utf8', timeout: 30_000 }); diff --git a/plugins/vibe-closedloop/lib/vibe/scripts/e2e-lock.mjs b/plugins/vibe-closedloop/lib/vibe/scripts/e2e-lock.mjs index 9ce28a7e..dcd5e60c 100644 --- a/plugins/vibe-closedloop/lib/vibe/scripts/e2e-lock.mjs +++ b/plugins/vibe-closedloop/lib/vibe/scripts/e2e-lock.mjs @@ -40,6 +40,9 @@ // and cache are reconciled in that order; a refusal retains a private pending // record. Caller and foreign projects stay. // +// On a machine whose fleet config bars heavy work (LOCAL_HEAVY_BARRED=1, read as fleet.sh reads it), `run` starts +// nothing and exits 78 naming the remote heavy slot. +// // `run` exits with the command's own code. When the stack stays busy past // `--wait-seconds` (default 3600) it runs nothing, prints // {"status":"busy","holder":{...}} and exits 75. `status` prints @@ -68,6 +71,7 @@ import { captureOwnedDockerResources, plannedLocalTags, reconcileGeneratedE2E, r removeOwnedDockerResources, reserveGeneratedE2E } from './owned-docker.mjs'; import { e2eWaitersDir, readE2eWaiters, waitForReloadFence, writeAtomic } from './owned-state.mjs'; import { failScript } from "./provider.mjs"; +import { fleetHeavyPolicy, HEAVY_BAR_EXIT, HEAVY_BAR_MESSAGE } from "../../codex-fleet-monitor/scripts/work-dir.mjs"; import { isEntryPoint } from "../../../shared/plugin-roots.mjs"; export { isContainerizedBuild, measureDockerDisk, requireDockerDisk } from './docker-disk-admission.mjs'; @@ -329,6 +333,10 @@ export async function runE2e(argv, machineSlot = MACHINE_SLOT) { throw new Error("Usage: e2e-lock.mjs run --head [--owner ] [--label