diff --git a/CHANGELOG.md b/CHANGELOG.md index 2dc1f426..e9cb1c74 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -4,8 +4,23 @@ 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 +### vibe v1.1.122 +#### Added + +- ISS-15046: PR create requires witnessed passing runs of every declared CI job for a new pull request's exact tree. Push-check reports missing runs as `CI-NOT-RUN` warnings on post-cutoff pull requests. `full-ci-check.mjs report` lists jobs still owed. +- ISS-15046: every check that can refuse a branch at push-check, the handoff gate or PR create is registered in `refusing-checks.mjs`. Node Tests fails on a gate refusal with no entry, and replays each registered check against a branch shaped like ox-14491 (495 inherited cases, a main sync, one new case), where it must refuse nothing already pushed and passed. PR create refuses a change to a replayed check until `refusing-check-replay.mjs` has run it against real worktrees on the PR's tree with no refusal of accepted work, or a ticketed `refusal replay` override quotes the ruling that allows it. +- ISS-15046: PR create requires receipts for owed e2e specs and checks required lanes listed as not run in the PR body. The handoff gate and push-check report missing e2e evidence as warnings. A skip requires a ticketed override quoting the ruling. +- ISS-15046: e2e requirements include graph-selected specs, changed specs, and specs reached through changed stories or new files. Without the graph, the workflow's changed-spec classifier determines where the full lane is owed. Targeted records can report outstanding specs without blocking ongoing work. + +#### Fixed + +- ISS-15046: mutation proofs are owed for cases changed after the 2026-12-01 ruling. Push-check also excludes cases unchanged since the pushed head or last proof pass. Handoff warns about unproved cases, and PR create checks the proofs against the last accepted gate pass. +- Across all plugin Markdown, including eval prompts and graders, the release is about 18 words longer than v1.1.120. The count covers the source files in `plugins/vibe` and excludes the generated ClosedLoop edition. + +### vibe-closedloop-provider v1.0.12 + +- ISS-15046: the provider names symphony-alpha's e2e workflow, its change-detection job and each surface's suite job and spec classifier, so vibe can compute the e2e specs a change owes the way CI does. - 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 diff --git a/plugins/vibe-closedloop-provider/.claude-plugin/plugin.json b/plugins/vibe-closedloop-provider/.claude-plugin/plugin.json index b4438bb8..3081e482 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.11", + "version": "1.0.12", "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 e2277aa4..924a3ebb 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.11", + "version": "1.0.12", "description": "ClosedLoop and symphony-alpha knowledge for vibe and fleet-orchestrator: tickets, plans, the code graph, repository memory and the symphony-alpha recipes. Build input for the vibe plugin: tools/vibe-closedloop-build assembles it into plugins/vibe-closedloop", "author": {"name": "ClosedLoop", "email": "support@closedloop.ai"}, "homepage": "https://github.com/closedloop-ai/claude-plugins", diff --git a/plugins/vibe-closedloop-provider/provider.json b/plugins/vibe-closedloop-provider/provider.json index 718a7202..8d188c25 100644 --- a/plugins/vibe-closedloop-provider/provider.json +++ b/plugins/vibe-closedloop-provider/provider.json @@ -663,6 +663,23 @@ }, "testHistory": "^apps/desktop/test/" }, + "e2eRequirement": { + "workflow": ".github/workflows/e2e-test.yml", + "changesJob": "changes", + "filterStep": "filter", + "surfaces": { + "web": { + "job": "e2e", + "runs": "e2e", + "classifier": "changed-specs" + }, + "desktop": { + "job": "desktop-e2e", + "runs": "desktop_e2e", + "classifier": "desktop-changed-specs" + } + } + }, "cloudValidation": { "toolRoot": "plugins/vibe-closedloop", "desktopRoot": "apps/desktop", diff --git a/plugins/vibe-closedloop-provider/skills/closedloop-provider/references/agents/vibe-change-worker.md b/plugins/vibe-closedloop-provider/skills/closedloop-provider/references/agents/vibe-change-worker.md index ae995197..fdacf858 100644 --- a/plugins/vibe-closedloop-provider/skills/closedloop-provider/references/agents/vibe-change-worker.md +++ b/plugins/vibe-closedloop-provider/skills/closedloop-provider/references/agents/vibe-change-worker.md @@ -84,8 +84,9 @@ nothing agent-written goes into public docs (`guardrails.md`, "Copy" and not safe preview publication with its explicit preparation evidence. The Desktop Electron lane never runs on a vibe machine: the executor returns it - under `e2eLeftForCi`, covered by the post-merge `desktop-e2e/validated` - run, and it does not hold `requiredE2eComplete`. + under `e2eLeftForCi`, and it does not hold `requiredE2eComplete`. That + not-run record satisfies nothing at handoff, push-check or PR create: the + lane runs in cloud validation or on the heavy host first. diff --git a/plugins/vibe-closedloop-provider/skills/closedloop-provider/references/agents/vibe-environment-worker.md b/plugins/vibe-closedloop-provider/skills/closedloop-provider/references/agents/vibe-environment-worker.md index a4446ae9..0fb4a09f 100644 --- a/plugins/vibe-closedloop-provider/skills/closedloop-provider/references/agents/vibe-environment-worker.md +++ b/plugins/vibe-closedloop-provider/skills/closedloop-provider/references/agents/vibe-environment-worker.md @@ -488,8 +488,9 @@ changes and gates fields. run (`NOT-RUN-LANE`) instead; the body's Test plan says that lane was not run locally and relies on the containerized or CI run. On a machine without the displayless Linux Electron harness it records the Desktop - e2e lane not run the same way, and the Test plan says the post-merge - `desktop-e2e/validated` run covers it. A lane printed as + e2e lane not run the same way; that record satisfies nothing, so the lane + runs in cloud validation or on the heavy host before the pull request + opens, and the Test plan names that run. A lane printed as `MAIN-PREEXISTING-LANE`, and every `testRuns` or `runs` entry recorded `main-preexisting`, also fails on the captured main: list each in the body under a `Known main failures` line with the main commit it failed diff --git a/plugins/vibe-closedloop-provider/skills/closedloop-provider/references/vibe/environment.md b/plugins/vibe-closedloop-provider/skills/closedloop-provider/references/vibe/environment.md index 8bca306b..5c2dec3a 100644 --- a/plugins/vibe-closedloop-provider/skills/closedloop-provider/references/vibe/environment.md +++ b/plugins/vibe-closedloop-provider/skills/closedloop-provider/references/vibe/environment.md @@ -253,9 +253,10 @@ stops an unrelated Desktop or changes a running renderer's tree. The Desktop Electron lane is the exception: no vibe machine runs it, and since symphony-alpha's desktop-e2e job skips pull requests no run exists for a branch before merge. The executor returns it under -`e2eLeftForCi`, covered by the post-merge desktop-e2e-validation run that -publishes `desktop-e2e/validated`, and it does not hold -`requiredE2eComplete`. The ticket's Engineering checklist carries it +`e2eLeftForCi`, and it does not hold `requiredE2eComplete`. The post-merge +desktop-e2e-validation run that publishes `desktop-e2e/validated` does not +cover it before a pull request: the lane runs in cloud validation or on the +heavy host first. The ticket's Engineering checklist carries it (`ticket-template.md`, "E2E left for CI"). An operator-dispatched run bound through `mainSyncCiRun` still verifies as above and replaces that entry. diff --git a/plugins/vibe-closedloop/.claude-plugin/plugin.json b/plugins/vibe-closedloop/.claude-plugin/plugin.json index 8ac02d85..8df73f3a 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.121", + "version": "1.1.122", "dependencies": [ "closedloop-core", "vibe-core" diff --git a/plugins/vibe-closedloop/.codex-plugin/plugin.json b/plugins/vibe-closedloop/.codex-plugin/plugin.json index b42f5b2f..c72a7554 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.121", + "version": "1.1.122", "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 9d53c6e7..f206a623 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.121` contains 17 skills and 17 agents, and no hook manifest: the +Version `1.1.122` 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 5036e9d7..e5b1d82a 100644 --- a/plugins/vibe-closedloop/agents/vibe-change-worker.md +++ b/plugins/vibe-closedloop/agents/vibe-change-worker.md @@ -465,8 +465,9 @@ Throughout: - `requiredE2eComplete: false` blocks final coverage/alignment/assignment, not safe preview publication with its explicit preparation evidence. The Desktop Electron lane never runs on a vibe machine: the executor returns it - under `e2eLeftForCi`, covered by the post-merge `desktop-e2e/validated` - run, and it does not hold `requiredE2eComplete`. + under `e2eLeftForCi`, and it does not hold `requiredE2eComplete`. That + not-run record satisfies nothing at handoff, push-check or PR create: the + lane runs in cloud validation or on the heavy host first. Compare actual source and behavior against the same session decision table's affected and interacting prior row IDs after implementation and every fix. diff --git a/plugins/vibe-closedloop/agents/vibe-environment-worker.md b/plugins/vibe-closedloop/agents/vibe-environment-worker.md index 09343062..2c5e4ea7 100644 --- a/plugins/vibe-closedloop/agents/vibe-environment-worker.md +++ b/plugins/vibe-closedloop/agents/vibe-environment-worker.md @@ -491,8 +491,9 @@ changes and gates fields. run (`NOT-RUN-LANE`) instead; the body's Test plan says that lane was not run locally and relies on the containerized or CI run. On a machine without the displayless Linux Electron harness it records the Desktop - e2e lane not run the same way, and the Test plan says the post-merge - `desktop-e2e/validated` run covers it. A lane printed as + e2e lane not run the same way; that record satisfies nothing, so the lane + runs in cloud validation or on the heavy host before the pull request + opens, and the Test plan names that run. A lane printed as `MAIN-PREEXISTING-LANE`, and every `testRuns` or `runs` entry recorded `main-preexisting`, also fails on the captured main: list each in the body under a `Known main failures` line with the main commit it failed diff --git a/plugins/vibe-closedloop/hooks/pr-create-guard.mjs b/plugins/vibe-closedloop/hooks/pr-create-guard.mjs index 04ff54c6..1e0361f8 100644 --- a/plugins/vibe-closedloop/hooks/pr-create-guard.mjs +++ b/plugins/vibe-closedloop/hooks/pr-create-guard.mjs @@ -9,6 +9,8 @@ // unrelated tool false positives. A call that overrides head ownership or the // session record has no gate witness, so it names its findings inline, as // merge-guard.mjs reads them: `VISUAL_QA_FINDINGS= gh pr create ...`. +// Any head in scope, vibe or not, also needs every declared CI workflow job run in full on it (full-ci-check.mjs), and +// a change to a registered refusing check needs that check replayed against real work (refusing-check-replay.mjs). import { execFileSync } from "node:child_process"; import { existsSync, lstatSync, readFileSync } from "node:fs"; import path from "node:path"; @@ -23,10 +25,13 @@ import { isProviderBroken, recordedBinding } from "../lib/vibe/scripts/provider. import { assertIsolatedTestRead } from "../lib/vibe/scripts/test-state-isolation.mjs"; import { conversationSkill } from "./hook-session-scope.mjs"; import { changedPaths, declaresUiPaths, visualQaFindingsProblems, visualQaRequired, VISUAL_QA_STEP } from "../lib/vibe/scripts/required-visual-qa.mjs"; -import { deliveryPlacementProblem, deliveryRepository } from "../lib/fleet-orchestrator/scripts/delivery-placement.mjs"; +import { deliveryPlacementProblem, deliveryRepository, fleetRowHasPullRequest } from "../lib/fleet-orchestrator/scripts/delivery-placement.mjs"; import { validChat } from "../lib/fleet-orchestrator/scripts/chat-binding.mjs"; import os from "node:os"; import { BodyFileError, OVERRIDE_CHECKS, overriddenChecks, readPrBodyFile } from "../lib/handoff/scripts/gate-override.mjs"; +import { declaredWorkflowLanes, fullCiProblem } from "../lib/handoff/scripts/full-ci-check.mjs"; +import { refusalReplayProblem } from "../lib/handoff/scripts/refusing-check-replay.mjs"; +import { e2eGateProblems } from "../lib/handoff/scripts/e2e-gate-check.mjs"; const VIBE_BRANCH = "vibe/"; const overrideHint = (check) => `if every real check and review passed and known Vibe gate bugs are the only blocker (operator ruling 2026-11-08), add \`Vibe gate override: [, ...]: ${check}: \` naming each bug ticket and the check it overrides to the PR body file`; @@ -292,6 +297,35 @@ function prVisualQaProblem({ cwd, head = null, base, binding, witnessWorktree = return problems.length ? `visual QA is required (${verdict.reason}): ${problems.join("; ")}` : null; } +/** + * Why the PR head may not be raised yet, or null: a declared CI workflow job not run on it in full (full-ci-check.mjs), + * a required e2e spec with no run receipt (e2e-gate-check.mjs), or a changed refusing check not replayed against real + * work (refusing-check-replay.mjs). It applies to every head in scope, vibe or not, since push-check leaves a row with + * no pull request to this gate (full-ci-check.mjs cites the rulings); the records are read from the worktree whose HEAD + * is the PR head, else the command worktree. + */ +function prReadinessProblem(call, target, binding) { + let headCommit; + try { headCommit = git(call.cwd, ["rev-parse", "--verify", `${call.head ? prHeadRef(call.cwd, call.head) : "HEAD"}^{commit}`]); } + catch { + try { return declaredWorkflowLanes(call.cwd, "HEAD") ? "the PR head cannot be read to check its CI workflow runs" : null; } + catch { return null; } + } + const worktree = git(call.cwd, ["worktree", "list", "--porcelain"]).split(/\n\s*\n/) + .find((entry) => entry.split("\n").includes(`HEAD ${headCommit}`))?.match(/^worktree (.+)$/m)?.[1] ?? target?.cwd ?? call.cwd; + try { + const bodyText = () => call.bodyFile ? readPrBodyFile(call.bodyFile) : ""; + const base = () => resolvePrBase(call.cwd, call.base).oid; + const e2e = () => e2eGateProblems(worktree, { base, head: headCommit, bodyText, binding }); + return fullCiProblem(worktree, headCommit, { bodyText, binding }) + ?? (e2e().join("; ") || null) + ?? refusalReplayProblem(worktree, { base, head: headCommit, bodyText, binding }); + } catch (error) { + if (error instanceof BodyFileError) return error.message; + return `the PR head's CI workflow runs, e2e runs and refusing-check replays could not be checked: ${error.message}`; + } +} + /** The local ref `head` stands for: its local branch, else the local branch pushed under that name, else origin's. */ function prHeadRef(cwd, head) { if (localBranchExists(cwd, head)) return `refs/heads/${head}`; @@ -347,6 +381,12 @@ export function prCreateGuard(event, home = os.homedir()) { if (inVibeSession(call.cwd)) target = { cwd: call.cwd }; else if (vibeWorktree(call.cwd) === false) continue; } + const chat = validChat(event?.session_id); + const creatingPullRequest = !fleetRowHasPullRequest({ cwd: target?.cwd ?? call.cwd, branch: call.head, chat }); + const readiness = creatingPullRequest + ? prReadinessProblem(call, target, recordedBinding({ worktree: call.cwd, conversation: event?.session_id ?? null, home })) + : null; + if (readiness) return refuse(readiness); if (target?.nonVibe) continue; let covered; try { covered = overriddenChecks(call.bodyFile ? readPrBodyFile(call.bodyFile) : "", recordedBinding({ worktree: call.cwd, conversation: event?.session_id ?? null, home })); } @@ -388,7 +428,7 @@ export function prCreateGuard(event, home = os.homedir()) { // Cloud import readiness, its own rerun of the handoff gate included, is a separate protection the override does not clear. const cloudProblem = cloudPrProblem(target.cwd, { base: call.base, bodyFile: call.bodyFile, title: call.title }); if (cloudProblem) return refuse(cloudProblem, CLOUD_RETRY); - const problem = handoffGateProblem(target.cwd, { base: call.base, bodyFile: call.bodyFile, title: call.title }); + const problem = handoffGateProblem(target.cwd, { base: call.base, bodyFile: call.bodyFile, title: call.title, creatingPullRequest }); if (problem && !override(OVERRIDE_CHECKS.HandoffGate)) return refuse(problem, `run the final handoff gate on the published source, or ${overrideHint(OVERRIDE_CHECKS.HandoffGate)}`); // A named handoff override leaves visual QA active. Without a passing witness, verify the inline findings. const placementProblem = missingPlacement() ?? missingVisualQa(target.cwd, null, problem ? null : target.cwd); diff --git a/plugins/vibe-closedloop/lib/fleet-orchestrator/scripts/delivery-placement.mjs b/plugins/vibe-closedloop/lib/fleet-orchestrator/scripts/delivery-placement.mjs index 75cdb5a1..793399b2 100644 --- a/plugins/vibe-closedloop/lib/fleet-orchestrator/scripts/delivery-placement.mjs +++ b/plugins/vibe-closedloop/lib/fleet-orchestrator/scripts/delivery-placement.mjs @@ -1,5 +1,5 @@ import { execFileSync } from "node:child_process"; -import { existsSync, readFileSync } from "node:fs"; +import { existsSync, readFileSync, realpathSync } from "node:fs"; import path from "node:path"; import { defaultHome } from "./fleet-home.mjs"; import { resolveWorkDir } from "../../codex-fleet-monitor/scripts/work-dir.mjs"; @@ -36,6 +36,21 @@ function readDeliveryBoard(chat, env = process.env) { return existsSync(file) ? JSON.parse(readFileSync(file, "utf8")) : {}; } +/** Whether the fleet board for this chat already has a pull request on this checkout or repository branch. */ +export function fleetRowHasPullRequest({ cwd, branch, chat, env = process.env }) { + try { + const worktree = realpathSync(cwd); + const repository = deliveryRepository(cwd)?.toLowerCase(); + const { writers } = readDeliveryBoard(chat, env); + return Object.values(writers ?? {}).some((row) => { + if (!row?.pr || row.retiredAt) return false; + if (branch && row.branch === branch && repository && row.repo?.toLowerCase() === repository) return true; + if (!row.worktree || row.where === "remote") return false; + try { return realpathSync(row.worktree) === worktree; } catch { return false; } + }); + } catch { return false; } +} + function recordedPlacements(content) { const entries = []; let fence = null; diff --git a/plugins/vibe-closedloop/lib/handoff/scripts/e2e-gate-check.mjs b/plugins/vibe-closedloop/lib/handoff/scripts/e2e-gate-check.mjs new file mode 100644 index 00000000..f9726b4c --- /dev/null +++ b/plugins/vibe-closedloop/lib/handoff/scripts/e2e-gate-check.mjs @@ -0,0 +1,93 @@ +// PR create requires passing receipts for the repository's required E2E specs and checks not-run claims in the PR +// body. The handoff gate and push-check report the same findings as warnings. A ticketed e2e lane override can quote a +// skip ruling. e2e-requirement.mjs determines when the full lane is owed (operator rulings, 2026-12-02). + +import { execFileSync } from "node:child_process"; +import { readGitInventory } from "../../vibe/scripts/git-inventory.mjs"; +import { e2eLaneRequirement, e2eRequirementDeclared, FULL_LANE, missingE2eSpecs, NO_GRAPH, recordedE2eEvidence } from "../../../skills/vibe/scripts/e2e-requirement.mjs"; +import { quotedRulingOverride } from "./gate-override.mjs"; + +/** The override check name an e2e skip uses: `Vibe gate override: : e2e lane: `. */ +export const E2E_LANE_OVERRIDE = "e2e lane"; + +const NOT_RUN = /\bnot\s+(?:been\s+)?run\b/i; +const E2E = /\b(?:e-?2-?e|end[-\s]to[-\s]end)\b/i; +const SURFACE_WORDS = Object.freeze({ web: /\b(?:web|browser|playwright)\b/i, desktop: /\b(?:desktop|electron)\b/i }); +// A clause that says only the full lane was not run ("full web e2e", "the rest of the Desktop e2e"). +const FULL_ONLY = /\b(?:full|whole|entire|complete|rest\s+of)\b/i; + +/** + * The surfaces a body says it did not run e2e on, each mapped to whether every such mention is of the full lane only: + * each comma or semicolon clause after "not run" that names e2e, with the surfaces it names ("full web and Desktop e2e" + * names both), or every surface when it names none. + */ +export function notRunE2eSurfaces(bodyText) { + const surfaces = new Map(); + for (const line of String(bodyText ?? "").split(/\r?\n/)) { + const at = line.search(NOT_RUN); + if (at < 0) continue; + for (const clause of line.slice(at).split(/[,;]/)) { + if (!E2E.test(clause)) continue; + const named = Object.entries(SURFACE_WORDS).filter(([, word]) => word.test(clause)).map(([surface]) => surface); + for (const surface of named.length ? named : Object.keys(SURFACE_WORDS)) surfaces.set(surface, (surfaces.get(surface) ?? true) && FULL_ONLY.test(clause)); + } + } + return surfaces; +} + +const quotedSkipRuling = (bodyText, binding) => quotedRulingOverride(bodyText, binding, E2E_LANE_OVERRIDE); + +/** Each required e2e lane the body lists as not run, from computed requirements ([{ surface, required, full, reasons, lane }]). */ +export function notRunE2eProblems(bodyText, requirements, binding = null) { + const notRun = notRunE2eSurfaces(bodyText); + if (!notRun.size || quotedSkipRuling(bodyText, binding)) return []; + return requirements.filter((lane) => lane.required && notRun.has(lane.surface) && (lane.full || !notRun.get(lane.surface))).map((lane) => + `the PR body lists the required ${lane.surface} e2e lane (${lane.lane}) as not run; run it${lane.full ? " in full" : ""} and record it, or add "Vibe gate override: : ${E2E_LANE_OVERRIDE}: "`); +} + +/** + * Each required e2e spec with no local run receipt, from missingE2eSpecs ([{ surface, spec, reason }]; spec "full" is + * the whole lane). A whole lane owed only because no graph test selection is recorded says how to narrow it. + */ +export function missingSpecProblems(missing) { + const skip = `add "Vibe gate override: : ${E2E_LANE_OVERRIDE}: "`; + return missing.map(({ surface, spec, reason }) => { + if (spec === FULL_LANE && reason.startsWith(NO_GRAPH)) { + return `the required ${surface} e2e lane is owed in full only because no graph test selection is recorded for this change (${reason}); ` + + `to narrow it, run the specs the graph test lookup selects for the change plus those the change owes, and record that run with ` + + `pre-pr-lanes.mjs record --targeted-specs '' --graph-query ''; otherwise run the whole lane and record it, or ${skip}`; + } + return `the required ${surface} e2e ${spec === FULL_LANE ? "lane, in full," : `spec ${spec}`} has no local run receipt (${reason}); ` + + `record its run with pre-pr-lanes.mjs, or ${skip}`; + }); +} + +/** + * Both halves against this change: missing spec receipts and the body's not-run lines. The change runs from the merge + * base of `base` and `head`; without `head`, to the worktree as it is now, uncommitted and untracked files included. + * `base` and `bodyText` may each be a function returning it, read only for a repository a provider declares e2e lanes for. + */ +export function e2eGateProblems(worktree, { base, head = null, bodyText: body = "", binding = null }) { + if (!e2eRequirementDeclared(worktree, binding)) return []; + const bodyText = typeof body === "function" ? body() : body; + if (quotedSkipRuling(bodyText, binding)) return []; + const at = head ?? git(worktree, ["rev-parse", "HEAD"]); + // The change is what the pull request shows, as CI's paths filter reads it: from the merge base, never main's tip. + const since = git(worktree, ["merge-base", typeof base === "function" ? base() : base, at]); + const scope = { base: since, head: at, binding, ...(head ? {} : { files: worktreeChanges(worktree, since) }) }; + // The lane records are read only when the change owes something, so a repository no provider declares never reads them. + const owed = missingE2eSpecs(worktree, scope).length ? missingE2eSpecs(worktree, { ...scope, ...recordedE2eEvidence(worktree, { head: at }) }) : []; + const missing = missingSpecProblems(owed); + const notRun = notRunE2eSurfaces(bodyText).size ? notRunE2eProblems(bodyText, e2eLaneRequirement(worktree, scope), binding) : []; + return [...missing, ...notRun]; +} + +const git = (worktree, args) => execFileSync("git", ["-C", worktree, ...args], { encoding: "utf8", stdio: ["ignore", "pipe", "pipe"], maxBuffer: 64 * 1024 * 1024 }).trim(); + +/** The files the worktree changes against `since`, committed, uncommitted and untracked. */ +function worktreeChanges(worktree, since) { + const changed = execFileSync("git", ["-C", worktree, "diff", "--name-only", "--no-renames", "-z", since, "--"], + { encoding: "utf8", stdio: ["ignore", "pipe", "pipe"], maxBuffer: 64 * 1024 * 1024 }); + const untracked = readGitInventory(worktree, ["ls-files", "--others", "--exclude-standard", "-z"]); + return [...changed.split("\0"), ...untracked.split("\0")].filter(Boolean); +} diff --git a/plugins/vibe-closedloop/lib/handoff/scripts/full-ci-check.mjs b/plugins/vibe-closedloop/lib/handoff/scripts/full-ci-check.mjs new file mode 100644 index 00000000..2fffa1b7 --- /dev/null +++ b/plugins/vibe-closedloop/lib/handoff/scripts/full-ci-check.mjs @@ -0,0 +1,101 @@ +// A pull request to a repository whose vibe-handoff-paths.json declares a github-workflow lane source is refused at PR +// create until every job and matrix entry of that workflow, read at the PR head, has a passing +// run of the head's exact tree recorded by pre-pr-lanes.mjs with its run witness, unless a ticketed gate override for +// "ci lanes" quotes the ruling that allows the skip (operator ruling, 2026-12-02 about 9:10 PM CST: "stop allowing +// things like this to even make it to a PR without adequate testing"). A pull request once opened after only its +// focused test files ran, and CI failed on tests outside them and on a missed plugin version bump. +// +// Usage: full-ci-check.mjs report --worktree writes the workflow lane report for HEAD into the git dir and +// prints `REPORT ` and one `UNRUN ` line per job still to run with +// pre-pr-lanes.mjs run --fleet-where remote --fleet-orch --fleet-owner --worktree +// --head --command '' --report (the recipe is the job's `command` in the report; the heavy +// host needs a worktree at the same path and HEAD). Exits 1 while any job is unrun. + +import { execFileSync } from "node:child_process"; +import { createHash } from "node:crypto"; +import { existsSync, readFileSync, writeFileSync } from "node:fs"; +import path from "node:path"; +import { parseArgs } from "node:util"; +import { capturedJson } from "../../vibe/scripts/captured-json.mjs"; +import { workflowLaneDefinitions } from "../../vibe/scripts/workflow-lane-definitions.mjs"; +import { committedSourceIdentity } from "../../vibe/scripts/tested-head.mjs"; +import { witnessProblem } from "../../../skills/vibe/scripts/lane-run-witness.mjs"; +import { LANE_RECORDS_FILE } from "../../../skills/vibe/scripts/lane-outcomes.mjs"; +import { quotedRulingOverride } from "./gate-override.mjs"; +import { isEntryPoint } from "../../../shared/plugin-roots.mjs"; + +// The operator's 2026-12-02 9:10 PM CST ruling requires adequate testing before PR create. +// The 11:58 PM CST ruling makes full CI and e2e checks advisory on existing PRs. +export const FULL_CI_GATE_SINCE = "2026-12-03T03:10:00Z"; + +/** Whether push-check asks the pre-PR checks of a row whose pull request was created at `createdAt` (null: none yet). */ +export function pushCheckAsksPrePrChecks(createdAt) { + return createdAt !== null && Date.parse(createdAt) >= Date.parse(FULL_CI_GATE_SINCE); +} + +/** The override check name: `Vibe gate override: : ci lanes: `. */ +export const CI_LANES_OVERRIDE = "ci lanes"; + +const git = (worktree, args) => execFileSync("git", ["-C", worktree, ...args], { encoding: "utf8", stdio: ["ignore", "pipe", "pipe"], maxBuffer: 64 * 1024 * 1024 }); + +/** The declared workflow's path and lanes at `head`, or null when the repository declares no github-workflow lane source there. */ +export function declaredWorkflowLanes(worktree, head) { + let source; + try { source = capturedJson(git(worktree, ["show", `${head}:vibe-handoff-paths.json`])).laneSource; } + catch { return null; } + if (source?.kind !== "github-workflow" || typeof source.path !== "string") return null; + return { path: source.path, lanes: workflowLaneDefinitions(git(worktree, ["show", `${head}:${source.path}`])) }; +} + +/** The lane records pre-pr-lanes.mjs keeps in the worktree's git dir. */ +function laneRecords(worktree) { + const file = path.join(git(worktree, ["rev-parse", "--absolute-git-dir"]).trim(), LANE_RECORDS_FILE); + if (!existsSync(file)) return []; + const records = JSON.parse(readFileSync(file, "utf8")); + return Array.isArray(records) ? records : []; +} + +/** The declared workflow lanes with no witnessed passing run of `head`'s tree, as `[{ name, command }]`; [] when none are declared. */ +export function unrunCiLanes(worktree, head) { + const declared = declaredWorkflowLanes(worktree, head); + if (!declared) return []; + const tree = committedSourceIdentity(worktree, head).treeSha256; + const records = laneRecords(worktree); + return declared.lanes.filter(({ command }) => !records.some((record) => record?.command === command && record.result === "pass" + && record.targeted === undefined && record.source?.treeSha256 === tree && !witnessProblem(record))); +} + +/** Why `head` may not be raised as a pull request yet, or null. `bodyText` may be a function, read only when a job is unrun. */ +export function fullCiProblem(worktree, head, { bodyText = "", binding = null } = {}) { + const unrun = unrunCiLanes(worktree, head); + if (!unrun.length || quotedRulingOverride(typeof bodyText === "function" ? bodyText() : bodyText, binding, CI_LANES_OVERRIDE)) return null; + return `every CI workflow job runs in full on the exact head before a pull request, and ${unrun.length} have no witnessed passing run of ${head.slice(0, 12)}: ` + + `${unrun.map(({ name }) => name).join(", ")}; full-ci-check.mjs report --worktree ${worktree} names each job's run, ` + + `or add "Vibe gate override: : ${CI_LANES_OVERRIDE}: "`; +} + +/** Write the declared workflow's lane report for `head` (the JSON pre-pr-lanes.mjs takes as --report) into the git dir. */ +export function writeWorkflowLaneReport(worktree, head) { + const declared = declaredWorkflowLanes(worktree, head); + if (!declared) throw new Error("the repository declares no github-workflow lane source in vibe-handoff-paths.json"); + const content = git(worktree, ["show", `${head}:${declared.path}`]); + const file = path.join(git(worktree, ["rev-parse", "--absolute-git-dir"]).trim(), "vibe-ci-lane-report.json"); + writeFileSync(file, `${JSON.stringify({ source: { kind: "github-workflow", path: declared.path, commit: head, sha256: createHash("sha256").update(content).digest("hex") }, + matches: declared.lanes.map(({ name, command }) => ({ name, command })) }, null, 2)}\n`); + return file; +} + +function main(argv) { + const { positionals, values } = parseArgs({ args: argv, allowPositionals: true, options: { worktree: { type: "string" } } }); + if (positionals[0] !== "report" || !values.worktree) throw new Error("usage: full-ci-check.mjs report --worktree "); + const head = git(values.worktree, ["rev-parse", "HEAD"]).trim(); + process.stdout.write(`REPORT ${writeWorkflowLaneReport(values.worktree, head)}\n`); + const unrun = unrunCiLanes(values.worktree, head); + for (const { name } of unrun) process.stdout.write(`UNRUN ${name}\n`); + return unrun.length ? 1 : 0; +} + +if (isEntryPoint(import.meta.url)) { + try { process.exitCode = main(process.argv.slice(2)); } + catch (error) { process.stderr.write(`${error.message}\n`); process.exitCode = 2; } +} diff --git a/plugins/vibe-closedloop/lib/handoff/scripts/full-ci-fixture.mjs b/plugins/vibe-closedloop/lib/handoff/scripts/full-ci-fixture.mjs new file mode 100644 index 00000000..9a4c5e37 --- /dev/null +++ b/plugins/vibe-closedloop/lib/handoff/scripts/full-ci-fixture.mjs @@ -0,0 +1,49 @@ +// A repository that declares its CI workflow as its lane source, for the full-ci-check.mjs tests and the PR-create and +// push-check wiring tests. +import { execFileSync } from "node:child_process"; +import { mkdirSync, mkdtempSync, rmSync, writeFileSync } from "node:fs"; +import { tmpdir } from "node:os"; +import path from "node:path"; +import { committedSourceIdentity } from "../../vibe/scripts/tested-head.mjs"; +import { workflowLaneDefinitions } from "../../vibe/scripts/workflow-lane-definitions.mjs"; + +// The jobs CI ran on #457 that its writer did not: the version bump check and the whole Node suite. +const WORKFLOW = JSON.stringify({ on: "pull_request", jobs: { + "plugin-version-bump": { name: "Plugin Version Bump", "runs-on": "ubuntu-latest", steps: [{ run: "node tools/version-bump.mjs" }] }, + "node-tests": { name: "Node Tests (skill scripts)", "runs-on": "ubuntu-latest", steps: [{ run: "node --test plugins" }] }, +} }); + +/** Write the workflow and, when `declared`, the lane-source declaration naming it into `worktree` (uncommitted). */ +export function writeCiDeclaration(worktree, { declared = true } = {}) { + mkdirSync(path.join(worktree, ".github", "workflows"), { recursive: true }); + writeFileSync(path.join(worktree, ".github", "workflows", "ci.yml"), WORKFLOW); + if (declared) writeFileSync(path.join(worktree, "vibe-handoff-paths.json"), JSON.stringify({ version: 1, laneSource: { kind: "github-workflow", path: ".github/workflows/ci.yml" } })); +} + +/** The declared workflow's lanes, `[{ name, command }]`. */ +export const CI_LANES = workflowLaneDefinitions(WORKFLOW); + +/** Replace the worktree's lane records with passes of `commands` at `head`, as pre-pr-lanes.mjs run writes them. */ +export function recordLanes(worktree, head, commands, { treeSha256 = committedSourceIdentity(worktree, head).treeSha256, ...extra } = {}) { + const gitDir = execFileSync("git", ["-C", worktree, "rev-parse", "--absolute-git-dir"], { encoding: "utf8" }).trim(); + writeFileSync(path.join(gitDir, "vibe-lane-results.json"), JSON.stringify(commands.map((command) => ({ + command, head, source: { head, treeSha256 }, laneKey: "0123456789abcdef", result: "pass", provenance: "fresh", recordedBy: "run", ...extra })))); +} + +/** A repository declaring its CI workflow as its lane source, on a non-vibe branch with one commit past main. */ +export function ciRepository(t, { declared = true, worktree = mkdtempSync(path.join(tmpdir(), "vibe-full-ci-")) } = {}) { + mkdirSync(worktree, { recursive: true }); + t.after(() => rmSync(worktree, { recursive: true, force: true })); + const git = (...args) => execFileSync("git", ["-C", worktree, "-c", "user.email=test@example.com", "-c", "user.name=Test", ...args], { encoding: "utf8" }).trim(); + execFileSync("git", ["init", "-q", "-b", "main", worktree]); + writeCiDeclaration(worktree, { declared }); + git("add", "."); + git("commit", "-qm", "base"); + git("checkout", "-q", "-b", "feat/cloud-scale"); + writeFileSync(path.join(worktree, "provider.json"), "{}\n"); + git("add", "."); + git("commit", "-qm", "change provider data"); + const head = git("rev-parse", "HEAD"); + const record = (commands, treeSha256, extra = {}) => recordLanes(worktree, head, commands, { ...(treeSha256 ? { treeSha256 } : {}), ...extra }); + return { worktree, git, head, lanes: CI_LANES, record }; +} diff --git a/plugins/vibe-closedloop/lib/handoff/scripts/gate-override.mjs b/plugins/vibe-closedloop/lib/handoff/scripts/gate-override.mjs index 447eb429..b63c927a 100644 --- a/plugins/vibe-closedloop/lib/handoff/scripts/gate-override.mjs +++ b/plugins/vibe-closedloop/lib/handoff/scripts/gate-override.mjs @@ -34,6 +34,20 @@ export function gateOverrideEntries(body, binding) { }); } +// A quoted ruling: text in straight or curly double quotes. +const QUOTED_RULING = /"[^"]{3,}"|“[^”]{3,}”/; + +/** + * Whether the body carries a ticketed override naming `check` whose reason quotes the ruling that allows the skip: + * `Vibe gate override: : [, ]: `. + */ +export function quotedRulingOverride(body, binding, check) { + return gateOverrideEntries(body, binding).some(({ reason }) => { + const [names, ...rest] = reason.split(":"); + return names.split(",").map((name) => name.trim().toLowerCase()).includes(check) && QUOTED_RULING.test(rest.join(":")); + }); +} + /** An entry must name only recognized checks and contain a specific reason. */ export function overriddenChecks(body, binding) { const covered = new Set(); diff --git a/plugins/vibe-closedloop/lib/handoff/scripts/handoff-gate-check.mjs b/plugins/vibe-closedloop/lib/handoff/scripts/handoff-gate-check.mjs index 5e169eb2..fc628e22 100644 --- a/plugins/vibe-closedloop/lib/handoff/scripts/handoff-gate-check.mjs +++ b/plugins/vibe-closedloop/lib/handoff/scripts/handoff-gate-check.mjs @@ -81,8 +81,8 @@ export function pathCitationProblem(worktree, citations = [], evidence = []) { return null; } -/** Current gate problem, or null when the final inventory covered this source. */ -export function handoffGateProblem(worktree, { base, bodyFile, title } = {}) { +/** Current witness problem. The PR-create boundary also verifies proof receipts for new pull requests. */ +export function handoffGateProblem(worktree, { base, bodyFile, title, creatingPullRequest = false } = {}) { try { readPrBodyFile(bodyFile, 8 * 1024 * 1024); } catch (error) { if (error instanceof BodyFileError) return error.message; throw error; } let record; @@ -117,9 +117,13 @@ export function handoffGateProblem(worktree, { base, bodyFile, title } = {}) { for (const [key, label] of Object.entries(DOCUMENT_EVIDENCE)) { if ((record.evidence?.[key] ?? []).some(saved => JSON.stringify(evidenceFingerprint(saved.path)) !== JSON.stringify(saved))) return `handoff ${label} evidence changed`; } - const proofs = proofGateProblems(worktree, { base: record.base?.oid, bodyText: readFileSync(bodyFile, "utf8"), - ticketText: proofTicketText(record.evidence?.ticket?.path, (record.evidence?.members ?? []).map((saved) => saved.path)), runs: JSON.parse(readFileSync(record.evidence.runs.path, "utf8")) }); - if (proofs.length) return `handoff proof receipts: ${proofs.join("; ")}`; + if (creatingPullRequest) { + // A pushed head never counts as accepted proof here. Read only the passed heads bound into this witness. + const proofs = proofGateProblems(worktree, { base: record.base?.oid, bodyText: readFileSync(bodyFile, "utf8"), + ticketText: proofTicketText(record.evidence?.ticket?.path, (record.evidence?.members ?? []).map((saved) => saved.path)), runs: JSON.parse(readFileSync(record.evidence.runs.path, "utf8")), + accepted: { passed: Array.isArray(record.proofAccepted?.passed) ? record.proofAccepted.passed : [] } }); + if (proofs.length) return `handoff proof receipts: ${proofs.join("; ")}`; + } if (!Array.isArray(record.receipts)) return "handoff review receipt changed"; if (reviewReceiptProblems(readReviewReceipts(record.receipts), sourceIdentity(worktree), { worktree, reusableRoles: new Set(Array.isArray(record.reviewCarry) ? record.reviewCarry : []) }).problems.length) return "handoff review evidence is stale or incomplete"; diff --git a/plugins/vibe-closedloop/lib/handoff/scripts/long-lived-branch-fixture.mjs b/plugins/vibe-closedloop/lib/handoff/scripts/long-lived-branch-fixture.mjs new file mode 100644 index 00000000..621f0bf6 --- /dev/null +++ b/plugins/vibe-closedloop/lib/handoff/scripts/long-lived-branch-fixture.mjs @@ -0,0 +1,62 @@ +// A Git history in the shape of fixtures/long-lived-branch-shape.json: a branch whose test cases were committed before +// the 2026-12-01 mutation-proof ruling, synced with main and pushed after it, then given new cases. Shared by the +// proof-scope tests and the refusing-check replay guard. + +import { execFileSync } from "node:child_process"; +import { mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from "node:fs"; +import { tmpdir } from "node:os"; +import path from "node:path"; +import { writeCiDeclaration } from "./full-ci-fixture.mjs"; + +export const LONG_LIVED_SHAPE = JSON.parse(readFileSync(new URL("./fixtures/long-lived-branch-shape.json", import.meta.url), "utf8")); +const RULING = Date.parse("2026-12-01T18:55:00Z"); +const DAY = 24 * 60 * 60 * 1000; + +/** An ISO time `days` from the ruling (negative is before it). */ +export const dayFromRuling = (days) => new Date(RULING + days * DAY).toISOString(); + +const caseFile = (index, cases) => `import test from "node:test";\n${Array.from({ length: cases }, (_, at) => `\ntest("inherited ${index} case ${at}", () => {\n console.log(${index}, ${at});\n});\n`).join("")}`; +const sharedFile = (index, value) => `import test from "node:test";\nconst shared = ${value};\n\ntest("main ${index} case", () => {\n console.log(shared);\n});\n`; + +/** + * Build the history in a new repository: `main` with the shared test files, a `vibe/long-lived` branch that adds the + * inherited cases over the shape's pre-ruling days and edits each shared file outside its case, a later main commit, + * a sync merge of main on the shape's sync day (the pushed head) and the shape's new cases after it, uncommitted + * unless `commitNew`. Main declares its CI workflow as its lane source. Returns the worktree, main's tip, the pushed head + * and a git runner. + */ +export function longLivedBranch(t, { shape = LONG_LIVED_SHAPE, commitNew = true } = {}) { + const root = mkdtempSync(path.join(tmpdir(), "vibe-long-lived-")); + t.after(() => rmSync(root, { recursive: true, force: true })); + const worktree = path.join(root, "wt"); + mkdirSync(path.join(worktree, "src"), { recursive: true }); + const git = (args, at) => execFileSync("git", ["-C", worktree, "-c", "user.email=test@example.com", "-c", "user.name=Test", ...args], + { encoding: "utf8", env: { ...process.env, ...(at ? { GIT_AUTHOR_DATE: at, GIT_COMMITTER_DATE: at } : {}) } }).trim(); + const commit = (message, at) => { git(["add", "-A"]); git(["commit", "-qm", message], at); return git(["rev-parse", "HEAD"]); }; + execFileSync("git", ["init", "-q", "-b", "main", worktree]); + const { caseFiles, cases, fileLevelFiles, commitsByDay } = shape.inherited; + for (let index = 0; index < fileLevelFiles; index += 1) writeFileSync(path.join(worktree, "src", `shared-${index}.test.mjs`), sharedFile(index, 0)); + writeFileSync(path.join(worktree, "src", "code.mjs"), "export const value = 1;\n"); + writeCiDeclaration(worktree); + commit("base", dayFromRuling(-30)); + git(["checkout", "-q", "-b", "vibe/long-lived"]); + const perFile = Array.from({ length: caseFiles }, (_, index) => Math.floor(cases / caseFiles) + (index < cases % caseFiles ? 1 : 0)); + const edits = [...perFile.map((count, index) => () => writeFileSync(path.join(worktree, "src", `inherited-${index}.test.mjs`), caseFile(index, count))), + ...Array.from({ length: fileLevelFiles }, (_, index) => () => writeFileSync(path.join(worktree, "src", `shared-${index}.test.mjs`), sharedFile(index, 1)))]; + const days = Object.entries(commitsByDay).flatMap(([day, count]) => Array.from({ length: count }, (_, at) => dayFromRuling(Number(day) + at / 1440))); + days.forEach((at, index) => { + edits.filter((_, edit) => edit % days.length === index).forEach((apply) => apply()); + commit(`inherited ${index}`, at); + }); + git(["checkout", "-q", "main"]); + writeFileSync(path.join(worktree, "src", "main-only.test.mjs"), `import test from "node:test";\n\ntest("main only", () => {});\n`); + const main = commit("main moves on", dayFromRuling(shape.syncWithMainDay - 0.5)); + git(["checkout", "-q", "vibe/long-lived"]); + git(["merge", "-q", "--no-edit", "main"], dayFromRuling(shape.syncWithMainDay)); + const pushed = git(["rev-parse", "HEAD"]); + writeFileSync(path.join(worktree, "src", "new.test.mjs"), `import test from "node:test";\n${Array.from({ length: shape.newCases }, (_, at) => `\ntest("new case ${at}", () => {});\n`).join("")}`); + const head = commitNew ? commit("new cases", dayFromRuling(shape.newCasesDay)) : null; + const gitDir = git(["rev-parse", "--absolute-git-dir"]); + writeFileSync(path.join(gitDir, "vibe-session.json"), JSON.stringify({ status: "active", summary: "Add a filter", flagKeys: { surfaces: [] } })); + return { root, worktree, gitDir, main, pushed, head, git: (...args) => git(args), commit }; +} diff --git a/plugins/vibe-closedloop/lib/handoff/scripts/proof-receipts.mjs b/plugins/vibe-closedloop/lib/handoff/scripts/proof-receipts.mjs index 9b2dd107..b4f1161d 100644 --- a/plugins/vibe-closedloop/lib/handoff/scripts/proof-receipts.mjs +++ b/plugins/vibe-closedloop/lib/handoff/scripts/proof-receipts.mjs @@ -9,7 +9,8 @@ // cite a program decision line (proof-acceptance.mjs). A reproduction and a command // run bind to the source they ran on by tree, the way review receipts do, so // committing that tree keeps them. A mutation proof holds until its own test or -// the code it tests changes (operator ruling, 2026-12-01). The handoff gate, its PR-create read side and the fleet push-check +// the code it tests changes (operator ruling, 2026-12-01). Which changed cases need one is proof-scope.mjs's rule +// (operator rulings, 2026-12-01 and 2026-12-02). The handoff gate, its PR-create read side and the fleet push-check // refuse through proofGateProblems (a non-vibe row: bodyCommandProblems); the // review launch refuses a session with no flag-keys record through // flag-keys.mjs's flagKeysBeforeReviewProblem. @@ -32,7 +33,7 @@ // proof-receipts.mjs refresh --worktree (reruns every recorded command and expired mutant on the current source) // proof-receipts.mjs inventory --worktree (writes the decision table's Mutant Inventory from the mutation log) // proof-receipts.mjs show --worktree -// proof-receipts.mjs check --worktree --base --body --ticket [--member ...] [--runs ] [--head ] +// proof-receipts.mjs check --worktree --base --body --ticket [--member ...] [--runs ] [--head ] [--pushed (push-check only)] // Every command prints one JSON object; a refusal exits 1. import { execFileSync, spawnSync } from "node:child_process"; @@ -50,6 +51,7 @@ import { isCollectedTestFile, isTestFile } from "../../../skills/vibe/scripts/te import { flagKeyProblems } from "../../../skills/vibe/scripts/flag-keys.mjs"; import { testIntegrityCandidates, testIntegrityProblems } from "../../../skills/handoff/scripts/test-integrity.mjs"; import { isEntryPoint } from "../../../shared/plugin-roots.mjs"; +import { acceptedSnapshots, ProofExemption, proofExemptions, skipsCase } from "./proof-scope.mjs"; const RECEIPT_FILE = "vibe-proof-receipt.json"; const KINDS = new Set(["bug-fix", "feature"]); @@ -512,7 +514,7 @@ function changedTests(worktree, base, head) { return tests.map((file) => { const source = read(file); const all = { added: source.split("\n").map((_, index) => index + 1), deleted: [] }; - return { file, source, ...(untracked.includes(file) ? all : hunks.get(file) ?? { added: [], deleted: [] }) }; + return { file, source, untracked: untracked.includes(file), ...(untracked.includes(file) ? all : hunks.get(file) ?? { added: [], deleted: [] }) }; }); } @@ -564,30 +566,41 @@ function integritySubstitute(worktree, head, changed, runs, current) { }); } -function testProofProblems(worktree, base, head, receipt, current, runs, view) { +function testProofProblems(worktree, base, head, receipt, current, runs, view, accepted) { const changed = changedTests(worktree, base, head); + const exempt = proofExemptions(worktree, { snapshots: acceptedSnapshots(worktree, { comparisonBase: base, head, ...accepted }), head, tests: changed }); const substitutes = integritySubstitute(worktree, head, changed, runs, current); const holds = (proof) => stillHolds(proof, view) && proof.mutatedExit !== 0 && proof.restoredPass === true; const authored = (proof) => proof.authoring?.requestId && GRANTS.has(proof.authoring.grant); + const expired = (label, proof) => `${label}: its mutation proof no longer holds: its test file's shared code or ${proof.target} changed, or it has no hashes of them (proof-receipts.mjs refresh)`; const problems = []; for (const { file, source, added, deleted } of changed) { const changes = changedTestCases(file, source, added, deleted); if (!changes) { - problems.push(unreadableTest(file)); + if (!exempt.file(file)) problems.push(unreadableTest(file)); continue; } const { cases, fileLevel } = changes; for (const name of cases) { - if (substitutes(file, name)) continue; + const exemption = exempt.testCase(file, source, name); + if (skipsCase(exemption) || substitutes(file, name)) continue; const proof = receipt.mutations.find((entry) => entry.path === file && entry.case === name); const label = `test ${file} case "${name}"`; + if (exemption === ProofExemption.Passed) { + if (proof && !holds(proof)) problems.push(expired(label, proof)); + continue; + } if (proof && proof.caseSha256 !== caseHash(file, source, name)) problems.push(`${label} changed since its mutation proof; record a new one (proof-receipts.mjs mutation)`); else if (!proof) problems.push(`${label} has no mutation proof (proof-receipts.mjs mutation)`); - else if (!holds(proof)) problems.push(`${label}: its mutation proof no longer holds: its test file's shared code or ${proof.target} changed, or it has no hashes of them (proof-receipts.mjs refresh)`); + else if (!holds(proof)) problems.push(expired(label, proof)); else if (!authored(proof)) problems.push(`${label}: its mutation proof has no test-authoring record (turn and grant)`); else if (!loggedProof(receipt, proof, view)) problems.push(`${label}: its proof (mutant "${proof.mutation}") does not match the mutation log; record it again (proof-receipts.mjs mutation)`); } - if (fileLevel && !cases.length && !receipt.mutations.some((proof) => proof.path === file && holds(proof) && authored(proof) && loggedProof(receipt, proof, view))) { + if (!fileLevel || cases.length) continue; + const exemption = exempt.fileLevel(file, source); + const fileProofs = receipt.mutations.filter((proof) => proof.path === file); + if (skipsCase(exemption) || (exemption === ProofExemption.Passed && !fileProofs.length)) continue; + if (exemption === ProofExemption.Passed ? !fileProofs.some(holds) : !fileProofs.some((proof) => holds(proof) && authored(proof) && loggedProof(receipt, proof, view))) { problems.push(`test ${file} changed outside any case and has no mutation proof that still holds with its test-authoring record (proof-receipts.mjs mutation)`); } } @@ -682,9 +695,11 @@ const quotedIn = (entry) => entry.in ?? "ticket"; * in the body, the ticket or a changed runbook without a matching passing run, and an added or changed test without a * 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. + * otherwise the worktree's current source is checked. `accepted` names the heads + * whose cases the gate already accepted ({ pushed, passed }: proof-scope.mjs); + * only push-check passes a pushed head. */ -export function proofGateProblems(worktree, { base, head, bodyText = "", ticketText: suppliedTicket, runs = {} } = {}) { +export function proofGateProblems(worktree, { base, head, bodyText = "", ticketText: suppliedTicket, runs = {}, accepted = {} } = {}) { const record = readSessionRecord(worktree); const problems = flagKeyProblems(record).map((problem) => `flag keys: ${problem}`); const ticket = sessionLiveTicket(record ?? {}); @@ -704,7 +719,7 @@ export function proofGateProblems(worktree, { base, head, bodyText = "", ticketT problems.push(...commandProblems(receipt, [...found(operatorCommands(bodyText), "body"), ...found(operatorCommands(ticketText), "ticket"), ...runbookCommands(worktree, comparisonBase, fullHead)], current, ticket)); const view = sourceView(worktree, fullHead, current); - problems.push(...testProofProblems(worktree, comparisonBase, fullHead, receipt, current, runs, view), ...mutantInventoryProblems(worktree, receipt, view)); + problems.push(...testProofProblems(worktree, comparisonBase, fullHead, receipt, current, runs, view, accepted), ...mutantInventoryProblems(worktree, receipt, view)); return problems; } @@ -739,19 +754,35 @@ export function proofTicketText(ticketFile, memberFiles = []) { } /** The push-check form: the head's committed tree, with the body, tickets and runs the handoff gate witness bound when no body is given. */ -export function pushReadyProofProblems(worktree, { base, head, bodyFile, witness }) { +export function pushReadyProofProblems(worktree, { base, head, bodyFile, witness, pushed = [] }) { const evidence = witness && existsSync(witness) ? JSON.parse(readFileSync(witness, "utf8")).evidence ?? {} : {}; const read = (file) => file && existsSync(file) ? readFileSync(file, "utf8") : ""; const ticketFile = evidence.ticket?.path && existsSync(evidence.ticket.path) ? evidence.ticket.path : null; return proofGateProblems(worktree, { base, head, bodyText: read(bodyFile ?? evidence.body?.path), - ticketText: proofTicketText(ticketFile, (evidence.members ?? []).map((saved) => saved.path)), runs: JSON.parse(read(evidence.runs?.path) || "{}") }); + ticketText: proofTicketText(ticketFile, (evidence.members ?? []).map((saved) => saved.path)), runs: JSON.parse(read(evidence.runs?.path) || "{}"), + accepted: { pushed, passed: passedGateHeads(worktree) } }); +} + +/** The last head that passed the handoff gate, as a list for `accepted.passed`; empty when none is recorded. */ +export function passedGateHeads(worktree) { + const head = readProofReceipt(worktree).gatePassed?.head; + return typeof head === "string" && /^[a-f0-9]{40}$/.test(head) ? [head] : []; +} + +/** Record a passing handoff gate's head, when the source it passed is exactly that commit; otherwise keep the last one. */ +export function recordGatePass(worktree, source) { + let committed = null; + try { committed = committedSourceIdentity(worktree, source?.head).treeSha256; } catch { return null; } + if (committed !== source.treeSha256) return null; + return update(worktree, (receipt) => { receipt.gatePassed = { head: source.head, at: new Date().toISOString() }; }).gatePassed; } if (isEntryPoint(import.meta.url)) { const [action] = process.argv.slice(2); const { values } = parseArgs({ args: process.argv.slice(3), options: { ...Object.fromEntries(["worktree", "kind", "source", "parent", "surface", "data", "steps", "parent-evidence", "fix-evidence", "parent-command", "fix-command", "missing", "reason", "by", "run", "timeout", "path", "case", "target", "mutation", - "find", "replace", "command", "request", "grant", "base", "head", "body", "ticket", "runs", "ruling", "for", "in"].map((name) => [name, { type: "string" }])), member: { type: "string", multiple: true } } }); + "find", "replace", "command", "request", "grant", "base", "head", "body", "ticket", "runs", "ruling", "for", "in"].map((name) => [name, { type: "string" }])), + member: { type: "string", multiple: true }, pushed: { type: "string", multiple: true } } }); try { const worktree = required(values.worktree, "--worktree"); const timeoutSeconds = values.timeout ? Number(values.timeout) : undefined; @@ -772,7 +803,8 @@ if (isEntryPoint(import.meta.url)) { inventory: () => writeMutantInventory(worktree), check: () => { const problems = proofGateProblems(worktree, { base: required(values.base, "--base"), head: values.head, bodyText: read(values.body), - ticketText: proofTicketText(values.ticket, values.member ?? []), runs: values.runs ? JSON.parse(read(values.runs)) : {} }); + ticketText: proofTicketText(values.ticket, values.member ?? []), runs: values.runs ? JSON.parse(read(values.runs)) : {}, + accepted: { pushed: values.pushed ?? [], passed: passedGateHeads(worktree) } }); return { ok: problems.length === 0, problems }; }, }; diff --git a/plugins/vibe-closedloop/lib/handoff/scripts/proof-scope.mjs b/plugins/vibe-closedloop/lib/handoff/scripts/proof-scope.mjs new file mode 100644 index 00000000..0df3281d --- /dev/null +++ b/plugins/vibe-closedloop/lib/handoff/scripts/proof-scope.mjs @@ -0,0 +1,100 @@ +// Which changed test cases the mutation-proof gate asks about. The gate diffs a branch against its merge base, so a +// long-lived branch built before the mutation-proof ruling (operator ruling, 2026-12-01) was refused for every test it +// ever changed. The scope rule (operator rulings, 2026-12-02): +// - A case whose text at the checked source equals its text at the branch's last commit before the 2026-12-01 ruling +// (first-parent, by committer time) is never asked about, even when an old proof of it expired. +// - At push-check only, a case unchanged since the upstream head (the last pushed head) is not asked about. The handoff +// gate and PR create do not count a pushed head: a redeploy push never passed the gate. +// - At all three, a case unchanged since the last head that passed the handoff gate is asked about only when its +// recorded mutation proof no longer holds (its test or the code it tests changed), as the 2026-12-01 ruling says. +// A case is unchanged since a snapshot when no line inside it was added or deleted between the snapshot, merged with the +// comparison base the way a sync with main merges it, and the checked source. A deletion inside an old case brings it +// back into scope; what a sync with main brought into a branch's old case does not. + +import { execFileSync, spawnSync } from "node:child_process"; +import { addedLineNumbers, changedTestCases } from "./proof-parsers.mjs"; + +/** The 2026-12-01 mutation-proof ruling, about 12:55 PM CST. */ +export const MUTATION_RULING_AT = "2026-12-01T18:55:00Z"; + +/** Why a changed case is out of the gate's scope. Ruling and Pushed skip it; Passed still asks about an expired proof. */ +export const ProofExemption = Object.freeze({ Ruling: "ruling", Pushed: "pushed", Passed: "passed" }); + +const STRENGTH = Object.freeze({ [ProofExemption.Ruling]: 2, [ProofExemption.Pushed]: 2, [ProofExemption.Passed]: 1 }); + +/** Whether an exemption skips the case outright, with no question about an expired proof. */ +export const skipsCase = (exemption) => exemption === ProofExemption.Ruling || exemption === ProofExemption.Pushed; + +/** + * The commits whose cases the gate already accepted, each with its exemption: the branch's last commit before the ruling + * and each given pushed or passed head. A snapshot inside the comparison base adds nothing and is dropped, and so is a + * head this repository cannot resolve. + */ +export function acceptedSnapshots(worktree, { comparisonBase, head, pushed = [], passed = [] }) { + const git = (...args) => execFileSync("git", ["-C", worktree, ...args], { encoding: "utf8", stdio: ["ignore", "pipe", "ignore"] }).trim(); + const snapshots = []; + const add = (exemption, ref) => { + if (typeof ref !== "string" || !ref.trim()) return; + let sha; + try { sha = git("rev-parse", "--verify", "--end-of-options", `${ref.trim()}^{commit}`); } catch { return; } + try { git("merge-base", "--is-ancestor", sha, comparisonBase); return; } catch { /* Not inside the base: it counts. */ } + snapshots.push({ exemption, sha, tree: syncedTree(worktree, sha, comparisonBase) }); + }; + let ruling = ""; + try { ruling = git("rev-list", "-1", "--first-parent", `--before=${MUTATION_RULING_AT}`, head ?? "HEAD"); } catch { /* No such commit. */ } + add(ProofExemption.Ruling, ruling); + for (const ref of pushed) add(ProofExemption.Pushed, ref); + for (const ref of passed) add(ProofExemption.Passed, ref); + return snapshots; +} + +/** + * The snapshot merged with the comparison base, as a tree: what the branch held then, synced with what main holds now. + * A conflicted file keeps its markers, so its conflicted lines count as changed since. When Git cannot merge them at + * all, the snapshot's own commit stands in. + */ +function syncedTree(worktree, sha, comparisonBase) { + const merged = spawnSync("git", ["-C", worktree, "merge-tree", "--write-tree", "--no-messages", sha, comparisonBase], { encoding: "utf8", maxBuffer: 64 * 1024 * 1024 }); + const tree = (merged.status === 0 || merged.status === 1) ? merged.stdout.split("\n")[0].trim() : ""; + return /^[a-f0-9]{40,64}$/.test(tree) ? tree : sha; +} + +/** + * The exemption of each changed test, case and file-level change, from the snapshots: for each, the strongest snapshot + * it is unchanged since, or null. `tests` are the gate's changed tests ({ file, source, untracked }); an untracked file + * is new since every snapshot. + */ +export function proofExemptions(worktree, { snapshots, head, tests }) { + const tracked = tests.filter((entry) => !entry.untracked).map((entry) => entry.file); + const since = snapshots.map(({ exemption, tree }) => { + const diff = tracked.length ? execFileSync("git", ["-C", worktree, "diff", "-U0", "--no-renames", "--no-color", "--no-ext-diff", "--src-prefix=a/", "--dst-prefix=b/", + tree, ...(head ? [head] : []), "--", ...tracked], { encoding: "utf8", maxBuffer: 256 * 1024 * 1024 }) : ""; + return { exemption, lines: addedLineNumbers(diff) }; + }); + const untracked = new Set(tests.filter((entry) => entry.untracked).map((entry) => entry.file)); + const strongest = (test) => { + let found = null; + for (const snapshot of since) if (test(snapshot) && (!found || STRENGTH[snapshot.exemption] > STRENGTH[found])) found = snapshot.exemption; + return found; + }; + const changes = new Map(); + const changesSince = (snapshot, file, source) => { + const key = `${since.indexOf(snapshot)}\0${file}`; + if (!changes.has(key)) { + const lines = snapshot.lines.get(file) ?? { added: [], deleted: [] }; + changes.set(key, changedTestCases(file, source, lines.added, lines.deleted)); + } + return changes.get(key); + }; + return { + file: (file) => untracked.has(file) ? null : strongest((snapshot) => !snapshot.lines.has(file)), + testCase: (file, source, name) => untracked.has(file) ? null : strongest((snapshot) => { + const found = changesSince(snapshot, file, source); + return Boolean(found) && !found.cases.includes(name); + }), + fileLevel: (file, source) => untracked.has(file) ? null : strongest((snapshot) => { + const found = changesSince(snapshot, file, source); + return Boolean(found) && !found.fileLevel; + }), + }; +} diff --git a/plugins/vibe-closedloop/lib/handoff/scripts/refusing-check-replay.mjs b/plugins/vibe-closedloop/lib/handoff/scripts/refusing-check-replay.mjs new file mode 100644 index 00000000..dca61c39 --- /dev/null +++ b/plugins/vibe-closedloop/lib/handoff/scripts/refusing-check-replay.mjs @@ -0,0 +1,87 @@ +#!/usr/bin/env node +// Replays the registered refusing checks (refusing-checks.mjs) against real worktrees, each at the head it already had +// accepted (its pushed upstream unless named), and writes the result as a receipt for the pull request's head. PR create +// refuses a pull request that changes a replayed check's source without a receipt for its exact tree that covers the +// changed checks, names at least one real target, and shows no refusal of accepted work, unless a ticketed gate override +// for "refusal replay" quotes the ruling that allows them (operator rulings, 2026-12-02 about 9:10 and 9:15 PM CST). +// Targets are only read, apart from the unreferenced merge objects `git merge-tree --write-tree` leaves in their +// object stores. +// +// Usage: refusing-check-replay.mjs --worktree --target [@]... +// [--check ]... +// Prints one line per target and check, and `RECEIPT `. Exits 1 when any check refused accepted work. + +import { execFileSync } from "node:child_process"; +import { existsSync, readFileSync, writeFileSync } from "node:fs"; +import path from "node:path"; +import { parseArgs } from "node:util"; +import { REFUSING_CHECKS, replayedChecksTouched } from "./refusing-checks.mjs"; +import { passedGateHeads } from "./proof-receipts.mjs"; +import { quotedRulingOverride } from "./gate-override.mjs"; +import { committedSourceIdentity } from "../../vibe/scripts/tested-head.mjs"; +import { isEntryPoint } from "../../../shared/plugin-roots.mjs"; + +export const REPLAY_RECEIPT = "vibe-refusal-replay.json"; +const REGISTRY_PATH = "plugins/vibe/lib/handoff/scripts/refusing-checks.mjs"; +/** The override check name: `Vibe gate override: : refusal replay: `. */ +export const REFUSAL_REPLAY_OVERRIDE = "refusal replay"; + +const git = (worktree, args) => execFileSync("git", ["-C", worktree, ...args], { encoding: "utf8", stdio: ["ignore", "pipe", "pipe"], maxBuffer: 64 * 1024 * 1024 }).trim(); +const receiptPath = (worktree) => path.join(git(worktree, ["rev-parse", "--absolute-git-dir"]), REPLAY_RECEIPT); + +/** Each replayed check's refusals for one target at its accepted head, `{ worktree, head, refusals: { [check]: string[] } }`. */ +export function replayTarget(worktree, head, checks) { + let base; + try { base = git(worktree, ["rev-parse", "--verify", "refs/remotes/origin/HEAD^{commit}"]); } + catch { base = git(worktree, ["rev-parse", "--verify", "refs/remotes/origin/main^{commit}"]); } + const input = { worktree, base, head, pushed: [head], passed: passedGateHeads(worktree), bodyText: "", binding: null }; + return { worktree, head, refusals: Object.fromEntries(checks.map((name) => [name, REFUSING_CHECKS[name].replay(input)])) }; +} + +/** + * Why `head` may not be raised before its changed refusing checks were replayed against real work, or null. Only a + * repository carrying this registry at `head` is asked; `base` is the PR base commit and `bodyText` the PR body, each + * or a function returning it. + */ +export function refusalReplayProblem(worktree, { base, head, bodyText = "", binding = null }) { + try { git(worktree, ["cat-file", "-e", `${head}:${REGISTRY_PATH}`]); } + catch { return null; } + const baseOid = typeof base === "function" ? base() : base; + const touched = replayedChecksTouched(git(worktree, ["diff", "--name-only", `${baseOid}...${head}`]).split("\n").filter(Boolean)); + if (!touched.length || quotedRulingOverride(typeof bodyText === "function" ? bodyText() : bodyText, binding, REFUSAL_REPLAY_OVERRIDE)) return null; + const fix = `run refusing-check-replay.mjs --worktree ${worktree} --target ... on this head, or add "Vibe gate override: : ${REFUSAL_REPLAY_OVERRIDE}: "`; + const file = receiptPath(worktree); + const receipt = existsSync(file) ? JSON.parse(readFileSync(file, "utf8")) : null; + if (receipt?.treeSha256 !== committedSourceIdentity(worktree, head).treeSha256) { + return `it changes refusing checks (${touched.join(", ")}) that have not been replayed against real work on this head; ${fix}`; + } + const missing = touched.filter((name) => !receipt.checks?.includes(name)); + if (missing.length || !receipt.targets?.length) return `the refusal replay on this head does not cover ${missing.length ? missing.join(", ") : "any real target"}; ${fix}`; + const refused = receipt.targets.flatMap((target) => touched.filter((name) => target.refusals?.[name] > 0).map((name) => `${name} refused ${target.refusals[name]} at ${target.head.slice(0, 12)}`)); + return refused.length ? `the refusal replay shows checks refusing accepted work (${refused.join("; ")}); fix them, or add "Vibe gate override: : ${REFUSAL_REPLAY_OVERRIDE}: "` : null; +} + +function main(argv) { + const { values } = parseArgs({ args: argv, options: { worktree: { type: "string" }, target: { type: "string", multiple: true }, check: { type: "string", multiple: true } } }); + if (!values.worktree || !values.target?.length) throw new Error("usage: refusing-check-replay.mjs --worktree --target [@]... [--check ]..."); + const checks = values.check?.length ? values.check : Object.keys(REFUSING_CHECKS).filter((name) => REFUSING_CHECKS[name].replay); + const unknown = checks.filter((name) => !REFUSING_CHECKS[name]?.replay); + if (unknown.length) throw new Error(`not a replayed check: ${unknown.join(", ")}`); + const targets = values.target.map((spec) => { + const [worktree, named] = spec.split("@"); + const head = git(worktree, ["rev-parse", "--verify", `${named || "@{upstream}"}^{commit}`]); + const replayed = replayTarget(worktree, head, checks); + for (const name of checks) process.stdout.write(`${head.slice(0, 12)} ${worktree} ${name}: ${replayed.refusals[name].length}\n`); + return { ...replayed, refusals: Object.fromEntries(Object.entries(replayed.refusals).map(([name, lines]) => [name, lines.length])) }; + }); + const head = git(values.worktree, ["rev-parse", "HEAD"]); + const file = receiptPath(values.worktree); + writeFileSync(file, `${JSON.stringify({ head, treeSha256: committedSourceIdentity(values.worktree, head).treeSha256, checks, targets, at: new Date().toISOString() }, null, 2)}\n`); + process.stdout.write(`RECEIPT ${file}\n`); + return targets.some((target) => Object.values(target.refusals).some((count) => count > 0)) ? 1 : 0; +} + +if (isEntryPoint(import.meta.url)) { + try { process.exitCode = main(process.argv.slice(2)); } + catch (error) { process.stderr.write(`${error.message}\n`); process.exitCode = 2; } +} diff --git a/plugins/vibe-closedloop/lib/handoff/scripts/refusing-checks.mjs b/plugins/vibe-closedloop/lib/handoff/scripts/refusing-checks.mjs new file mode 100644 index 00000000..1c83f459 --- /dev/null +++ b/plugins/vibe-closedloop/lib/handoff/scripts/refusing-checks.mjs @@ -0,0 +1,75 @@ +// Every check that can refuse a writer's branch at the fleet push-check, the handoff gate or PR create, keyed by the +// function its gate calls or the refusal prefix push-check prints (refusing-checks.test.mjs enumerates both from the gate +// sources and fails on one missing here). A check with `replay` is run in Node Tests against a branch shaped like real +// long-lived work (long-lived-branch-fixture.mjs) and must refuse nothing that branch already had accepted; with +// refusing-check-replay.mjs it runs against real worktrees, and a pull request changing one of its `files` needs that +// run's receipt (pr-create-guard.mjs). Operator rulings, 2026-12-02 about 9:10 and 9:15 PM CST: a push guard that +// refused 551 tests on its first real branch "should have been caught before a PR was even raised"; "use +// prevent-recurrence so that we really fix that from ever happening again". +// +// UNREPLAYED holds the checks that predate this registry and have no replay yet. It only shrinks: give an entry a +// replay and move it to REFUSING_CHECKS, never add one. + +import { e2eGateProblems } from "./e2e-gate-check.mjs"; +import { fullCiProblem } from "./full-ci-check.mjs"; +import { proofGateProblems, pushReadyProofProblems } from "./proof-receipts.mjs"; +import { refusalReplayProblem } from "./refusing-check-replay.mjs"; + +const HANDOFF = "plugins/vibe/lib/handoff/scripts"; +const PROOF_FILES = [`${HANDOFF}/proof-receipts.mjs`, `${HANDOFF}/proof-scope.mjs`, `${HANDOFF}/proof-parsers.mjs`]; +const E2E_FILES = [`${HANDOFF}/e2e-gate-check.mjs`, "plugins/vibe/skills/vibe/scripts/e2e-requirement.mjs"]; + +/** + * Each replayed check: the source files that define it and `replay(input)`, its refusals for a branch at `head`, given + * `{ worktree, base, head, pushed, passed, bodyText, binding }` (pushed and passed are the heads the branch already had + * accepted). `via` names the entry a push-check prefix or a wrapper reports through. + */ +export const REFUSING_CHECKS = Object.freeze({ + proofGateProblems: { files: PROOF_FILES, gates: ["PR create"], + replay: ({ worktree, base, head, passed, bodyText }) => proofGateProblems(worktree, { base, head, bodyText, ticketText: "", accepted: { passed } }) }, + pushReadyProofProblems: { files: [...PROOF_FILES, "plugins/vibe/skills/fleet-orchestrator/scripts/push-proof.mjs"], gates: ["push-check"], + replay: ({ worktree, base, head, pushed }) => pushReadyProofProblems(worktree, { base, head, pushed }) }, + e2eGateProblems: { files: E2E_FILES, gates: ["PR create"], + replay: ({ worktree, base, head, bodyText, binding }) => e2eGateProblems(worktree, { base, head, bodyText, binding }) }, + fullCiProblem: { files: [`${HANDOFF}/full-ci-check.mjs`], gates: ["PR create"], + replay: ({ worktree, head, bodyText, binding }) => [fullCiProblem(worktree, head, { bodyText, binding })].filter(Boolean) }, + refusalReplayProblem: { files: [`${HANDOFF}/refusing-check-replay.mjs`, `${HANDOFF}/refusing-checks.mjs`], gates: ["PR create"], + replay: ({ worktree, base, head, bodyText, binding }) => [refusalReplayProblem(worktree, { base, head, bodyText, binding })].filter(Boolean) }, + "PROOF-MISSING": { via: "pushReadyProofProblems" }, + "E2E-NOT-RUN": { via: "e2eGateProblems" }, + "CI-NOT-RUN": { via: "fullCiProblem" }, + prReadinessProblem: { via: "fullCiProblem" }, +}); + +/** Refusing checks that predate the registry and have no replay (shrink-only). */ +export const UNREPLAYED = Object.freeze([ + "bodyCommandProblems", "checkedMergeProblem", "cloudPrProblem", "decisionTableProblems", "deliveryPlacementProblem", + "handoffGateProblem", "inventoryGateProblem", "memberNameProblems", "mergeabilityProblem", "pathCitationProblem", + "placementLineProblem", "prVisualQaProblem", "reviewFindingProblems", "reviewReceiptProblems", "visualQaFindingsProblems", + "HANDOFF-MISSING", "HANDOFF-UNVERIFIED", "NO-HEAD", "NOT-READY", "PR-HELD-NOT-DRAFT", "PR-HOLD-UNKNOWN", "PROOF-UNCHECKED", + "PUSH-READY-UNKNOWN", "UNIT-UNREVIEWED", "UNREADY-COMMIT", "VISUAL-QA-MISSING", +]); + +/** + * The gate sources whose refusal producers the registry must cover. board.mjs runs many board actions besides + * push-check, so only its push-check refusal prefixes count there; every push-check refusal prints one. + */ +export const GATE_SOURCES = Object.freeze([ + { path: "plugins/vibe/skills/handoff/scripts/handoff-gate.mjs" }, { path: `${HANDOFF}/handoff-gate-check.mjs` }, + { path: "plugins/vibe/skills/fleet-orchestrator/scripts/push-proof.mjs" }, { path: "plugins/vibe/hooks/pr-create-guard.mjs" }, + { path: "plugins/vibe/skills/fleet-orchestrator/scripts/board.mjs", prefixesOnly: true }, +]); + +const PRODUCER = /\b([a-z][A-Za-z0-9]*Problems?)\(/g; +const PUSH_CHECK_PREFIX = /`([A-Z0-9]+(?:-[A-Z0-9]+)+) \$\{name\}/g; + +/** The refusal producers a gate source calls or prints: `*Problem(s)(` calls and push-check's `PREFIX ${name}` lines. */ +export function refusalProducers(source, { prefixesOnly = false } = {}) { + return new Set([...(prefixesOnly ? [] : source.matchAll(PRODUCER)), ...source.matchAll(PUSH_CHECK_PREFIX)].map((match) => match[1])); +} + +/** The replayed checks whose files a change touches. */ +export function replayedChecksTouched(paths) { + const changed = new Set(paths); + return Object.entries(REFUSING_CHECKS).filter(([, entry]) => entry.replay && entry.files.some((file) => changed.has(file))).map(([name]) => name); +} diff --git a/plugins/vibe-closedloop/provider/provider.json b/plugins/vibe-closedloop/provider/provider.json index 01c873c2..74144978 100644 --- a/plugins/vibe-closedloop/provider/provider.json +++ b/plugins/vibe-closedloop/provider/provider.json @@ -676,6 +676,23 @@ }, "testHistory": "^apps/desktop/test/" }, + "e2eRequirement": { + "workflow": ".github/workflows/e2e-test.yml", + "changesJob": "changes", + "filterStep": "filter", + "surfaces": { + "web": { + "job": "e2e", + "runs": "e2e", + "classifier": "changed-specs" + }, + "desktop": { + "job": "desktop-e2e", + "runs": "desktop_e2e", + "classifier": "desktop-changed-specs" + } + } + }, "cloudValidation": { "toolRoot": "plugins/vibe-closedloop", "desktopRoot": "apps/desktop", diff --git a/plugins/vibe-closedloop/skills/fleet-orchestrator/SKILL.md b/plugins/vibe-closedloop/skills/fleet-orchestrator/SKILL.md index 48dbcb54..3bce3546 100644 --- a/plugins/vibe-closedloop/skills/fleet-orchestrator/SKILL.md +++ b/plugins/vibe-closedloop/skills/fleet-orchestrator/SKILL.md @@ -122,7 +122,7 @@ Run [codex-fleet-monitor](../codex-fleet-monitor/SKILL.md) (`vibe:codex-fleet-mo - Answer a writer's question within 15 minutes, echoing its id (`board.mjs answered --id --text `); send other mid-run changes to what it builds as `deliver --kind scope --to --text `, a message naming the id, then `told`. The watcher and `board.mjs status` flag `QUESTION-UNANSWERED`, `UNACKED` and `UNACKED-SCOPE` after 15 minutes, and `SCOPE-NOT-STARTED` for a worktree still clean at its old head 30 minutes on. - On a `HOOK-APPROVAL ` line (that machine's Codex vibe or vibe-core changed version and a vibe-core hook now needs approval), relay it to the operator at once in one plain line; approving is theirs, never a worker's. - On `STALE-PR` (a PR needing its writer with no push for 45 minutes), ask the owning writer for an ETA, unblock it, or reassign it, whatever it reports being busy with. -- Push only a declared push-ready head (`--ready `, with `--visual-qa ` for a UI diff). Review and verification accept the uncommitted diff before its first commit; then commit once, declare, push once and open the PR. `writer --base ` records the verified pre-PR parent; parent commits are never ready. The live GitHub base is authoritative afterward. `push-check` must print `READY` (pass `--body ` once one exists; a vibe head missing proof receipts prints `PROOF-MISSING`, and one whose receipts are not readable here, such as a remote writer registered with `--branch vibe/`, prints `PROOF-UNCHECKED`, as does a writer with no local tree (remote, or registered without `--worktree`) and no `--branch` until it is registered again with one; other rows get a non-blocking `PROOF-UNCHECKED` note); `status`/`watch-lines` flag undeclared local commits as `UNREADY-COMMIT` and unreadable history/base as `PUSH-READY-UNKNOWN`. Restore evidence before pushing; cadence never authorizes checkpoint commits. Operator ruling, 2026-10-29: "every commit to an open PR is a sign of a bad orchestration framework. we should codify this to never happen again. we don't commit until we're sure that commit is push ready." +- Push only a declared push-ready head (`--ready `, with `--visual-qa ` for a UI diff). Review and verification accept the uncommitted diff before its first commit; then commit once, declare, push once and open the PR. `writer --base ` records the verified pre-PR parent; parent commits are never ready. The live GitHub base is authoritative afterward. `push-check` must print `READY` (pass `--body ` once one exists; a vibe head missing proof receipts prints `PROOF-MISSING`, and one whose receipts are not readable here, such as a remote writer registered with `--branch vibe/`, prints `PROOF-UNCHECKED`, as does a writer with no local tree (remote, or registered without `--worktree`) and no `--branch` until it is registered again with one; other rows get a non-blocking `PROOF-UNCHECKED` note; a local row whose PR postdates the pre-PR ruling gets advisory `CI-NOT-RUN` and `E2E-NOT-RUN` lines about missing runs); `status`/`watch-lines` flag undeclared local commits as `UNREADY-COMMIT` and unreadable history/base as `PUSH-READY-UNKNOWN`. Restore evidence before pushing; cadence never authorizes checkpoint commits. Operator ruling, 2026-10-29: "every commit to an open PR is a sign of a bad orchestration framework. we should codify this to never happen again. we don't commit until we're sure that commit is push ready." - For an in-flight branch that already has old checkpoint commits, treat its current pushed PR head as historical baseline. Never rewrite it or declare its ancestors ready; keep the next repair uncommitted until one new head is push-ready. A remote board row uses `--where remote --base `: `NO-HEAD` is informational because its owning machine checks history, while this board still requires the exact declared ready head before push. - Before opening a PR, reviewers inspect the uncommitted change identified by HEAD plus diff/tree hashes. After opening, compare published evidence with the pushed PR head (`gh pr view --json headRefOid`); observe automatically started checks and reviews, never manually trigger another review. diff --git a/plugins/vibe-closedloop/skills/fleet-orchestrator/scripts/board.mjs b/plugins/vibe-closedloop/skills/fleet-orchestrator/scripts/board.mjs index d946844e..7ab92200 100644 --- a/plugins/vibe-closedloop/skills/fleet-orchestrator/scripts/board.mjs +++ b/plugins/vibe-closedloop/skills/fleet-orchestrator/scripts/board.mjs @@ -64,6 +64,7 @@ // the recorded findings, and `status` prints `VISUAL-QA-MISSING ...` // for a ready head without them. A user-visible PR was reported ready to merge // with no visual QA on any head. +// Post-cutoff PR rows get advisory CI-NOT-RUN and E2E-NOT-RUN lines. // A writer records each question it sends you under an id (`question`), your // answer echoes that id (`answered`), and the writer acknowledges it in its next // status (`ack`). `status` prints `QUESTION-UNANSWERED m: @@ -139,7 +140,8 @@ const { readConfig, resolveWorkDir } = await vibeCore("lib/codex-fleet-monitor/s const { homeProblems, programShape, Shape } = await vibeCore("lib/fleet-orchestrator/scripts/fleet-home.mjs"); const { readSessionRecord } = await vibeCore("lib/vibe/scripts/session-record.mjs"); const { unitReviewProblem } = await vibeCore("lib/handoff/scripts/unit-review-record.mjs"); -const { failScript } = await vibeCore("lib/vibe/scripts/provider.mjs"); +const { fullCiProblem, pushCheckAsksPrePrChecks } = await vibeCore("lib/handoff/scripts/full-ci-check.mjs"); +const { failScript, sessionBinding } = await vibeCore("lib/vibe/scripts/provider.mjs"); const STATE = "board.json"; const PAGE = "board.md"; @@ -717,6 +719,12 @@ function boardAction({ workDir, action, values, positionals, orchDir, home }) { const remoteHost = row.where === "remote" ? readConfig(resolveWorkDir(orchDir)).REMOTE_HOST : undefined; // Older remote rows can carry only a ready SHA and visual evidence, with no repository or host to inspect. const headOnly = row.where === "remote" && !remoteHost && !row.repo && !row.releaseRuns; + // A row registered with a PR but no repository predates the gate: its PR's creation time cannot be read. + const created = row.where !== "remote" && row.pr ? (row.repo ? ghOid(row, "createdAt") : "1970-01-01T00:00:00Z") : null; + if (row.where !== "remote" && row.pr && !created) { + process.stdout.write(`CI-NOT-RUN ${name} ${values.head}: cannot determine which pre-PR checks apply to pull request ${row.pr}\n`); + } + const prePrChecks = pushCheckAsksPrePrChecks(created); if (row.worktree && !headOnly) { const git = (...args) => row.where === "remote" ? remoteWriterRead(remoteHost, ["git", "-C", row.worktree, ...args]) @@ -729,18 +737,24 @@ function boardAction({ workDir, action, values, positionals, orchDir, home }) { const problem = !base ? "missing trusted release base" : releaseSuiteProblem(git, base, head, report); if (problem) { process.stdout.write(`NOT-READY ${name}: ${problem}\n`); return 1; } } + if (row.where !== "remote" && prePrChecks) { + const prefix = `CI-NOT-RUN ${name} ${values.head}:`; + try { + const ci = fullCiProblem(row.worktree, head, { bodyText: () => values.body ? readFileSync(values.body, "utf8") : "", binding: sessionBinding(row.worktree) }); + if (ci) process.stdout.write(`${prefix} ${ci}\n`); + } catch (error) { + process.stdout.write(`${prefix} could not check CI evidence: ${error.message}\n`); + } + } } const visual = readyVisualQaProblem(row); if (visual) { process.stdout.write(`VISUAL-QA-MISSING ${name} head ${values.head}: ${visual}\n`); return 1; } - const trustedBase = () => { - const git = (...args) => repositoryGit(row.worktree, args); - let published; try { published = git("rev-parse", "@{upstream}"); } catch { published = null; } - return trustedBaseOid(row, git, published); - }; - const proof = pushProofLines(name, row, { ...values, trustedBase }); + const published = () => { try { return repositoryGit(row.worktree, ["rev-parse", "@{upstream}"]); } catch { return null; } }; + const trustedBase = () => trustedBaseOid(row, (...args) => repositoryGit(row.worktree, args), published()); + const proof = pushProofLines(name, row, { ...values, trustedBase, published, prePrChecks }); if (proof.refuse.length) { for (const line of proof.refuse) process.stdout.write(`${line}\n`); return 1; diff --git a/plugins/vibe-closedloop/skills/fleet-orchestrator/scripts/push-proof.mjs b/plugins/vibe-closedloop/skills/fleet-orchestrator/scripts/push-proof.mjs index b2bb180d..a7c6214d 100644 --- a/plugins/vibe-closedloop/skills/fleet-orchestrator/scripts/push-proof.mjs +++ b/plugins/vibe-closedloop/skills/fleet-orchestrator/scripts/push-proof.mjs @@ -1,20 +1,24 @@ // Proof lines for a fleet writer's push-ready head, read by board.mjs push-check (proof-receipts.mjs holds the checks). -import { readFileSync } from "node:fs"; +import { existsSync, readFileSync } from "node:fs"; import { vibeCore } from "../../../shared/vibe-core.mjs"; const { readSessionRecord } = await vibeCore("lib/vibe/scripts/session-record.mjs"); const { bodyCommandProblems, pushReadyProofProblems } = await vibeCore("lib/handoff/scripts/proof-receipts.mjs"); const { gatePath } = await vibeCore("lib/handoff/scripts/handoff-gate-check.mjs"); +const { e2eGateProblems } = await vibeCore("lib/handoff/scripts/e2e-gate-check.mjs"); +const { sessionBinding } = await vibeCore("lib/vibe/scripts/provider.mjs"); /** * Proof lines for a writer's head. A vibe row (a readable session record, or a `vibe/` branch) is refused when its * receipts are missing or unreadable here, and so is a row with no local tree and no branch, remote or not, whose kind * cannot be read; any other row has only its PR body's commands checked and a note for the rest (orchestrator rulings, - * 2026-11-25 and 2026-11-26). `trustedBase` returns the base a local vibe row's receipts are checked against. `refuse` - * lines hold READY; `notes` print after it. + * 2026-11-25 and 2026-11-26). `trustedBase` returns the base a local vibe row's receipts are checked against, and + * `published` its upstream head: a test case unchanged since that pushed head needs no mutation proof here, though the + * proof checks before PR create still ask (proof-scope.mjs). With `prePrChecks`, a local row gets advisory e2e notes + * only. `refuse` lines hold READY; `notes` print after it. */ -export function pushProofLines(name, row, { head, body, trustedBase }) { +export function pushProofLines(name, row, { head, body, trustedBase, published = () => null, prePrChecks = false }) { const local = Boolean(row?.worktree) && row.where !== "remote"; const session = local ? readSessionRecord(row.worktree) : null; if (!session && /^vibe\//.test(row?.branch ?? "")) { @@ -24,12 +28,26 @@ export function pushProofLines(name, row, { head, body, trustedBase }) { const registered = row?.where === "remote" ? "a remote row registered without --branch" : "a row registered with no --worktree and no --branch"; return { refuse: [`PROOF-UNCHECKED ${name} ${head}: ${registered} has no readable kind; re-register it with board.mjs writer ${name} --branch so the kind can be read; it is not ready`], notes: [] }; } + const e2eLines = (bodyFile, binding) => { + if (!prePrChecks || !local) return []; + const prefix = `E2E-NOT-RUN ${name} ${head}:`; + try { + return e2eGateProblems(row.worktree, { base: trustedBase, head, binding, + bodyText: () => bodyFile && existsSync(bodyFile) ? readFileSync(bodyFile, "utf8") : "" }).map((problem) => `${prefix} ${problem}`); + } catch (error) { + return [`${prefix} could not check e2e evidence: ${error.message}`]; + } + }; if (session) { - return { refuse: pushReadyProofProblems(row.worktree, { base: trustedBase(), head, bodyFile: body, witness: gatePath(row.worktree) }) - .map((problem) => `PROOF-MISSING ${name} ${head}: ${problem}`), notes: [] }; + const pushed = published(); + const witness = gatePath(row.worktree); + const boundBody = existsSync(witness) ? JSON.parse(readFileSync(witness, "utf8")).evidence?.body?.path : null; + return { refuse: [...pushReadyProofProblems(row.worktree, { base: trustedBase(), head, bodyFile: body, witness, pushed: pushed ? [pushed] : [] }) + .map((problem) => `PROOF-MISSING ${name} ${head}: ${problem}`)], notes: e2eLines(body ?? boundBody, sessionBinding(row.worktree)) }; } const notes = [`PROOF-UNCHECKED ${name} ${head}: not a vibe row; reproduction, mutation proofs and ticket commands are not checked`]; - if (!body) return { refuse: [], notes }; + if (!body) return { refuse: [], notes: [...notes, ...e2eLines(null, null)] }; if (!local) return { refuse: [], notes: [...notes, `PROOF-UNCHECKED ${name} ${head}: no local receipt to check the PR body's commands against`] }; - return { refuse: bodyCommandProblems(row.worktree, { head, bodyText: readFileSync(body, "utf8") }).map((problem) => `PROOF-MISSING ${name} ${head}: ${problem}`), notes }; + return { refuse: bodyCommandProblems(row.worktree, { head, bodyText: readFileSync(body, "utf8") }).map((problem) => `PROOF-MISSING ${name} ${head}: ${problem}`), + notes: [...notes, ...e2eLines(body, null)] }; } diff --git a/plugins/vibe-closedloop/skills/handoff/scripts/handoff-gate.mjs b/plugins/vibe-closedloop/skills/handoff/scripts/handoff-gate.mjs index 89f88719..614da433 100644 --- a/plugins/vibe-closedloop/skills/handoff/scripts/handoff-gate.mjs +++ b/plugins/vibe-closedloop/skills/handoff/scripts/handoff-gate.mjs @@ -42,7 +42,8 @@ const { exitOnProviderBroken, sessionBinding } = await vibeCore("lib/vibe/script const { changedPaths, readVisualQaFindings, recordVerifiedDispositions, visualQaRequired } = await vibeCore("lib/vibe/scripts/required-visual-qa.mjs"); const { placementLineProblem } = await vibeCore("lib/fleet-orchestrator/scripts/delivery-placement.mjs"); const { readSessionRecord } = await vibeCore("lib/vibe/scripts/session-record.mjs"); -const { proofGateProblems, proofTicketText } = await vibeCore("lib/handoff/scripts/proof-receipts.mjs"); +const { passedGateHeads, proofGateProblems, proofTicketText, recordGatePass } = await vibeCore("lib/handoff/scripts/proof-receipts.mjs"); +const { e2eGateProblems } = await vibeCore("lib/handoff/scripts/e2e-gate-check.mjs"); const { OVERRIDE_CHECKS, overriddenChecks, readPrBodyEvidence } = await vibeCore("lib/handoff/scripts/gate-override.mjs"); /** Refresh the actual main branch before a publication witness can be recorded. */ @@ -165,7 +166,7 @@ export function visualQaGate(worktree, baseOid, head, findings, binding = sessio } /** Run the canonical inventory with PR body and verifier evidence before recording readiness. */ -export function recordHandoffGate({ worktree, body, runs, ticket, rulings, base, receipts, audit, matrix, members = [], prds = [], plans = [], review, title, visualQa }, { runScript = spawnSync } = {}) { +export function recordHandoffGate({ worktree, body, runs, ticket, rulings, base, receipts, audit, matrix, members = [], prds = [], plans = [], review, title, visualQa }, { runScript = spawnSync, warn = (line) => process.stderr.write(`${line}\n`) } = {}) { const witness = gatePath(worktree); if (existsSync(witness)) unlinkSync(witness); fetchCurrentMain(worktree); @@ -204,9 +205,22 @@ export function recordHandoffGate({ worktree, body, runs, ticket, rulings, base, // The PR-create hook refuses an active session's PR without one placement line; checking it here keeps the gated body final. const placement = session?.status === "active" ? placementLineProblem(bodyText) : null; if (placement) throw new Error(placement); - const proofs = proofGateProblems(worktree, { base: targets.base.oid, bodyText, - ticketText: proofTicketText(ticket, members.map((member) => member.slice(member.indexOf("=") + 1))), runs: runsEvidence }); - if (proofs.length) throw new Error(`proof receipts: ${proofs.join("; ")}`); + // A head that passed this gate counts; a pushed one does not, since a redeploy push never passed it (proof-scope.mjs). + let proofAccepted = { passed: [] }; + let proofs; + try { + proofAccepted = { passed: passedGateHeads(worktree) }; + proofs = proofGateProblems(worktree, { base: targets.base.oid, bodyText, + ticketText: proofTicketText(ticket, members.map((member) => member.slice(member.indexOf("=") + 1))), runs: runsEvidence, accepted: proofAccepted }); + } catch (error) { + proofs = [`could not check proof evidence: ${error.message}`]; + } + for (const problem of proofs) warn(`PROOF-MISSING: ${problem}`); + try { + for (const problem of e2eGateProblems(worktree, { base: targets.base.oid, bodyText, binding })) warn(`E2E-NOT-RUN: ${problem}`); + } catch (error) { + warn(`E2E-NOT-RUN: could not check e2e evidence: ${error.message}`); + } const evidenceInputs = { body, runs, ticket, rulings, audit, matrix, review }; const evidence = { body: bodyEvidence.fingerprint, runs: checkedRuns.fingerprint }; const manifest = new Map(); @@ -259,7 +273,8 @@ export function recordHandoffGate({ worktree, body, runs, ticket, rulings, base, ...(inventory.pathCitations?.length ? { pathCitations: inventory.pathCitations, pathCitationEvidence: inventory.pathCitationEvidence } : {}), reviewCarry: [...reusableRoles].sort(), memberTickets, unitReviewPassed: Boolean(review), visualQa: { required: visual.required, reason: visual.reason, findings: visual.required ? visual.fingerprint : null, ...(visual.dispositions ? { dispositions: visual.dispositions } : {}) }, inventoryPassed: true, - prBodyPassed: true, prEvidencePassed: true, reviewPassed: true, ...(overridden ? { inventoryOverride: "diffRulesClear" } : {}) })}\n`, { mode: 0o600 }); + prBodyPassed: true, prEvidencePassed: true, reviewPassed: true, proofAccepted, ...(overridden ? { inventoryOverride: "diffRulesClear" } : {}) })}\n`, { mode: 0o600 }); + if (!proofs.length) recordGatePass(worktree, source); return { branch, source }; } diff --git a/plugins/vibe-closedloop/skills/handoff/scripts/pr-facts.mjs b/plugins/vibe-closedloop/skills/handoff/scripts/pr-facts.mjs index 7ccb16cc..c4e0f7d1 100644 --- a/plugins/vibe-closedloop/skills/handoff/scripts/pr-facts.mjs +++ b/plugins/vibe-closedloop/skills/handoff/scripts/pr-facts.mjs @@ -876,8 +876,9 @@ export function ciCheckProblems(runsFile, changed, commit) { /** * The Desktop Electron lane cannot run on a machine without the displayless * Linux harness, and vibe never launches Electron natively; there - * `pre-pr-lanes.mjs check` records it `not-run` and the post-merge - * `desktop-e2e/validated` run covers it. + * `pre-pr-lanes.mjs check` records it `not-run`, and the facts carry that + * record. The e2e gate (e2e-gate-check.mjs) still owes the lane until it runs + * in cloud validation or on the heavy host. */ function desktopLeftForCi(run) { return run?.status === "not-run" && isDesktopE2eLane(run.command ?? "") && text(run.reason); diff --git a/plugins/vibe-closedloop/skills/vibe/references/environment.md b/plugins/vibe-closedloop/skills/vibe/references/environment.md index 2e18f8f6..b331c646 100644 --- a/plugins/vibe-closedloop/skills/vibe/references/environment.md +++ b/plugins/vibe-closedloop/skills/vibe/references/environment.md @@ -453,9 +453,10 @@ main repeatedly while CI waits. CI is per push; `qa-impact.mjs` decides local QA The Desktop Electron lane is the exception: no vibe machine runs it, and since symphony-alpha's desktop-e2e job skips pull requests no run exists for a branch before merge. The executor returns it under -`e2eLeftForCi`, covered by the post-merge desktop-e2e-validation run that -publishes `desktop-e2e/validated`, and it does not hold -`requiredE2eComplete`. The ticket's Engineering checklist carries it +`e2eLeftForCi`, and it does not hold `requiredE2eComplete`. The post-merge +desktop-e2e-validation run that publishes `desktop-e2e/validated` does not +cover it before a pull request: the lane runs in cloud validation or on the +heavy host first. The ticket's Engineering checklist carries it (`ticket-template.md`, "E2E left for CI"). An operator-dispatched run bound through `mainSyncCiRun` still verifies as above and replaces that entry. diff --git a/plugins/vibe-closedloop/skills/vibe/scripts/e2e-requirement.mjs b/plugins/vibe-closedloop/skills/vibe/scripts/e2e-requirement.mjs new file mode 100644 index 00000000..9223dad6 --- /dev/null +++ b/plugins/vibe-closedloop/skills/vibe/scripts/e2e-requirement.mjs @@ -0,0 +1,569 @@ +#!/usr/bin/env node +// The e2e specs a change owes locally before its pull request opens, beyond what the graph test selector chose. The +// repository's rule: an e2e lane is satisfied by the graph-selected specs, plus specs the branch's own changes newly +// reach, plus every spec the change adds or edits; without a graph result, by the CI changes job's changed-spec union, +// and by the whole lane wherever that union cannot narrow. A pull request once changed a shared e2e helper, six +// stories and one spec, ran two targeted specs, and broke main in a spec that opens one of those stories by its +// Storybook URL. The graph selector cannot see that edge (a spec reaches its story through the id parameter of the iframe page, +// not an import), so this module computes it: a changed story owes every suite spec that names the story's id, read +// at `head`; a story whose id or whose specs cannot be found completely owes the whole lane. +// +// The provider names the workflow, its change-detection job, the paths-filter step and, per surface, the suite job, +// the filter that decides whether that job runs and the step that lists its narrowable specs. Everything else comes +// from the workflow file at `head` (git show, never a copy): the filter globs, and the classifier step's own shell, +// which runs read-only in a scratch folder holding only the files it reads. A workflow this reader cannot parse, or a +// classifier it cannot run as CI runs it, owes the whole lane when there is no graph result; it never narrows. +// +// Usage: e2e-requirement.mjs --worktree --base --head +// prints one JSON line per surface (no graph result: the changes-job fallback); nothing when no provider declares one. + +import { spawnSync } from "node:child_process"; +import { mkdirSync, mkdtempSync, readFileSync, rmSync, symlinkSync, writeFileSync, lstatSync, readlinkSync } from "node:fs"; +import path from "node:path"; +import { parseArgs } from "node:util"; +import { vibeCore } from "../../../shared/vibe-core.mjs"; +import { isEntryPoint } from "../../../shared/plugin-roots.mjs"; + +import { containerizedIntent } from "../../../lib/vibe/scripts/docker-disk-admission.mjs"; +import { LANE_RECORDS_FILE } from "./lane-outcomes.mjs"; +import { witnessProblem } from "./lane-witness-check.mjs"; + +const { git } = await vibeCore("lib/vibe/scripts/session-record.mjs"); +const { boundWith, installedProviders } = await vibeCore("lib/vibe/scripts/provider.mjs"); + +export const E2eSurface = Object.freeze({ Web: "web", Desktop: "desktop" }); +export const NO_GRAPH = "no graph test selection for this change: the changes job's changed-spec union applies"; +export const FULL_LANE = "full"; +// The repo's web Playwright lanes (`pnpm test:e2e`, `pnpm test:web-smoke`); a lane naming desktop is the Electron one. +const WEB_E2E_LANE = /\b(?:test:e2e|test:web-smoke)\b/; +// Match the desktop path, workspace selector, or the npm script suffix used by the runners. +const DESKTOP_LANE = /(?:^|[\s/=:])desktop(?=$|[\s/:'"])/; +const STORY = /\.stories\.[cm]?[jt]sx?$/; +const SPEC = /\.spec\.[cm]?[jt]sx?$/; +const STORY_URL = `iframe.html${"?id="}`; +const DEFAULT_EXPORT = /^export default (?:(\{)|([A-Za-z_$][\w$]*);?\s*$)/; +const META_TITLE = /^ {2}title:\s*(["'`])((?:(?!\1).)*)\1,?\s*$/; +const WRAPPED_TITLE_KEY = /^ {2}title:\s*$/; +const FILES_OUTPUT = /^\$\{\{\s*steps\.([A-Za-z0-9_-]+)\.outputs\.([A-Za-z0-9_-]+)_files\s*\}\}$/; +const EVENT_EXPRESSION = /^\$\{\{\s*github\.event_name\s*\}\}$/; +const EXPRESSION = /\$\{\{/; +const PATH_TOKEN = /[A-Za-z0-9._-]+(?:\/[A-Za-z0-9._-]+)+/g; +const SAFE_SHELL_WORD = /^[\w@%+=:,./-]+$/; +const CLASSIFIER_TIMEOUT_MS = 10_000; +const GREP_BUFFER = 256 * 1024 * 1024; +// Where a lane this machine recorded not-run does run (orchestrator ruling). +export const RUN_ELSEWHERE = Object.freeze({ + [E2eSurface.Web]: "in the containerized web lane, or on the heavy host with pre-pr-lanes.mjs run --fleet-where remote", + [E2eSurface.Desktop]: "in cloud validation, which runs the whole Desktop suite, or on the heavy host with pre-pr-lanes.mjs run --fleet-where remote", +}); +// Lane results pre-pr-lanes.mjs check accepts as a run of the lane (a cached record is not one; not-run is left to CI). +const RAN_RESULTS = new Set(["pass", "env-skip", "main-preexisting"]); + +/** + * What the change from `base` to `head` owes each e2e lane the provider declares: + * `[{ surface, required, full, reasons, lane, specs }]`. `specs` are the specs owed beyond the graph selection (those a + * changed story's id reaches, those that import a file the change adds, and the surface's changed specs). `full` is true + * only for a fallback: a changed story whose specs cannot be found completely, or, with no graph result for the surface + * (`graphSelection[surface]` not a list), a change the changes job's union cannot narrow. `reasons` name the story ids that + * added specs, the incomplete story, or the missing graph and the paths the union could not narrow. + * `binding` is the session's provider binding; with none (a row outside a vibe session) the installed provider serving + * this repository's origin is read. `files` replaces the committed diff with the caller's changed-file set, read from + * the worktree (uncommitted files included). [] when no provider declares a workflow for this repository. + */ +export function e2eLaneRequirement(worktree, { base, head, binding = null, files, graphSelection = null, providers } = {}) { + const declared = declaredRequirement(worktree, binding, providers); + if (!declared) return []; + const source = files ? worktreeSource(worktree, head) : treeSource(worktree, head); + const changed = files ? [...new Set(files)].sort() : changedFiles(worktree, base, head); + const added = base ? changed.filter((file) => !existsAt(worktree, base, file)) : []; + const surfaces = Object.entries(declared.surfaces ?? {}); + let workflow; + try { + workflow = readWorkflow(worktree, head, declared); + } catch (error) { + const why = `${declared.workflow} at ${head.slice(0, 12)} cannot be read as CI reads it (${error.message})`; + return surfaces.map(([surface, spec]) => ({ surface, required: true, full: true, reasons: [why], lane: laneName(declared, spec), specs: [] })); + } + const context = { worktree, head, base, source, changed, added, declared, workflow, fromWorktree: Boolean(files) }; + return surfaces.map(([surface, spec]) => surfaceRequirement(context, surface, spec, graphSelection?.[surface])); +} + +/** + * What the change still owes after `receipts`, the passing local runs (`[{ surface, full, specs }]`; a `full` run of a + * surface covers all of it), and `notRun`, the lanes recorded not-run (recordedE2eEvidence's): `[{ surface, spec, reason }]`, + * with `spec` "full" where only the whole lane will do, and [] when nothing is owed. A not-run lane satisfies nothing + * unless its record quotes the skip ruling that waived it (orchestrator ruling); otherwise its rows stay owed + * and their reason names where the lane does run. `graphSelection` and the other options are e2eLaneRequirement's. + */ +export function missingE2eSpecs(worktree, { receipts = [], notRun = [], ...options } = {}) { + return e2eLaneRequirement(worktree, options).filter((row) => row.required).flatMap((row) => { + const runs = receipts.filter((receipt) => receipt?.surface === row.surface); + if (runs.some((receipt) => receipt.full === true)) return []; + const left = notRun.filter((entry) => entry?.surface === row.surface); + if (left.some((entry) => entry.ruling)) return []; + const where = left.length ? `; recorded not-run here, which satisfies nothing: run it ${RUN_ELSEWHERE[row.surface]}` : ""; + if (row.full) return [{ surface: row.surface, spec: FULL_LANE, reason: `${row.reasons.join("; ")}${where}` }]; + const ran = new Set(runs.flatMap((receipt) => receipt.specs ?? [])); + const owed = [...new Set([...(options.graphSelection?.[row.surface] ?? []), ...row.specs])].sort(); + return owed.filter((spec) => !ran.has(spec)).map((spec) => ({ surface: row.surface, spec, + reason: `${row.specs.includes(spec) ? specReason(row) : "selected by the graph"}${where}` })); + }); +} + +function specReason(row) { + const ids = row.reasons.filter((reason) => reason !== NO_GRAPH); + return ids.length ? `changed, reached by an added file, or naming a changed story (${ids.join(", ")})` : "changed or reached by an added file"; +} + +/** Whether a lane is the repo's local web e2e lane. */ +export function isWebE2eLane(lane) { + return WEB_E2E_LANE.test(lane) && !DESKTOP_LANE.test(lane); +} + +/** Whether a lane is the repo's Desktop Electron e2e lane. */ +export function isDesktopE2eLane(lane) { + return WEB_E2E_LANE.test(lane) && DESKTOP_LANE.test(lane); +} + +/** The e2e surface a recorded lane command runs, or null: the web Playwright lane or its containerized form, or the Desktop one. */ +export function laneSurface(command) { + if (isDesktopE2eLane(command)) return E2eSurface.Desktop; + if (isWebE2eLane(command) || (!DESKTOP_LANE.test(command) && containerizedIntent("sh", ["-c", command]))) return E2eSurface.Web; + return null; +} + +/** + * The e2e evidence pre-pr-lanes.mjs recorded for `head` (default: the worktree's HEAD) in the session's lane records. + * `receipts`: one per witnessed e2e lane run that `check` accepts as run (`pass`, `env-skip`, `main-preexisting`), `full` + * unless it was a targeted run, with the specs it ran. `notRun`: the e2e lanes recorded not-run, with the record's reason + * and the skip ruling it quotes (`{ id, source }`, else null); only a quoted ruling lets one stand in for a run. `graphSelection`: the union of the graph selections the targeted records carry, + * null when none does. No records (a worktree outside a vibe session) is empty evidence; an unparseable file throws. + */ +export function recordedE2eEvidence(worktree, { head } = {}) { + const empty = { graphSelection: null, receipts: [], notRun: [] }; + let file; + try { file = path.join(git(worktree, ["rev-parse", "--absolute-git-dir"]), LANE_RECORDS_FILE); } catch { return empty; } + let text; + try { text = readFileSync(file, "utf8"); } catch (error) { if (error?.code === "ENOENT") return empty; throw error; } + const records = JSON.parse(text); + if (!Array.isArray(records)) throw new Error(`${file} is not a list of lane records`); + const at = head ?? git(worktree, ["rev-parse", "HEAD"]); + const current = records.filter((record) => record?.head === at && typeof record.command === "string" && laneSurface(record.command)); + const ran = current.filter((record) => RAN_RESULTS.has(record.result) && !witnessProblem(record)); + const receipts = ran.map((record) => ({ surface: laneSurface(record.command), lane: record.command, result: record.result, + full: !record.targeted, specs: Array.isArray(record.targeted?.specs) ? [...record.targeted.specs] : [] })); + const notRun = current.filter((record) => record.result === "not-run").map((record) => ({ surface: laneSurface(record.command), + lane: record.command, reason: record.reason ?? null, ruling: quotedRuling(record) })); + let graphSelection = null; + for (const result of ran.map((record) => record.targeted?.graph?.result).filter(Boolean)) { + for (const surface of Object.values(E2eSurface)) { + if (!Array.isArray(result[surface])) continue; + graphSelection ??= {}; + graphSelection[surface] = [...new Set([...(graphSelection[surface] ?? []), ...result[surface]])].sort(); + } + } + return { graphSelection, receipts, notRun }; +} + +/** + * The `recipes.e2eRequirement` block of the provider serving this worktree's origin (its `memory.repository.remote`), + * or null: the bound provider's in a session, else each installed one's. + */ +function declaredRequirement(worktree, binding, providers) { + let origin = ""; + try { origin = git(worktree, ["config", "--get", "remote.origin.url"]); } catch { return null; } + const contracts = binding ? [boundWith(binding, "recipes")?.contract] : (providers ?? installedProviders({ cwd: worktree })).map((item) => item.contract); + for (const contract of contracts) { + const remote = contract?.data?.memory?.repository?.remote; + const block = contract?.data?.recipes?.e2eRequirement; + if (block && typeof remote === "string" && new RegExp(remote).test(origin)) return block; + } + return null; +} + +/** Whether a provider (the bound one, else each installed one) declares e2e lanes for this repository's origin. */ +export function e2eRequirementDeclared(worktree, binding = null) { + return declaredRequirement(worktree, binding) !== null; +} + +function laneName(declared, spec) { + return `${path.posix.basename(declared.workflow)}:${spec.job}`; +} + +function changedFiles(worktree, base, head) { + return git(worktree, ["diff", "--name-only", "--no-renames", "-z", base, head, "--"]).split("\0").filter(Boolean).sort(); +} + +function existsAt(worktree, commit, file) { + return spawnSync("git", ["-C", worktree, "cat-file", "-e", `${commit}:${file}`]).status === 0; +} + +function surfaceRequirement(context, surface, spec, graphSelection) { + const { declared, workflow, changed } = context; + const lane = laneName(declared, spec); + const row = (fields) => ({ surface, required: true, full: false, reasons: [], lane, specs: [], ...fields }); + let runs, suiteGlobs, classifier; + try { + const globs = (key) => { + if (!workflow.filters[key]) throw new Error(`the ${workflow.filterStep} step declares no ${key} filter`); + return workflow.filters[key]; + }; + runs = changed.filter((file) => globs(spec.runs).some((glob) => glob.test(file))); + classifier = workflow.steps.get(spec.classifier); + if (!classifier) throw new Error(`the changes job has no ${spec.classifier} step`); + suiteGlobs = globs(classifierInput(classifier).filter); + } catch (error) { + return row({ full: true, reasons: [`${declared.workflow}: ${error.message}`] }); + } + const inSuite = (file) => suiteGlobs.some((glob) => glob.test(file)); + const stories = storyReach(context, inSuite); + const reached = newlyReached(context, inSuite); + const changedSpecs = changed.filter((file) => SPEC.test(file) && inSuite(file) && context.source.exists(file)); + if (runs.length === 0 && stories.specs.length === 0 && stories.incomplete.length === 0 && reached.length === 0) { + return row({ required: false }); + } + const owed = (extra) => [...new Set([...stories.specs, ...reached, ...extra])].sort(); + if (stories.incomplete.length) return row({ full: true, reasons: stories.incomplete, specs: owed(changedSpecs) }); + if (Array.isArray(graphSelection)) return row({ reasons: stories.ids, specs: owed(changedSpecs) }); + const suite = changed.filter(inSuite); + if (suite.length === 0) return row({ reasons: [NO_GRAPH, ...stories.ids], specs: owed([]) }); + try { + // The whole set decides, as in CI; each path is then asked alone so the reasons name only those it cannot narrow. + const narrowed = runClassifier(context, classifier, suite); + if (narrowed.length > 0) return row({ reasons: [NO_GRAPH, ...stories.ids], specs: owed(changedSpecs) }); + const blocking = suite.filter((file) => runClassifier(context, classifier, [file]).length === 0); + return row({ full: true, reasons: [NO_GRAPH, ...(blocking.length ? blocking : suite)], specs: owed(changedSpecs) }); + } catch (error) { + return row({ full: true, reasons: [NO_GRAPH, `${spec.classifier} could not run as CI runs it (${error.message})`], specs: owed(changedSpecs) }); + } +} + +/** + * The suite specs that name a changed story's Storybook id (its component id, the sanitized meta title, which every + * story id in the file starts with), directly or through a helper they import. `incomplete` names each story whose + * title is not a plain literal, or whose id appears in a helper no spec imports by name. + */ +function storyReach(context, inSuite) { + const ids = new Map(); + const incomplete = []; + for (const file of context.changed.filter((entry) => STORY.test(entry))) { + const text = context.source.read(file) ?? (context.base ? showAt(context.worktree, context.base, file) : null); + const title = text === null ? null : metaTitle(text); + if (title === null) incomplete.push(`${file}: no literal Storybook title to derive its story ids from`); + else ids.set(storybookId(title), file); + } + if (ids.size === 0 && incomplete.length === 0) return { specs: [], ids: [], incomplete }; + // A surface none of whose specs opens a story by URL, itself or through a helper it imports, cannot reach one. + const opening = [...new Set(context.source.grep([STORY_URL]).map(({ file }) => file).filter(inSuite))]; + if (!opening.some((file) => SPEC.test(file) || importingSpecs(context, inSuite, file).length > 0)) return { specs: [], ids: [], incomplete: [] }; + if (ids.size === 0) return { specs: [], ids: [], incomplete }; + // A spec may hold the component id alone and append the story name; any other file counts only for a whole story id. + const named = (id, file) => new RegExp(`(? inSuite(file)); + const specs = new Set(); + const used = new Set(); + for (const id of ids.keys()) { + const files = [...new Set(hits.filter(({ file, line }) => named(id, file).test(line)).map(({ file }) => file))]; + for (const file of files) { + const reaching = SPEC.test(file) ? [file] : importingSpecs(context, inSuite, file); + if (reaching.length === 0) incomplete.push(`${ids.get(id)}: story id ${id} appears in ${file}, which no spec imports by name`); + for (const spec of reaching) { specs.add(spec); used.add(id); } + } + } + return { specs: [...specs].sort(), ids: [...used].sort(), incomplete }; +} + +/** Suite specs that import a non-spec file the change adds, which the trunk-indexed graph cannot have seen. */ +function newlyReached(context, inSuite) { + const specs = new Set(); + for (const file of context.added.filter((entry) => inSuite(entry) && !SPEC.test(entry) && context.source.exists(entry))) { + for (const spec of importingSpecs(context, inSuite, file)) specs.add(spec); + } + return [...specs].sort(); +} + +/** Suite specs whose import specifier ends in `file`'s module name (`.../` or `.../.`). */ +function importingSpecs(context, inSuite, file) { + const name = path.posix.basename(file).replace(/\.[cm]?[jt]sx?$/, ""); + const specifier = new RegExp(`(?:from|import\\()\\s*["'][^"']*/${escapeRegExp(name)}(?:\\.[cm]?[jt]sx?)?["']`); + return [...new Set(context.source.grep([`/${name}`]).filter(({ file: hit, line }) => hit !== file && SPEC.test(hit) && inSuite(hit) && specifier.test(line)) + .map(({ file: hit }) => hit))].sort(); +} + +/** The default-exported Storybook meta's `title` when it is a plain string literal, else null. */ +export function metaTitle(text) { + const lines = text.split("\n"); + let start = -1; + for (const [index, line] of lines.entries()) { + const match = DEFAULT_EXPORT.exec(line); + if (!match) continue; + if (match[1]) { start = index; break; } + const declaration = new RegExp(`^(?:export )?(?:const|let|var) ${escapeRegExp(match[2])}\\b[^=]*=\\s*\\{\\s*$`); + start = lines.findIndex((entry) => declaration.test(entry)); + break; + } + if (start < 0) return null; + const titles = []; + const body = lines.slice(start + 1); + for (const [index, line] of body.entries()) { + if (/^\}/.test(line)) break; + // A formatter wraps a long title onto the line after its key. + const match = META_TITLE.exec(WRAPPED_TITLE_KEY.test(line) ? ` title: ${(body[index + 1] ?? "").trim()}` : line); + if (match) titles.push(match[1] === "`" && match[2].includes("${") ? null : match[2]); + } + return titles.length === 1 ? titles[0] : null; +} + +/** Storybook's id for a title (its `sanitize`): lower case, punctuation and spaces to single dashes. */ +export function storybookId(title) { + return title.toLowerCase().replace(/[ ’–—―′¿'`~!@#$%^&*()_|+\-=?;:'",.<>{}[\]\\/]/gi, "-").replace(/-+/g, "-").replace(/^-+/, "").replace(/-+$/, ""); +} + +function showAt(worktree, commit, file) { + const result = spawnSync("git", ["-C", worktree, "show", `${commit}:${file}`], { encoding: "utf8", maxBuffer: GREP_BUFFER }); + return result.status === 0 ? result.stdout : null; +} + +/** Reads, lists and greps the committed tree at `head`. */ +function treeSource(worktree, head) { + return { + read: (file) => showAt(worktree, head, file), + exists: (file) => existsAt(worktree, head, file), + grep: (patterns) => grepLines(worktree, [head], patterns, `${head}:`), + }; +} + +/** Reads, lists and greps the worktree's files as they are now, untracked ones included. */ +function worktreeSource(worktree) { + const on = (file) => path.join(worktree, file); + return { + read: (file) => { try { return readFileSync(on(file), "utf8"); } catch { return null; } }, + exists: (file) => { try { return lstatSync(on(file)).isFile() || lstatSync(on(file)).isSymbolicLink(); } catch { return false; } }, + grep: (patterns) => grepLines(worktree, ["--untracked"], patterns, ""), + }; +} + +/** `git grep -F` for any of `patterns`, as `{ file, line }`; a grep that fails throws. */ +function grepLines(worktree, scope, patterns, prefix) { + const result = spawnSync("git", ["-C", worktree, "grep", "-I", "-F", ...patterns.flatMap((pattern) => ["-e", pattern]), ...scope, "--"], + { encoding: "utf8", maxBuffer: GREP_BUFFER }); + if (result.status === 1) return []; + if (result.status !== 0) throw new Error(`git grep failed: ${(result.stderr ?? "").trim()}`); + return result.stdout.split("\n").filter(Boolean).map((entry) => { + const rest = entry.slice(prefix.length); + const at = rest.indexOf(":"); + return { file: rest.slice(0, at), line: rest.slice(at + 1) }; + }); +} + +/** The classifier step's inputs: the filter whose `_files` list it reads, the env name, and the event variable. */ +function classifierInput(step) { + let input = null; + const env = {}; + for (const [key, value] of Object.entries(step.env)) { + const files = FILES_OUTPUT.exec(value); + if (files) { + if (input) throw new Error(`${step.id} reads more than one changed-file list`); + input = { filter: files[2], name: key }; + } else if (EVENT_EXPRESSION.test(value)) { + env[key] = "pull_request"; + } else if (EXPRESSION.test(value)) { + throw new Error(`${step.id} binds ${key} to an expression this reader cannot evaluate`); + } else { + env[key] = value; + } + } + if (!input) throw new Error(`${step.id} reads no changed-file list`); + if (!step.run || EXPRESSION.test(step.run)) throw new Error(`${step.id} has no plain shell run`); + return { ...input, env }; +} + +/** + * Runs the classifier step's own shell, as the changes job runs it on a pull request, in a scratch folder holding the + * changed suite files and every repository file its script names, as they are at `head`. Returns the specs it names. + */ +function runClassifier({ worktree, head, fromWorktree }, step, suite) { + const input = classifierInput(step); + const gitDir = git(worktree, ["rev-parse", "--absolute-git-dir"]); + const scratch = mkdtempSync(path.join(gitDir, "vibe-e2e-classifier-")); + try { + const tree = path.join(scratch, "tree"); + mkdirSync(tree); + const scripts = [...new Set(step.run.match(PATH_TOKEN) ?? [])]; + for (const file of [...new Set([...suite, ...scripts])]) materialize(worktree, head, tree, file, fromWorktree && suite.includes(file)); + const output = path.join(scratch, "output"); + writeFileSync(output, ""); + const result = spawnSync("bash", ["-c", step.run], { cwd: tree, encoding: "utf8", timeout: CLASSIFIER_TIMEOUT_MS, + env: { PATH: process.env.PATH, ...input.env, [input.name]: suite.map(shellWord).join(" "), GITHUB_OUTPUT: output } }); + if (result.status !== 0) throw new Error(`exit ${result.status ?? result.signal}: ${(result.stderr ?? "").trim().split("\n").at(-1) ?? ""}`); + const lines = readFileSync(output, "utf8").split("\n").filter(Boolean); + if (lines.length !== 1 || !lines[0].includes("=")) throw new Error(`wrote ${lines.length} outputs, not one`); + return lines[0].slice(lines[0].indexOf("=") + 1).split(/\s+/).filter(Boolean); + } finally { + rmSync(scratch, { recursive: true, force: true }); + } +} + +/** Writes `file` under `tree` as it is in the worktree now (`fromWorktree`) or at `head`; a symlink stays one, an absent file stays absent. */ +function materialize(worktree, head, tree, file, fromWorktree) { + const target = path.join(tree, file); + if (!target.startsWith(`${tree}${path.sep}`)) return; + if (fromWorktree) { + let stat; + try { stat = lstatSync(path.join(worktree, file)); } catch { return; } + mkdirSync(path.dirname(target), { recursive: true }); + if (stat.isSymbolicLink()) symlinkSync(readlinkSync(path.join(worktree, file)), target); + else if (stat.isFile()) writeFileSync(target, readFileSync(path.join(worktree, file))); + return; + } + const entry = git(worktree, ["ls-tree", "-z", head, "--", file]).split("\0").find((line) => line.endsWith(`\t${file}`)); + if (!entry) return; + const [mode, type, object] = entry.split("\t")[0].split(" "); + if (type !== "blob") return; + mkdirSync(path.dirname(target), { recursive: true }); + const blob = spawnSync("git", ["-C", worktree, "cat-file", "blob", object], { maxBuffer: GREP_BUFFER }); + if (blob.status !== 0) throw new Error(`cannot read classifier input ${file}`); + const content = blob.stdout; + if (mode === "120000") symlinkSync(content.toString("utf8"), target); + else writeFileSync(target, content); +} + +/** A path as the paths-filter action's `list-files: shell` writes it: bare when safe, else single-quoted. */ +function shellWord(file) { + return SAFE_SHELL_WORD.test(file) ? file : `'${file.replaceAll("'", "'\\''")}'`; +} + +/** + * The parts of the workflow at `head` the requirement reads: the change-detection job's steps by id, and the + * paths-filter step's filters as glob matchers. Throws on any shape it does not recognize. + */ +export function readWorkflow(worktree, head, declared) { + const text = git(worktree, ["show", `${head}:${declared.workflow}`]); + const steps = jobSteps(text.split("\n"), declared.changesJob); + const filterStep = steps.get(declared.filterStep); + if (!filterStep?.with.filters) throw new Error(`the ${declared.changesJob} job has no ${declared.filterStep} step with filters`); + return { steps, filters: parseFilters(filterStep.with.filters), filterStep: declared.filterStep }; +} + +const indentOf = (line) => line.length - line.trimStart().length; +const isBlankOrComment = (line) => line.trim() === "" || line.trimStart().startsWith("#"); + +/** The steps of job `name` under `jobs:`, by id. */ +function jobSteps(lines, name) { + const jobsAt = lines.findIndex((line) => /^jobs:\s*$/.test(line)); + if (jobsAt < 0) throw new Error("no jobs"); + const start = lines.findIndex((line, index) => index > jobsAt && new RegExp(`^ {2}${escapeRegExp(name)}:\\s*$`).test(line)); + if (start < 0) throw new Error(`no ${name} job`); + let end = start + 1; + while (end < lines.length && (isBlankOrComment(lines[end]) || indentOf(lines[end]) > 2)) end += 1; + const job = lines.slice(start + 1, end); + const stepsAt = job.findIndex((line) => /^ {4}steps:\s*$/.test(line)); + if (stepsAt < 0) throw new Error(`the ${name} job has no steps`); + const items = []; + let itemIndent = null; + for (const line of job.slice(stepsAt + 1)) { + if (isBlankOrComment(line)) { if (items.length) items.at(-1).push(line); continue; } + if (indentOf(line) <= 4) break; + const dash = /^( *)- /.exec(line); + itemIndent ??= dash ? dash[1].length : null; + if (itemIndent === null) throw new Error("steps is not a list"); + if (dash && dash[1].length === itemIndent) items.push([`${" ".repeat(itemIndent + 2)}${line.slice(itemIndent + 2)}`]); + else items.at(-1).push(line); + } + const steps = new Map(); + for (const item of items) { + const step = mapping(item, itemIndent + 2); + if (typeof step.id === "string") steps.set(step.id, { id: step.id, env: step.env ?? {}, with: step.with ?? {}, run: step.run ?? null }); + } + return steps; +} + +/** A YAML block mapping at `indent`: plain or quoted scalars, `|` block scalars and nested mappings. */ +function mapping(lines, indent) { + const result = {}; + for (let index = 0; index < lines.length;) { + const line = lines[index]; + if (isBlankOrComment(line)) { index += 1; continue; } + if (indentOf(line) !== indent) throw new Error(`unexpected indentation at "${line.trim()}"`); + const pair = /^ *([A-Za-z0-9_-]+):(?: +(.*?))?\s*$/.exec(line); + if (!pair) throw new Error(`unrecognized line "${line.trim()}"`); + let next = index + 1; + while (next < lines.length && (lines[next].trim() === "" || indentOf(lines[next]) > indent)) next += 1; + const body = lines.slice(index + 1, next); + const value = pair[2] ?? ""; + if (/^\|-?$/.test(value)) result[pair[1]] = blockScalar(body); + else if (value === "") result[pair[1]] = body.some((entry) => !isBlankOrComment(entry)) ? mapping(body, indentOf(body.find((entry) => !isBlankOrComment(entry)))) : ""; + else if (body.some((entry) => !isBlankOrComment(entry))) throw new Error(`multi-line scalar at ${pair[1]}`); + else result[pair[1]] = scalar(value); + index = next; + } + return result; +} + +function blockScalar(lines) { + const content = lines.filter((line) => line.trim() !== ""); + if (content.length === 0) return ""; + const indent = Math.min(...content.map(indentOf)); + return `${lines.map((line) => line.slice(indent)).join("\n").replace(/\n+$/, "")}\n`; +} + +function scalar(value) { + if (/^'.*'$/.test(value)) return value.slice(1, -1).replaceAll("''", "'"); + if (/^".*"$/.test(value)) return JSON.parse(value); + if (/^[|>&*!{[]/.test(value)) throw new Error(`unsupported scalar ${value}`); + return value.replace(/\s+#.*$/, ""); +} + +/** The paths-filter `filters` text: each key's globs as anchored matchers. */ +export function parseFilters(text) { + const filters = {}; + let key = null; + for (const line of text.split("\n")) { + if (isBlankOrComment(line)) continue; + const name = /^([A-Za-z0-9_-]+):\s*$/.exec(line); + if (name) { key = name[1]; filters[key] = []; continue; } + const item = /^\s+-\s+(.+?)\s*$/.exec(line); + if (!item || key === null) throw new Error(`unrecognized filter line "${line.trim()}"`); + filters[key].push(globMatcher(scalar(item[1]))); + } + return filters; +} + +/** A paths-filter glob (picomatch with dotfiles) as an anchored matcher; braces, classes and negation are refused. */ +export function globMatcher(glob) { + if (/[{}[\]!]/.test(glob)) throw new Error(`unsupported glob ${glob}`); + let source = ""; + for (let index = 0; index < glob.length; index += 1) { + const rest = glob.slice(index); + if (rest.startsWith("**/")) { source += "(?:.*/)?"; index += 2; } + else if (rest === "**") { source += ".*"; index += 1; } + else if (rest.startsWith("/**") && rest.length === 3) { source += "(?:/.*)?"; index += 2; } + else if (glob[index] === "*") source += "[^/]*"; + else if (glob[index] === "?") source += "[^/]"; + else source += escapeRegExp(glob[index]); + } + return new RegExp(`^${source}$`); +} + +function escapeRegExp(text) { + return text.replace(/[.*+?^${}()|[\]\\]/g, "\\$&"); +} + +if (isEntryPoint(import.meta.url)) { + const { values } = parseArgs({ options: { worktree: { type: "string" }, base: { type: "string" }, head: { type: "string" } } }); + if (!values.worktree || !values.base || !values.head) { + process.stderr.write("Usage: e2e-requirement.mjs --worktree --base --head \n"); + process.exit(2); + } + const { sessionBinding } = await vibeCore("lib/vibe/scripts/provider.mjs"); + for (const row of e2eLaneRequirement(values.worktree, { base: values.base, head: values.head, binding: sessionBinding(values.worktree) })) { + process.stdout.write(`${JSON.stringify(row)}\n`); + } +} + +/** The skip ruling a not-run record quotes, `{ id, source }`, or null when it names none. */ +function quotedRuling(record) { + const id = typeof record.ruling === "string" ? record.ruling.trim() : ""; + const source = typeof record.rulingSource === "string" ? record.rulingSource.trim() : ""; + return id && source ? { id, source } : null; +} diff --git a/plugins/vibe-closedloop/skills/vibe/scripts/lane-run-witness.mjs b/plugins/vibe-closedloop/skills/vibe/scripts/lane-run-witness.mjs index 7c5cac1e..ee5d4843 100644 --- a/plugins/vibe-closedloop/skills/vibe/scripts/lane-run-witness.mjs +++ b/plugins/vibe-closedloop/skills/vibe/scripts/lane-run-witness.mjs @@ -11,12 +11,12 @@ import { evidenceFingerprint, readEvidence } from "../../../lib/handoff/scripts/ import { replayedJobStatus, WORKFLOW_WITNESS } from "../../../lib/vibe/scripts/workflow-lane-replay.mjs"; import { githubRepository } from "../../../lib/vibe/scripts/github-remote.mjs"; -import { environmentalSkipProblem, readLaneOutcomes } from "./lane-outcomes.mjs"; +import { LANE_LOG_MAX_BYTES } from "./lane-witness-check.mjs"; +export { witnessProblem } from "./lane-witness-check.mjs"; import { RUNNER_HOST } from "../../handoff/scripts/e2e-tier.mjs"; const COMMIT = /^[a-f0-9]{40}$/; const NO_DIFF = createHash("sha256").digest("hex"); -const LANE_LOG_MAX_BYTES = 100 * 1024 * 1024; /** A unique private directory even when multiple lanes start together. */ function witnessDirectory(worktree) { @@ -106,37 +106,6 @@ export async function witnessWorkflowRun({ bin, args }, worktree, source, comman return { status, signal, recorded: { witness: evidenceFingerprint(witnessPath), environment: result.environment } }; } -/** Why a lane record no longer matches its run witness, or null when its head, tree, command and environment do. */ -export function witnessProblem(record) { - if (record?.ranOn?.source === "cloud-worker" && record.result === "pass") return cloudWitnessProblem(record); - if (!record?.witness) { - if (record?.result !== "env-skip" && (record?.recordedBy !== "record" || record.result !== "pass")) return null; - return "it has no run witness"; - } - let witness; - try { - witness = JSON.parse(readEvidence(record.witness.path, record.witness).text); - const log = record.ranOn ? record.runLog : witness.log; - if (!log?.sha256 || log.sha256 !== witness.log?.sha256 || evidenceFingerprint(log.path, LANE_LOG_MAX_BYTES).sha256 !== log.sha256) { - return "its witness log changed or cannot be read"; - } - if (record.result === "env-skip") { - const { sha256, path: file } = record.envSkip.outcomes; - if (sha256 !== witness.outcomes?.sha256 || evidenceFingerprint(file).sha256 !== sha256) return "outcomes differ from its witness"; - const problem = environmentalSkipProblem(record.envSkip.timedOut, readLaneOutcomes(file)); - if (problem) return problem; - } - } catch (error) { - return `its witness or log changed or cannot be read: ${error.message}`; - } - if (witness.head !== (record.ranOn?.proofCommit ?? record.head) || record.head !== record.source?.head) return "head differs from its witness"; - if (witness.source?.treeSha256 !== record.source?.treeSha256 || (record.ranOn && witness.gitTree !== record.ranOn.gitTree)) return "tree differs from its witness"; - if (witness.command !== record.command || (record.ranOn && witness.command !== record.ranOn.command)) return "command differs from its witness"; - if (!isDeepStrictEqual(witness.environment ?? {}, record.environment ?? {})) return "environment differs from its witness"; - if (record.result === "pass" && witness.exitCode !== 0) return `the witnessed run exited ${witness.exitCode}, not a pass`; - return null; -} - /** * The fingerprint of the transported remote log. Witness verification compares it to the runner's original hash. */ @@ -147,24 +116,6 @@ export function remoteRunLog(values) { return evidenceFingerprint(values["run-log"], LANE_LOG_MAX_BYTES); } -/** A cloud workflow recipe carries its environment in the committed recipe, and its log hash in the host result. */ -function cloudWitnessProblem({ cloudEvidence, runLog, ranOn, source, head, command, environment }) { - try { - const result = JSON.parse(readEvidence(cloudEvidence.path, cloudEvidence).text); - if (result.commit !== head || head !== ranOn.proofCommit || head !== source.head) return "head differs from its witness"; - if (result.provenance?.gitTree !== ranOn.gitTree) return "tree differs from its witness"; - if (result.provenance.host !== ranOn.host || result.repository !== ranOn.repository) return "runner differs from its witness"; - const lane = result.lanes.find((item) => item.name === ranOn.lane); - if (lane?.command !== command || command !== ranOn.command) return "command differs from its witness"; - if (environment && Object.keys(environment).length) return "environment differs from its witness"; - if (lane.exitCode !== 0) return `the witnessed run exited ${lane.exitCode}, not a pass`; - const streams = [...Object.values(lane.privateStreams ?? {}), lane.combinedOutput].filter(Boolean); - if (!streams.some((stream) => stream.sha256 === runLog.sha256) || - evidenceFingerprint(runLog.path, LANE_LOG_MAX_BYTES).sha256 !== runLog.sha256) return "its log differs from the witnessed cloud output"; - return null; - } catch (error) { return `its witness or log changed or cannot be read: ${error.message}`; } -} - /** * The remote run a `record --ran-on` names, or null without it. Its proof commit is provenance only: the * binding is the clean local HEAD's Git tree, so the row's source identity is this content's. diff --git a/plugins/vibe-closedloop/skills/vibe/scripts/lane-witness-check.mjs b/plugins/vibe-closedloop/skills/vibe/scripts/lane-witness-check.mjs new file mode 100644 index 00000000..39645bd0 --- /dev/null +++ b/plugins/vibe-closedloop/skills/vibe/scripts/lane-witness-check.mjs @@ -0,0 +1,54 @@ +import { isDeepStrictEqual } from "node:util"; +import { evidenceFingerprint, readEvidence } from "../../../lib/handoff/scripts/handoff-evidence.mjs"; +import { environmentalSkipProblem, readLaneOutcomes } from "./lane-outcomes.mjs"; + +export const LANE_LOG_MAX_BYTES = 100 * 1024 * 1024; + +/** Why a lane record no longer matches its run witness, or null when its head, tree, command and environment do. */ +export function witnessProblem(record) { + if (record?.ranOn?.source === "cloud-worker" && record.result === "pass") return cloudWitnessProblem(record); + if (!record?.witness) { + if (record?.result !== "env-skip" && (record?.recordedBy !== "record" || record.result !== "pass")) return null; + return "it has no run witness"; + } + let witness; + try { + witness = JSON.parse(readEvidence(record.witness.path, record.witness).text); + const log = record.ranOn ? record.runLog : witness.log; + if (!log?.sha256 || log.sha256 !== witness.log?.sha256 || evidenceFingerprint(log.path, LANE_LOG_MAX_BYTES).sha256 !== log.sha256) { + return "its witness log changed or cannot be read"; + } + if (record.result === "env-skip") { + const { sha256, path: file } = record.envSkip.outcomes; + if (sha256 !== witness.outcomes?.sha256 || evidenceFingerprint(file).sha256 !== sha256) return "outcomes differ from its witness"; + const problem = environmentalSkipProblem(record.envSkip.timedOut, readLaneOutcomes(file)); + if (problem) return problem; + } + } catch (error) { + return `its witness or log changed or cannot be read: ${error.message}`; + } + if (witness.head !== (record.ranOn?.proofCommit ?? record.head) || record.head !== record.source?.head) return "head differs from its witness"; + if (witness.source?.treeSha256 !== record.source?.treeSha256 || (record.ranOn && witness.gitTree !== record.ranOn.gitTree)) return "tree differs from its witness"; + if (witness.command !== record.command || (record.ranOn && witness.command !== record.ranOn.command)) return "command differs from its witness"; + if (!isDeepStrictEqual(witness.environment ?? {}, record.environment ?? {})) return "environment differs from its witness"; + if (record.result === "pass" && witness.exitCode !== 0) return `the witnessed run exited ${witness.exitCode}, not a pass`; + return null; +} + +/** A cloud workflow recipe carries its environment in the committed recipe, and its log hash in the host result. */ +function cloudWitnessProblem({ cloudEvidence, runLog, ranOn, source, head, command, environment }) { + try { + const result = JSON.parse(readEvidence(cloudEvidence.path, cloudEvidence).text); + if (result.commit !== head || head !== ranOn.proofCommit || head !== source.head) return "head differs from its witness"; + if (result.provenance?.gitTree !== ranOn.gitTree) return "tree differs from its witness"; + if (result.provenance.host !== ranOn.host || result.repository !== ranOn.repository) return "runner differs from its witness"; + const lane = result.lanes.find((item) => item.name === ranOn.lane); + if (lane?.command !== command || command !== ranOn.command) return "command differs from its witness"; + if (environment && Object.keys(environment).length) return "environment differs from its witness"; + if (lane.exitCode !== 0) return `the witnessed run exited ${lane.exitCode}, not a pass`; + const streams = [...Object.values(lane.privateStreams ?? {}), lane.combinedOutput].filter(Boolean); + if (!streams.some((stream) => stream.sha256 === runLog.sha256) || + evidenceFingerprint(runLog.path, LANE_LOG_MAX_BYTES).sha256 !== runLog.sha256) return "its log differs from the witnessed cloud output"; + return null; + } catch (error) { return `its witness or log changed or cannot be read: ${error.message}`; } +} diff --git a/plugins/vibe-closedloop/skills/vibe/scripts/pre-pr-lanes.mjs b/plugins/vibe-closedloop/skills/vibe/scripts/pre-pr-lanes.mjs index be76ca06..4a5286d2 100644 --- a/plugins/vibe-closedloop/skills/vibe/scripts/pre-pr-lanes.mjs +++ b/plugins/vibe-closedloop/skills/vibe/scripts/pre-pr-lanes.mjs @@ -63,9 +63,10 @@ // The Desktop Electron e2e lane runs only under the displayless Linux harness // (dbus, keyring and Xvfb); vibe never launches Electron natively, and the // repo's container tier has no display server. On any other machine `check` -// records it `not-run` the same way (`NOT-RUN-LANE`), and the post-merge -// desktop-e2e-validation run, which publishes `desktop-e2e/validated`, covers -// it. A passing run recorded from a remote runner still counts. +// records it `not-run` the same way (`NOT-RUN-LANE`). That record satisfies +// nothing before the pull request: the lane runs in cloud validation or on the +// heavy host (e2e-requirement.mjs). A passing run recorded from a remote runner +// counts. // // A selected lane that fails on the branch source and on captured main is // not the session's to fix (the handoff's rule for failures already on main). @@ -131,6 +132,7 @@ import { CACHED_RESULT, cachedRecord, findReusable, laneKeyFor, Provenance } fro import { storyTypecheckLane } from "./story-typecheck.mjs"; import { launchedReviewerOrVerifier } from "./agent-models.mjs"; import { E2E_SPEC, observedGraphSelection, relativePath } from "./lane-graph.mjs"; +import { E2eSurface, FULL_LANE, isDesktopE2eLane, isWebE2eLane, missingE2eSpecs, RUN_ELSEWHERE } from "./e2e-requirement.mjs"; import { declaredEnvironment, remoteRun, remoteRunLog, witnessProblem, witnessRun, witnessWorkflowRun } from "./lane-run-witness.mjs"; export { witnessProblem }; import { environmentalSkipProblem, interruptedRuns, LANE_RECORDS_FILE, laneRunOutcome, readLaneOutcomes, rerunOf, runningRecord, startLaneInBackground } from "./lane-outcomes.mjs"; @@ -148,8 +150,6 @@ const FLEET_SCRIPT = fileURLToPath(new URL("../../fleet-orchestrator/scripts/fle const LANE_LINE = /^ {4}((?:[A-Za-z_][A-Za-z0-9_]*=(?:'(?:[^']|'\\'')*'|\S+)\s+)*(?:pnpm|npm|npx|yarn|node)\s.*?)(?:\s+\(.*\))?\s*$/; const NOTHING = /nothing to cover|No paths changed/i; -// The repo's web Playwright lanes (`pnpm test:e2e`, `pnpm test:web-smoke`); a lane naming desktop is the Electron one. -const WEB_E2E = /\b(?:test:e2e|test:web-smoke)\b/; const DESKTOP = /\bdesktop\b/i; const TARGETED_POLICY = [ /An e2e lane \(`e2e`, `desktop-e2e`\) is the exception/i, @@ -165,7 +165,7 @@ export const stagingIdentity = (binding = sessionBinding()) => { }; const ENV_LINE = /^\s*(?:export\s+)?([A-Za-z_][A-Za-z0-9_]*)\s*=\s*(.*?)\s*$/; export const NOT_RUN_NO_IDENTITY = "no staging e2e identities on this machine; the containerized or CI run covers it"; -export const NOT_RUN_NO_DESKTOP_HARNESS = "no displayless Linux Electron harness on this machine and vibe never launches Electron natively; the post-merge desktop-e2e-validation run (desktop-e2e/validated) covers it"; +export const NOT_RUN_NO_DESKTOP_HARNESS = `no displayless Linux Electron harness on this machine and vibe never launches Electron natively; recorded not-run here, which satisfies nothing: run it ${RUN_ELSEWHERE[E2eSurface.Desktop]}`; const HARNESS_TOOLS = ["dbus-run-session", "xvfb-run", "gnome-keyring-daemon"]; /** The lane commands a lane report names, or null when it names none and does not say nothing changed. */ @@ -180,15 +180,7 @@ export function reportLanes(report) { return all; } -/** Whether a lane is the repo's local web e2e lane. */ -export function isWebE2eLane(lane) { - return WEB_E2E.test(lane) && !DESKTOP.test(lane); -} - -/** Whether a lane is the repo's Desktop Electron e2e lane. */ -export function isDesktopE2eLane(lane) { - return WEB_E2E.test(lane) && DESKTOP.test(lane); -} +export { isDesktopE2eLane, isWebE2eLane }; /** Whether this machine can run the Desktop lane displayless: Linux with dbus, Xvfb and the keyring daemon. */ export function hasDisplaylessElectronHarness(platform = process.platform, onPath = commandOnPath) { @@ -528,19 +520,64 @@ function assertGraphScope(values, graph, scope) { throw new Error("the observed graph query must cover the exact changed-file scope of this worktree"); } -/** The specs a targeted record of `lane` must list: its graph selection plus each changed spec on its surface. */ -function requiredTargetedSpecs(graph, scope, lane) { +/** The graph-selected and changed specs previously required for a targeted record on this lane. */ +function baselineTargetedSpecs(graph, scope, lane) { const desktop = isDesktopE2eLane(lane); - const selected = graph.result[desktop ? "desktop" : "web"]; + const surface = desktop ? E2eSurface.Desktop : E2eSurface.Web; + const selected = graph.result[surface]; if (!Array.isArray(selected)) { throw new Error(`the graph result has unread pages: read the remaining pages (${selected?.unread ?? "every page"}) in the same turn, then record again`); } - const changed = scope.changedSpecs.filter((file) => DESKTOP.test(file) === desktop); - return [...new Set([...selected, ...changed])].sort(); + return [...new Set([...selected, ...scope.changedSpecs.filter((file) => DESKTOP.test(file) === desktop)])].sort(); } +/** Compare a targeted selection with the minimum the lane used to require and the additional PR requirements. */ +function targetedSpecRequirements(values, graph, scope, lane, specs) { + const baseline = baselineTargetedSpecs(graph, scope, lane); + const surface = isDesktopE2eLane(lane) ? E2eSurface.Desktop : E2eSurface.Web; + let owed; + try { + owed = owedTargetedSpecs(values, scope, surface, graph.result[surface]); + } catch (error) { + return { accepted: sameStringList(specs, baseline), expected: baseline, + warning: `E2E-NOT-RUN ${lane}: could not check the full PR requirements: ${error.message}` }; + } + const full = owed.find((item) => item.spec === FULL_LANE); + const expected = [...new Set([...baseline, ...owed.filter((item) => item.spec !== FULL_LANE).map((item) => item.spec)])].sort(); + const missing = expected.filter((file) => !specs.includes(file)); + return { + accepted: baseline.every((file) => specs.includes(file)) && specs.every((file) => expected.includes(file)), + expected, + warning: full ? fullLaneRequired(lane, full.reason) : missing.length ? `E2E-NOT-RUN ${lane}: PR create still requires ${missing.join(", ")}` : null, + }; +} + +function owedTargetedSpecs(values, scope, surface, selected) { + return missingE2eSpecs(values.worktree, { base: scope.base, head: git(values.worktree, ["rev-parse", "HEAD"]), + binding: sessionBinding(values.worktree), files: scope.changedFiles, graphSelection: { [surface]: selected } }).filter((item) => item.surface === surface); +} -export async function targetedRecord(values, lane, readTurn) { +function fullLaneRequired(lane, reason) { + return `FULL-E2E-REQUIRED ${lane}: ${reason}; run the whole lane and record it without --targeted-specs`; +} + +/** + * The missing E2E lanes that can satisfy PR create with a targeted record, and the warning for every lane owed in full. + */ +export function targetedE2eHints(values, missing) { + const lanes = missing.filter((lane) => isWebE2eLane(lane) || isDesktopE2eLane(lane)); + if (lanes.length === 0) return { targetable: [], full: [] }; + const scope = targetedScope(values); + const verdicts = lanes.map((lane) => { + const surface = isDesktopE2eLane(lane) ? E2eSurface.Desktop : E2eSurface.Web; + return { lane, full: owedTargetedSpecs(values, scope, surface, []).find((item) => item.spec === FULL_LANE) }; + }); + return { targetable: verdicts.filter((item) => !item.full).map((item) => item.lane), + full: verdicts.filter((item) => item.full).map((item) => fullLaneRequired(item.lane, item.full.reason)) }; +} + + +export async function targetedRecord(values, lane, readTurn, warn = (line) => process.stderr.write(`${line}\n`)) { const baseSupplied = [values["targeted-specs"], values["graph-query"]]; const nativeSupplied = [values["graph-session"], values["graph-turn"]]; const launcherSupplied = values["graph-launcher-result"] !== undefined; @@ -559,8 +596,9 @@ export async function targetedRecord(values, lane, readTurn) { if (graph.query !== graphQuery) throw new Error("--graph-query must exactly match the observed graph tool arguments JSON"); const scope = targetedScope(values); assertGraphScope(values, graph, scope); - const required = requiredTargetedSpecs(graph, scope, lane); - if (!sameStringList(specs, required)) throw new Error(`--targeted-specs must exactly match graph-selected plus added or edited E2E specs: ${required.join(", ")}`); + const requirement = targetedSpecRequirements(values, graph, scope, lane, specs); + if (!requirement.accepted) throw new Error(`--targeted-specs must exactly match graph-selected plus added or edited E2E specs, with any additional specs this change requires: ${requirement.expected.join(", ")}`); + if (requirement.warning) warn(requirement.warning); return { specs, graphQuery, graph, changedFiles: scope.changedFiles }; } @@ -590,9 +628,9 @@ export async function targetedE2eCoverage(values, lanes, records, selected, read if (current.toolCallId !== record.targeted.graph?.toolCallId || current.query !== record.targeted.graphQuery || current.runtime !== record.targeted.graph?.runtime || JSON.stringify(current.result) !== JSON.stringify(record.targeted.graph?.result) || (current.runtime === "claude" && JSON.stringify(current.evidence) !== JSON.stringify(record.targeted.graph?.evidence))) continue; - let required; - try { required = requiredTargetedSpecs(current, scope, lane); } catch { continue; } - if (sameStringList(record.targeted.specs, required)) covered.push({ lane, specs: record.targeted.specs }); + let requirement; + try { requirement = targetedSpecRequirements(values, current, scope, lane, record.targeted.specs); } catch { continue; } + if (requirement.accepted) covered.push({ lane, specs: record.targeted.specs }); } return covered; } @@ -863,7 +901,11 @@ async function main(argv) { const roles = reviewRolePlan(reuse.impact, reuse.request.graphImporters ?? null); process.stdout.write(`REVIEW-ROLES ${roles.affected.join(", ") || "none"} (the delta since ${reuse.boundary.slice(0, 12)} affects these; ${roles.reused.length ? `earlier clean reviews still hold for ${roles.reused.join(", ")}` : "no earlier review still holds"})\n`); } - if (missing.length > 0 && allowsTargetedE2e(values.worktree)) process.stdout.write(`TARGETED-E2E: this repository allows a targeted E2E lane in place of the full one; ${TARGETED_RECORD}\n`); + if (missing.length > 0 && allowsTargetedE2e(values.worktree)) { + const hints = targetedE2eHints(values, missing); + for (const line of hints.full) process.stdout.write(`${line}\n`); + if (hints.targetable.length > 0) process.stdout.write(`TARGETED-E2E: this repository allows a targeted E2E lane in place of the full one for ${hints.targetable.join(", ")}; ${TARGETED_RECORD}\n`); + } process.stdout.write(`pre-pr lanes: ${lanes.length} lanes, ${missing.length} missing${notRun.length ? `, ${notRun.length} not run locally` : ""}${values["reuse-cache"] || values["reuse-unaffected"] ? `, ${covered.length + unaffected.length} cached` : ""} for changed-file scope ${selected.laneKey ?? "none"}\n`); return { exitCode: missing.length === 0 ? 0 : 1 }; })(); diff --git a/plugins/vibe/.claude-plugin/plugin.json b/plugins/vibe/.claude-plugin/plugin.json index cf5b195c..b2c76c2e 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.121", + "version": "1.1.122", "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 2751095f..b2f87225 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.121", + "version": "1.1.122", "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 b9d73989..eb2e37bf 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.121` contains 17 skills and 17 agents, and no hook manifest: the +Version `1.1.122` contains 17 skills and 17 agents, and no hook manifest: the `vibe-core` plugin, which vibe declares as a dependency, registers the hooks and runs `hooks/runtime.mjs` from the vibe a session uses. Skill commands forward to guards in `hooks/` and runtime modules in `lib/`. The package has no standalone commands, root shell scripts or production Python tools. Tests sit beside their owners; Python contract helpers and the generic scan live in `tools/python/`. diff --git a/plugins/vibe/hooks/pr-create-full-ci.test.mjs b/plugins/vibe/hooks/pr-create-full-ci.test.mjs new file mode 100644 index 00000000..7bf3f9dc --- /dev/null +++ b/plugins/vibe/hooks/pr-create-full-ci.test.mjs @@ -0,0 +1,28 @@ +// PR create refuses any head in scope, vibe or not, until every declared CI workflow job ran on it in full (full-ci-check.mjs). +import assert from "node:assert/strict"; +import { mkdtempSync, rmSync, writeFileSync } from "node:fs"; +import { tmpdir } from "node:os"; +import path from "node:path"; +import test from "node:test"; +import { prCreateGuard } from "./pr-create-guard.mjs"; +import { recordHookSkill } from "./hook-session-scope.mjs"; +import { ciRepository } from "../lib/handoff/scripts/full-ci-fixture.mjs"; + +test("class B: a plain worker's PR from a fleet conversation is refused until every CI job ran in full on its head", (t) => { + const home = mkdtempSync(path.join(tmpdir(), "pr-full-ci-home-")); + t.after(() => rmSync(home, { recursive: true, force: true })); + recordHookSkill("fleet-ci", "vibe:fleet-orchestrator", home); + const r = ciRepository(t); + const body = path.join(home, "body.md"); + writeFileSync(body, "Ran the focused test files.\n"); + const create = (command) => prCreateGuard({ cwd: r.worktree, session_id: "fleet-ci", transcript_path: null, tool_input: { command } }, home); + r.record(["node --test plugins/vibe/lib/vibe/scripts/cloud-worker.test.mjs"]); + const refused = create(`gh pr create --base main --body-file ${body}`); + assert.equal(refused?.decision, "deny"); + assert.match(refused.reason, /gh pr create refused: every CI workflow job runs in full on the exact head before a pull request, and 2 have no witnessed passing run of [0-9a-f]{12}: plugin-version-bump, node-tests/); + assert.match(create(`gh pr create --base main --head feat/cloud-scale --body-file ${body}`)?.reason ?? "", /plugin-version-bump, node-tests/, "a named head reads the same records"); + assert.equal(prCreateGuard({ cwd: r.worktree, session_id: "unscoped", transcript_path: null, tool_input: { command: "gh pr create --fill" } }, home), null, + "a conversation with no vibe skill is not in the guard's scope"); + r.record(r.lanes.map(({ command }) => command)); + assert.equal(create(`gh pr create --base main --body-file ${body}`), null, "every job ran on the head's tree"); +}); diff --git a/plugins/vibe/hooks/pr-create-guard.mjs b/plugins/vibe/hooks/pr-create-guard.mjs index 04ff54c6..1e0361f8 100644 --- a/plugins/vibe/hooks/pr-create-guard.mjs +++ b/plugins/vibe/hooks/pr-create-guard.mjs @@ -9,6 +9,8 @@ // unrelated tool false positives. A call that overrides head ownership or the // session record has no gate witness, so it names its findings inline, as // merge-guard.mjs reads them: `VISUAL_QA_FINDINGS= gh pr create ...`. +// Any head in scope, vibe or not, also needs every declared CI workflow job run in full on it (full-ci-check.mjs), and +// a change to a registered refusing check needs that check replayed against real work (refusing-check-replay.mjs). import { execFileSync } from "node:child_process"; import { existsSync, lstatSync, readFileSync } from "node:fs"; import path from "node:path"; @@ -23,10 +25,13 @@ import { isProviderBroken, recordedBinding } from "../lib/vibe/scripts/provider. import { assertIsolatedTestRead } from "../lib/vibe/scripts/test-state-isolation.mjs"; import { conversationSkill } from "./hook-session-scope.mjs"; import { changedPaths, declaresUiPaths, visualQaFindingsProblems, visualQaRequired, VISUAL_QA_STEP } from "../lib/vibe/scripts/required-visual-qa.mjs"; -import { deliveryPlacementProblem, deliveryRepository } from "../lib/fleet-orchestrator/scripts/delivery-placement.mjs"; +import { deliveryPlacementProblem, deliveryRepository, fleetRowHasPullRequest } from "../lib/fleet-orchestrator/scripts/delivery-placement.mjs"; import { validChat } from "../lib/fleet-orchestrator/scripts/chat-binding.mjs"; import os from "node:os"; import { BodyFileError, OVERRIDE_CHECKS, overriddenChecks, readPrBodyFile } from "../lib/handoff/scripts/gate-override.mjs"; +import { declaredWorkflowLanes, fullCiProblem } from "../lib/handoff/scripts/full-ci-check.mjs"; +import { refusalReplayProblem } from "../lib/handoff/scripts/refusing-check-replay.mjs"; +import { e2eGateProblems } from "../lib/handoff/scripts/e2e-gate-check.mjs"; const VIBE_BRANCH = "vibe/"; const overrideHint = (check) => `if every real check and review passed and known Vibe gate bugs are the only blocker (operator ruling 2026-11-08), add \`Vibe gate override: [, ...]: ${check}: \` naming each bug ticket and the check it overrides to the PR body file`; @@ -292,6 +297,35 @@ function prVisualQaProblem({ cwd, head = null, base, binding, witnessWorktree = return problems.length ? `visual QA is required (${verdict.reason}): ${problems.join("; ")}` : null; } +/** + * Why the PR head may not be raised yet, or null: a declared CI workflow job not run on it in full (full-ci-check.mjs), + * a required e2e spec with no run receipt (e2e-gate-check.mjs), or a changed refusing check not replayed against real + * work (refusing-check-replay.mjs). It applies to every head in scope, vibe or not, since push-check leaves a row with + * no pull request to this gate (full-ci-check.mjs cites the rulings); the records are read from the worktree whose HEAD + * is the PR head, else the command worktree. + */ +function prReadinessProblem(call, target, binding) { + let headCommit; + try { headCommit = git(call.cwd, ["rev-parse", "--verify", `${call.head ? prHeadRef(call.cwd, call.head) : "HEAD"}^{commit}`]); } + catch { + try { return declaredWorkflowLanes(call.cwd, "HEAD") ? "the PR head cannot be read to check its CI workflow runs" : null; } + catch { return null; } + } + const worktree = git(call.cwd, ["worktree", "list", "--porcelain"]).split(/\n\s*\n/) + .find((entry) => entry.split("\n").includes(`HEAD ${headCommit}`))?.match(/^worktree (.+)$/m)?.[1] ?? target?.cwd ?? call.cwd; + try { + const bodyText = () => call.bodyFile ? readPrBodyFile(call.bodyFile) : ""; + const base = () => resolvePrBase(call.cwd, call.base).oid; + const e2e = () => e2eGateProblems(worktree, { base, head: headCommit, bodyText, binding }); + return fullCiProblem(worktree, headCommit, { bodyText, binding }) + ?? (e2e().join("; ") || null) + ?? refusalReplayProblem(worktree, { base, head: headCommit, bodyText, binding }); + } catch (error) { + if (error instanceof BodyFileError) return error.message; + return `the PR head's CI workflow runs, e2e runs and refusing-check replays could not be checked: ${error.message}`; + } +} + /** The local ref `head` stands for: its local branch, else the local branch pushed under that name, else origin's. */ function prHeadRef(cwd, head) { if (localBranchExists(cwd, head)) return `refs/heads/${head}`; @@ -347,6 +381,12 @@ export function prCreateGuard(event, home = os.homedir()) { if (inVibeSession(call.cwd)) target = { cwd: call.cwd }; else if (vibeWorktree(call.cwd) === false) continue; } + const chat = validChat(event?.session_id); + const creatingPullRequest = !fleetRowHasPullRequest({ cwd: target?.cwd ?? call.cwd, branch: call.head, chat }); + const readiness = creatingPullRequest + ? prReadinessProblem(call, target, recordedBinding({ worktree: call.cwd, conversation: event?.session_id ?? null, home })) + : null; + if (readiness) return refuse(readiness); if (target?.nonVibe) continue; let covered; try { covered = overriddenChecks(call.bodyFile ? readPrBodyFile(call.bodyFile) : "", recordedBinding({ worktree: call.cwd, conversation: event?.session_id ?? null, home })); } @@ -388,7 +428,7 @@ export function prCreateGuard(event, home = os.homedir()) { // Cloud import readiness, its own rerun of the handoff gate included, is a separate protection the override does not clear. const cloudProblem = cloudPrProblem(target.cwd, { base: call.base, bodyFile: call.bodyFile, title: call.title }); if (cloudProblem) return refuse(cloudProblem, CLOUD_RETRY); - const problem = handoffGateProblem(target.cwd, { base: call.base, bodyFile: call.bodyFile, title: call.title }); + const problem = handoffGateProblem(target.cwd, { base: call.base, bodyFile: call.bodyFile, title: call.title, creatingPullRequest }); if (problem && !override(OVERRIDE_CHECKS.HandoffGate)) return refuse(problem, `run the final handoff gate on the published source, or ${overrideHint(OVERRIDE_CHECKS.HandoffGate)}`); // A named handoff override leaves visual QA active. Without a passing witness, verify the inline findings. const placementProblem = missingPlacement() ?? missingVisualQa(target.cwd, null, problem ? null : target.cwd); diff --git a/plugins/vibe/lib/fleet-orchestrator/scripts/delivery-placement.mjs b/plugins/vibe/lib/fleet-orchestrator/scripts/delivery-placement.mjs index 75cdb5a1..793399b2 100644 --- a/plugins/vibe/lib/fleet-orchestrator/scripts/delivery-placement.mjs +++ b/plugins/vibe/lib/fleet-orchestrator/scripts/delivery-placement.mjs @@ -1,5 +1,5 @@ import { execFileSync } from "node:child_process"; -import { existsSync, readFileSync } from "node:fs"; +import { existsSync, readFileSync, realpathSync } from "node:fs"; import path from "node:path"; import { defaultHome } from "./fleet-home.mjs"; import { resolveWorkDir } from "../../codex-fleet-monitor/scripts/work-dir.mjs"; @@ -36,6 +36,21 @@ function readDeliveryBoard(chat, env = process.env) { return existsSync(file) ? JSON.parse(readFileSync(file, "utf8")) : {}; } +/** Whether the fleet board for this chat already has a pull request on this checkout or repository branch. */ +export function fleetRowHasPullRequest({ cwd, branch, chat, env = process.env }) { + try { + const worktree = realpathSync(cwd); + const repository = deliveryRepository(cwd)?.toLowerCase(); + const { writers } = readDeliveryBoard(chat, env); + return Object.values(writers ?? {}).some((row) => { + if (!row?.pr || row.retiredAt) return false; + if (branch && row.branch === branch && repository && row.repo?.toLowerCase() === repository) return true; + if (!row.worktree || row.where === "remote") return false; + try { return realpathSync(row.worktree) === worktree; } catch { return false; } + }); + } catch { return false; } +} + function recordedPlacements(content) { const entries = []; let fence = null; diff --git a/plugins/vibe/lib/handoff/scripts/e2e-gate-check.mjs b/plugins/vibe/lib/handoff/scripts/e2e-gate-check.mjs new file mode 100644 index 00000000..f9726b4c --- /dev/null +++ b/plugins/vibe/lib/handoff/scripts/e2e-gate-check.mjs @@ -0,0 +1,93 @@ +// PR create requires passing receipts for the repository's required E2E specs and checks not-run claims in the PR +// body. The handoff gate and push-check report the same findings as warnings. A ticketed e2e lane override can quote a +// skip ruling. e2e-requirement.mjs determines when the full lane is owed (operator rulings, 2026-12-02). + +import { execFileSync } from "node:child_process"; +import { readGitInventory } from "../../vibe/scripts/git-inventory.mjs"; +import { e2eLaneRequirement, e2eRequirementDeclared, FULL_LANE, missingE2eSpecs, NO_GRAPH, recordedE2eEvidence } from "../../../skills/vibe/scripts/e2e-requirement.mjs"; +import { quotedRulingOverride } from "./gate-override.mjs"; + +/** The override check name an e2e skip uses: `Vibe gate override: : e2e lane: `. */ +export const E2E_LANE_OVERRIDE = "e2e lane"; + +const NOT_RUN = /\bnot\s+(?:been\s+)?run\b/i; +const E2E = /\b(?:e-?2-?e|end[-\s]to[-\s]end)\b/i; +const SURFACE_WORDS = Object.freeze({ web: /\b(?:web|browser|playwright)\b/i, desktop: /\b(?:desktop|electron)\b/i }); +// A clause that says only the full lane was not run ("full web e2e", "the rest of the Desktop e2e"). +const FULL_ONLY = /\b(?:full|whole|entire|complete|rest\s+of)\b/i; + +/** + * The surfaces a body says it did not run e2e on, each mapped to whether every such mention is of the full lane only: + * each comma or semicolon clause after "not run" that names e2e, with the surfaces it names ("full web and Desktop e2e" + * names both), or every surface when it names none. + */ +export function notRunE2eSurfaces(bodyText) { + const surfaces = new Map(); + for (const line of String(bodyText ?? "").split(/\r?\n/)) { + const at = line.search(NOT_RUN); + if (at < 0) continue; + for (const clause of line.slice(at).split(/[,;]/)) { + if (!E2E.test(clause)) continue; + const named = Object.entries(SURFACE_WORDS).filter(([, word]) => word.test(clause)).map(([surface]) => surface); + for (const surface of named.length ? named : Object.keys(SURFACE_WORDS)) surfaces.set(surface, (surfaces.get(surface) ?? true) && FULL_ONLY.test(clause)); + } + } + return surfaces; +} + +const quotedSkipRuling = (bodyText, binding) => quotedRulingOverride(bodyText, binding, E2E_LANE_OVERRIDE); + +/** Each required e2e lane the body lists as not run, from computed requirements ([{ surface, required, full, reasons, lane }]). */ +export function notRunE2eProblems(bodyText, requirements, binding = null) { + const notRun = notRunE2eSurfaces(bodyText); + if (!notRun.size || quotedSkipRuling(bodyText, binding)) return []; + return requirements.filter((lane) => lane.required && notRun.has(lane.surface) && (lane.full || !notRun.get(lane.surface))).map((lane) => + `the PR body lists the required ${lane.surface} e2e lane (${lane.lane}) as not run; run it${lane.full ? " in full" : ""} and record it, or add "Vibe gate override: : ${E2E_LANE_OVERRIDE}: "`); +} + +/** + * Each required e2e spec with no local run receipt, from missingE2eSpecs ([{ surface, spec, reason }]; spec "full" is + * the whole lane). A whole lane owed only because no graph test selection is recorded says how to narrow it. + */ +export function missingSpecProblems(missing) { + const skip = `add "Vibe gate override: : ${E2E_LANE_OVERRIDE}: "`; + return missing.map(({ surface, spec, reason }) => { + if (spec === FULL_LANE && reason.startsWith(NO_GRAPH)) { + return `the required ${surface} e2e lane is owed in full only because no graph test selection is recorded for this change (${reason}); ` + + `to narrow it, run the specs the graph test lookup selects for the change plus those the change owes, and record that run with ` + + `pre-pr-lanes.mjs record --targeted-specs '' --graph-query ''; otherwise run the whole lane and record it, or ${skip}`; + } + return `the required ${surface} e2e ${spec === FULL_LANE ? "lane, in full," : `spec ${spec}`} has no local run receipt (${reason}); ` + + `record its run with pre-pr-lanes.mjs, or ${skip}`; + }); +} + +/** + * Both halves against this change: missing spec receipts and the body's not-run lines. The change runs from the merge + * base of `base` and `head`; without `head`, to the worktree as it is now, uncommitted and untracked files included. + * `base` and `bodyText` may each be a function returning it, read only for a repository a provider declares e2e lanes for. + */ +export function e2eGateProblems(worktree, { base, head = null, bodyText: body = "", binding = null }) { + if (!e2eRequirementDeclared(worktree, binding)) return []; + const bodyText = typeof body === "function" ? body() : body; + if (quotedSkipRuling(bodyText, binding)) return []; + const at = head ?? git(worktree, ["rev-parse", "HEAD"]); + // The change is what the pull request shows, as CI's paths filter reads it: from the merge base, never main's tip. + const since = git(worktree, ["merge-base", typeof base === "function" ? base() : base, at]); + const scope = { base: since, head: at, binding, ...(head ? {} : { files: worktreeChanges(worktree, since) }) }; + // The lane records are read only when the change owes something, so a repository no provider declares never reads them. + const owed = missingE2eSpecs(worktree, scope).length ? missingE2eSpecs(worktree, { ...scope, ...recordedE2eEvidence(worktree, { head: at }) }) : []; + const missing = missingSpecProblems(owed); + const notRun = notRunE2eSurfaces(bodyText).size ? notRunE2eProblems(bodyText, e2eLaneRequirement(worktree, scope), binding) : []; + return [...missing, ...notRun]; +} + +const git = (worktree, args) => execFileSync("git", ["-C", worktree, ...args], { encoding: "utf8", stdio: ["ignore", "pipe", "pipe"], maxBuffer: 64 * 1024 * 1024 }).trim(); + +/** The files the worktree changes against `since`, committed, uncommitted and untracked. */ +function worktreeChanges(worktree, since) { + const changed = execFileSync("git", ["-C", worktree, "diff", "--name-only", "--no-renames", "-z", since, "--"], + { encoding: "utf8", stdio: ["ignore", "pipe", "pipe"], maxBuffer: 64 * 1024 * 1024 }); + const untracked = readGitInventory(worktree, ["ls-files", "--others", "--exclude-standard", "-z"]); + return [...changed.split("\0"), ...untracked.split("\0")].filter(Boolean); +} diff --git a/plugins/vibe/lib/handoff/scripts/e2e-gate-check.test.mjs b/plugins/vibe/lib/handoff/scripts/e2e-gate-check.test.mjs new file mode 100644 index 00000000..57784c69 --- /dev/null +++ b/plugins/vibe/lib/handoff/scripts/e2e-gate-check.test.mjs @@ -0,0 +1,186 @@ +import assert from "node:assert/strict"; +import { execFileSync } from "node:child_process"; +import { mkdirSync, mkdtempSync, rmSync, writeFileSync } from "node:fs"; +import { tmpdir } from "node:os"; +import path from "node:path"; +import test from "node:test"; +import { E2E_LANE_OVERRIDE, e2eGateProblems, notRunE2eProblems, notRunE2eSurfaces } from "./e2e-gate-check.mjs"; +import { LANE_RECORDS_FILE } from "../../../skills/vibe/scripts/lane-outcomes.mjs"; +import { NOT_RUN_NO_DESKTOP_HARNESS } from "../../../skills/vibe/scripts/pre-pr-lanes.mjs"; +import { bindProviderInProcess, PROVIDER_BINDING, SYMPHONY_REMOTE } from "../../../skills/vibe/scripts/test-fixtures.mjs"; + +// The not-run line of a pull request that opened with its required browser lane unrun and turned main red. +const NOT_RUN_LINE = "- Not run locally: the rest of the turbo packages the selector names, full web and Desktop e2e, api integration and compatibility, and test:ci (named by mention only)."; +const REQUIRED = [ + { surface: "web", required: true, full: false, reasons: [], lane: "pnpm test:e2e" }, + { surface: "desktop", required: true, full: false, reasons: [], lane: "pnpm test:e2e:desktop" }, +]; + +test("9(b) a body that lists the full web and Desktop e2e lanes as not run is refused only where the full lane is required", () => { + assert.deepEqual([...notRunE2eSurfaces(NOT_RUN_LINE)].sort(), [["desktop", true], ["web", true]]); + assert.deepEqual(notRunE2eProblems(`## Testing\n${NOT_RUN_LINE}\n`, REQUIRED), [], "the targeted specs are the requirement; the full lane is not owed"); + const full = REQUIRED.map((lane) => ({ ...lane, full: true, reasons: ["no graph result"] })); + const problems = notRunE2eProblems(`## Testing\n${NOT_RUN_LINE}\n`, full); + assert.equal(problems.length, 2); + assert.match(problems[0], /required web e2e lane \(pnpm test:e2e\) as not run; run it in full/); + assert.match(problems[1], /required desktop e2e lane \(pnpm test:e2e:desktop\) as not run; run it in full/); +}); + +test("9(b) a not-run line that does not say full says the required specs were not run", () => { + const problems = notRunE2eProblems("- Not run locally: web e2e (no stack here).", REQUIRED); + assert.equal(problems.length, 1); + assert.match(problems[0], /required web e2e lane/); +}); + +test("9(b) only a lane the change requires is refused, and only when the body says it was not run", () => { + const webOnly = REQUIRED.map((lane) => ({ ...lane, full: true, required: lane.surface === "web" })); + assert.equal(notRunE2eProblems(NOT_RUN_LINE, webOnly).length, 1); + assert.deepEqual(notRunE2eProblems(NOT_RUN_LINE, REQUIRED.map((lane) => ({ ...lane, full: true, required: false }))), []); + assert.deepEqual(notRunE2eProblems("- Not run locally: api integration and test:ci.\n- Pass: full web e2e.", REQUIRED), []); + assert.deepEqual([...notRunE2eSurfaces("- Not run: e2e")].sort(), [["desktop", false], ["web", false]], "e2e with no surface named covers every surface"); +}); + +test("9(b) a ticketed gate override for the e2e lane covers the skip only when it quotes the ruling", () => { + const FULL = REQUIRED.map((lane) => ({ ...lane, full: true })); + const unquoted = `${NOT_RUN_LINE}\nVibe gate override: #12: ${E2E_LANE_OVERRIDE}: the operator said to skip it`; + assert.equal(notRunE2eProblems(unquoted, FULL).length, 2); + const quoted = `${NOT_RUN_LINE}\nVibe gate override: #12: ${E2E_LANE_OVERRIDE}: operator ruling 2026-12-02, "skip the Desktop e2e for this one"`; + assert.deepEqual(notRunE2eProblems(quoted, FULL), []); + const otherCheck = `${NOT_RUN_LINE}\nVibe gate override: #12: visual QA: "no UI change"`; + assert.equal(notRunE2eProblems(otherCheck, FULL).length, 2); +}); + +/** A repository served by the bound provider whose change cannot be narrowed: its e2e workflow is absent at head. */ +function unnarrowable(t, remote = SYMPHONY_REMOTE) { + const worktree = mkdtempSync(path.join(tmpdir(), "vibe-e2e-gate-")); + t.after(() => rmSync(worktree, { recursive: true, force: true })); + const run = (...args) => execFileSync("git", ["-C", worktree, "-c", "user.email=test@example.com", "-c", "user.name=Test", ...args], { encoding: "utf8" }).trim(); + execFileSync("git", ["init", "-q", "-b", "main", worktree]); + run("remote", "add", "origin", remote); + writeFileSync(path.join(worktree, "README.md"), "base\n"); + run("add", "."); + run("commit", "-qm", "base"); + const base = run("rev-parse", "HEAD"); + mkdirSync(path.join(worktree, "apps/web"), { recursive: true }); + writeFileSync(path.join(worktree, "apps/web/page.tsx"), "export const page = 1;\n"); + run("add", "."); + run("commit", "-qm", "change"); + return { worktree, base, head: run("rev-parse", "HEAD"), gitDir: run("rev-parse", "--absolute-git-dir") }; +} + +test("9(b) through the real requirement: a change that owes both whole e2e lanes is refused until a quoted skip ruling covers it", (t) => { + const repo = unnarrowable(t); + const problems = e2eGateProblems(repo.worktree, { base: repo.base, head: repo.head, binding: PROVIDER_BINDING }); + assert.equal(problems.length, 2, problems.join("\n")); + assert.match(problems.join("\n"), /required web e2e lane, in full, has no local run receipt/); + assert.match(problems.join("\n"), /required desktop e2e lane, in full, has no local run receipt/); + const bodyText = `Vibe gate override: ISS-12: ${E2E_LANE_OVERRIDE}: operator ruling 2026-12-02, "skip the e2e lanes for this one"\n`; + assert.deepEqual(e2eGateProblems(repo.worktree, { base: repo.base, head: repo.head, bodyText, binding: PROVIDER_BINDING }), []); + const other = unnarrowable(t, "git@github.com:example/other.git"); + writeFileSync(path.join(other.gitDir, LANE_RECORDS_FILE), JSON.stringify({ schema: 1, lanes: [] })); + assert.deepEqual(e2eGateProblems(other.worktree, { base: other.base, head: other.head, binding: PROVIDER_BINDING }), [], + "a repository no provider declares owes nothing, and its lane records, here an older runs file, are never read"); +}); + +test("push-check lets a post-cutoff PR head through with a warning when e2e receipts are absent", async (t) => { + bindProviderInProcess((clean) => t.after(clean)); + const { pushProofLines } = await import("../../../skills/fleet-orchestrator/scripts/push-proof.mjs"); + const { pushCheckAsksPrePrChecks } = await import("./full-ci-check.mjs"); + const { worktree, base, head, gitDir } = unnarrowable(t); + writeFileSync(path.join(gitDir, "vibe-session.json"), JSON.stringify({ status: "active", flagKeys: { surfaces: [] } })); + const outcome = pushProofLines("writer", { worktree, branch: "feature", pr: 7 }, { + head, trustedBase: () => base, published: () => head, prePrChecks: pushCheckAsksPrePrChecks("2026-12-03T03:11:00Z"), + }); + assert.deepEqual(outcome.refuse, []); + assert.match(outcome.notes.join("\n"), /^E2E-NOT-RUN writer .*required web e2e lane/m); +}); + +test("9(b) a Desktop lane this machine recorded not-run satisfies nothing, and the refusal says where it runs", (t) => { + const repo = unnarrowable(t); + writeFileSync(path.join(repo.gitDir, LANE_RECORDS_FILE), JSON.stringify([ + { head: repo.head, command: "pnpm --filter desktop test:e2e", result: "not-run", reason: NOT_RUN_NO_DESKTOP_HARNESS }])); + const desktop = e2eGateProblems(repo.worktree, { base: repo.base, head: repo.head, binding: PROVIDER_BINDING }).filter((line) => /desktop e2e/.test(line)); + assert.equal(desktop.length, 1); + assert.match(desktop[0], /recorded not-run here, which satisfies nothing: run it in cloud validation/); +}); + +test("9(b) the change is read from the merge base, so main moving on after a docs-only branch forked owes no e2e spec", (t) => { + const { worktree, run, commit } = workflowRepo(t, WORKFLOW); + commit("e2e/shared.spec.ts", "test(\"shared\", () => {});\n"); + run("checkout", "-q", "-b", "docs"); + const head = commit("README.md", "docs\n"); + run("checkout", "-q", "main"); + commit("apps/web/page.tsx", "export const page = 2;\n"); + const main = commit("e2e/shared.spec.ts", "test(\"shared, edited on main\", () => {});\n"); + assert.deepEqual(e2eGateProblems(worktree, { base: main, head, binding: PROVIDER_BINDING }), [], "a web change and a spec edit main made after the fork are not the branch's"); + run("checkout", "-q", "docs"); + assert.equal(e2eGateProblems(worktree, { base: main, binding: PROVIDER_BINDING }).length, 0, "the worktree form reads the same merge base"); +}); + +test("9(b) a whole lane owed only for want of a graph selection says to record one through pre-pr-lanes to narrow it", (t) => { + const { commit } = workflowRepo(t, WORKFLOW.replace('echo "e2e_changed_specs=${E2E_SPEC_FILES:-}"', 'echo "e2e_changed_specs="')); + const base = commit("README.md", "base\n"); + commit("apps/web/page.tsx", "export const page = 1;\n"); + const head = commit("e2e/helpers/menu.ts", "export const menu = 1;\n"); + const [web, ...rest] = e2eGateProblems(commit.worktree, { base, head, binding: PROVIDER_BINDING }); + assert.deepEqual(rest, []); + assert.match(web, /^the required web e2e lane is owed in full only because no graph test selection is recorded for this change \(no graph test selection/); + assert.match(web, /e2e\/helpers\/menu\.ts/); + assert.match(web, /to narrow it, run the specs the graph test lookup selects .+ pre-pr-lanes\.mjs record --targeted-specs '' --graph-query '/); +}); + +/** A repository served by the bound provider, its e2e workflow committed on main. */ +function workflowRepo(t, workflow) { + const worktree = mkdtempSync(path.join(tmpdir(), "vibe-e2e-gate-flow-")); + t.after(() => rmSync(worktree, { recursive: true, force: true })); + const run = (...args) => execFileSync("git", ["-C", worktree, "-c", "user.email=test@example.com", "-c", "user.name=Test", ...args], { encoding: "utf8" }).trim(); + const commit = (file, text) => { mkdirSync(path.dirname(path.join(worktree, file)), { recursive: true }); writeFileSync(path.join(worktree, file), text); run("add", "."); run("commit", "-qm", file); return run("rev-parse", "HEAD"); }; + commit.worktree = worktree; + execFileSync("git", ["init", "-q", "-b", "main", worktree]); + run("remote", "add", "origin", SYMPHONY_REMOTE); + commit(".github/workflows/e2e-test.yml", workflow); + return { worktree, run, commit }; +} + +// The declared e2e workflow reduced to the change-detection job: a branch touching neither filter owes nothing. +const WORKFLOW = `name: E2E Tests +on: + pull_request: +jobs: + changes: + runs-on: ubuntu-latest + steps: + - id: filter + uses: dorny/paths-filter@v3 + with: + list-files: shell + filters: | + e2e: + - 'apps/web/**' + e2e_specs: + - 'e2e/**/*.ts' + desktop_e2e_specs: + - 'apps/desktop/test/e2e/**' + desktop_e2e: + - 'apps/desktop/**' + - id: changed-specs + shell: bash + env: + E2E_SPEC_FILES: \${{ steps.filter.outputs.e2e_specs_files }} + run: echo "e2e_changed_specs=\${E2E_SPEC_FILES:-}" >> "$GITHUB_OUTPUT" + - id: desktop-changed-specs + shell: bash + env: + DESKTOP_SPEC_FILES: \${{ steps.filter.outputs.desktop_e2e_specs_files }} + run: echo "desktop_changed_specs=\${DESKTOP_SPEC_FILES:-}" >> "$GITHUB_OUTPUT" + e2e: + needs: [changes] + runs-on: ubuntu-latest + steps: + - run: echo suite + desktop-e2e: + needs: [changes] + runs-on: ubuntu-latest + steps: + - run: echo suite +`; diff --git a/plugins/vibe/lib/handoff/scripts/fixtures/long-lived-branch-shape.json b/plugins/vibe/lib/handoff/scripts/fixtures/long-lived-branch-shape.json new file mode 100644 index 00000000..67ee272b --- /dev/null +++ b/plugins/vibe/lib/handoff/scripts/fixtures/long-lived-branch-shape.json @@ -0,0 +1,13 @@ +{ + "about": "A three-week branch the push-check refused on 2026-12-02, reduced to its shape: counts, and days relative to the 2026-12-01 mutation-proof ruling. Its tests were pushed before the check existed.", + "inherited": { + "caseFiles": 225, + "cases": 495, + "fileLevelFiles": 56, + "commitsByDay": { "-6": 5, "-5": 10, "-1": 9 } + }, + "syncWithMainDay": 1, + "pushedAfterSync": true, + "newCasesDay": 2, + "newCases": 1 +} diff --git a/plugins/vibe/lib/handoff/scripts/full-ci-check.mjs b/plugins/vibe/lib/handoff/scripts/full-ci-check.mjs new file mode 100644 index 00000000..2fffa1b7 --- /dev/null +++ b/plugins/vibe/lib/handoff/scripts/full-ci-check.mjs @@ -0,0 +1,101 @@ +// A pull request to a repository whose vibe-handoff-paths.json declares a github-workflow lane source is refused at PR +// create until every job and matrix entry of that workflow, read at the PR head, has a passing +// run of the head's exact tree recorded by pre-pr-lanes.mjs with its run witness, unless a ticketed gate override for +// "ci lanes" quotes the ruling that allows the skip (operator ruling, 2026-12-02 about 9:10 PM CST: "stop allowing +// things like this to even make it to a PR without adequate testing"). A pull request once opened after only its +// focused test files ran, and CI failed on tests outside them and on a missed plugin version bump. +// +// Usage: full-ci-check.mjs report --worktree writes the workflow lane report for HEAD into the git dir and +// prints `REPORT ` and one `UNRUN ` line per job still to run with +// pre-pr-lanes.mjs run --fleet-where remote --fleet-orch --fleet-owner --worktree +// --head --command '' --report (the recipe is the job's `command` in the report; the heavy +// host needs a worktree at the same path and HEAD). Exits 1 while any job is unrun. + +import { execFileSync } from "node:child_process"; +import { createHash } from "node:crypto"; +import { existsSync, readFileSync, writeFileSync } from "node:fs"; +import path from "node:path"; +import { parseArgs } from "node:util"; +import { capturedJson } from "../../vibe/scripts/captured-json.mjs"; +import { workflowLaneDefinitions } from "../../vibe/scripts/workflow-lane-definitions.mjs"; +import { committedSourceIdentity } from "../../vibe/scripts/tested-head.mjs"; +import { witnessProblem } from "../../../skills/vibe/scripts/lane-run-witness.mjs"; +import { LANE_RECORDS_FILE } from "../../../skills/vibe/scripts/lane-outcomes.mjs"; +import { quotedRulingOverride } from "./gate-override.mjs"; +import { isEntryPoint } from "../../../shared/plugin-roots.mjs"; + +// The operator's 2026-12-02 9:10 PM CST ruling requires adequate testing before PR create. +// The 11:58 PM CST ruling makes full CI and e2e checks advisory on existing PRs. +export const FULL_CI_GATE_SINCE = "2026-12-03T03:10:00Z"; + +/** Whether push-check asks the pre-PR checks of a row whose pull request was created at `createdAt` (null: none yet). */ +export function pushCheckAsksPrePrChecks(createdAt) { + return createdAt !== null && Date.parse(createdAt) >= Date.parse(FULL_CI_GATE_SINCE); +} + +/** The override check name: `Vibe gate override: : ci lanes: `. */ +export const CI_LANES_OVERRIDE = "ci lanes"; + +const git = (worktree, args) => execFileSync("git", ["-C", worktree, ...args], { encoding: "utf8", stdio: ["ignore", "pipe", "pipe"], maxBuffer: 64 * 1024 * 1024 }); + +/** The declared workflow's path and lanes at `head`, or null when the repository declares no github-workflow lane source there. */ +export function declaredWorkflowLanes(worktree, head) { + let source; + try { source = capturedJson(git(worktree, ["show", `${head}:vibe-handoff-paths.json`])).laneSource; } + catch { return null; } + if (source?.kind !== "github-workflow" || typeof source.path !== "string") return null; + return { path: source.path, lanes: workflowLaneDefinitions(git(worktree, ["show", `${head}:${source.path}`])) }; +} + +/** The lane records pre-pr-lanes.mjs keeps in the worktree's git dir. */ +function laneRecords(worktree) { + const file = path.join(git(worktree, ["rev-parse", "--absolute-git-dir"]).trim(), LANE_RECORDS_FILE); + if (!existsSync(file)) return []; + const records = JSON.parse(readFileSync(file, "utf8")); + return Array.isArray(records) ? records : []; +} + +/** The declared workflow lanes with no witnessed passing run of `head`'s tree, as `[{ name, command }]`; [] when none are declared. */ +export function unrunCiLanes(worktree, head) { + const declared = declaredWorkflowLanes(worktree, head); + if (!declared) return []; + const tree = committedSourceIdentity(worktree, head).treeSha256; + const records = laneRecords(worktree); + return declared.lanes.filter(({ command }) => !records.some((record) => record?.command === command && record.result === "pass" + && record.targeted === undefined && record.source?.treeSha256 === tree && !witnessProblem(record))); +} + +/** Why `head` may not be raised as a pull request yet, or null. `bodyText` may be a function, read only when a job is unrun. */ +export function fullCiProblem(worktree, head, { bodyText = "", binding = null } = {}) { + const unrun = unrunCiLanes(worktree, head); + if (!unrun.length || quotedRulingOverride(typeof bodyText === "function" ? bodyText() : bodyText, binding, CI_LANES_OVERRIDE)) return null; + return `every CI workflow job runs in full on the exact head before a pull request, and ${unrun.length} have no witnessed passing run of ${head.slice(0, 12)}: ` + + `${unrun.map(({ name }) => name).join(", ")}; full-ci-check.mjs report --worktree ${worktree} names each job's run, ` + + `or add "Vibe gate override: : ${CI_LANES_OVERRIDE}: "`; +} + +/** Write the declared workflow's lane report for `head` (the JSON pre-pr-lanes.mjs takes as --report) into the git dir. */ +export function writeWorkflowLaneReport(worktree, head) { + const declared = declaredWorkflowLanes(worktree, head); + if (!declared) throw new Error("the repository declares no github-workflow lane source in vibe-handoff-paths.json"); + const content = git(worktree, ["show", `${head}:${declared.path}`]); + const file = path.join(git(worktree, ["rev-parse", "--absolute-git-dir"]).trim(), "vibe-ci-lane-report.json"); + writeFileSync(file, `${JSON.stringify({ source: { kind: "github-workflow", path: declared.path, commit: head, sha256: createHash("sha256").update(content).digest("hex") }, + matches: declared.lanes.map(({ name, command }) => ({ name, command })) }, null, 2)}\n`); + return file; +} + +function main(argv) { + const { positionals, values } = parseArgs({ args: argv, allowPositionals: true, options: { worktree: { type: "string" } } }); + if (positionals[0] !== "report" || !values.worktree) throw new Error("usage: full-ci-check.mjs report --worktree "); + const head = git(values.worktree, ["rev-parse", "HEAD"]).trim(); + process.stdout.write(`REPORT ${writeWorkflowLaneReport(values.worktree, head)}\n`); + const unrun = unrunCiLanes(values.worktree, head); + for (const { name } of unrun) process.stdout.write(`UNRUN ${name}\n`); + return unrun.length ? 1 : 0; +} + +if (isEntryPoint(import.meta.url)) { + try { process.exitCode = main(process.argv.slice(2)); } + catch (error) { process.stderr.write(`${error.message}\n`); process.exitCode = 2; } +} diff --git a/plugins/vibe/lib/handoff/scripts/full-ci-check.test.mjs b/plugins/vibe/lib/handoff/scripts/full-ci-check.test.mjs new file mode 100644 index 00000000..b24c3a7b --- /dev/null +++ b/plugins/vibe/lib/handoff/scripts/full-ci-check.test.mjs @@ -0,0 +1,51 @@ +import assert from "node:assert/strict"; +import { spawnSync } from "node:child_process"; +import { readFileSync } from "node:fs"; +import test from "node:test"; +import { fileURLToPath } from "node:url"; +import { repositoryLaneReportProblems } from "../../../skills/handoff/scripts/ci-job-shape.mjs"; +import { CI_LANES_OVERRIDE, fullCiProblem, unrunCiLanes } from "./full-ci-check.mjs"; +import { ciRepository } from "./full-ci-fixture.mjs"; + +test("class B: a head whose only recorded run is its focused test files has every CI job unrun, the version bump check included", (t) => { + const r = ciRepository(t); + r.record(["node --test plugins/vibe/lib/vibe/scripts/cloud-worker.test.mjs"]); + assert.deepEqual(unrunCiLanes(r.worktree, r.head).map(({ name }) => name), ["plugin-version-bump", "node-tests"]); + assert.match(fullCiProblem(r.worktree, r.head) ?? "", /2 have no witnessed passing run of [0-9a-f]{12}: plugin-version-bump, node-tests; full-ci-check\.mjs report --worktree \S+ names each job's run/); +}); + +test("class B: each job needs a passing run of the head's exact tree with a witness that still holds", (t) => { + const r = ciRepository(t); + const [bump, node] = r.lanes.map(({ command }) => command); + r.record([bump]); + assert.deepEqual(unrunCiLanes(r.worktree, r.head).map(({ name }) => name), ["node-tests"]); + r.record([bump, node], "0".repeat(64)); + assert.equal(unrunCiLanes(r.worktree, r.head).length, 2, "a run of another tree is not a run of this head"); + r.record([bump, node], undefined, { recordedBy: "record" }); + assert.equal(unrunCiLanes(r.worktree, r.head).length, 2, "a typed pass with no run witness does not count"); + r.record([bump, node], undefined, { result: "fail" }); + assert.equal(unrunCiLanes(r.worktree, r.head).length, 2); + r.record([bump, node]); + assert.deepEqual(unrunCiLanes(r.worktree, r.head), []); + assert.equal(fullCiProblem(r.worktree, r.head), null); +}); + +test("class B: only a ticketed override for ci lanes that quotes its ruling covers the skip; an undeclared repository is not asked", (t) => { + const r = ciRepository(t); + assert.equal(fullCiProblem(r.worktree, r.head, { bodyText: `Vibe gate override: #12: ${CI_LANES_OVERRIDE}: "skip the Node suite for this docs-only change" (operator, 2026-12-02)\n` }), null); + assert.ok(fullCiProblem(r.worktree, r.head, { bodyText: `Vibe gate override: #12: ${CI_LANES_OVERRIDE}: ran the focused files\n` }), "an unquoted reason covers nothing"); + assert.ok(fullCiProblem(r.worktree, r.head, { bodyText: `Vibe gate override: #12: visual QA: "a ruling"\n` }), "an override for another check covers nothing"); + const undeclared = ciRepository(t, { declared: false }); + assert.deepEqual(unrunCiLanes(undeclared.worktree, undeclared.head), []); +}); + +test("class B: the report command writes the lane report pre-pr-lanes.mjs verifies and names each job still to run", (t) => { + const r = ciRepository(t); + r.record([r.lanes[0].command]); + const run = spawnSync(process.execPath, [fileURLToPath(new URL("./full-ci-check.mjs", import.meta.url)), "report", "--worktree", r.worktree], { encoding: "utf8" }); + assert.equal(run.status, 1, run.stderr); + assert.match(run.stdout, /^UNRUN node-tests$/m); + assert.doesNotMatch(run.stdout, /UNRUN plugin-version-bump/); + const report = JSON.parse(readFileSync(/^REPORT (.+)$/m.exec(run.stdout)[1], "utf8")); + assert.deepEqual(repositoryLaneReportProblems(report, r.worktree, r.head), []); +}); diff --git a/plugins/vibe/lib/handoff/scripts/full-ci-fixture.mjs b/plugins/vibe/lib/handoff/scripts/full-ci-fixture.mjs new file mode 100644 index 00000000..9a4c5e37 --- /dev/null +++ b/plugins/vibe/lib/handoff/scripts/full-ci-fixture.mjs @@ -0,0 +1,49 @@ +// A repository that declares its CI workflow as its lane source, for the full-ci-check.mjs tests and the PR-create and +// push-check wiring tests. +import { execFileSync } from "node:child_process"; +import { mkdirSync, mkdtempSync, rmSync, writeFileSync } from "node:fs"; +import { tmpdir } from "node:os"; +import path from "node:path"; +import { committedSourceIdentity } from "../../vibe/scripts/tested-head.mjs"; +import { workflowLaneDefinitions } from "../../vibe/scripts/workflow-lane-definitions.mjs"; + +// The jobs CI ran on #457 that its writer did not: the version bump check and the whole Node suite. +const WORKFLOW = JSON.stringify({ on: "pull_request", jobs: { + "plugin-version-bump": { name: "Plugin Version Bump", "runs-on": "ubuntu-latest", steps: [{ run: "node tools/version-bump.mjs" }] }, + "node-tests": { name: "Node Tests (skill scripts)", "runs-on": "ubuntu-latest", steps: [{ run: "node --test plugins" }] }, +} }); + +/** Write the workflow and, when `declared`, the lane-source declaration naming it into `worktree` (uncommitted). */ +export function writeCiDeclaration(worktree, { declared = true } = {}) { + mkdirSync(path.join(worktree, ".github", "workflows"), { recursive: true }); + writeFileSync(path.join(worktree, ".github", "workflows", "ci.yml"), WORKFLOW); + if (declared) writeFileSync(path.join(worktree, "vibe-handoff-paths.json"), JSON.stringify({ version: 1, laneSource: { kind: "github-workflow", path: ".github/workflows/ci.yml" } })); +} + +/** The declared workflow's lanes, `[{ name, command }]`. */ +export const CI_LANES = workflowLaneDefinitions(WORKFLOW); + +/** Replace the worktree's lane records with passes of `commands` at `head`, as pre-pr-lanes.mjs run writes them. */ +export function recordLanes(worktree, head, commands, { treeSha256 = committedSourceIdentity(worktree, head).treeSha256, ...extra } = {}) { + const gitDir = execFileSync("git", ["-C", worktree, "rev-parse", "--absolute-git-dir"], { encoding: "utf8" }).trim(); + writeFileSync(path.join(gitDir, "vibe-lane-results.json"), JSON.stringify(commands.map((command) => ({ + command, head, source: { head, treeSha256 }, laneKey: "0123456789abcdef", result: "pass", provenance: "fresh", recordedBy: "run", ...extra })))); +} + +/** A repository declaring its CI workflow as its lane source, on a non-vibe branch with one commit past main. */ +export function ciRepository(t, { declared = true, worktree = mkdtempSync(path.join(tmpdir(), "vibe-full-ci-")) } = {}) { + mkdirSync(worktree, { recursive: true }); + t.after(() => rmSync(worktree, { recursive: true, force: true })); + const git = (...args) => execFileSync("git", ["-C", worktree, "-c", "user.email=test@example.com", "-c", "user.name=Test", ...args], { encoding: "utf8" }).trim(); + execFileSync("git", ["init", "-q", "-b", "main", worktree]); + writeCiDeclaration(worktree, { declared }); + git("add", "."); + git("commit", "-qm", "base"); + git("checkout", "-q", "-b", "feat/cloud-scale"); + writeFileSync(path.join(worktree, "provider.json"), "{}\n"); + git("add", "."); + git("commit", "-qm", "change provider data"); + const head = git("rev-parse", "HEAD"); + const record = (commands, treeSha256, extra = {}) => recordLanes(worktree, head, commands, { ...(treeSha256 ? { treeSha256 } : {}), ...extra }); + return { worktree, git, head, lanes: CI_LANES, record }; +} diff --git a/plugins/vibe/lib/handoff/scripts/gate-override.mjs b/plugins/vibe/lib/handoff/scripts/gate-override.mjs index 447eb429..b63c927a 100644 --- a/plugins/vibe/lib/handoff/scripts/gate-override.mjs +++ b/plugins/vibe/lib/handoff/scripts/gate-override.mjs @@ -34,6 +34,20 @@ export function gateOverrideEntries(body, binding) { }); } +// A quoted ruling: text in straight or curly double quotes. +const QUOTED_RULING = /"[^"]{3,}"|“[^”]{3,}”/; + +/** + * Whether the body carries a ticketed override naming `check` whose reason quotes the ruling that allows the skip: + * `Vibe gate override: : [, ]: `. + */ +export function quotedRulingOverride(body, binding, check) { + return gateOverrideEntries(body, binding).some(({ reason }) => { + const [names, ...rest] = reason.split(":"); + return names.split(",").map((name) => name.trim().toLowerCase()).includes(check) && QUOTED_RULING.test(rest.join(":")); + }); +} + /** An entry must name only recognized checks and contain a specific reason. */ export function overriddenChecks(body, binding) { const covered = new Set(); diff --git a/plugins/vibe/lib/handoff/scripts/handoff-gate-check.mjs b/plugins/vibe/lib/handoff/scripts/handoff-gate-check.mjs index 5e169eb2..fc628e22 100644 --- a/plugins/vibe/lib/handoff/scripts/handoff-gate-check.mjs +++ b/plugins/vibe/lib/handoff/scripts/handoff-gate-check.mjs @@ -81,8 +81,8 @@ export function pathCitationProblem(worktree, citations = [], evidence = []) { return null; } -/** Current gate problem, or null when the final inventory covered this source. */ -export function handoffGateProblem(worktree, { base, bodyFile, title } = {}) { +/** Current witness problem. The PR-create boundary also verifies proof receipts for new pull requests. */ +export function handoffGateProblem(worktree, { base, bodyFile, title, creatingPullRequest = false } = {}) { try { readPrBodyFile(bodyFile, 8 * 1024 * 1024); } catch (error) { if (error instanceof BodyFileError) return error.message; throw error; } let record; @@ -117,9 +117,13 @@ export function handoffGateProblem(worktree, { base, bodyFile, title } = {}) { for (const [key, label] of Object.entries(DOCUMENT_EVIDENCE)) { if ((record.evidence?.[key] ?? []).some(saved => JSON.stringify(evidenceFingerprint(saved.path)) !== JSON.stringify(saved))) return `handoff ${label} evidence changed`; } - const proofs = proofGateProblems(worktree, { base: record.base?.oid, bodyText: readFileSync(bodyFile, "utf8"), - ticketText: proofTicketText(record.evidence?.ticket?.path, (record.evidence?.members ?? []).map((saved) => saved.path)), runs: JSON.parse(readFileSync(record.evidence.runs.path, "utf8")) }); - if (proofs.length) return `handoff proof receipts: ${proofs.join("; ")}`; + if (creatingPullRequest) { + // A pushed head never counts as accepted proof here. Read only the passed heads bound into this witness. + const proofs = proofGateProblems(worktree, { base: record.base?.oid, bodyText: readFileSync(bodyFile, "utf8"), + ticketText: proofTicketText(record.evidence?.ticket?.path, (record.evidence?.members ?? []).map((saved) => saved.path)), runs: JSON.parse(readFileSync(record.evidence.runs.path, "utf8")), + accepted: { passed: Array.isArray(record.proofAccepted?.passed) ? record.proofAccepted.passed : [] } }); + if (proofs.length) return `handoff proof receipts: ${proofs.join("; ")}`; + } if (!Array.isArray(record.receipts)) return "handoff review receipt changed"; if (reviewReceiptProblems(readReviewReceipts(record.receipts), sourceIdentity(worktree), { worktree, reusableRoles: new Set(Array.isArray(record.reviewCarry) ? record.reviewCarry : []) }).problems.length) return "handoff review evidence is stale or incomplete"; diff --git a/plugins/vibe/lib/handoff/scripts/long-lived-branch-fixture.mjs b/plugins/vibe/lib/handoff/scripts/long-lived-branch-fixture.mjs new file mode 100644 index 00000000..621f0bf6 --- /dev/null +++ b/plugins/vibe/lib/handoff/scripts/long-lived-branch-fixture.mjs @@ -0,0 +1,62 @@ +// A Git history in the shape of fixtures/long-lived-branch-shape.json: a branch whose test cases were committed before +// the 2026-12-01 mutation-proof ruling, synced with main and pushed after it, then given new cases. Shared by the +// proof-scope tests and the refusing-check replay guard. + +import { execFileSync } from "node:child_process"; +import { mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from "node:fs"; +import { tmpdir } from "node:os"; +import path from "node:path"; +import { writeCiDeclaration } from "./full-ci-fixture.mjs"; + +export const LONG_LIVED_SHAPE = JSON.parse(readFileSync(new URL("./fixtures/long-lived-branch-shape.json", import.meta.url), "utf8")); +const RULING = Date.parse("2026-12-01T18:55:00Z"); +const DAY = 24 * 60 * 60 * 1000; + +/** An ISO time `days` from the ruling (negative is before it). */ +export const dayFromRuling = (days) => new Date(RULING + days * DAY).toISOString(); + +const caseFile = (index, cases) => `import test from "node:test";\n${Array.from({ length: cases }, (_, at) => `\ntest("inherited ${index} case ${at}", () => {\n console.log(${index}, ${at});\n});\n`).join("")}`; +const sharedFile = (index, value) => `import test from "node:test";\nconst shared = ${value};\n\ntest("main ${index} case", () => {\n console.log(shared);\n});\n`; + +/** + * Build the history in a new repository: `main` with the shared test files, a `vibe/long-lived` branch that adds the + * inherited cases over the shape's pre-ruling days and edits each shared file outside its case, a later main commit, + * a sync merge of main on the shape's sync day (the pushed head) and the shape's new cases after it, uncommitted + * unless `commitNew`. Main declares its CI workflow as its lane source. Returns the worktree, main's tip, the pushed head + * and a git runner. + */ +export function longLivedBranch(t, { shape = LONG_LIVED_SHAPE, commitNew = true } = {}) { + const root = mkdtempSync(path.join(tmpdir(), "vibe-long-lived-")); + t.after(() => rmSync(root, { recursive: true, force: true })); + const worktree = path.join(root, "wt"); + mkdirSync(path.join(worktree, "src"), { recursive: true }); + const git = (args, at) => execFileSync("git", ["-C", worktree, "-c", "user.email=test@example.com", "-c", "user.name=Test", ...args], + { encoding: "utf8", env: { ...process.env, ...(at ? { GIT_AUTHOR_DATE: at, GIT_COMMITTER_DATE: at } : {}) } }).trim(); + const commit = (message, at) => { git(["add", "-A"]); git(["commit", "-qm", message], at); return git(["rev-parse", "HEAD"]); }; + execFileSync("git", ["init", "-q", "-b", "main", worktree]); + const { caseFiles, cases, fileLevelFiles, commitsByDay } = shape.inherited; + for (let index = 0; index < fileLevelFiles; index += 1) writeFileSync(path.join(worktree, "src", `shared-${index}.test.mjs`), sharedFile(index, 0)); + writeFileSync(path.join(worktree, "src", "code.mjs"), "export const value = 1;\n"); + writeCiDeclaration(worktree); + commit("base", dayFromRuling(-30)); + git(["checkout", "-q", "-b", "vibe/long-lived"]); + const perFile = Array.from({ length: caseFiles }, (_, index) => Math.floor(cases / caseFiles) + (index < cases % caseFiles ? 1 : 0)); + const edits = [...perFile.map((count, index) => () => writeFileSync(path.join(worktree, "src", `inherited-${index}.test.mjs`), caseFile(index, count))), + ...Array.from({ length: fileLevelFiles }, (_, index) => () => writeFileSync(path.join(worktree, "src", `shared-${index}.test.mjs`), sharedFile(index, 1)))]; + const days = Object.entries(commitsByDay).flatMap(([day, count]) => Array.from({ length: count }, (_, at) => dayFromRuling(Number(day) + at / 1440))); + days.forEach((at, index) => { + edits.filter((_, edit) => edit % days.length === index).forEach((apply) => apply()); + commit(`inherited ${index}`, at); + }); + git(["checkout", "-q", "main"]); + writeFileSync(path.join(worktree, "src", "main-only.test.mjs"), `import test from "node:test";\n\ntest("main only", () => {});\n`); + const main = commit("main moves on", dayFromRuling(shape.syncWithMainDay - 0.5)); + git(["checkout", "-q", "vibe/long-lived"]); + git(["merge", "-q", "--no-edit", "main"], dayFromRuling(shape.syncWithMainDay)); + const pushed = git(["rev-parse", "HEAD"]); + writeFileSync(path.join(worktree, "src", "new.test.mjs"), `import test from "node:test";\n${Array.from({ length: shape.newCases }, (_, at) => `\ntest("new case ${at}", () => {});\n`).join("")}`); + const head = commitNew ? commit("new cases", dayFromRuling(shape.newCasesDay)) : null; + const gitDir = git(["rev-parse", "--absolute-git-dir"]); + writeFileSync(path.join(gitDir, "vibe-session.json"), JSON.stringify({ status: "active", summary: "Add a filter", flagKeys: { surfaces: [] } })); + return { root, worktree, gitDir, main, pushed, head, git: (...args) => git(args), commit }; +} diff --git a/plugins/vibe/lib/handoff/scripts/proof-receipts.mjs b/plugins/vibe/lib/handoff/scripts/proof-receipts.mjs index 9b2dd107..b4f1161d 100644 --- a/plugins/vibe/lib/handoff/scripts/proof-receipts.mjs +++ b/plugins/vibe/lib/handoff/scripts/proof-receipts.mjs @@ -9,7 +9,8 @@ // cite a program decision line (proof-acceptance.mjs). A reproduction and a command // run bind to the source they ran on by tree, the way review receipts do, so // committing that tree keeps them. A mutation proof holds until its own test or -// the code it tests changes (operator ruling, 2026-12-01). The handoff gate, its PR-create read side and the fleet push-check +// the code it tests changes (operator ruling, 2026-12-01). Which changed cases need one is proof-scope.mjs's rule +// (operator rulings, 2026-12-01 and 2026-12-02). The handoff gate, its PR-create read side and the fleet push-check // refuse through proofGateProblems (a non-vibe row: bodyCommandProblems); the // review launch refuses a session with no flag-keys record through // flag-keys.mjs's flagKeysBeforeReviewProblem. @@ -32,7 +33,7 @@ // proof-receipts.mjs refresh --worktree (reruns every recorded command and expired mutant on the current source) // proof-receipts.mjs inventory --worktree (writes the decision table's Mutant Inventory from the mutation log) // proof-receipts.mjs show --worktree -// proof-receipts.mjs check --worktree --base --body --ticket [--member ...] [--runs ] [--head ] +// proof-receipts.mjs check --worktree --base --body --ticket [--member ...] [--runs ] [--head ] [--pushed (push-check only)] // Every command prints one JSON object; a refusal exits 1. import { execFileSync, spawnSync } from "node:child_process"; @@ -50,6 +51,7 @@ import { isCollectedTestFile, isTestFile } from "../../../skills/vibe/scripts/te import { flagKeyProblems } from "../../../skills/vibe/scripts/flag-keys.mjs"; import { testIntegrityCandidates, testIntegrityProblems } from "../../../skills/handoff/scripts/test-integrity.mjs"; import { isEntryPoint } from "../../../shared/plugin-roots.mjs"; +import { acceptedSnapshots, ProofExemption, proofExemptions, skipsCase } from "./proof-scope.mjs"; const RECEIPT_FILE = "vibe-proof-receipt.json"; const KINDS = new Set(["bug-fix", "feature"]); @@ -512,7 +514,7 @@ function changedTests(worktree, base, head) { return tests.map((file) => { const source = read(file); const all = { added: source.split("\n").map((_, index) => index + 1), deleted: [] }; - return { file, source, ...(untracked.includes(file) ? all : hunks.get(file) ?? { added: [], deleted: [] }) }; + return { file, source, untracked: untracked.includes(file), ...(untracked.includes(file) ? all : hunks.get(file) ?? { added: [], deleted: [] }) }; }); } @@ -564,30 +566,41 @@ function integritySubstitute(worktree, head, changed, runs, current) { }); } -function testProofProblems(worktree, base, head, receipt, current, runs, view) { +function testProofProblems(worktree, base, head, receipt, current, runs, view, accepted) { const changed = changedTests(worktree, base, head); + const exempt = proofExemptions(worktree, { snapshots: acceptedSnapshots(worktree, { comparisonBase: base, head, ...accepted }), head, tests: changed }); const substitutes = integritySubstitute(worktree, head, changed, runs, current); const holds = (proof) => stillHolds(proof, view) && proof.mutatedExit !== 0 && proof.restoredPass === true; const authored = (proof) => proof.authoring?.requestId && GRANTS.has(proof.authoring.grant); + const expired = (label, proof) => `${label}: its mutation proof no longer holds: its test file's shared code or ${proof.target} changed, or it has no hashes of them (proof-receipts.mjs refresh)`; const problems = []; for (const { file, source, added, deleted } of changed) { const changes = changedTestCases(file, source, added, deleted); if (!changes) { - problems.push(unreadableTest(file)); + if (!exempt.file(file)) problems.push(unreadableTest(file)); continue; } const { cases, fileLevel } = changes; for (const name of cases) { - if (substitutes(file, name)) continue; + const exemption = exempt.testCase(file, source, name); + if (skipsCase(exemption) || substitutes(file, name)) continue; const proof = receipt.mutations.find((entry) => entry.path === file && entry.case === name); const label = `test ${file} case "${name}"`; + if (exemption === ProofExemption.Passed) { + if (proof && !holds(proof)) problems.push(expired(label, proof)); + continue; + } if (proof && proof.caseSha256 !== caseHash(file, source, name)) problems.push(`${label} changed since its mutation proof; record a new one (proof-receipts.mjs mutation)`); else if (!proof) problems.push(`${label} has no mutation proof (proof-receipts.mjs mutation)`); - else if (!holds(proof)) problems.push(`${label}: its mutation proof no longer holds: its test file's shared code or ${proof.target} changed, or it has no hashes of them (proof-receipts.mjs refresh)`); + else if (!holds(proof)) problems.push(expired(label, proof)); else if (!authored(proof)) problems.push(`${label}: its mutation proof has no test-authoring record (turn and grant)`); else if (!loggedProof(receipt, proof, view)) problems.push(`${label}: its proof (mutant "${proof.mutation}") does not match the mutation log; record it again (proof-receipts.mjs mutation)`); } - if (fileLevel && !cases.length && !receipt.mutations.some((proof) => proof.path === file && holds(proof) && authored(proof) && loggedProof(receipt, proof, view))) { + if (!fileLevel || cases.length) continue; + const exemption = exempt.fileLevel(file, source); + const fileProofs = receipt.mutations.filter((proof) => proof.path === file); + if (skipsCase(exemption) || (exemption === ProofExemption.Passed && !fileProofs.length)) continue; + if (exemption === ProofExemption.Passed ? !fileProofs.some(holds) : !fileProofs.some((proof) => holds(proof) && authored(proof) && loggedProof(receipt, proof, view))) { problems.push(`test ${file} changed outside any case and has no mutation proof that still holds with its test-authoring record (proof-receipts.mjs mutation)`); } } @@ -682,9 +695,11 @@ const quotedIn = (entry) => entry.in ?? "ticket"; * in the body, the ticket or a changed runbook without a matching passing run, and an added or changed test without a * 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. + * otherwise the worktree's current source is checked. `accepted` names the heads + * whose cases the gate already accepted ({ pushed, passed }: proof-scope.mjs); + * only push-check passes a pushed head. */ -export function proofGateProblems(worktree, { base, head, bodyText = "", ticketText: suppliedTicket, runs = {} } = {}) { +export function proofGateProblems(worktree, { base, head, bodyText = "", ticketText: suppliedTicket, runs = {}, accepted = {} } = {}) { const record = readSessionRecord(worktree); const problems = flagKeyProblems(record).map((problem) => `flag keys: ${problem}`); const ticket = sessionLiveTicket(record ?? {}); @@ -704,7 +719,7 @@ export function proofGateProblems(worktree, { base, head, bodyText = "", ticketT problems.push(...commandProblems(receipt, [...found(operatorCommands(bodyText), "body"), ...found(operatorCommands(ticketText), "ticket"), ...runbookCommands(worktree, comparisonBase, fullHead)], current, ticket)); const view = sourceView(worktree, fullHead, current); - problems.push(...testProofProblems(worktree, comparisonBase, fullHead, receipt, current, runs, view), ...mutantInventoryProblems(worktree, receipt, view)); + problems.push(...testProofProblems(worktree, comparisonBase, fullHead, receipt, current, runs, view, accepted), ...mutantInventoryProblems(worktree, receipt, view)); return problems; } @@ -739,19 +754,35 @@ export function proofTicketText(ticketFile, memberFiles = []) { } /** The push-check form: the head's committed tree, with the body, tickets and runs the handoff gate witness bound when no body is given. */ -export function pushReadyProofProblems(worktree, { base, head, bodyFile, witness }) { +export function pushReadyProofProblems(worktree, { base, head, bodyFile, witness, pushed = [] }) { const evidence = witness && existsSync(witness) ? JSON.parse(readFileSync(witness, "utf8")).evidence ?? {} : {}; const read = (file) => file && existsSync(file) ? readFileSync(file, "utf8") : ""; const ticketFile = evidence.ticket?.path && existsSync(evidence.ticket.path) ? evidence.ticket.path : null; return proofGateProblems(worktree, { base, head, bodyText: read(bodyFile ?? evidence.body?.path), - ticketText: proofTicketText(ticketFile, (evidence.members ?? []).map((saved) => saved.path)), runs: JSON.parse(read(evidence.runs?.path) || "{}") }); + ticketText: proofTicketText(ticketFile, (evidence.members ?? []).map((saved) => saved.path)), runs: JSON.parse(read(evidence.runs?.path) || "{}"), + accepted: { pushed, passed: passedGateHeads(worktree) } }); +} + +/** The last head that passed the handoff gate, as a list for `accepted.passed`; empty when none is recorded. */ +export function passedGateHeads(worktree) { + const head = readProofReceipt(worktree).gatePassed?.head; + return typeof head === "string" && /^[a-f0-9]{40}$/.test(head) ? [head] : []; +} + +/** Record a passing handoff gate's head, when the source it passed is exactly that commit; otherwise keep the last one. */ +export function recordGatePass(worktree, source) { + let committed = null; + try { committed = committedSourceIdentity(worktree, source?.head).treeSha256; } catch { return null; } + if (committed !== source.treeSha256) return null; + return update(worktree, (receipt) => { receipt.gatePassed = { head: source.head, at: new Date().toISOString() }; }).gatePassed; } if (isEntryPoint(import.meta.url)) { const [action] = process.argv.slice(2); const { values } = parseArgs({ args: process.argv.slice(3), options: { ...Object.fromEntries(["worktree", "kind", "source", "parent", "surface", "data", "steps", "parent-evidence", "fix-evidence", "parent-command", "fix-command", "missing", "reason", "by", "run", "timeout", "path", "case", "target", "mutation", - "find", "replace", "command", "request", "grant", "base", "head", "body", "ticket", "runs", "ruling", "for", "in"].map((name) => [name, { type: "string" }])), member: { type: "string", multiple: true } } }); + "find", "replace", "command", "request", "grant", "base", "head", "body", "ticket", "runs", "ruling", "for", "in"].map((name) => [name, { type: "string" }])), + member: { type: "string", multiple: true }, pushed: { type: "string", multiple: true } } }); try { const worktree = required(values.worktree, "--worktree"); const timeoutSeconds = values.timeout ? Number(values.timeout) : undefined; @@ -772,7 +803,8 @@ if (isEntryPoint(import.meta.url)) { inventory: () => writeMutantInventory(worktree), check: () => { const problems = proofGateProblems(worktree, { base: required(values.base, "--base"), head: values.head, bodyText: read(values.body), - ticketText: proofTicketText(values.ticket, values.member ?? []), runs: values.runs ? JSON.parse(read(values.runs)) : {} }); + ticketText: proofTicketText(values.ticket, values.member ?? []), runs: values.runs ? JSON.parse(read(values.runs)) : {}, + accepted: { pushed: values.pushed ?? [], passed: passedGateHeads(worktree) } }); return { ok: problems.length === 0, problems }; }, }; diff --git a/plugins/vibe/lib/handoff/scripts/proof-scope.mjs b/plugins/vibe/lib/handoff/scripts/proof-scope.mjs new file mode 100644 index 00000000..0df3281d --- /dev/null +++ b/plugins/vibe/lib/handoff/scripts/proof-scope.mjs @@ -0,0 +1,100 @@ +// Which changed test cases the mutation-proof gate asks about. The gate diffs a branch against its merge base, so a +// long-lived branch built before the mutation-proof ruling (operator ruling, 2026-12-01) was refused for every test it +// ever changed. The scope rule (operator rulings, 2026-12-02): +// - A case whose text at the checked source equals its text at the branch's last commit before the 2026-12-01 ruling +// (first-parent, by committer time) is never asked about, even when an old proof of it expired. +// - At push-check only, a case unchanged since the upstream head (the last pushed head) is not asked about. The handoff +// gate and PR create do not count a pushed head: a redeploy push never passed the gate. +// - At all three, a case unchanged since the last head that passed the handoff gate is asked about only when its +// recorded mutation proof no longer holds (its test or the code it tests changed), as the 2026-12-01 ruling says. +// A case is unchanged since a snapshot when no line inside it was added or deleted between the snapshot, merged with the +// comparison base the way a sync with main merges it, and the checked source. A deletion inside an old case brings it +// back into scope; what a sync with main brought into a branch's old case does not. + +import { execFileSync, spawnSync } from "node:child_process"; +import { addedLineNumbers, changedTestCases } from "./proof-parsers.mjs"; + +/** The 2026-12-01 mutation-proof ruling, about 12:55 PM CST. */ +export const MUTATION_RULING_AT = "2026-12-01T18:55:00Z"; + +/** Why a changed case is out of the gate's scope. Ruling and Pushed skip it; Passed still asks about an expired proof. */ +export const ProofExemption = Object.freeze({ Ruling: "ruling", Pushed: "pushed", Passed: "passed" }); + +const STRENGTH = Object.freeze({ [ProofExemption.Ruling]: 2, [ProofExemption.Pushed]: 2, [ProofExemption.Passed]: 1 }); + +/** Whether an exemption skips the case outright, with no question about an expired proof. */ +export const skipsCase = (exemption) => exemption === ProofExemption.Ruling || exemption === ProofExemption.Pushed; + +/** + * The commits whose cases the gate already accepted, each with its exemption: the branch's last commit before the ruling + * and each given pushed or passed head. A snapshot inside the comparison base adds nothing and is dropped, and so is a + * head this repository cannot resolve. + */ +export function acceptedSnapshots(worktree, { comparisonBase, head, pushed = [], passed = [] }) { + const git = (...args) => execFileSync("git", ["-C", worktree, ...args], { encoding: "utf8", stdio: ["ignore", "pipe", "ignore"] }).trim(); + const snapshots = []; + const add = (exemption, ref) => { + if (typeof ref !== "string" || !ref.trim()) return; + let sha; + try { sha = git("rev-parse", "--verify", "--end-of-options", `${ref.trim()}^{commit}`); } catch { return; } + try { git("merge-base", "--is-ancestor", sha, comparisonBase); return; } catch { /* Not inside the base: it counts. */ } + snapshots.push({ exemption, sha, tree: syncedTree(worktree, sha, comparisonBase) }); + }; + let ruling = ""; + try { ruling = git("rev-list", "-1", "--first-parent", `--before=${MUTATION_RULING_AT}`, head ?? "HEAD"); } catch { /* No such commit. */ } + add(ProofExemption.Ruling, ruling); + for (const ref of pushed) add(ProofExemption.Pushed, ref); + for (const ref of passed) add(ProofExemption.Passed, ref); + return snapshots; +} + +/** + * The snapshot merged with the comparison base, as a tree: what the branch held then, synced with what main holds now. + * A conflicted file keeps its markers, so its conflicted lines count as changed since. When Git cannot merge them at + * all, the snapshot's own commit stands in. + */ +function syncedTree(worktree, sha, comparisonBase) { + const merged = spawnSync("git", ["-C", worktree, "merge-tree", "--write-tree", "--no-messages", sha, comparisonBase], { encoding: "utf8", maxBuffer: 64 * 1024 * 1024 }); + const tree = (merged.status === 0 || merged.status === 1) ? merged.stdout.split("\n")[0].trim() : ""; + return /^[a-f0-9]{40,64}$/.test(tree) ? tree : sha; +} + +/** + * The exemption of each changed test, case and file-level change, from the snapshots: for each, the strongest snapshot + * it is unchanged since, or null. `tests` are the gate's changed tests ({ file, source, untracked }); an untracked file + * is new since every snapshot. + */ +export function proofExemptions(worktree, { snapshots, head, tests }) { + const tracked = tests.filter((entry) => !entry.untracked).map((entry) => entry.file); + const since = snapshots.map(({ exemption, tree }) => { + const diff = tracked.length ? execFileSync("git", ["-C", worktree, "diff", "-U0", "--no-renames", "--no-color", "--no-ext-diff", "--src-prefix=a/", "--dst-prefix=b/", + tree, ...(head ? [head] : []), "--", ...tracked], { encoding: "utf8", maxBuffer: 256 * 1024 * 1024 }) : ""; + return { exemption, lines: addedLineNumbers(diff) }; + }); + const untracked = new Set(tests.filter((entry) => entry.untracked).map((entry) => entry.file)); + const strongest = (test) => { + let found = null; + for (const snapshot of since) if (test(snapshot) && (!found || STRENGTH[snapshot.exemption] > STRENGTH[found])) found = snapshot.exemption; + return found; + }; + const changes = new Map(); + const changesSince = (snapshot, file, source) => { + const key = `${since.indexOf(snapshot)}\0${file}`; + if (!changes.has(key)) { + const lines = snapshot.lines.get(file) ?? { added: [], deleted: [] }; + changes.set(key, changedTestCases(file, source, lines.added, lines.deleted)); + } + return changes.get(key); + }; + return { + file: (file) => untracked.has(file) ? null : strongest((snapshot) => !snapshot.lines.has(file)), + testCase: (file, source, name) => untracked.has(file) ? null : strongest((snapshot) => { + const found = changesSince(snapshot, file, source); + return Boolean(found) && !found.cases.includes(name); + }), + fileLevel: (file, source) => untracked.has(file) ? null : strongest((snapshot) => { + const found = changesSince(snapshot, file, source); + return Boolean(found) && !found.fileLevel; + }), + }; +} diff --git a/plugins/vibe/lib/handoff/scripts/proof-scope.test.mjs b/plugins/vibe/lib/handoff/scripts/proof-scope.test.mjs new file mode 100644 index 00000000..7062380a --- /dev/null +++ b/plugins/vibe/lib/handoff/scripts/proof-scope.test.mjs @@ -0,0 +1,149 @@ +import assert from "node:assert/strict"; +import { execFileSync } from "node:child_process"; +import { mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from "node:fs"; +import { tmpdir } from "node:os"; +import path from "node:path"; +import test from "node:test"; +import { passedGateHeads, proofGateProblems, pushReadyProofProblems, readProofReceipt, recordGatePass, recordMutationProof } from "./proof-receipts.mjs"; +import { dayFromRuling, LONG_LIVED_SHAPE, longLivedBranch } from "./long-lived-branch-fixture.mjs"; +import { sourceIdentity } from "../../vibe/scripts/tested-head.mjs"; + +const NO_PROOF = /has no mutation proof/; +const BEFORE = dayFromRuling(-3); +const AFTER = dayFromRuling(1); + +/** A repository on `main` with code, and a session record, ready for a `vibe/scope` branch. */ +function repo(t) { + const root = mkdtempSync(path.join(tmpdir(), "vibe-proof-scope-")); + t.after(() => rmSync(root, { recursive: true, force: true })); + const worktree = path.join(root, "wt"); + mkdirSync(path.join(worktree, "src"), { recursive: true }); + const git = (args, at) => execFileSync("git", ["-C", worktree, "-c", "user.email=test@example.com", "-c", "user.name=Test", ...args], + { encoding: "utf8", env: { ...process.env, ...(at ? { GIT_AUTHOR_DATE: at, GIT_COMMITTER_DATE: at } : {}) } }).trim(); + const write = (file, text) => writeFileSync(path.join(worktree, file), text); + const commit = (message, at) => { git(["add", "-A"]); git(["commit", "-qm", message], at); return git(["rev-parse", "HEAD"]); }; + execFileSync("git", ["init", "-q", "-b", "main", worktree]); + write("src/add.mjs", "export const add = (a, b) => a + b;\n"); + const main = commit("base", dayFromRuling(-30)); + git(["checkout", "-q", "-b", "vibe/scope"]); + writeFileSync(path.join(git(["rev-parse", "--absolute-git-dir"]), "vibe-session.json"), JSON.stringify({ status: "active", summary: "Add a filter", flagKeys: { surfaces: [] } })); + return { worktree, main, git, write, commit }; +} + +const testFile = (cases) => `import assert from "node:assert/strict";\nimport test from "node:test";\nimport { add } from "./add.mjs";\n${cases.map(([name, body]) => `\ntest("${name}", () => {\n${body}\n});\n`).join("")}`; +const gate = (r, options = {}) => proofGateProblems(r.worktree, { base: r.main, ticketText: "", bodyText: "", ...options }); +const cases = (problems) => problems.map((line) => /case "([^"]+)"/.exec(line)?.[1] ?? line).sort(); + +test("AC-1 a case last committed before the 2026-12-01 ruling needs no proof; one added or changed after it does, on a branch begun before it", (t) => { + const r = repo(t); + r.write("src/add.test.mjs", testFile([["old one", " assert.equal(add(1, 2), 3);"], ["old two", " assert.equal(add(2, 2), 4);"]])); + r.commit("old cases", BEFORE); + r.write("src/add.test.mjs", testFile([["old one", " assert.equal(add(1, 2), 3);"], ["old two", " assert.equal(add(2, 3), 5);"], ["new one", " assert.equal(add(0, 0), 0);"]])); + const head = r.commit("new case and a changed old one", AFTER); + for (const [where, options] of [["push-check", { head }], ["handoff and PR create", {}]]) { + const problems = gate(r, options); + assert.deepEqual(cases(problems), ["new one", "old two"], where); + assert.ok(problems.every((line) => NO_PROOF.test(line)), where); + } + r.write("src/add.test.mjs", testFile([["old one", " assert.equal(add(1, 1), 2);"], ["old two", " assert.equal(add(2, 3), 5);"], ["new one", " assert.equal(add(0, 0), 0);"]])); + assert.deepEqual(cases(gate(r)), ["new one", "old one", "old two"], "an uncommitted change to an old case is a change after the ruling"); +}); + +test("AC-1 a line deleted after the ruling inside a case committed before it brings the case back into scope", (t) => { + const r = repo(t); + r.write("src/add.test.mjs", testFile([["old one", " assert.equal(add(1, 2), 3);\n assert.equal(add(2, 2), 4);"]])); + r.commit("old case", BEFORE); + assert.deepEqual(gate(r), []); + r.write("src/add.test.mjs", testFile([["old one", " assert.equal(add(1, 2), 3);"]])); + const head = r.commit("weaken the old case", AFTER); + assert.deepEqual(cases(gate(r, { head })), ["old one"]); +}); + +test("AC-2 a long-lived branch with many inherited cases, a main sync and one new case gets exactly one refusal", (t) => { + const shape = LONG_LIVED_SHAPE; + const f = longLivedBranch(t); + const check = (options) => proofGateProblems(f.worktree, { base: f.main, ticketText: "", bodyText: "", ...options }); + assert.deepEqual(check({ head: f.head, accepted: { pushed: [f.pushed] } }).map((line) => line.replace(/"[^"]+"/, "")), + ["test src/new.test.mjs case has no mutation proof (proof-receipts.mjs mutation)"], "push-check"); + assert.equal(check({ head: f.head }).length, shape.newCases, "the handoff gate and PR create read the same pre-ruling scope"); + const uncommitted = longLivedBranch(t, { commitNew: false }); + assert.equal(proofGateProblems(uncommitted.worktree, { base: uncommitted.main, ticketText: "", bodyText: "" }).length, shape.newCases, "an uncommitted new case at handoff"); +}); + +/** A branch begun after the ruling: two cases passed the gate at `passed`, one more was pushed by a redeploy, main was synced and a fourth added. */ +function afterRuling(t) { + const r = repo(t); + r.write("src/add.test.mjs", testFile([["gated", " assert.equal(add(1, 2), 3);"]])); + const passed = r.commit("gated case", dayFromRuling(1)); + r.write("src/add.test.mjs", testFile([["gated", " assert.equal(add(1, 2), 3);"], ["redeployed", " assert.equal(add(2, 2), 4);"]])); + const pushed = r.commit("redeployed case", dayFromRuling(1.1)); + r.git(["checkout", "-q", "main"]); + r.write("src/main.test.mjs", `import test from "node:test";\n\ntest("main case", () => {});\n`); + r.main = r.commit("main moves on", dayFromRuling(1.2)); + r.git(["checkout", "-q", "vibe/scope"]); + r.git(["merge", "-q", "--no-edit", "main"], dayFromRuling(1.3)); + r.write("src/add.test.mjs", testFile([["gated", " assert.equal(add(1, 2), 3);"], ["redeployed", " assert.equal(add(2, 2), 4);"], ["latest", " assert.equal(add(0, 0), 0);"]])); + const head = r.commit("latest case", dayFromRuling(1.4)); + return { ...r, passed, pushed, head }; +} + +test("AC-2 after a redeploy push past the last gate pass, push-check asks only what changed since the push; handoff and PR create ask what changed since the pass", (t) => { + const r = afterRuling(t); + assert.deepEqual(cases(gate(r, { head: r.head, accepted: { pushed: [r.pushed], passed: [r.passed] } })), ["latest"], "push-check"); + assert.deepEqual(cases(gate(r, { head: r.head, accepted: { passed: [r.passed] } })), ["latest", "redeployed"], "handoff gate"); + assert.deepEqual(cases(gate(r, { accepted: { passed: [r.passed] } })), ["latest", "redeployed"], "PR create reads the worktree with the gate's passed heads"); + assert.deepEqual(cases(gate(r, { head: r.head })), ["gated", "latest", "redeployed"], "no accepted head: every case changed after the ruling"); +}); + +test("AC-2 the push-check form reads the last passed gate head from the receipt and the pushed head from its caller", (t) => { + const r = afterRuling(t); + assert.deepEqual(passedGateHeads(r.worktree), []); + r.git(["checkout", "-q", r.passed]); + assert.equal(recordGatePass(r.worktree, sourceIdentity(r.worktree)).head, r.passed); + r.git(["checkout", "-q", "vibe/scope"]); + r.write("src/scratch.txt", "uncommitted\n"); + assert.equal(recordGatePass(r.worktree, sourceIdentity(r.worktree)), null, "a gate pass on uncommitted source is no commit to compare with"); + assert.deepEqual(passedGateHeads(r.worktree), [r.passed]); + const push = (pushed) => cases(pushReadyProofProblems(r.worktree, { base: r.main, head: r.head, pushed })); + assert.deepEqual(push([r.pushed]), ["latest"]); + assert.deepEqual(push([]), ["latest", "redeployed"]); +}); + +test("ruling split: a case committed before the ruling is never asked, even when its old proof expired", (t) => { + const r = repo(t); + r.write("src/add.test.mjs", testFile([["old one", " assert.equal(add(1, 2), 3);"]])); + r.commit("old case", BEFORE); + const receipt = path.join(r.git(["rev-parse", "--absolute-git-dir"]), "vibe-proof-receipt.json"); + writeFileSync(receipt, JSON.stringify({ mutations: [{ path: "src/add.test.mjs", case: "old one", target: "src/add.mjs", caseSha256: "0".repeat(64), testSha256: "0".repeat(64), targetSha256: "0".repeat(64), mutatedExit: 1, restoredPass: true }] })); + r.write("src/add.mjs", "export const add = (a, b) => b + a;\n"); + const head = r.commit("the code under test changes", AFTER); + const testLines = (problems) => problems.filter((line) => line.startsWith("test ")); + assert.deepEqual(testLines(gate(r, { head })), []); + assert.deepEqual(testLines(gate(r, { head, accepted: { passed: [head] } })), []); +}); + +test("ruling split: a case exempt only by the last gate pass is still asked when the code it tests changed", (t) => { + const r = repo(t); + r.write("src/add.test.mjs", testFile([["adds", " assert.equal(add(1, 2), 3);"]])); + r.commit("case", AFTER); + recordMutationProof(r.worktree, { path: "src/add.test.mjs", case: "adds", target: "src/add.mjs", mutation: "add subtracts", find: "a + b", replace: "a - b", + command: "node --test src/add.test.mjs", request: "r1-build", grant: "tests-required" }); + const passed = r.git(["rev-parse", "HEAD"]); + assert.ok(gate(r, { head: passed }).every((line) => !/case "adds"/.test(line)), "the proof holds where the gate passed"); + r.write("src/add.mjs", "export const add = (a, b) => b + a;\n"); + const head = r.commit("the code under test changes", dayFromRuling(2)); + const asked = gate(r, { head, accepted: { passed: [passed] } }).filter((line) => /case "adds"/.test(line)); + assert.equal(asked.length, 1); + assert.match(asked[0], /its mutation proof no longer holds/); + assert.equal(readProofReceipt(r.worktree).mutations.length, 1); +}); + +test("ruling split: a case exempt at push-check only by the pushed head, never proven, is asked at the handoff gate and PR create", (t) => { + const r = repo(t); + r.write("src/add.test.mjs", testFile([["pushed only", " assert.equal(add(1, 2), 3);"]])); + const pushed = r.commit("pushed case", AFTER); + assert.deepEqual(gate(r, { head: pushed, accepted: { pushed: [pushed] } }), [], "push-check"); + assert.deepEqual(cases(gate(r, { head: pushed })), ["pushed only"], "handoff gate"); + assert.deepEqual(cases(gate(r)), ["pushed only"], "PR create"); + assert.match(readFileSync(path.join(r.worktree, "src/add.test.mjs"), "utf8"), /pushed only/); +}); diff --git a/plugins/vibe/lib/handoff/scripts/refusing-check-replay.mjs b/plugins/vibe/lib/handoff/scripts/refusing-check-replay.mjs new file mode 100644 index 00000000..dca61c39 --- /dev/null +++ b/plugins/vibe/lib/handoff/scripts/refusing-check-replay.mjs @@ -0,0 +1,87 @@ +#!/usr/bin/env node +// Replays the registered refusing checks (refusing-checks.mjs) against real worktrees, each at the head it already had +// accepted (its pushed upstream unless named), and writes the result as a receipt for the pull request's head. PR create +// refuses a pull request that changes a replayed check's source without a receipt for its exact tree that covers the +// changed checks, names at least one real target, and shows no refusal of accepted work, unless a ticketed gate override +// for "refusal replay" quotes the ruling that allows them (operator rulings, 2026-12-02 about 9:10 and 9:15 PM CST). +// Targets are only read, apart from the unreferenced merge objects `git merge-tree --write-tree` leaves in their +// object stores. +// +// Usage: refusing-check-replay.mjs --worktree --target [@]... +// [--check ]... +// Prints one line per target and check, and `RECEIPT `. Exits 1 when any check refused accepted work. + +import { execFileSync } from "node:child_process"; +import { existsSync, readFileSync, writeFileSync } from "node:fs"; +import path from "node:path"; +import { parseArgs } from "node:util"; +import { REFUSING_CHECKS, replayedChecksTouched } from "./refusing-checks.mjs"; +import { passedGateHeads } from "./proof-receipts.mjs"; +import { quotedRulingOverride } from "./gate-override.mjs"; +import { committedSourceIdentity } from "../../vibe/scripts/tested-head.mjs"; +import { isEntryPoint } from "../../../shared/plugin-roots.mjs"; + +export const REPLAY_RECEIPT = "vibe-refusal-replay.json"; +const REGISTRY_PATH = "plugins/vibe/lib/handoff/scripts/refusing-checks.mjs"; +/** The override check name: `Vibe gate override: : refusal replay: `. */ +export const REFUSAL_REPLAY_OVERRIDE = "refusal replay"; + +const git = (worktree, args) => execFileSync("git", ["-C", worktree, ...args], { encoding: "utf8", stdio: ["ignore", "pipe", "pipe"], maxBuffer: 64 * 1024 * 1024 }).trim(); +const receiptPath = (worktree) => path.join(git(worktree, ["rev-parse", "--absolute-git-dir"]), REPLAY_RECEIPT); + +/** Each replayed check's refusals for one target at its accepted head, `{ worktree, head, refusals: { [check]: string[] } }`. */ +export function replayTarget(worktree, head, checks) { + let base; + try { base = git(worktree, ["rev-parse", "--verify", "refs/remotes/origin/HEAD^{commit}"]); } + catch { base = git(worktree, ["rev-parse", "--verify", "refs/remotes/origin/main^{commit}"]); } + const input = { worktree, base, head, pushed: [head], passed: passedGateHeads(worktree), bodyText: "", binding: null }; + return { worktree, head, refusals: Object.fromEntries(checks.map((name) => [name, REFUSING_CHECKS[name].replay(input)])) }; +} + +/** + * Why `head` may not be raised before its changed refusing checks were replayed against real work, or null. Only a + * repository carrying this registry at `head` is asked; `base` is the PR base commit and `bodyText` the PR body, each + * or a function returning it. + */ +export function refusalReplayProblem(worktree, { base, head, bodyText = "", binding = null }) { + try { git(worktree, ["cat-file", "-e", `${head}:${REGISTRY_PATH}`]); } + catch { return null; } + const baseOid = typeof base === "function" ? base() : base; + const touched = replayedChecksTouched(git(worktree, ["diff", "--name-only", `${baseOid}...${head}`]).split("\n").filter(Boolean)); + if (!touched.length || quotedRulingOverride(typeof bodyText === "function" ? bodyText() : bodyText, binding, REFUSAL_REPLAY_OVERRIDE)) return null; + const fix = `run refusing-check-replay.mjs --worktree ${worktree} --target ... on this head, or add "Vibe gate override: : ${REFUSAL_REPLAY_OVERRIDE}: "`; + const file = receiptPath(worktree); + const receipt = existsSync(file) ? JSON.parse(readFileSync(file, "utf8")) : null; + if (receipt?.treeSha256 !== committedSourceIdentity(worktree, head).treeSha256) { + return `it changes refusing checks (${touched.join(", ")}) that have not been replayed against real work on this head; ${fix}`; + } + const missing = touched.filter((name) => !receipt.checks?.includes(name)); + if (missing.length || !receipt.targets?.length) return `the refusal replay on this head does not cover ${missing.length ? missing.join(", ") : "any real target"}; ${fix}`; + const refused = receipt.targets.flatMap((target) => touched.filter((name) => target.refusals?.[name] > 0).map((name) => `${name} refused ${target.refusals[name]} at ${target.head.slice(0, 12)}`)); + return refused.length ? `the refusal replay shows checks refusing accepted work (${refused.join("; ")}); fix them, or add "Vibe gate override: : ${REFUSAL_REPLAY_OVERRIDE}: "` : null; +} + +function main(argv) { + const { values } = parseArgs({ args: argv, options: { worktree: { type: "string" }, target: { type: "string", multiple: true }, check: { type: "string", multiple: true } } }); + if (!values.worktree || !values.target?.length) throw new Error("usage: refusing-check-replay.mjs --worktree --target [@]... [--check ]..."); + const checks = values.check?.length ? values.check : Object.keys(REFUSING_CHECKS).filter((name) => REFUSING_CHECKS[name].replay); + const unknown = checks.filter((name) => !REFUSING_CHECKS[name]?.replay); + if (unknown.length) throw new Error(`not a replayed check: ${unknown.join(", ")}`); + const targets = values.target.map((spec) => { + const [worktree, named] = spec.split("@"); + const head = git(worktree, ["rev-parse", "--verify", `${named || "@{upstream}"}^{commit}`]); + const replayed = replayTarget(worktree, head, checks); + for (const name of checks) process.stdout.write(`${head.slice(0, 12)} ${worktree} ${name}: ${replayed.refusals[name].length}\n`); + return { ...replayed, refusals: Object.fromEntries(Object.entries(replayed.refusals).map(([name, lines]) => [name, lines.length])) }; + }); + const head = git(values.worktree, ["rev-parse", "HEAD"]); + const file = receiptPath(values.worktree); + writeFileSync(file, `${JSON.stringify({ head, treeSha256: committedSourceIdentity(values.worktree, head).treeSha256, checks, targets, at: new Date().toISOString() }, null, 2)}\n`); + process.stdout.write(`RECEIPT ${file}\n`); + return targets.some((target) => Object.values(target.refusals).some((count) => count > 0)) ? 1 : 0; +} + +if (isEntryPoint(import.meta.url)) { + try { process.exitCode = main(process.argv.slice(2)); } + catch (error) { process.stderr.write(`${error.message}\n`); process.exitCode = 2; } +} diff --git a/plugins/vibe/lib/handoff/scripts/refusing-check-replay.test.mjs b/plugins/vibe/lib/handoff/scripts/refusing-check-replay.test.mjs new file mode 100644 index 00000000..271055fb --- /dev/null +++ b/plugins/vibe/lib/handoff/scripts/refusing-check-replay.test.mjs @@ -0,0 +1,70 @@ +// A pull request that changes a replayed refusing check needs that check replayed against real work on its exact tree +// (refusing-check-replay.mjs), read by PR create. +import assert from "node:assert/strict"; +import { execFileSync, spawnSync } from "node:child_process"; +import { mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from "node:fs"; +import { tmpdir } from "node:os"; +import path from "node:path"; +import test from "node:test"; +import { fileURLToPath } from "node:url"; +import { REFUSAL_REPLAY_OVERRIDE, REPLAY_RECEIPT, refusalReplayProblem } from "./refusing-check-replay.mjs"; +import { longLivedBranch } from "./long-lived-branch-fixture.mjs"; +import { CI_LANES, recordLanes } from "./full-ci-fixture.mjs"; + +const SCRIPT = fileURLToPath(new URL("./refusing-check-replay.mjs", import.meta.url)); +const SCRIPTS = "plugins/vibe/lib/handoff/scripts"; + +/** A plugin repository whose branch changes the proof scope, with origin's main at its base. */ +function pluginChange(t) { + const worktree = mkdtempSync(path.join(tmpdir(), "vibe-replay-pr-")); + t.after(() => rmSync(worktree, { recursive: true, force: true })); + const git = (...args) => execFileSync("git", ["-C", worktree, "-c", "user.email=test@example.com", "-c", "user.name=Test", ...args], { encoding: "utf8" }).trim(); + execFileSync("git", ["init", "-q", "-b", "main", worktree]); + mkdirSync(path.join(worktree, SCRIPTS), { recursive: true }); + writeFileSync(path.join(worktree, SCRIPTS, "refusing-checks.mjs"), "export {};\n"); + writeFileSync(path.join(worktree, SCRIPTS, "proof-scope.mjs"), "export const scope = 1;\n"); + git("add", "."); + git("commit", "-qm", "base"); + const base = git("rev-parse", "HEAD"); + git("update-ref", "refs/remotes/origin/main", base); + git("checkout", "-q", "-b", "feat/scope"); + writeFileSync(path.join(worktree, SCRIPTS, "proof-scope.mjs"), "export const scope = 2;\n"); + git("add", "."); + git("commit", "-qm", "change the scope"); + const receipt = path.join(git("rev-parse", "--absolute-git-dir"), REPLAY_RECEIPT); + return { worktree, git, base, head: git("rev-parse", "HEAD"), receipt }; +} + +test("class A: a change to a replayed check is refused until a replay against real work on its tree refuses nothing accepted", (t) => { + const pr = pluginChange(t); + const check = (bodyText = "") => refusalReplayProblem(pr.worktree, { base: pr.base, head: pr.head, bodyText }); + assert.match(check() ?? "", /changes refusing checks \(proofGateProblems, pushReadyProofProblems\) that have not been replayed against real work on this head/); + const target = longLivedBranch(t); + target.git("update-ref", "refs/remotes/origin/main", target.main); + target.git("branch", "pushed", target.pushed); + target.git("branch", "--set-upstream-to=pushed"); + recordLanes(target.worktree, target.pushed, CI_LANES.map(({ command }) => command)); + const run = spawnSync(process.execPath, [SCRIPT, "--worktree", pr.worktree, "--target", target.worktree], { encoding: "utf8", env: { ...process.env, CLAUDE_CODE_SESSION_ID: "" } }); + assert.equal(run.status, 0, run.stdout + run.stderr); + assert.match(run.stdout, new RegExp(`${target.pushed.slice(0, 12)} .+ pushReadyProofProblems: 0`)); + assert.equal(check(), null); + const receipt = JSON.parse(readFileSync(pr.receipt, "utf8")); + writeFileSync(pr.receipt, JSON.stringify({ ...receipt, targets: [{ ...receipt.targets[0], refusals: { ...receipt.targets[0].refusals, proofGateProblems: 551 } }] })); + assert.match(check() ?? "", /checks refusing accepted work \(proofGateProblems refused 551 at [0-9a-f]{12}\)/); + assert.equal(check(`Vibe gate override: #12: ${REFUSAL_REPLAY_OVERRIDE}: "cases changed after the ruling are asked" (orchestrator, 2026-12-02)\n`), null); + writeFileSync(pr.receipt, JSON.stringify({ ...receipt, targets: [] })); + assert.match(check() ?? "", /does not cover any real target/); + writeFileSync(pr.receipt, JSON.stringify({ ...receipt, treeSha256: "0".repeat(64) })); + assert.match(check() ?? "", /not been replayed against real work on this head/, "a replay of another tree does not count"); +}); + +test("class A: a change outside the replayed checks, or in a repository without the registry, needs no replay", (t) => { + const pr = pluginChange(t); + writeFileSync(path.join(pr.worktree, "README.md"), "docs\n"); + pr.git("add", "."); + pr.git("commit", "-qm", "docs"); + assert.ok(refusalReplayProblem(pr.worktree, { base: pr.head, head: pr.git("rev-parse", "HEAD") }) === null); + pr.git("rm", "-q", `${SCRIPTS}/refusing-checks.mjs`); + pr.git("commit", "-qm", "no registry"); + assert.equal(refusalReplayProblem(pr.worktree, { base: () => { throw new Error("not read"); }, head: pr.git("rev-parse", "HEAD") }), null); +}); diff --git a/plugins/vibe/lib/handoff/scripts/refusing-checks.mjs b/plugins/vibe/lib/handoff/scripts/refusing-checks.mjs new file mode 100644 index 00000000..1c83f459 --- /dev/null +++ b/plugins/vibe/lib/handoff/scripts/refusing-checks.mjs @@ -0,0 +1,75 @@ +// Every check that can refuse a writer's branch at the fleet push-check, the handoff gate or PR create, keyed by the +// function its gate calls or the refusal prefix push-check prints (refusing-checks.test.mjs enumerates both from the gate +// sources and fails on one missing here). A check with `replay` is run in Node Tests against a branch shaped like real +// long-lived work (long-lived-branch-fixture.mjs) and must refuse nothing that branch already had accepted; with +// refusing-check-replay.mjs it runs against real worktrees, and a pull request changing one of its `files` needs that +// run's receipt (pr-create-guard.mjs). Operator rulings, 2026-12-02 about 9:10 and 9:15 PM CST: a push guard that +// refused 551 tests on its first real branch "should have been caught before a PR was even raised"; "use +// prevent-recurrence so that we really fix that from ever happening again". +// +// UNREPLAYED holds the checks that predate this registry and have no replay yet. It only shrinks: give an entry a +// replay and move it to REFUSING_CHECKS, never add one. + +import { e2eGateProblems } from "./e2e-gate-check.mjs"; +import { fullCiProblem } from "./full-ci-check.mjs"; +import { proofGateProblems, pushReadyProofProblems } from "./proof-receipts.mjs"; +import { refusalReplayProblem } from "./refusing-check-replay.mjs"; + +const HANDOFF = "plugins/vibe/lib/handoff/scripts"; +const PROOF_FILES = [`${HANDOFF}/proof-receipts.mjs`, `${HANDOFF}/proof-scope.mjs`, `${HANDOFF}/proof-parsers.mjs`]; +const E2E_FILES = [`${HANDOFF}/e2e-gate-check.mjs`, "plugins/vibe/skills/vibe/scripts/e2e-requirement.mjs"]; + +/** + * Each replayed check: the source files that define it and `replay(input)`, its refusals for a branch at `head`, given + * `{ worktree, base, head, pushed, passed, bodyText, binding }` (pushed and passed are the heads the branch already had + * accepted). `via` names the entry a push-check prefix or a wrapper reports through. + */ +export const REFUSING_CHECKS = Object.freeze({ + proofGateProblems: { files: PROOF_FILES, gates: ["PR create"], + replay: ({ worktree, base, head, passed, bodyText }) => proofGateProblems(worktree, { base, head, bodyText, ticketText: "", accepted: { passed } }) }, + pushReadyProofProblems: { files: [...PROOF_FILES, "plugins/vibe/skills/fleet-orchestrator/scripts/push-proof.mjs"], gates: ["push-check"], + replay: ({ worktree, base, head, pushed }) => pushReadyProofProblems(worktree, { base, head, pushed }) }, + e2eGateProblems: { files: E2E_FILES, gates: ["PR create"], + replay: ({ worktree, base, head, bodyText, binding }) => e2eGateProblems(worktree, { base, head, bodyText, binding }) }, + fullCiProblem: { files: [`${HANDOFF}/full-ci-check.mjs`], gates: ["PR create"], + replay: ({ worktree, head, bodyText, binding }) => [fullCiProblem(worktree, head, { bodyText, binding })].filter(Boolean) }, + refusalReplayProblem: { files: [`${HANDOFF}/refusing-check-replay.mjs`, `${HANDOFF}/refusing-checks.mjs`], gates: ["PR create"], + replay: ({ worktree, base, head, bodyText, binding }) => [refusalReplayProblem(worktree, { base, head, bodyText, binding })].filter(Boolean) }, + "PROOF-MISSING": { via: "pushReadyProofProblems" }, + "E2E-NOT-RUN": { via: "e2eGateProblems" }, + "CI-NOT-RUN": { via: "fullCiProblem" }, + prReadinessProblem: { via: "fullCiProblem" }, +}); + +/** Refusing checks that predate the registry and have no replay (shrink-only). */ +export const UNREPLAYED = Object.freeze([ + "bodyCommandProblems", "checkedMergeProblem", "cloudPrProblem", "decisionTableProblems", "deliveryPlacementProblem", + "handoffGateProblem", "inventoryGateProblem", "memberNameProblems", "mergeabilityProblem", "pathCitationProblem", + "placementLineProblem", "prVisualQaProblem", "reviewFindingProblems", "reviewReceiptProblems", "visualQaFindingsProblems", + "HANDOFF-MISSING", "HANDOFF-UNVERIFIED", "NO-HEAD", "NOT-READY", "PR-HELD-NOT-DRAFT", "PR-HOLD-UNKNOWN", "PROOF-UNCHECKED", + "PUSH-READY-UNKNOWN", "UNIT-UNREVIEWED", "UNREADY-COMMIT", "VISUAL-QA-MISSING", +]); + +/** + * The gate sources whose refusal producers the registry must cover. board.mjs runs many board actions besides + * push-check, so only its push-check refusal prefixes count there; every push-check refusal prints one. + */ +export const GATE_SOURCES = Object.freeze([ + { path: "plugins/vibe/skills/handoff/scripts/handoff-gate.mjs" }, { path: `${HANDOFF}/handoff-gate-check.mjs` }, + { path: "plugins/vibe/skills/fleet-orchestrator/scripts/push-proof.mjs" }, { path: "plugins/vibe/hooks/pr-create-guard.mjs" }, + { path: "plugins/vibe/skills/fleet-orchestrator/scripts/board.mjs", prefixesOnly: true }, +]); + +const PRODUCER = /\b([a-z][A-Za-z0-9]*Problems?)\(/g; +const PUSH_CHECK_PREFIX = /`([A-Z0-9]+(?:-[A-Z0-9]+)+) \$\{name\}/g; + +/** The refusal producers a gate source calls or prints: `*Problem(s)(` calls and push-check's `PREFIX ${name}` lines. */ +export function refusalProducers(source, { prefixesOnly = false } = {}) { + return new Set([...(prefixesOnly ? [] : source.matchAll(PRODUCER)), ...source.matchAll(PUSH_CHECK_PREFIX)].map((match) => match[1])); +} + +/** The replayed checks whose files a change touches. */ +export function replayedChecksTouched(paths) { + const changed = new Set(paths); + return Object.entries(REFUSING_CHECKS).filter(([, entry]) => entry.replay && entry.files.some((file) => changed.has(file))).map(([name]) => name); +} diff --git a/plugins/vibe/lib/handoff/scripts/refusing-checks.test.mjs b/plugins/vibe/lib/handoff/scripts/refusing-checks.test.mjs new file mode 100644 index 00000000..de6dd2a1 --- /dev/null +++ b/plugins/vibe/lib/handoff/scripts/refusing-checks.test.mjs @@ -0,0 +1,56 @@ +// Class A guard: every check that can refuse a writer's branch is registered, and each replayed one refuses nothing a +// long-lived branch already had accepted (refusing-checks.mjs). #450's mutation-proof gate refused 551 already-pushed +// tests on its first real branch; this replay of the same shape fails on it. +import assert from "node:assert/strict"; +import { readFileSync } from "node:fs"; +import test, { after, before } from "node:test"; +import { fileURLToPath } from "node:url"; +import { GATE_SOURCES, REFUSING_CHECKS, refusalProducers, replayedChecksTouched, UNREPLAYED } from "./refusing-checks.mjs"; +import { LONG_LIVED_SHAPE, longLivedBranch } from "./long-lived-branch-fixture.mjs"; +import { CI_LANES, recordLanes } from "./full-ci-fixture.mjs"; + +const ROOT = fileURLToPath(new URL("../../../../../", import.meta.url)); +const UNREPLAYED_AT_INTRODUCTION = 26; +// One branch for every replay: the replays only read it, and building it takes seconds. +let branch; +const cleanups = []; +after(() => { for (const cleanup of cleanups) cleanup(); }); +before(() => { + branch = longLivedBranch({ after: (cleanup) => cleanups.push(cleanup) }); + recordLanes(branch.worktree, branch.pushed, CI_LANES.map(({ command }) => command)); +}); + +test("class A: every refusal producer the gates call or print is registered, and the unreplayed list only shrinks", () => { + const producers = new Set(GATE_SOURCES.flatMap(({ path: file, prefixesOnly }) => [...refusalProducers(readFileSync(`${ROOT}${file}`, "utf8"), { prefixesOnly })])); + const registered = new Set([...Object.keys(REFUSING_CHECKS), ...UNREPLAYED]); + assert.deepEqual([...producers].filter((name) => !registered.has(name)).sort(), [], + "a new refusing check needs a REFUSING_CHECKS entry with a replay (refusing-checks.mjs)"); + assert.deepEqual([...registered].filter((name) => !producers.has(name)).sort(), [], "a removed check leaves the registry too"); + assert.ok(UNREPLAYED.length <= UNREPLAYED_AT_INTRODUCTION, "UNREPLAYED only shrinks"); + assert.deepEqual(Object.keys(REFUSING_CHECKS).filter((name) => UNREPLAYED.includes(name)), []); + for (const [name, entry] of Object.entries(REFUSING_CHECKS)) { + assert.ok(entry.replay ? entry.files.length > 0 : REFUSING_CHECKS[entry.via]?.replay, `${name} has a replay or reports through one`); + } +}); + +test("class A: a change to a replayed check's source names that check", () => { + assert.deepEqual(replayedChecksTouched(["plugins/vibe/lib/handoff/scripts/proof-scope.mjs", "README.md"]), ["proofGateProblems", "pushReadyProofProblems"]); + assert.deepEqual(replayedChecksTouched(["plugins/vibe/lib/handoff/scripts/full-ci-check.mjs"]), ["fullCiProblem"]); + assert.deepEqual(replayedChecksTouched(["plugins/vibe/README.md"]), []); +}); + +for (const [name, entry] of Object.entries(REFUSING_CHECKS).filter(([, item]) => item.replay)) { + test(`class A: ${name} refuses nothing a long-lived branch already had accepted (${LONG_LIVED_SHAPE.inherited.cases} inherited cases)`, () => { + const f = branch; + const accepted = { worktree: f.worktree, base: f.main, head: f.pushed, pushed: [f.pushed], passed: [f.pushed], bodyText: "", binding: null }; + assert.deepEqual(entry.replay(accepted), [], `${name} refused work the branch had pushed and passed`); + }); +} + +test("class A: on the same branch the proof checks still ask about the case added after the accepted head", () => { + const f = branch; + const input = { worktree: f.worktree, base: f.main, head: f.head, pushed: [f.pushed], passed: [f.pushed], bodyText: "", binding: null }; + for (const name of ["proofGateProblems", "pushReadyProofProblems"]) { + assert.equal(REFUSING_CHECKS[name].replay(input).filter((line) => line.startsWith("test ")).length, LONG_LIVED_SHAPE.newCases, name); + } +}); diff --git a/plugins/vibe/skills/fleet-orchestrator/SKILL.md b/plugins/vibe/skills/fleet-orchestrator/SKILL.md index f66d4836..576b60a0 100644 --- a/plugins/vibe/skills/fleet-orchestrator/SKILL.md +++ b/plugins/vibe/skills/fleet-orchestrator/SKILL.md @@ -140,7 +140,7 @@ Run [codex-fleet-monitor](../codex-fleet-monitor/SKILL.md) (`vibe-generic:codex- - Answer a writer's question within 15 minutes, echoing its id (`board.mjs answered --id --text `); send other mid-run changes to what it builds as `deliver --kind scope --to --text `, a message naming the id, then `told`. The watcher and `board.mjs status` flag `QUESTION-UNANSWERED`, `UNACKED` and `UNACKED-SCOPE` after 15 minutes, and `SCOPE-NOT-STARTED` for a worktree still clean at its old head 30 minutes on. - On a `HOOK-APPROVAL ` line (that machine's Codex vibe or vibe-core changed version and a vibe-core hook now needs approval), relay it to the operator at once in one plain line; approving is theirs, never a worker's. - On `STALE-PR` (a PR needing its writer with no push for 45 minutes), ask the owning writer for an ETA, unblock it, or reassign it, whatever it reports being busy with. -- Push only a declared push-ready head (`--ready `, with `--visual-qa ` for a UI diff). Review and verification accept the uncommitted diff before its first commit; then commit once, declare, push once and open the PR. `writer --base ` records the verified pre-PR parent; parent commits are never ready. The live GitHub base is authoritative afterward. `push-check` must print `READY` (pass `--body ` once one exists; a vibe head missing proof receipts prints `PROOF-MISSING`, and one whose receipts are not readable here, such as a remote writer registered with `--branch vibe/`, prints `PROOF-UNCHECKED`, as does a writer with no local tree (remote, or registered without `--worktree`) and no `--branch` until it is registered again with one; other rows get a non-blocking `PROOF-UNCHECKED` note); `status`/`watch-lines` flag undeclared local commits as `UNREADY-COMMIT` and unreadable history/base as `PUSH-READY-UNKNOWN`. Restore evidence before pushing; cadence never authorizes checkpoint commits. Operator ruling, 2026-10-29: "every commit to an open PR is a sign of a bad orchestration framework. we should codify this to never happen again. we don't commit until we're sure that commit is push ready." +- Push only a declared push-ready head (`--ready `, with `--visual-qa ` for a UI diff). Review and verification accept the uncommitted diff before its first commit; then commit once, declare, push once and open the PR. `writer --base ` records the verified pre-PR parent; parent commits are never ready. The live GitHub base is authoritative afterward. `push-check` must print `READY` (pass `--body ` once one exists; a vibe head missing proof receipts prints `PROOF-MISSING`, and one whose receipts are not readable here, such as a remote writer registered with `--branch vibe/`, prints `PROOF-UNCHECKED`, as does a writer with no local tree (remote, or registered without `--worktree`) and no `--branch` until it is registered again with one; other rows get a non-blocking `PROOF-UNCHECKED` note; a local row whose PR postdates the pre-PR ruling gets advisory `CI-NOT-RUN` and `E2E-NOT-RUN` lines about missing runs); `status`/`watch-lines` flag undeclared local commits as `UNREADY-COMMIT` and unreadable history/base as `PUSH-READY-UNKNOWN`. Restore evidence before pushing; cadence never authorizes checkpoint commits. Operator ruling, 2026-10-29: "every commit to an open PR is a sign of a bad orchestration framework. we should codify this to never happen again. we don't commit until we're sure that commit is push ready." - For an in-flight branch that already has old checkpoint commits, treat its current pushed PR head as historical baseline. Never rewrite it or declare its ancestors ready; keep the next repair uncommitted until one new head is push-ready. A remote board row uses `--where remote --base `: `NO-HEAD` is informational because its owning machine checks history, while this board still requires the exact declared ready head before push. - Before opening a PR, reviewers inspect the uncommitted change identified by HEAD plus diff/tree hashes. After opening, compare published evidence with the pushed PR head (`gh pr view --json headRefOid`); observe automatically started checks and reviews, never manually trigger another review. diff --git a/plugins/vibe/skills/fleet-orchestrator/scripts/board-push-proof.test.mjs b/plugins/vibe/skills/fleet-orchestrator/scripts/board-push-proof.test.mjs index 7da59b14..e30628d7 100644 --- a/plugins/vibe/skills/fleet-orchestrator/scripts/board-push-proof.test.mjs +++ b/plugins/vibe/skills/fleet-orchestrator/scripts/board-push-proof.test.mjs @@ -1,11 +1,16 @@ // push-check proof lines (push-proof.mjs) through the real board CLI; split from board.test.mjs by responsibility. import assert from 'node:assert/strict'; import { spawnSync } from 'node:child_process'; -import { mkdirSync, readFileSync, writeFileSync } from 'node:fs'; +import { chmodSync, mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from 'node:fs'; +import { tmpdir } from 'node:os'; import path from 'node:path'; import test, { after } from 'node:test'; -import { bindProviderInProcess } from '../../vibe/scripts/test-fixtures.mjs'; +import { bindProvider, bindProviderInProcess, PROVIDER_REPO_REMOTE } from '../../vibe/scripts/test-fixtures.mjs'; import { acceptRemoteCritic, fixture, NEEDS_APP } from './writer-placement-test-fixture.mjs'; +import { ciRepository } from '../../../lib/handoff/scripts/full-ci-fixture.mjs'; +import { FULL_CI_GATE_SINCE } from '../../../lib/handoff/scripts/full-ci-check.mjs'; +import { prCreateGuard } from '../../../hooks/pr-create-guard.mjs'; +import { recordHookSkill } from '../../../hooks/hook-session-scope.mjs'; bindProviderInProcess(after); @@ -60,6 +65,38 @@ test('AC-9 push-check refuses a vibe head whose new test has no mutation proof o assert.match(bugFix.stdout, /PROOF-MISSING w [0-9a-f]+: bug fix: no reproduction receipt and no accepted cannot-reproduce reason for this head/); }); +test('AC-9 push-check asks only about test cases changed since the pushed upstream head', t => { + const { dir, run } = program(t, ['ISS-1']); + const wt = path.join(dir, 'scope-wt'); + mkdirSync(path.join(wt, 'src'), { recursive: true }); + const git = (...args) => { + const result = spawnSync('git', ['-C', wt, '-c', 'user.name=Test', '-c', 'user.email=test', ...args], { encoding: 'utf8' }); + assert.equal(result.status, 0, result.stderr); + return result.stdout.trim(); + }; + git('init', '--quiet'); + git('commit', '--quiet', '--allow-empty', '-m', 'base'); + git('update-ref', 'refs/remotes/origin/main', git('rev-parse', 'HEAD')); + git('branch', 'pushed', git('rev-parse', 'HEAD')); + git('branch', '--set-upstream-to=pushed'); + writeFileSync(path.join(git('rev-parse', '--absolute-git-dir'), 'vibe-session.json'), JSON.stringify({ status: 'active', summary: 'Add a filter', flagKeys: { surfaces: [] } })); + run('writer', 'w', '--tickets', 'ISS-1', '--head', git('rev-parse', 'HEAD'), '--worktree', wt); + writeFileSync(path.join(wt, 'src', 'pins.test.mjs'), "import test from 'node:test';\ntest('pushed case', () => {});\n"); + git('add', '.'); + git('commit', '--quiet', '-m', 'pushed case'); + const pushedHead = git('rev-parse', 'HEAD'); + git('branch', '-f', 'pushed', pushedHead); + writeFileSync(path.join(wt, 'src', 'pins.test.mjs'), "import test from 'node:test';\ntest('pushed case', () => {});\ntest('new case', () => {});\n"); + git('add', '.'); + git('commit', '--quiet', '-m', 'new case'); + const head = git('rev-parse', 'HEAD'); + run('writer', 'w', '--tickets', 'ISS-1', '--ready', head); + const check = run('push-check', 'w', '--head', head); + assert.equal(check.status, 1, check.stdout); + assert.match(check.stdout, /PROOF-MISSING w [0-9a-f]+: test src\/pins\.test\.mjs case "new case" has no mutation proof/); + assert.doesNotMatch(check.stdout, /pushed case/, 'a case unchanged since the pushed head is not asked at push-check'); +}); + /** A committed repository registered as a local writer, with a ready head that adds one test case. */ function readyWriter(dir, run, name, ticket, branch) { const wt = path.join(dir, `${name}-wt`); @@ -168,3 +205,108 @@ test('AC-9 a row refused for an unreadable kind is checked once re-registered wi assert.match(checked.stdout, new RegExp(`^READY ${name} f+\\nPROOF-UNCHECKED ${name} f+: not a vibe row; reproduction, mutation proofs and ticket commands are not checked$`, 'm')); } }); + +test('class B a row with no pull request passes push-check on focused runs, and PR create refuses it until every CI job ran in full', t => { + const { dir, run } = program(t, ['ISS-1']); + const r = ciRepository(t, { worktree: path.join(dir, 'ci-wt') }); + r.git('update-ref', 'refs/remotes/origin/main', r.git('rev-parse', 'main')); + r.git('branch', '--set-upstream-to=main'); + run('writer', 'w', '--tickets', 'ISS-1', '--head', r.head, '--worktree', r.worktree); + run('writer', 'w', '--tickets', 'ISS-1', '--ready', r.head); + r.record(['node --test plugins/vibe/lib/vibe/scripts/cloud-worker.test.mjs']); + const pushed = run('push-check', 'w', '--head', r.head); + assert.equal(pushed.status, 0, pushed.stdout); + assert.match(pushed.stdout, /^READY w /m); + assert.doesNotMatch(pushed.stdout, /CI-NOT-RUN/); + const home = hookHome(t, 'fleet-no-pr'); + const create = () => prCreateGuard({ cwd: r.worktree, session_id: 'fleet-no-pr', transcript_path: null, tool_input: { command: 'gh pr create --base main --fill' } }, home); + assert.match(create()?.reason ?? '', /every CI workflow job runs in full on the exact head before a pull request, and 2 have no witnessed passing run of [0-9a-f]{12}: plugin-version-bump, node-tests/); + r.record(r.lanes.map(({ command }) => command)); + assert.equal(create(), null); +}); + +test('9(b) push-check asks a row for its e2e runs only once its pull request was opened at or after the gate, and PR create asks it before', t => { + const { dir, run } = program(t, ['ISS-1']); + const wt = path.join(dir, 'e2e-wt'); + mkdirSync(path.join(wt, 'scripts'), { recursive: true }); + const git = (...args) => { + const result = spawnSync('git', ['-C', wt, '-c', 'user.name=Test', '-c', 'user.email=test', ...args], { encoding: 'utf8' }); + assert.equal(result.status, 0, result.stderr); + return result.stdout.trim(); + }; + git('init', '--quiet', '-b', 'main'); + git('remote', 'add', 'origin', PROVIDER_REPO_REMOTE); + git('commit', '--quiet', '--allow-empty', '-m', 'base'); + const main = git('rev-parse', 'HEAD'); + git('update-ref', 'refs/remotes/origin/main', main); + git('checkout', '--quiet', '-b', 'feat/e2e'); + git('branch', 'pushed', main); + git('branch', '--set-upstream-to=pushed'); + writeFileSync(path.join(git('rev-parse', '--absolute-git-dir'), 'vibe-session.json'), JSON.stringify({ status: 'active', summary: 'Add a tool', flagKeys: { surfaces: [] } })); + writeFileSync(path.join(wt, 'scripts', 'tool.mjs'), 'export const tool = 1;\n'); + git('add', '.'); + git('commit', '--quiet', '-m', 'add a tool'); + const head = git('rev-parse', 'HEAD'); + const gh = path.join(dir, 'gh'); + const opened = (at) => { writeFileSync(gh, `#!/bin/sh\ncase "$*" in *createdAt*) echo "${at}";; *baseRefOid*) echo ${main};; *) echo ${head};; esac\n`); chmodSync(gh, 0o755); }; + const saved = process.env.BOARD_GH; + process.env.BOARD_GH = gh; + t.after(() => { if (saved === undefined) delete process.env.BOARD_GH; else process.env.BOARD_GH = saved; }); + run('writer', 'w', '--tickets', 'ISS-1', '--head', head, '--worktree', wt); + run('writer', 'w', '--tickets', 'ISS-1', '--ready', head); + const noPr = run('push-check', 'w', '--head', head); + assert.equal(noPr.status, 0, noPr.stdout); + assert.doesNotMatch(noPr.stdout, /E2E-NOT-RUN/); + const home = hookHome(t, 'fleet-e2e'); + const create = prCreateGuard({ cwd: wt, session_id: 'fleet-e2e', transcript_path: null, tool_input: { command: 'gh pr create --base main --fill' } }, home); + assert.match(create?.reason ?? '', /the required web e2e lane, in full, has no local run receipt/, 'PR create asks the row push-check let through'); + opened('2026-12-01T00:00:00Z'); + const registered = run('writer', 'w', '--tickets', 'ISS-1', '--pr', '7', '--repo', 'acme/app'); + assert.equal(registered.status, 0, registered.stderr + registered.stdout); + const before = run('push-check', 'w', '--head', head); + assert.equal(before.status, 0, before.stdout); + assert.doesNotMatch(before.stdout, /E2E-NOT-RUN/); + opened(FULL_CI_GATE_SINCE); + const after = run('push-check', 'w', '--head', head); + assert.equal(after.status, 0, after.stdout); + assert.match(after.stdout, /^READY w /m); + assert.match(after.stdout, /^E2E-NOT-RUN w [0-9a-f]+: the required web e2e lane, in full, has no local run receipt/m); + assert.match(after.stdout, /^E2E-NOT-RUN w [0-9a-f]+: the required desktop e2e lane, in full, has no local run receipt/m); +}); + +test('class B push-check keeps a pull request opened before the full CI gate on its old check and asks one opened after it', t => { + const { dir, run } = program(t, ['ISS-1']); + const r = ciRepository(t, { worktree: path.join(dir, 'ci-wt') }); + r.git('update-ref', 'refs/remotes/origin/main', r.git('rev-parse', 'main')); + r.git('branch', '--set-upstream-to=main'); + r.record(['node --test plugins/vibe/lib/vibe/scripts/cloud-worker.test.mjs']); + const main = r.git('rev-parse', 'main'); + const gh = path.join(dir, 'gh'); + const opened = (at) => { writeFileSync(gh, `#!/bin/sh\ncase "$*" in *createdAt*) echo "${at}";; *baseRefOid*) echo ${main};; *) echo ${r.head};; esac\n`); chmodSync(gh, 0o755); }; + const saved = process.env.BOARD_GH; + process.env.BOARD_GH = gh; + t.after(() => { if (saved === undefined) delete process.env.BOARD_GH; else process.env.BOARD_GH = saved; }); + opened('2026-12-01T00:00:00Z'); + for (const args of [['--head', r.head, '--worktree', r.worktree, '--pr', '7', '--repo', 'acme/app'], ['--ready', r.head]]) { + const registered = run('writer', 'w', '--tickets', 'ISS-1', ...args); + assert.equal(registered.status, 0, registered.stderr + registered.stdout); + } + opened('2026-12-01T00:00:00Z'); + const before = run('push-check', 'w', '--head', r.head); + assert.equal(before.status, 0, before.stdout); + assert.doesNotMatch(before.stdout, /CI-NOT-RUN/); + opened(FULL_CI_GATE_SINCE); + const after = run('push-check', 'w', '--head', r.head); + assert.equal(after.status, 0, after.stdout); + assert.match(after.stdout, /^READY w /m); + assert.match(after.stdout, /CI-NOT-RUN w /); +}); + +/** A hook home where conversation `session` runs the fleet orchestrator with the provider bound. */ +function hookHome(t, session) { + const home = mkdtempSync(path.join(tmpdir(), 'pr-create-home-')); + t.after(() => rmSync(home, { recursive: true, force: true })); + recordHookSkill(session, 'vibe:fleet-orchestrator', home); + bindProvider(home, { conversation: session }); + return home; +} diff --git a/plugins/vibe/skills/fleet-orchestrator/scripts/board.mjs b/plugins/vibe/skills/fleet-orchestrator/scripts/board.mjs index d946844e..7ab92200 100644 --- a/plugins/vibe/skills/fleet-orchestrator/scripts/board.mjs +++ b/plugins/vibe/skills/fleet-orchestrator/scripts/board.mjs @@ -64,6 +64,7 @@ // the recorded findings, and `status` prints `VISUAL-QA-MISSING ...` // for a ready head without them. A user-visible PR was reported ready to merge // with no visual QA on any head. +// Post-cutoff PR rows get advisory CI-NOT-RUN and E2E-NOT-RUN lines. // A writer records each question it sends you under an id (`question`), your // answer echoes that id (`answered`), and the writer acknowledges it in its next // status (`ack`). `status` prints `QUESTION-UNANSWERED m: @@ -139,7 +140,8 @@ const { readConfig, resolveWorkDir } = await vibeCore("lib/codex-fleet-monitor/s const { homeProblems, programShape, Shape } = await vibeCore("lib/fleet-orchestrator/scripts/fleet-home.mjs"); const { readSessionRecord } = await vibeCore("lib/vibe/scripts/session-record.mjs"); const { unitReviewProblem } = await vibeCore("lib/handoff/scripts/unit-review-record.mjs"); -const { failScript } = await vibeCore("lib/vibe/scripts/provider.mjs"); +const { fullCiProblem, pushCheckAsksPrePrChecks } = await vibeCore("lib/handoff/scripts/full-ci-check.mjs"); +const { failScript, sessionBinding } = await vibeCore("lib/vibe/scripts/provider.mjs"); const STATE = "board.json"; const PAGE = "board.md"; @@ -717,6 +719,12 @@ function boardAction({ workDir, action, values, positionals, orchDir, home }) { const remoteHost = row.where === "remote" ? readConfig(resolveWorkDir(orchDir)).REMOTE_HOST : undefined; // Older remote rows can carry only a ready SHA and visual evidence, with no repository or host to inspect. const headOnly = row.where === "remote" && !remoteHost && !row.repo && !row.releaseRuns; + // A row registered with a PR but no repository predates the gate: its PR's creation time cannot be read. + const created = row.where !== "remote" && row.pr ? (row.repo ? ghOid(row, "createdAt") : "1970-01-01T00:00:00Z") : null; + if (row.where !== "remote" && row.pr && !created) { + process.stdout.write(`CI-NOT-RUN ${name} ${values.head}: cannot determine which pre-PR checks apply to pull request ${row.pr}\n`); + } + const prePrChecks = pushCheckAsksPrePrChecks(created); if (row.worktree && !headOnly) { const git = (...args) => row.where === "remote" ? remoteWriterRead(remoteHost, ["git", "-C", row.worktree, ...args]) @@ -729,18 +737,24 @@ function boardAction({ workDir, action, values, positionals, orchDir, home }) { const problem = !base ? "missing trusted release base" : releaseSuiteProblem(git, base, head, report); if (problem) { process.stdout.write(`NOT-READY ${name}: ${problem}\n`); return 1; } } + if (row.where !== "remote" && prePrChecks) { + const prefix = `CI-NOT-RUN ${name} ${values.head}:`; + try { + const ci = fullCiProblem(row.worktree, head, { bodyText: () => values.body ? readFileSync(values.body, "utf8") : "", binding: sessionBinding(row.worktree) }); + if (ci) process.stdout.write(`${prefix} ${ci}\n`); + } catch (error) { + process.stdout.write(`${prefix} could not check CI evidence: ${error.message}\n`); + } + } } const visual = readyVisualQaProblem(row); if (visual) { process.stdout.write(`VISUAL-QA-MISSING ${name} head ${values.head}: ${visual}\n`); return 1; } - const trustedBase = () => { - const git = (...args) => repositoryGit(row.worktree, args); - let published; try { published = git("rev-parse", "@{upstream}"); } catch { published = null; } - return trustedBaseOid(row, git, published); - }; - const proof = pushProofLines(name, row, { ...values, trustedBase }); + const published = () => { try { return repositoryGit(row.worktree, ["rev-parse", "@{upstream}"]); } catch { return null; } }; + const trustedBase = () => trustedBaseOid(row, (...args) => repositoryGit(row.worktree, args), published()); + const proof = pushProofLines(name, row, { ...values, trustedBase, published, prePrChecks }); if (proof.refuse.length) { for (const line of proof.refuse) process.stdout.write(`${line}\n`); return 1; diff --git a/plugins/vibe/skills/fleet-orchestrator/scripts/push-proof.mjs b/plugins/vibe/skills/fleet-orchestrator/scripts/push-proof.mjs index b2bb180d..a7c6214d 100644 --- a/plugins/vibe/skills/fleet-orchestrator/scripts/push-proof.mjs +++ b/plugins/vibe/skills/fleet-orchestrator/scripts/push-proof.mjs @@ -1,20 +1,24 @@ // Proof lines for a fleet writer's push-ready head, read by board.mjs push-check (proof-receipts.mjs holds the checks). -import { readFileSync } from "node:fs"; +import { existsSync, readFileSync } from "node:fs"; import { vibeCore } from "../../../shared/vibe-core.mjs"; const { readSessionRecord } = await vibeCore("lib/vibe/scripts/session-record.mjs"); const { bodyCommandProblems, pushReadyProofProblems } = await vibeCore("lib/handoff/scripts/proof-receipts.mjs"); const { gatePath } = await vibeCore("lib/handoff/scripts/handoff-gate-check.mjs"); +const { e2eGateProblems } = await vibeCore("lib/handoff/scripts/e2e-gate-check.mjs"); +const { sessionBinding } = await vibeCore("lib/vibe/scripts/provider.mjs"); /** * Proof lines for a writer's head. A vibe row (a readable session record, or a `vibe/` branch) is refused when its * receipts are missing or unreadable here, and so is a row with no local tree and no branch, remote or not, whose kind * cannot be read; any other row has only its PR body's commands checked and a note for the rest (orchestrator rulings, - * 2026-11-25 and 2026-11-26). `trustedBase` returns the base a local vibe row's receipts are checked against. `refuse` - * lines hold READY; `notes` print after it. + * 2026-11-25 and 2026-11-26). `trustedBase` returns the base a local vibe row's receipts are checked against, and + * `published` its upstream head: a test case unchanged since that pushed head needs no mutation proof here, though the + * proof checks before PR create still ask (proof-scope.mjs). With `prePrChecks`, a local row gets advisory e2e notes + * only. `refuse` lines hold READY; `notes` print after it. */ -export function pushProofLines(name, row, { head, body, trustedBase }) { +export function pushProofLines(name, row, { head, body, trustedBase, published = () => null, prePrChecks = false }) { const local = Boolean(row?.worktree) && row.where !== "remote"; const session = local ? readSessionRecord(row.worktree) : null; if (!session && /^vibe\//.test(row?.branch ?? "")) { @@ -24,12 +28,26 @@ export function pushProofLines(name, row, { head, body, trustedBase }) { const registered = row?.where === "remote" ? "a remote row registered without --branch" : "a row registered with no --worktree and no --branch"; return { refuse: [`PROOF-UNCHECKED ${name} ${head}: ${registered} has no readable kind; re-register it with board.mjs writer ${name} --branch so the kind can be read; it is not ready`], notes: [] }; } + const e2eLines = (bodyFile, binding) => { + if (!prePrChecks || !local) return []; + const prefix = `E2E-NOT-RUN ${name} ${head}:`; + try { + return e2eGateProblems(row.worktree, { base: trustedBase, head, binding, + bodyText: () => bodyFile && existsSync(bodyFile) ? readFileSync(bodyFile, "utf8") : "" }).map((problem) => `${prefix} ${problem}`); + } catch (error) { + return [`${prefix} could not check e2e evidence: ${error.message}`]; + } + }; if (session) { - return { refuse: pushReadyProofProblems(row.worktree, { base: trustedBase(), head, bodyFile: body, witness: gatePath(row.worktree) }) - .map((problem) => `PROOF-MISSING ${name} ${head}: ${problem}`), notes: [] }; + const pushed = published(); + const witness = gatePath(row.worktree); + const boundBody = existsSync(witness) ? JSON.parse(readFileSync(witness, "utf8")).evidence?.body?.path : null; + return { refuse: [...pushReadyProofProblems(row.worktree, { base: trustedBase(), head, bodyFile: body, witness, pushed: pushed ? [pushed] : [] }) + .map((problem) => `PROOF-MISSING ${name} ${head}: ${problem}`)], notes: e2eLines(body ?? boundBody, sessionBinding(row.worktree)) }; } const notes = [`PROOF-UNCHECKED ${name} ${head}: not a vibe row; reproduction, mutation proofs and ticket commands are not checked`]; - if (!body) return { refuse: [], notes }; + if (!body) return { refuse: [], notes: [...notes, ...e2eLines(null, null)] }; if (!local) return { refuse: [], notes: [...notes, `PROOF-UNCHECKED ${name} ${head}: no local receipt to check the PR body's commands against`] }; - return { refuse: bodyCommandProblems(row.worktree, { head, bodyText: readFileSync(body, "utf8") }).map((problem) => `PROOF-MISSING ${name} ${head}: ${problem}`), notes }; + return { refuse: bodyCommandProblems(row.worktree, { head, bodyText: readFileSync(body, "utf8") }).map((problem) => `PROOF-MISSING ${name} ${head}: ${problem}`), + notes: [...notes, ...e2eLines(body, null)] }; } diff --git a/plugins/vibe/skills/handoff/scripts/handoff-gate-members.test.mjs b/plugins/vibe/skills/handoff/scripts/handoff-gate-members.test.mjs index 3135b0e4..12f45845 100644 --- a/plugins/vibe/skills/handoff/scripts/handoff-gate-members.test.mjs +++ b/plugins/vibe/skills/handoff/scripts/handoff-gate-members.test.mjs @@ -135,24 +135,28 @@ function fixture(t) { }; } -test("AC-7 AC-10 the handoff gate refuses a session with no flag-keys record, and a bug fix with no reproduction receipt", (t) => { +test("AC-7 AC-10 handoff warns about missing flag keys and reproduction, and PR creation still refuses them", (t) => { const { gitDir, worktree, receipts, body, ticket, member, audit, matrix, review } = fixture(t); const ids = ["AC-1", "ISS-124:AC-1"]; const runScript = (command, args, options) => args[0].endsWith("criteria-audit.mjs") ? spawnSync(command, args, options) : { status: 0, stdout: JSON.stringify(passingInventory), stderr: "" }; + const warnings = []; const gate = () => recordHandoffGate({ worktree, base: "main", body, runs: receipts[0], receipts, ticket, audit: audit(ids), matrix: matrix(ids), - members: [`ISS-124=${member}`], title: TITLE, review: review(ids) }, { runScript }); + members: [`ISS-124=${member}`], title: TITLE, review: review(ids) }, { runScript, warn: (line) => warnings.push(line) }); const sessionFile = path.join(gitDir, "vibe-session.json"); gate(); - const current = () => handoffGateProblem(worktree, { base: "main", bodyFile: body, title: TITLE }); + const current = () => handoffGateProblem(worktree, { base: "main", bodyFile: body, title: TITLE, creatingPullRequest: true }); assert.equal(current(), null); const { flagKeys, ...withoutKeys } = JSON.parse(readFileSync(sessionFile, "utf8")); writeFileSync(sessionFile, JSON.stringify(withoutKeys)); assert.match(current(), /^handoff proof receipts: flag keys: no keys to see the work are recorded/, "PR creation rechecks the proofs"); - assert.throws(gate, /flag keys: no keys to see the work are recorded/); + gate(); + assert.match(warnings.join("\n"), /^PROOF-MISSING: flag keys: no keys to see the work are recorded/m); writeFileSync(sessionFile, JSON.stringify({ ...withoutKeys, flagKeys })); writeFileSync(path.join(gitDir, "vibe-proof-receipt.json"), JSON.stringify({ version: 1, kind: { value: "bug-fix", source: "ISS-123 is a bug report" } })); - assert.throws(gate, /bug fix: no reproduction receipt/); + gate(); + assert.match(warnings.join("\n"), /^PROOF-MISSING: bug fix: no reproduction receipt/m); + assert.match(current(), /^handoff proof receipts: bug fix: no reproduction receipt/); }); test("the gate runs the real criteria audit over each member ticket it is given, with the unit's review of the completed work", (t) => { diff --git a/plugins/vibe/skills/handoff/scripts/handoff-gate-proof-scope.test.mjs b/plugins/vibe/skills/handoff/scripts/handoff-gate-proof-scope.test.mjs new file mode 100644 index 00000000..f9e0728a --- /dev/null +++ b/plugins/vibe/skills/handoff/scripts/handoff-gate-proof-scope.test.mjs @@ -0,0 +1,74 @@ +// The handoff gate and its PR-create read side scope mutation proofs by the last head that passed the gate, never by a pushed head (proof-scope.mjs). +import assert from "node:assert/strict"; +import { execFileSync } from "node:child_process"; +import { mkdtempSync, readFileSync, rmSync, writeFileSync } from "node:fs"; +import { tmpdir } from "node:os"; +import path from "node:path"; +import test from "node:test"; +import { gatePath, handoffGateProblem } from "../../../lib/handoff/scripts/handoff-gate-check.mjs"; +import { readProofReceipt } from "../../../lib/handoff/scripts/proof-receipts.mjs"; +import { recordHandoffGate } from "./handoff-gate.mjs"; +import { seedAlignedDecisionTable } from "../../vibe/scripts/test-fixtures.mjs"; +import { passingReviewReceipts } from "./handoff-review-test-fixture.mjs"; + +const AFTER_RULING = "2026-12-02T12:00:00Z"; + +/** A vibe worktree with a fetched origin main, a session record and a PR body. */ +function fixture(t) { + const worktree = mkdtempSync(path.join(tmpdir(), "vibe-gate-scope-")); + t.after(() => rmSync(worktree, { recursive: true, force: true })); + const git = (...args) => execFileSync("git", ["-C", worktree, "-c", "user.email=test@example.com", "-c", "user.name=Test", ...args], + { encoding: "utf8", env: { ...process.env, GIT_AUTHOR_DATE: AFTER_RULING, GIT_COMMITTER_DATE: AFTER_RULING } }).trim(); + execFileSync("git", ["init", "-q", "-b", "vibe/example", worktree]); + writeFileSync(path.join(worktree, "file.txt"), "base\n"); + git("add", "."); + git("commit", "-qm", "base"); + git("update-ref", "refs/remotes/origin/main", "HEAD"); + git("symbolic-ref", "refs/remotes/origin/HEAD", "refs/remotes/origin/main"); + const gitDir = git("rev-parse", "--absolute-git-dir"); + const origin = path.join(gitDir, "origin.git"); + execFileSync("git", ["init", "--bare", "-q", origin]); + git("remote", "add", "origin", origin); + git("push", "-q", "origin", "HEAD:refs/heads/main"); + writeFileSync(path.join(gitDir, "vibe-session.json"), `${JSON.stringify({ flagKeys: { surfaces: [] } })}\n`); + seedAlignedDecisionTable(worktree); + const body = path.join(gitDir, "body.md"); + writeFileSync(body, "PR body\n"); + const commit = (file, text) => { writeFileSync(path.join(worktree, file), text); git("add", "."); git("commit", "-qm", file); return git("rev-parse", "HEAD"); }; + const mark = (warn) => { + const receipts = passingReviewReceipts(worktree); + return recordHandoffGate({ worktree, base: "main", body, runs: receipts[0], receipts }, { + warn, runScript: () => ({ status: 0, stdout: JSON.stringify({ ok: true, blocking: { prBody: true, prEvidence: true } }), stderr: "" }) }); + }; + return { worktree, gitDir, git, body, commit, mark }; +} + +const unproved = (name) => `import test from "node:test";\n\ntest("${name}", () => {});\n`; + +test("the handoff gate asks about a case pushed by a redeploy after its last pass; PR create reads the passed heads the gate counted", (t) => { + const f = fixture(t); + const passed = f.commit("passed.test.mjs", unproved("passed case")); + writeFileSync(path.join(f.gitDir, "vibe-proof-receipt.json"), JSON.stringify({ gatePassed: { head: passed, at: AFTER_RULING } })); + const redeployed = f.commit("redeployed.test.mjs", unproved("redeployed case")); + f.git("update-ref", "refs/remotes/origin/vibe/example", redeployed); + f.git("branch", "--set-upstream-to=origin/vibe/example"); + const warnings = []; + f.mark((line) => warnings.push(line)); + assert.match(warnings.join("\n"), /case "redeployed case" has no mutation proof/); + assert.doesNotMatch(warnings.join("\n"), /passed case/); + assert.equal(readProofReceipt(f.worktree).gatePassed.head, passed, "an advisory handoff cannot accept an unproved case"); + assert.equal(handoffGateProblem(f.worktree, { base: "main", bodyFile: f.body }), null); + assert.match(handoffGateProblem(f.worktree, { base: "main", bodyFile: f.body, creatingPullRequest: true }), + /case "redeployed case" has no mutation proof/); + f.git("rm", "-q", "redeployed.test.mjs"); + f.git("commit", "-qm", "drop the redeployed case"); + const head = f.git("rev-parse", "HEAD"); + f.mark(); + const witness = JSON.parse(readFileSync(gatePath(f.worktree), "utf8")); + assert.deepEqual(witness.proofAccepted, { passed: [passed] }); + assert.equal(readProofReceipt(f.worktree).gatePassed.head, head, "the gate records the head it passed"); + assert.equal(handoffGateProblem(f.worktree, { base: "main", bodyFile: f.body }), null); + writeFileSync(gatePath(f.worktree), JSON.stringify({ ...witness, proofAccepted: undefined })); + assert.match(handoffGateProblem(f.worktree, { base: "main", bodyFile: f.body, creatingPullRequest: true }) ?? "", /handoff proof receipts: test passed\.test\.mjs case "passed case" has no mutation proof/, + "PR create counts only the passed heads the witness recorded"); +}); diff --git a/plugins/vibe/skills/handoff/scripts/handoff-gate.mjs b/plugins/vibe/skills/handoff/scripts/handoff-gate.mjs index 89f88719..614da433 100644 --- a/plugins/vibe/skills/handoff/scripts/handoff-gate.mjs +++ b/plugins/vibe/skills/handoff/scripts/handoff-gate.mjs @@ -42,7 +42,8 @@ const { exitOnProviderBroken, sessionBinding } = await vibeCore("lib/vibe/script const { changedPaths, readVisualQaFindings, recordVerifiedDispositions, visualQaRequired } = await vibeCore("lib/vibe/scripts/required-visual-qa.mjs"); const { placementLineProblem } = await vibeCore("lib/fleet-orchestrator/scripts/delivery-placement.mjs"); const { readSessionRecord } = await vibeCore("lib/vibe/scripts/session-record.mjs"); -const { proofGateProblems, proofTicketText } = await vibeCore("lib/handoff/scripts/proof-receipts.mjs"); +const { passedGateHeads, proofGateProblems, proofTicketText, recordGatePass } = await vibeCore("lib/handoff/scripts/proof-receipts.mjs"); +const { e2eGateProblems } = await vibeCore("lib/handoff/scripts/e2e-gate-check.mjs"); const { OVERRIDE_CHECKS, overriddenChecks, readPrBodyEvidence } = await vibeCore("lib/handoff/scripts/gate-override.mjs"); /** Refresh the actual main branch before a publication witness can be recorded. */ @@ -165,7 +166,7 @@ export function visualQaGate(worktree, baseOid, head, findings, binding = sessio } /** Run the canonical inventory with PR body and verifier evidence before recording readiness. */ -export function recordHandoffGate({ worktree, body, runs, ticket, rulings, base, receipts, audit, matrix, members = [], prds = [], plans = [], review, title, visualQa }, { runScript = spawnSync } = {}) { +export function recordHandoffGate({ worktree, body, runs, ticket, rulings, base, receipts, audit, matrix, members = [], prds = [], plans = [], review, title, visualQa }, { runScript = spawnSync, warn = (line) => process.stderr.write(`${line}\n`) } = {}) { const witness = gatePath(worktree); if (existsSync(witness)) unlinkSync(witness); fetchCurrentMain(worktree); @@ -204,9 +205,22 @@ export function recordHandoffGate({ worktree, body, runs, ticket, rulings, base, // The PR-create hook refuses an active session's PR without one placement line; checking it here keeps the gated body final. const placement = session?.status === "active" ? placementLineProblem(bodyText) : null; if (placement) throw new Error(placement); - const proofs = proofGateProblems(worktree, { base: targets.base.oid, bodyText, - ticketText: proofTicketText(ticket, members.map((member) => member.slice(member.indexOf("=") + 1))), runs: runsEvidence }); - if (proofs.length) throw new Error(`proof receipts: ${proofs.join("; ")}`); + // A head that passed this gate counts; a pushed one does not, since a redeploy push never passed it (proof-scope.mjs). + let proofAccepted = { passed: [] }; + let proofs; + try { + proofAccepted = { passed: passedGateHeads(worktree) }; + proofs = proofGateProblems(worktree, { base: targets.base.oid, bodyText, + ticketText: proofTicketText(ticket, members.map((member) => member.slice(member.indexOf("=") + 1))), runs: runsEvidence, accepted: proofAccepted }); + } catch (error) { + proofs = [`could not check proof evidence: ${error.message}`]; + } + for (const problem of proofs) warn(`PROOF-MISSING: ${problem}`); + try { + for (const problem of e2eGateProblems(worktree, { base: targets.base.oid, bodyText, binding })) warn(`E2E-NOT-RUN: ${problem}`); + } catch (error) { + warn(`E2E-NOT-RUN: could not check e2e evidence: ${error.message}`); + } const evidenceInputs = { body, runs, ticket, rulings, audit, matrix, review }; const evidence = { body: bodyEvidence.fingerprint, runs: checkedRuns.fingerprint }; const manifest = new Map(); @@ -259,7 +273,8 @@ export function recordHandoffGate({ worktree, body, runs, ticket, rulings, base, ...(inventory.pathCitations?.length ? { pathCitations: inventory.pathCitations, pathCitationEvidence: inventory.pathCitationEvidence } : {}), reviewCarry: [...reusableRoles].sort(), memberTickets, unitReviewPassed: Boolean(review), visualQa: { required: visual.required, reason: visual.reason, findings: visual.required ? visual.fingerprint : null, ...(visual.dispositions ? { dispositions: visual.dispositions } : {}) }, inventoryPassed: true, - prBodyPassed: true, prEvidencePassed: true, reviewPassed: true, ...(overridden ? { inventoryOverride: "diffRulesClear" } : {}) })}\n`, { mode: 0o600 }); + prBodyPassed: true, prEvidencePassed: true, reviewPassed: true, proofAccepted, ...(overridden ? { inventoryOverride: "diffRulesClear" } : {}) })}\n`, { mode: 0o600 }); + if (!proofs.length) recordGatePass(worktree, source); return { branch, source }; } diff --git a/plugins/vibe/skills/handoff/scripts/pr-facts.mjs b/plugins/vibe/skills/handoff/scripts/pr-facts.mjs index 7ccb16cc..c4e0f7d1 100644 --- a/plugins/vibe/skills/handoff/scripts/pr-facts.mjs +++ b/plugins/vibe/skills/handoff/scripts/pr-facts.mjs @@ -876,8 +876,9 @@ export function ciCheckProblems(runsFile, changed, commit) { /** * The Desktop Electron lane cannot run on a machine without the displayless * Linux harness, and vibe never launches Electron natively; there - * `pre-pr-lanes.mjs check` records it `not-run` and the post-merge - * `desktop-e2e/validated` run covers it. + * `pre-pr-lanes.mjs check` records it `not-run`, and the facts carry that + * record. The e2e gate (e2e-gate-check.mjs) still owes the lane until it runs + * in cloud validation or on the heavy host. */ function desktopLeftForCi(run) { return run?.status === "not-run" && isDesktopE2eLane(run.command ?? "") && text(run.reason); diff --git a/plugins/vibe/skills/vibe/scripts/e2e-requirement.mjs b/plugins/vibe/skills/vibe/scripts/e2e-requirement.mjs new file mode 100644 index 00000000..9223dad6 --- /dev/null +++ b/plugins/vibe/skills/vibe/scripts/e2e-requirement.mjs @@ -0,0 +1,569 @@ +#!/usr/bin/env node +// The e2e specs a change owes locally before its pull request opens, beyond what the graph test selector chose. The +// repository's rule: an e2e lane is satisfied by the graph-selected specs, plus specs the branch's own changes newly +// reach, plus every spec the change adds or edits; without a graph result, by the CI changes job's changed-spec union, +// and by the whole lane wherever that union cannot narrow. A pull request once changed a shared e2e helper, six +// stories and one spec, ran two targeted specs, and broke main in a spec that opens one of those stories by its +// Storybook URL. The graph selector cannot see that edge (a spec reaches its story through the id parameter of the iframe page, +// not an import), so this module computes it: a changed story owes every suite spec that names the story's id, read +// at `head`; a story whose id or whose specs cannot be found completely owes the whole lane. +// +// The provider names the workflow, its change-detection job, the paths-filter step and, per surface, the suite job, +// the filter that decides whether that job runs and the step that lists its narrowable specs. Everything else comes +// from the workflow file at `head` (git show, never a copy): the filter globs, and the classifier step's own shell, +// which runs read-only in a scratch folder holding only the files it reads. A workflow this reader cannot parse, or a +// classifier it cannot run as CI runs it, owes the whole lane when there is no graph result; it never narrows. +// +// Usage: e2e-requirement.mjs --worktree --base --head +// prints one JSON line per surface (no graph result: the changes-job fallback); nothing when no provider declares one. + +import { spawnSync } from "node:child_process"; +import { mkdirSync, mkdtempSync, readFileSync, rmSync, symlinkSync, writeFileSync, lstatSync, readlinkSync } from "node:fs"; +import path from "node:path"; +import { parseArgs } from "node:util"; +import { vibeCore } from "../../../shared/vibe-core.mjs"; +import { isEntryPoint } from "../../../shared/plugin-roots.mjs"; + +import { containerizedIntent } from "../../../lib/vibe/scripts/docker-disk-admission.mjs"; +import { LANE_RECORDS_FILE } from "./lane-outcomes.mjs"; +import { witnessProblem } from "./lane-witness-check.mjs"; + +const { git } = await vibeCore("lib/vibe/scripts/session-record.mjs"); +const { boundWith, installedProviders } = await vibeCore("lib/vibe/scripts/provider.mjs"); + +export const E2eSurface = Object.freeze({ Web: "web", Desktop: "desktop" }); +export const NO_GRAPH = "no graph test selection for this change: the changes job's changed-spec union applies"; +export const FULL_LANE = "full"; +// The repo's web Playwright lanes (`pnpm test:e2e`, `pnpm test:web-smoke`); a lane naming desktop is the Electron one. +const WEB_E2E_LANE = /\b(?:test:e2e|test:web-smoke)\b/; +// Match the desktop path, workspace selector, or the npm script suffix used by the runners. +const DESKTOP_LANE = /(?:^|[\s/=:])desktop(?=$|[\s/:'"])/; +const STORY = /\.stories\.[cm]?[jt]sx?$/; +const SPEC = /\.spec\.[cm]?[jt]sx?$/; +const STORY_URL = `iframe.html${"?id="}`; +const DEFAULT_EXPORT = /^export default (?:(\{)|([A-Za-z_$][\w$]*);?\s*$)/; +const META_TITLE = /^ {2}title:\s*(["'`])((?:(?!\1).)*)\1,?\s*$/; +const WRAPPED_TITLE_KEY = /^ {2}title:\s*$/; +const FILES_OUTPUT = /^\$\{\{\s*steps\.([A-Za-z0-9_-]+)\.outputs\.([A-Za-z0-9_-]+)_files\s*\}\}$/; +const EVENT_EXPRESSION = /^\$\{\{\s*github\.event_name\s*\}\}$/; +const EXPRESSION = /\$\{\{/; +const PATH_TOKEN = /[A-Za-z0-9._-]+(?:\/[A-Za-z0-9._-]+)+/g; +const SAFE_SHELL_WORD = /^[\w@%+=:,./-]+$/; +const CLASSIFIER_TIMEOUT_MS = 10_000; +const GREP_BUFFER = 256 * 1024 * 1024; +// Where a lane this machine recorded not-run does run (orchestrator ruling). +export const RUN_ELSEWHERE = Object.freeze({ + [E2eSurface.Web]: "in the containerized web lane, or on the heavy host with pre-pr-lanes.mjs run --fleet-where remote", + [E2eSurface.Desktop]: "in cloud validation, which runs the whole Desktop suite, or on the heavy host with pre-pr-lanes.mjs run --fleet-where remote", +}); +// Lane results pre-pr-lanes.mjs check accepts as a run of the lane (a cached record is not one; not-run is left to CI). +const RAN_RESULTS = new Set(["pass", "env-skip", "main-preexisting"]); + +/** + * What the change from `base` to `head` owes each e2e lane the provider declares: + * `[{ surface, required, full, reasons, lane, specs }]`. `specs` are the specs owed beyond the graph selection (those a + * changed story's id reaches, those that import a file the change adds, and the surface's changed specs). `full` is true + * only for a fallback: a changed story whose specs cannot be found completely, or, with no graph result for the surface + * (`graphSelection[surface]` not a list), a change the changes job's union cannot narrow. `reasons` name the story ids that + * added specs, the incomplete story, or the missing graph and the paths the union could not narrow. + * `binding` is the session's provider binding; with none (a row outside a vibe session) the installed provider serving + * this repository's origin is read. `files` replaces the committed diff with the caller's changed-file set, read from + * the worktree (uncommitted files included). [] when no provider declares a workflow for this repository. + */ +export function e2eLaneRequirement(worktree, { base, head, binding = null, files, graphSelection = null, providers } = {}) { + const declared = declaredRequirement(worktree, binding, providers); + if (!declared) return []; + const source = files ? worktreeSource(worktree, head) : treeSource(worktree, head); + const changed = files ? [...new Set(files)].sort() : changedFiles(worktree, base, head); + const added = base ? changed.filter((file) => !existsAt(worktree, base, file)) : []; + const surfaces = Object.entries(declared.surfaces ?? {}); + let workflow; + try { + workflow = readWorkflow(worktree, head, declared); + } catch (error) { + const why = `${declared.workflow} at ${head.slice(0, 12)} cannot be read as CI reads it (${error.message})`; + return surfaces.map(([surface, spec]) => ({ surface, required: true, full: true, reasons: [why], lane: laneName(declared, spec), specs: [] })); + } + const context = { worktree, head, base, source, changed, added, declared, workflow, fromWorktree: Boolean(files) }; + return surfaces.map(([surface, spec]) => surfaceRequirement(context, surface, spec, graphSelection?.[surface])); +} + +/** + * What the change still owes after `receipts`, the passing local runs (`[{ surface, full, specs }]`; a `full` run of a + * surface covers all of it), and `notRun`, the lanes recorded not-run (recordedE2eEvidence's): `[{ surface, spec, reason }]`, + * with `spec` "full" where only the whole lane will do, and [] when nothing is owed. A not-run lane satisfies nothing + * unless its record quotes the skip ruling that waived it (orchestrator ruling); otherwise its rows stay owed + * and their reason names where the lane does run. `graphSelection` and the other options are e2eLaneRequirement's. + */ +export function missingE2eSpecs(worktree, { receipts = [], notRun = [], ...options } = {}) { + return e2eLaneRequirement(worktree, options).filter((row) => row.required).flatMap((row) => { + const runs = receipts.filter((receipt) => receipt?.surface === row.surface); + if (runs.some((receipt) => receipt.full === true)) return []; + const left = notRun.filter((entry) => entry?.surface === row.surface); + if (left.some((entry) => entry.ruling)) return []; + const where = left.length ? `; recorded not-run here, which satisfies nothing: run it ${RUN_ELSEWHERE[row.surface]}` : ""; + if (row.full) return [{ surface: row.surface, spec: FULL_LANE, reason: `${row.reasons.join("; ")}${where}` }]; + const ran = new Set(runs.flatMap((receipt) => receipt.specs ?? [])); + const owed = [...new Set([...(options.graphSelection?.[row.surface] ?? []), ...row.specs])].sort(); + return owed.filter((spec) => !ran.has(spec)).map((spec) => ({ surface: row.surface, spec, + reason: `${row.specs.includes(spec) ? specReason(row) : "selected by the graph"}${where}` })); + }); +} + +function specReason(row) { + const ids = row.reasons.filter((reason) => reason !== NO_GRAPH); + return ids.length ? `changed, reached by an added file, or naming a changed story (${ids.join(", ")})` : "changed or reached by an added file"; +} + +/** Whether a lane is the repo's local web e2e lane. */ +export function isWebE2eLane(lane) { + return WEB_E2E_LANE.test(lane) && !DESKTOP_LANE.test(lane); +} + +/** Whether a lane is the repo's Desktop Electron e2e lane. */ +export function isDesktopE2eLane(lane) { + return WEB_E2E_LANE.test(lane) && DESKTOP_LANE.test(lane); +} + +/** The e2e surface a recorded lane command runs, or null: the web Playwright lane or its containerized form, or the Desktop one. */ +export function laneSurface(command) { + if (isDesktopE2eLane(command)) return E2eSurface.Desktop; + if (isWebE2eLane(command) || (!DESKTOP_LANE.test(command) && containerizedIntent("sh", ["-c", command]))) return E2eSurface.Web; + return null; +} + +/** + * The e2e evidence pre-pr-lanes.mjs recorded for `head` (default: the worktree's HEAD) in the session's lane records. + * `receipts`: one per witnessed e2e lane run that `check` accepts as run (`pass`, `env-skip`, `main-preexisting`), `full` + * unless it was a targeted run, with the specs it ran. `notRun`: the e2e lanes recorded not-run, with the record's reason + * and the skip ruling it quotes (`{ id, source }`, else null); only a quoted ruling lets one stand in for a run. `graphSelection`: the union of the graph selections the targeted records carry, + * null when none does. No records (a worktree outside a vibe session) is empty evidence; an unparseable file throws. + */ +export function recordedE2eEvidence(worktree, { head } = {}) { + const empty = { graphSelection: null, receipts: [], notRun: [] }; + let file; + try { file = path.join(git(worktree, ["rev-parse", "--absolute-git-dir"]), LANE_RECORDS_FILE); } catch { return empty; } + let text; + try { text = readFileSync(file, "utf8"); } catch (error) { if (error?.code === "ENOENT") return empty; throw error; } + const records = JSON.parse(text); + if (!Array.isArray(records)) throw new Error(`${file} is not a list of lane records`); + const at = head ?? git(worktree, ["rev-parse", "HEAD"]); + const current = records.filter((record) => record?.head === at && typeof record.command === "string" && laneSurface(record.command)); + const ran = current.filter((record) => RAN_RESULTS.has(record.result) && !witnessProblem(record)); + const receipts = ran.map((record) => ({ surface: laneSurface(record.command), lane: record.command, result: record.result, + full: !record.targeted, specs: Array.isArray(record.targeted?.specs) ? [...record.targeted.specs] : [] })); + const notRun = current.filter((record) => record.result === "not-run").map((record) => ({ surface: laneSurface(record.command), + lane: record.command, reason: record.reason ?? null, ruling: quotedRuling(record) })); + let graphSelection = null; + for (const result of ran.map((record) => record.targeted?.graph?.result).filter(Boolean)) { + for (const surface of Object.values(E2eSurface)) { + if (!Array.isArray(result[surface])) continue; + graphSelection ??= {}; + graphSelection[surface] = [...new Set([...(graphSelection[surface] ?? []), ...result[surface]])].sort(); + } + } + return { graphSelection, receipts, notRun }; +} + +/** + * The `recipes.e2eRequirement` block of the provider serving this worktree's origin (its `memory.repository.remote`), + * or null: the bound provider's in a session, else each installed one's. + */ +function declaredRequirement(worktree, binding, providers) { + let origin = ""; + try { origin = git(worktree, ["config", "--get", "remote.origin.url"]); } catch { return null; } + const contracts = binding ? [boundWith(binding, "recipes")?.contract] : (providers ?? installedProviders({ cwd: worktree })).map((item) => item.contract); + for (const contract of contracts) { + const remote = contract?.data?.memory?.repository?.remote; + const block = contract?.data?.recipes?.e2eRequirement; + if (block && typeof remote === "string" && new RegExp(remote).test(origin)) return block; + } + return null; +} + +/** Whether a provider (the bound one, else each installed one) declares e2e lanes for this repository's origin. */ +export function e2eRequirementDeclared(worktree, binding = null) { + return declaredRequirement(worktree, binding) !== null; +} + +function laneName(declared, spec) { + return `${path.posix.basename(declared.workflow)}:${spec.job}`; +} + +function changedFiles(worktree, base, head) { + return git(worktree, ["diff", "--name-only", "--no-renames", "-z", base, head, "--"]).split("\0").filter(Boolean).sort(); +} + +function existsAt(worktree, commit, file) { + return spawnSync("git", ["-C", worktree, "cat-file", "-e", `${commit}:${file}`]).status === 0; +} + +function surfaceRequirement(context, surface, spec, graphSelection) { + const { declared, workflow, changed } = context; + const lane = laneName(declared, spec); + const row = (fields) => ({ surface, required: true, full: false, reasons: [], lane, specs: [], ...fields }); + let runs, suiteGlobs, classifier; + try { + const globs = (key) => { + if (!workflow.filters[key]) throw new Error(`the ${workflow.filterStep} step declares no ${key} filter`); + return workflow.filters[key]; + }; + runs = changed.filter((file) => globs(spec.runs).some((glob) => glob.test(file))); + classifier = workflow.steps.get(spec.classifier); + if (!classifier) throw new Error(`the changes job has no ${spec.classifier} step`); + suiteGlobs = globs(classifierInput(classifier).filter); + } catch (error) { + return row({ full: true, reasons: [`${declared.workflow}: ${error.message}`] }); + } + const inSuite = (file) => suiteGlobs.some((glob) => glob.test(file)); + const stories = storyReach(context, inSuite); + const reached = newlyReached(context, inSuite); + const changedSpecs = changed.filter((file) => SPEC.test(file) && inSuite(file) && context.source.exists(file)); + if (runs.length === 0 && stories.specs.length === 0 && stories.incomplete.length === 0 && reached.length === 0) { + return row({ required: false }); + } + const owed = (extra) => [...new Set([...stories.specs, ...reached, ...extra])].sort(); + if (stories.incomplete.length) return row({ full: true, reasons: stories.incomplete, specs: owed(changedSpecs) }); + if (Array.isArray(graphSelection)) return row({ reasons: stories.ids, specs: owed(changedSpecs) }); + const suite = changed.filter(inSuite); + if (suite.length === 0) return row({ reasons: [NO_GRAPH, ...stories.ids], specs: owed([]) }); + try { + // The whole set decides, as in CI; each path is then asked alone so the reasons name only those it cannot narrow. + const narrowed = runClassifier(context, classifier, suite); + if (narrowed.length > 0) return row({ reasons: [NO_GRAPH, ...stories.ids], specs: owed(changedSpecs) }); + const blocking = suite.filter((file) => runClassifier(context, classifier, [file]).length === 0); + return row({ full: true, reasons: [NO_GRAPH, ...(blocking.length ? blocking : suite)], specs: owed(changedSpecs) }); + } catch (error) { + return row({ full: true, reasons: [NO_GRAPH, `${spec.classifier} could not run as CI runs it (${error.message})`], specs: owed(changedSpecs) }); + } +} + +/** + * The suite specs that name a changed story's Storybook id (its component id, the sanitized meta title, which every + * story id in the file starts with), directly or through a helper they import. `incomplete` names each story whose + * title is not a plain literal, or whose id appears in a helper no spec imports by name. + */ +function storyReach(context, inSuite) { + const ids = new Map(); + const incomplete = []; + for (const file of context.changed.filter((entry) => STORY.test(entry))) { + const text = context.source.read(file) ?? (context.base ? showAt(context.worktree, context.base, file) : null); + const title = text === null ? null : metaTitle(text); + if (title === null) incomplete.push(`${file}: no literal Storybook title to derive its story ids from`); + else ids.set(storybookId(title), file); + } + if (ids.size === 0 && incomplete.length === 0) return { specs: [], ids: [], incomplete }; + // A surface none of whose specs opens a story by URL, itself or through a helper it imports, cannot reach one. + const opening = [...new Set(context.source.grep([STORY_URL]).map(({ file }) => file).filter(inSuite))]; + if (!opening.some((file) => SPEC.test(file) || importingSpecs(context, inSuite, file).length > 0)) return { specs: [], ids: [], incomplete: [] }; + if (ids.size === 0) return { specs: [], ids: [], incomplete }; + // A spec may hold the component id alone and append the story name; any other file counts only for a whole story id. + const named = (id, file) => new RegExp(`(? inSuite(file)); + const specs = new Set(); + const used = new Set(); + for (const id of ids.keys()) { + const files = [...new Set(hits.filter(({ file, line }) => named(id, file).test(line)).map(({ file }) => file))]; + for (const file of files) { + const reaching = SPEC.test(file) ? [file] : importingSpecs(context, inSuite, file); + if (reaching.length === 0) incomplete.push(`${ids.get(id)}: story id ${id} appears in ${file}, which no spec imports by name`); + for (const spec of reaching) { specs.add(spec); used.add(id); } + } + } + return { specs: [...specs].sort(), ids: [...used].sort(), incomplete }; +} + +/** Suite specs that import a non-spec file the change adds, which the trunk-indexed graph cannot have seen. */ +function newlyReached(context, inSuite) { + const specs = new Set(); + for (const file of context.added.filter((entry) => inSuite(entry) && !SPEC.test(entry) && context.source.exists(entry))) { + for (const spec of importingSpecs(context, inSuite, file)) specs.add(spec); + } + return [...specs].sort(); +} + +/** Suite specs whose import specifier ends in `file`'s module name (`.../` or `.../.`). */ +function importingSpecs(context, inSuite, file) { + const name = path.posix.basename(file).replace(/\.[cm]?[jt]sx?$/, ""); + const specifier = new RegExp(`(?:from|import\\()\\s*["'][^"']*/${escapeRegExp(name)}(?:\\.[cm]?[jt]sx?)?["']`); + return [...new Set(context.source.grep([`/${name}`]).filter(({ file: hit, line }) => hit !== file && SPEC.test(hit) && inSuite(hit) && specifier.test(line)) + .map(({ file: hit }) => hit))].sort(); +} + +/** The default-exported Storybook meta's `title` when it is a plain string literal, else null. */ +export function metaTitle(text) { + const lines = text.split("\n"); + let start = -1; + for (const [index, line] of lines.entries()) { + const match = DEFAULT_EXPORT.exec(line); + if (!match) continue; + if (match[1]) { start = index; break; } + const declaration = new RegExp(`^(?:export )?(?:const|let|var) ${escapeRegExp(match[2])}\\b[^=]*=\\s*\\{\\s*$`); + start = lines.findIndex((entry) => declaration.test(entry)); + break; + } + if (start < 0) return null; + const titles = []; + const body = lines.slice(start + 1); + for (const [index, line] of body.entries()) { + if (/^\}/.test(line)) break; + // A formatter wraps a long title onto the line after its key. + const match = META_TITLE.exec(WRAPPED_TITLE_KEY.test(line) ? ` title: ${(body[index + 1] ?? "").trim()}` : line); + if (match) titles.push(match[1] === "`" && match[2].includes("${") ? null : match[2]); + } + return titles.length === 1 ? titles[0] : null; +} + +/** Storybook's id for a title (its `sanitize`): lower case, punctuation and spaces to single dashes. */ +export function storybookId(title) { + return title.toLowerCase().replace(/[ ’–—―′¿'`~!@#$%^&*()_|+\-=?;:'",.<>{}[\]\\/]/gi, "-").replace(/-+/g, "-").replace(/^-+/, "").replace(/-+$/, ""); +} + +function showAt(worktree, commit, file) { + const result = spawnSync("git", ["-C", worktree, "show", `${commit}:${file}`], { encoding: "utf8", maxBuffer: GREP_BUFFER }); + return result.status === 0 ? result.stdout : null; +} + +/** Reads, lists and greps the committed tree at `head`. */ +function treeSource(worktree, head) { + return { + read: (file) => showAt(worktree, head, file), + exists: (file) => existsAt(worktree, head, file), + grep: (patterns) => grepLines(worktree, [head], patterns, `${head}:`), + }; +} + +/** Reads, lists and greps the worktree's files as they are now, untracked ones included. */ +function worktreeSource(worktree) { + const on = (file) => path.join(worktree, file); + return { + read: (file) => { try { return readFileSync(on(file), "utf8"); } catch { return null; } }, + exists: (file) => { try { return lstatSync(on(file)).isFile() || lstatSync(on(file)).isSymbolicLink(); } catch { return false; } }, + grep: (patterns) => grepLines(worktree, ["--untracked"], patterns, ""), + }; +} + +/** `git grep -F` for any of `patterns`, as `{ file, line }`; a grep that fails throws. */ +function grepLines(worktree, scope, patterns, prefix) { + const result = spawnSync("git", ["-C", worktree, "grep", "-I", "-F", ...patterns.flatMap((pattern) => ["-e", pattern]), ...scope, "--"], + { encoding: "utf8", maxBuffer: GREP_BUFFER }); + if (result.status === 1) return []; + if (result.status !== 0) throw new Error(`git grep failed: ${(result.stderr ?? "").trim()}`); + return result.stdout.split("\n").filter(Boolean).map((entry) => { + const rest = entry.slice(prefix.length); + const at = rest.indexOf(":"); + return { file: rest.slice(0, at), line: rest.slice(at + 1) }; + }); +} + +/** The classifier step's inputs: the filter whose `_files` list it reads, the env name, and the event variable. */ +function classifierInput(step) { + let input = null; + const env = {}; + for (const [key, value] of Object.entries(step.env)) { + const files = FILES_OUTPUT.exec(value); + if (files) { + if (input) throw new Error(`${step.id} reads more than one changed-file list`); + input = { filter: files[2], name: key }; + } else if (EVENT_EXPRESSION.test(value)) { + env[key] = "pull_request"; + } else if (EXPRESSION.test(value)) { + throw new Error(`${step.id} binds ${key} to an expression this reader cannot evaluate`); + } else { + env[key] = value; + } + } + if (!input) throw new Error(`${step.id} reads no changed-file list`); + if (!step.run || EXPRESSION.test(step.run)) throw new Error(`${step.id} has no plain shell run`); + return { ...input, env }; +} + +/** + * Runs the classifier step's own shell, as the changes job runs it on a pull request, in a scratch folder holding the + * changed suite files and every repository file its script names, as they are at `head`. Returns the specs it names. + */ +function runClassifier({ worktree, head, fromWorktree }, step, suite) { + const input = classifierInput(step); + const gitDir = git(worktree, ["rev-parse", "--absolute-git-dir"]); + const scratch = mkdtempSync(path.join(gitDir, "vibe-e2e-classifier-")); + try { + const tree = path.join(scratch, "tree"); + mkdirSync(tree); + const scripts = [...new Set(step.run.match(PATH_TOKEN) ?? [])]; + for (const file of [...new Set([...suite, ...scripts])]) materialize(worktree, head, tree, file, fromWorktree && suite.includes(file)); + const output = path.join(scratch, "output"); + writeFileSync(output, ""); + const result = spawnSync("bash", ["-c", step.run], { cwd: tree, encoding: "utf8", timeout: CLASSIFIER_TIMEOUT_MS, + env: { PATH: process.env.PATH, ...input.env, [input.name]: suite.map(shellWord).join(" "), GITHUB_OUTPUT: output } }); + if (result.status !== 0) throw new Error(`exit ${result.status ?? result.signal}: ${(result.stderr ?? "").trim().split("\n").at(-1) ?? ""}`); + const lines = readFileSync(output, "utf8").split("\n").filter(Boolean); + if (lines.length !== 1 || !lines[0].includes("=")) throw new Error(`wrote ${lines.length} outputs, not one`); + return lines[0].slice(lines[0].indexOf("=") + 1).split(/\s+/).filter(Boolean); + } finally { + rmSync(scratch, { recursive: true, force: true }); + } +} + +/** Writes `file` under `tree` as it is in the worktree now (`fromWorktree`) or at `head`; a symlink stays one, an absent file stays absent. */ +function materialize(worktree, head, tree, file, fromWorktree) { + const target = path.join(tree, file); + if (!target.startsWith(`${tree}${path.sep}`)) return; + if (fromWorktree) { + let stat; + try { stat = lstatSync(path.join(worktree, file)); } catch { return; } + mkdirSync(path.dirname(target), { recursive: true }); + if (stat.isSymbolicLink()) symlinkSync(readlinkSync(path.join(worktree, file)), target); + else if (stat.isFile()) writeFileSync(target, readFileSync(path.join(worktree, file))); + return; + } + const entry = git(worktree, ["ls-tree", "-z", head, "--", file]).split("\0").find((line) => line.endsWith(`\t${file}`)); + if (!entry) return; + const [mode, type, object] = entry.split("\t")[0].split(" "); + if (type !== "blob") return; + mkdirSync(path.dirname(target), { recursive: true }); + const blob = spawnSync("git", ["-C", worktree, "cat-file", "blob", object], { maxBuffer: GREP_BUFFER }); + if (blob.status !== 0) throw new Error(`cannot read classifier input ${file}`); + const content = blob.stdout; + if (mode === "120000") symlinkSync(content.toString("utf8"), target); + else writeFileSync(target, content); +} + +/** A path as the paths-filter action's `list-files: shell` writes it: bare when safe, else single-quoted. */ +function shellWord(file) { + return SAFE_SHELL_WORD.test(file) ? file : `'${file.replaceAll("'", "'\\''")}'`; +} + +/** + * The parts of the workflow at `head` the requirement reads: the change-detection job's steps by id, and the + * paths-filter step's filters as glob matchers. Throws on any shape it does not recognize. + */ +export function readWorkflow(worktree, head, declared) { + const text = git(worktree, ["show", `${head}:${declared.workflow}`]); + const steps = jobSteps(text.split("\n"), declared.changesJob); + const filterStep = steps.get(declared.filterStep); + if (!filterStep?.with.filters) throw new Error(`the ${declared.changesJob} job has no ${declared.filterStep} step with filters`); + return { steps, filters: parseFilters(filterStep.with.filters), filterStep: declared.filterStep }; +} + +const indentOf = (line) => line.length - line.trimStart().length; +const isBlankOrComment = (line) => line.trim() === "" || line.trimStart().startsWith("#"); + +/** The steps of job `name` under `jobs:`, by id. */ +function jobSteps(lines, name) { + const jobsAt = lines.findIndex((line) => /^jobs:\s*$/.test(line)); + if (jobsAt < 0) throw new Error("no jobs"); + const start = lines.findIndex((line, index) => index > jobsAt && new RegExp(`^ {2}${escapeRegExp(name)}:\\s*$`).test(line)); + if (start < 0) throw new Error(`no ${name} job`); + let end = start + 1; + while (end < lines.length && (isBlankOrComment(lines[end]) || indentOf(lines[end]) > 2)) end += 1; + const job = lines.slice(start + 1, end); + const stepsAt = job.findIndex((line) => /^ {4}steps:\s*$/.test(line)); + if (stepsAt < 0) throw new Error(`the ${name} job has no steps`); + const items = []; + let itemIndent = null; + for (const line of job.slice(stepsAt + 1)) { + if (isBlankOrComment(line)) { if (items.length) items.at(-1).push(line); continue; } + if (indentOf(line) <= 4) break; + const dash = /^( *)- /.exec(line); + itemIndent ??= dash ? dash[1].length : null; + if (itemIndent === null) throw new Error("steps is not a list"); + if (dash && dash[1].length === itemIndent) items.push([`${" ".repeat(itemIndent + 2)}${line.slice(itemIndent + 2)}`]); + else items.at(-1).push(line); + } + const steps = new Map(); + for (const item of items) { + const step = mapping(item, itemIndent + 2); + if (typeof step.id === "string") steps.set(step.id, { id: step.id, env: step.env ?? {}, with: step.with ?? {}, run: step.run ?? null }); + } + return steps; +} + +/** A YAML block mapping at `indent`: plain or quoted scalars, `|` block scalars and nested mappings. */ +function mapping(lines, indent) { + const result = {}; + for (let index = 0; index < lines.length;) { + const line = lines[index]; + if (isBlankOrComment(line)) { index += 1; continue; } + if (indentOf(line) !== indent) throw new Error(`unexpected indentation at "${line.trim()}"`); + const pair = /^ *([A-Za-z0-9_-]+):(?: +(.*?))?\s*$/.exec(line); + if (!pair) throw new Error(`unrecognized line "${line.trim()}"`); + let next = index + 1; + while (next < lines.length && (lines[next].trim() === "" || indentOf(lines[next]) > indent)) next += 1; + const body = lines.slice(index + 1, next); + const value = pair[2] ?? ""; + if (/^\|-?$/.test(value)) result[pair[1]] = blockScalar(body); + else if (value === "") result[pair[1]] = body.some((entry) => !isBlankOrComment(entry)) ? mapping(body, indentOf(body.find((entry) => !isBlankOrComment(entry)))) : ""; + else if (body.some((entry) => !isBlankOrComment(entry))) throw new Error(`multi-line scalar at ${pair[1]}`); + else result[pair[1]] = scalar(value); + index = next; + } + return result; +} + +function blockScalar(lines) { + const content = lines.filter((line) => line.trim() !== ""); + if (content.length === 0) return ""; + const indent = Math.min(...content.map(indentOf)); + return `${lines.map((line) => line.slice(indent)).join("\n").replace(/\n+$/, "")}\n`; +} + +function scalar(value) { + if (/^'.*'$/.test(value)) return value.slice(1, -1).replaceAll("''", "'"); + if (/^".*"$/.test(value)) return JSON.parse(value); + if (/^[|>&*!{[]/.test(value)) throw new Error(`unsupported scalar ${value}`); + return value.replace(/\s+#.*$/, ""); +} + +/** The paths-filter `filters` text: each key's globs as anchored matchers. */ +export function parseFilters(text) { + const filters = {}; + let key = null; + for (const line of text.split("\n")) { + if (isBlankOrComment(line)) continue; + const name = /^([A-Za-z0-9_-]+):\s*$/.exec(line); + if (name) { key = name[1]; filters[key] = []; continue; } + const item = /^\s+-\s+(.+?)\s*$/.exec(line); + if (!item || key === null) throw new Error(`unrecognized filter line "${line.trim()}"`); + filters[key].push(globMatcher(scalar(item[1]))); + } + return filters; +} + +/** A paths-filter glob (picomatch with dotfiles) as an anchored matcher; braces, classes and negation are refused. */ +export function globMatcher(glob) { + if (/[{}[\]!]/.test(glob)) throw new Error(`unsupported glob ${glob}`); + let source = ""; + for (let index = 0; index < glob.length; index += 1) { + const rest = glob.slice(index); + if (rest.startsWith("**/")) { source += "(?:.*/)?"; index += 2; } + else if (rest === "**") { source += ".*"; index += 1; } + else if (rest.startsWith("/**") && rest.length === 3) { source += "(?:/.*)?"; index += 2; } + else if (glob[index] === "*") source += "[^/]*"; + else if (glob[index] === "?") source += "[^/]"; + else source += escapeRegExp(glob[index]); + } + return new RegExp(`^${source}$`); +} + +function escapeRegExp(text) { + return text.replace(/[.*+?^${}()|[\]\\]/g, "\\$&"); +} + +if (isEntryPoint(import.meta.url)) { + const { values } = parseArgs({ options: { worktree: { type: "string" }, base: { type: "string" }, head: { type: "string" } } }); + if (!values.worktree || !values.base || !values.head) { + process.stderr.write("Usage: e2e-requirement.mjs --worktree --base --head \n"); + process.exit(2); + } + const { sessionBinding } = await vibeCore("lib/vibe/scripts/provider.mjs"); + for (const row of e2eLaneRequirement(values.worktree, { base: values.base, head: values.head, binding: sessionBinding(values.worktree) })) { + process.stdout.write(`${JSON.stringify(row)}\n`); + } +} + +/** The skip ruling a not-run record quotes, `{ id, source }`, or null when it names none. */ +function quotedRuling(record) { + const id = typeof record.ruling === "string" ? record.ruling.trim() : ""; + const source = typeof record.rulingSource === "string" ? record.rulingSource.trim() : ""; + return id && source ? { id, source } : null; +} diff --git a/plugins/vibe/skills/vibe/scripts/e2e-requirement.test.mjs b/plugins/vibe/skills/vibe/scripts/e2e-requirement.test.mjs new file mode 100644 index 00000000..819ba957 --- /dev/null +++ b/plugins/vibe/skills/vibe/scripts/e2e-requirement.test.mjs @@ -0,0 +1,509 @@ +import assert from "node:assert/strict"; +import { mkdirSync, readFileSync, rmSync, symlinkSync, writeFileSync } from "node:fs"; +import path from "node:path"; +import test from "node:test"; +import { spawnSync } from "node:child_process"; +import { fileURLToPath } from "node:url"; +import { e2eLaneRequirement, globMatcher, metaTitle, missingE2eSpecs, NO_GRAPH, recordedE2eEvidence, storybookId } from "./e2e-requirement.mjs"; +import { targetedE2eCoverage, targetedRecord } from "./pre-pr-lanes.mjs"; +import { bindProvider, bindProviderInProcess, git, makeHome, passingPnpmPath, PROVIDER_BINDING, PROVIDER_ROOT, SYMPHONY_REMOTE, witnessArgs } from "./test-fixtures.mjs"; + +const PRE_PR_LANES = fileURLToPath(new URL("./pre-pr-lanes.mjs", import.meta.url)); +const CONTRACT = JSON.parse(readFileSync(path.join(PROVIDER_ROOT, "provider.json"), "utf8")); +const PROVIDERS = [{ contract: CONTRACT }]; +const DECLARED = CONTRACT.data.recipes.e2eRequirement; +const WEB = DECLARED.surfaces.web; +const DESKTOP = DECLARED.surfaces.desktop; +const WEB_LANE = `${path.posix.basename(DECLARED.workflow)}:${WEB.job}`; +const STORY_FRAME = "/iframe.html"; +const DESKTOP_LANE = `${path.posix.basename(DECLARED.workflow)}:${DESKTOP.job}`; + +// The target repository's change-detection job reduced to its shape: the same step ids, filter keys, and +// changed-spec classifiers (the web one inline, the Desktop one a script). +const WORKFLOW = `name: E2E Tests + +on: + pull_request: + types: [opened, synchronize] + +jobs: + ${DECLARED.changesJob}: + if: \${{ github.event_name != 'schedule' }} + runs-on: ubuntu-latest + outputs: + e2e: \${{ steps.decide.outputs.e2e }} + steps: + - name: Checkout repository + uses: actions/checkout@v4 + + # The filter step lists the changed paths of each filter. + - name: Detect e2e-relevant changed paths + if: github.event_name == 'pull_request' || github.event_name == 'merge_group' + id: ${DECLARED.filterStep} + uses: dorny/paths-filter@v3 + with: + base: \${{ github.event_name == 'merge_group' && github.event.merge_group.base_ref || '' }} + list-files: shell + filters: | + # Paths that produce something to test. + ${WEB.runs}: + - 'apps/web/**' + - 'packages/**' + - 'e2e/**' + - 'playwright.config.ts' + # The suite itself. + e2e_specs: + - 'e2e/**/*.ts' + - 'playwright.config.ts' + desktop_e2e_specs: + - 'apps/desktop/test/e2e/**' + - 'e2e/helpers/**' + ${DESKTOP.runs}: + - 'apps/desktop/**' + - 'e2e/helpers/**' + + - name: List the changed Playwright specs + if: github.event_name == 'pull_request' || github.event_name == 'merge_group' + id: ${WEB.classifier} + shell: bash + env: + E2E_SPEC_FILES: \${{ steps.${DECLARED.filterStep}.outputs.e2e_specs_files }} + run: | + set -euo pipefail + selected="" + for path in \${E2E_SPEC_FILES:-}; do + case "\${path}" in + e2e/*/*) selected=""; break ;; + e2e/*[!A-Za-z0-9._-]*) selected=""; break ;; + e2e/?*.spec.ts) + if [ ! -f "\${path}" ] || [ -L "\${path}" ]; then selected=""; break; fi + selected="\${selected:+\${selected} }\${path}" + ;; + *) selected=""; break ;; + esac + done + echo "e2e_changed_specs=\${selected}" >> "$GITHUB_OUTPUT" + + - name: List the changed Electron specs + if: github.event_name == 'pull_request' || github.event_name == 'merge_group' + id: ${DESKTOP.classifier} + shell: bash + env: + DESKTOP_SPEC_FILES: \${{ steps.${DECLARED.filterStep}.outputs.desktop_e2e_specs_files }} + EVENT_NAME: \${{ github.event_name }} + run: bash apps/desktop/test/e2e-changed-specs.sh + + ${WEB.job}: + needs: + - ${DECLARED.changesJob} + runs-on: ubuntu-latest + steps: + - run: echo suite + + ${DESKTOP.job}: + needs: + - ${DECLARED.changesJob} + runs-on: ubuntu-latest + steps: + - run: echo suite +`; + +const DESKTOP_CLASSIFIER = `set -euo pipefail +selected="" +for path in \${DESKTOP_SPEC_FILES:-}; do + case "\${path}" in + apps/desktop/test/e2e/*/*) selected=""; break ;; + apps/desktop/test/e2e/*[!A-Za-z0-9._-]*) selected=""; break ;; + apps/desktop/test/e2e/?*.spec.ts) + if [ ! -f "\${path}" ] || [ -L "\${path}" ]; then selected=""; break; fi + selected="\${selected:+\${selected} }\${path##*/}" + ;; + *) selected=""; break ;; + esac +done +echo "desktop_e2e_changed_specs=\${selected}" >> "$GITHUB_OUTPUT" +`; + +const TARGETED_POLICY = [ + "An e2e lane (`e2e`, `desktop-e2e`) is the exception: locally it is satisfied by the specs the graph selects for the diff (`code_tests_for_changes`), plus every spec the PR adds or edits.", + "The full lane runs after merge.", +].join("\n"); + +const NARROW_LIST_SPEC = "e2e/grid-table-v2-narrow-list.local-trusted.spec.ts"; +const NEW_SPEC = "e2e/org-issues-narrow-name-cap.spec.ts"; +const HELPER = "e2e/helpers/pinned-name-strip.ts"; +const STORY_DIR = "apps/storybook/stories"; +const STORIES = { + [`${STORY_DIR}/start-here-version-history.stories.tsx`]: "Start Here/Version History", + [`${STORY_DIR}/surfaces-v2/v2-branches-list.stories.tsx`]: "Surfaces/Artifacts/Branches/Branches List", + [`${STORY_DIR}/surfaces-v2/v2-documents-list.stories.tsx`]: "Surfaces/Artifacts/Documents/Documents List", + [`${STORY_DIR}/surfaces-v2/v2-issues-list.stories.tsx`]: "Surfaces/Artifacts/Issues/Issues List", + [`${STORY_DIR}/surfaces-v2/v2-projects-list.stories.tsx`]: "Surfaces/Your Teams/Projects List", + [`${STORY_DIR}/surfaces-v2/v2-sessions-list.stories.tsx`]: "Surfaces/Artifacts/Sessions/Sessions List", +}; + +const story = (title, name = "Narrow") => [ + "import type { Meta, StoryObj } from \"@storybook/react\";", + "", + "const meta = {", + ` title: "${title}",`, + " args: { heading: \"Not the title\" },", + "} satisfies Meta;", + "", + "export default meta;", + `export const ${name}: StoryObj = {};`, + "", +].join("\n"); + +/** The base tree: the workflow, the Desktop classifier, two web specs (one opening stories by URL) and one Desktop spec. */ +function repository(t, prefix, { remote = SYMPHONY_REMOTE, files = {} } = {}) { + const { root, home, cleanup } = makeHome(prefix); + t.after(cleanup); + const worktree = path.join(root, "wt"); + git(root, ["init", "--quiet", "--initial-branch=main", worktree], home); + git(worktree, ["remote", "add", "origin", remote], home); + write(worktree, { + [DECLARED.workflow]: WORKFLOW, + "apps/desktop/test/e2e-changed-specs.sh": DESKTOP_CLASSIFIER, + "AGENTS.md": TARGETED_POLICY, + "e2e/existing.spec.ts": "import { test } from \"./test\";\ntest(\"existing\", () => {});\n", + [NARROW_LIST_SPEC]: [ + "const PRODUCTION_COMPACT_STORY_IDS = [\"surfaces-artifacts-sessions-sessions-list--narrow\"] as const;", + "for (const storyId of PRODUCTION_COMPACT_STORY_IDS) {", + ` test(storyId, async ({ page }) => { await page.goto(\`${STORY_FRAME}?id=\${storyId}&viewMode=story\`); });`, + "}", + "", + ].join("\n"), + "apps/desktop/test/e2e/home.spec.ts": "export const home = true;\n", + "apps/desktop/test/e2e/helpers/app.ts": "export const app = true;\n", + "packages/app/table.tsx": "export const table = 1;\n", + ...Object.fromEntries(Object.entries(STORIES).map(([file, title]) => [file, story(title)])), + ...files, + }); + const base = commit(worktree, home, "base"); + return { root, home, worktree, base, change: (changes, message = "change") => { write(worktree, changes); return commit(worktree, home, message); } }; +} + +function write(worktree, files) { + for (const [file, content] of Object.entries(files)) { + const target = path.join(worktree, file); + if (content === null) { rmSync(target); continue; } + mkdirSync(path.dirname(target), { recursive: true }); + writeFileSync(target, content); + } +} + +function commit(worktree, home, message) { + git(worktree, ["add", "-A"], home); + git(worktree, ["commit", "--quiet", "-m", message], home); + return git(worktree, ["rev-parse", "HEAD"], home); +} + +const surface = (rows, name) => rows.find((row) => row.surface === name); + +/** The pull request that broke main: a shared e2e helper, six stories and one new spec. */ +function brokeMainChange() { + return { + [HELPER]: "export const pinnedNameStrip = () => 1;\n", + [NEW_SPEC]: "import { pinnedNameStrip } from \"./helpers/pinned-name-strip\";\ntest(\"cap\", () => pinnedNameStrip());\n", + ...Object.fromEntries(Object.entries(STORIES).map(([file, title]) => [file, story(title, "Narrower")])), + }; +} + +test("a changed story owes every spec that opens it by its Storybook id, which the graph cannot select", (t) => { + const repo = repository(t, "e2e-req-story-"); + const head = repo.change(brokeMainChange()); + const rows = e2eLaneRequirement(repo.worktree, { base: repo.base, head, providers: PROVIDERS, graphSelection: { web: [], desktop: [] } }); + const web = surface(rows, "web"); + assert.equal(web.required, true); + assert.equal(web.full, false, "with a graph result the change is narrowed, never forced to the whole lane"); + assert.deepEqual(web.specs, [NARROW_LIST_SPEC, NEW_SPEC].sort()); + assert.deepEqual(web.reasons, ["surfaces-artifacts-sessions-sessions-list"]); + assert.equal(web.lane, WEB_LANE); + assert.deepEqual(surface(rows, "desktop"), { surface: "desktop", required: true, full: false, reasons: [], lane: DESKTOP_LANE, specs: [] }); +}); + +test("without a graph result the changes job's own classifier decides: a helper forces the whole lane, a spec narrows", (t) => { + const repo = repository(t, "e2e-req-fallback-"); + const head = repo.change(brokeMainChange()); + const web = surface(e2eLaneRequirement(repo.worktree, { base: repo.base, head, providers: PROVIDERS }), "web"); + assert.equal(web.full, true); + assert.deepEqual(web.reasons, [NO_GRAPH, HELPER], "the reasons name the path the union cannot narrow, not the narrowable spec"); + + const specOnly = repository(t, "e2e-req-spec-only-"); + const specHead = specOnly.change({ "e2e/existing.spec.ts": "test(\"existing\", () => { /* edited */ });\n" }); + const rows = e2eLaneRequirement(specOnly.worktree, { base: specOnly.base, head: specHead, providers: PROVIDERS }); + assert.deepEqual(surface(rows, "web"), { surface: "web", required: true, full: false, reasons: [NO_GRAPH], lane: WEB_LANE, specs: ["e2e/existing.spec.ts"] }); + assert.equal(surface(rows, "desktop").required, false); + + const desktop = repository(t, "e2e-req-desktop-"); + const desktopSpec = desktop.change({ "apps/desktop/test/e2e/home.spec.ts": "export const home = 2;\n" }); + assert.equal(surface(e2eLaneRequirement(desktop.worktree, { base: desktop.base, head: desktopSpec, providers: PROVIDERS }), "desktop").full, false); + const desktopHelper = desktop.change({ "apps/desktop/test/e2e/helpers/app.ts": "export const app = 2;\n" }); + const helperRow = surface(e2eLaneRequirement(desktop.worktree, { base: desktopSpec, head: desktopHelper, providers: PROVIDERS }), "desktop"); + assert.deepEqual([helperRow.full, helperRow.reasons], [true, [NO_GRAPH, "apps/desktop/test/e2e/helpers/app.ts"]]); +}); + +test("a spec deleted or symlinked by the change cannot narrow the union, as in CI", (t) => { + const repo = repository(t, "e2e-req-deleted-"); + const head = repo.change({ "e2e/existing.spec.ts": null }); + const web = surface(e2eLaneRequirement(repo.worktree, { base: repo.base, head, providers: PROVIDERS }), "web"); + assert.deepEqual([web.full, web.specs], [true, []]); + symlinkSync("existing.spec.ts", path.join(repo.worktree, "e2e/alias.spec.ts")); + write(repo.worktree, { "e2e/existing.spec.ts": "test(\"back\", () => {});\n" }); + const linked = repo.change({}, "alias"); + const aliased = surface(e2eLaneRequirement(repo.worktree, { base: head, head: linked, providers: PROVIDERS }), "web"); + assert.deepEqual([aliased.full, aliased.reasons], [true, [NO_GRAPH, "e2e/alias.spec.ts"]]); +}); + +test("a classifier step that cannot be read or exits non-zero owes the whole lane and never narrows", (t) => { + const failing = repository(t, "e2e-req-exit-", { files: { "apps/desktop/test/e2e-changed-specs.sh": "exit 3\n" } }); + const failingHead = failing.change({ "apps/desktop/test/e2e/home.spec.ts": "export const home = 2;\n" }); + const desktop = surface(e2eLaneRequirement(failing.worktree, { base: failing.base, head: failingHead, providers: PROVIDERS }), "desktop"); + assert.equal(desktop.full, true); + assert.match(desktop.reasons.join(" "), /could not run as CI runs it \(exit 3/); + + const expression = repository(t, "e2e-req-expression-", { files: { [DECLARED.workflow]: WORKFLOW.replace("EVENT_NAME: ${{ github.event_name }}", "EVENT_NAME: ${{ inputs.event }}") } }); + const expressionHead = expression.change({ "apps/desktop/test/e2e/home.spec.ts": "export const home = 2;\n" }); + assert.match(surface(e2eLaneRequirement(expression.worktree, { base: expression.base, head: expressionHead, providers: PROVIDERS }), "desktop").reasons.join(" "), + /cannot evaluate/); + + const unreadable = repository(t, "e2e-req-unreadable-", { files: { [DECLARED.workflow]: WORKFLOW.replace("- 'e2e/**/*.ts'", "- 'e2e/{a,b}/*.ts'") } }); + const unreadableHead = unreadable.change({ "e2e/existing.spec.ts": "test(\"edited\", () => {});\n" }); + for (const row of e2eLaneRequirement(unreadable.worktree, { base: unreadable.base, head: unreadableHead, providers: PROVIDERS, graphSelection: { web: [], desktop: [] } })) { + assert.deepEqual([row.required, row.full], [true, true], `${row.surface}: an unparseable workflow is never read as nothing to run`); + assert.match(row.reasons[0], /cannot be read as CI reads it \(unsupported glob/); + } +}); + +test("the workflow is read at head, never from the working tree", (t) => { + const repo = repository(t, "e2e-req-at-head-"); + const head = repo.change({ [HELPER]: "export const pinnedNameStrip = 2;\n" }); + writeFileSync(path.join(repo.worktree, DECLARED.workflow), "not: [a workflow\n"); + assert.equal(surface(e2eLaneRequirement(repo.worktree, { base: repo.base, head, providers: PROVIDERS }), "web").reasons.at(-1), HELPER); +}); + +test("a story whose title is not a literal, or whose id only a helper no spec imports names, owes the whole lane", (t) => { + const repo = repository(t, "e2e-req-incomplete-", { files: { "e2e/helpers/story-flow.ts": `export const url = "${STORY_FRAME}?id=surfaces-your-teams-projects-list--wide";\n` } }); + const computed = repo.change({ [`${STORY_DIR}/computed.stories.tsx`]: "const meta = {\n title: `Surfaces/${area}`,\n};\nexport default meta;\n", + "apps/desktop/test/e2e/home.spec.ts": "export const home = 2;\n" }); + const rows = e2eLaneRequirement(repo.worktree, { base: repo.base, head: computed, providers: PROVIDERS, graphSelection: { web: [], desktop: [] } }); + const web = surface(rows, "web"); + assert.equal(web.full, true); + assert.match(web.reasons[0], /computed\.stories\.tsx: no literal Storybook title/); + assert.deepEqual(surface(rows, "desktop"), { surface: "desktop", required: true, full: false, reasons: [], lane: DESKTOP_LANE, + specs: ["apps/desktop/test/e2e/home.spec.ts"] }, "a surface none of whose suite files opens a story by URL owes nothing for a story"); + + const helperOnly = repo.change({ [`${STORY_DIR}/computed.stories.tsx`]: null, [`${STORY_DIR}/surfaces-v2/v2-projects-list.stories.tsx`]: story("Surfaces/Your Teams/Projects List", "Wide") }); + const helperRow = surface(e2eLaneRequirement(repo.worktree, { base: computed, head: helperOnly, providers: PROVIDERS, graphSelection: { web: [] } }), "web"); + assert.equal(helperRow.full, true); + assert.match(helperRow.reasons.join(" "), /story id surfaces-your-teams-projects-list appears in e2e\/helpers\/story-flow\.ts, which no spec imports/); + + const imported = repo.change({ "e2e/projects.spec.ts": "import { url } from \"./helpers/story-flow\";\ntest(\"wide\", () => url);\n" }); + write(repo.worktree, { [`${STORY_DIR}/surfaces-v2/v2-projects-list.stories.tsx`]: story("Surfaces/Your Teams/Projects List", "Wider") }); + const viaHelper = repo.change({}, "story again"); + const reached = surface(e2eLaneRequirement(repo.worktree, { base: imported, head: viaHelper, providers: PROVIDERS, graphSelection: { web: [] } }), "web"); + assert.deepEqual([reached.full, reached.specs], [false, ["e2e/projects.spec.ts"]]); +}); + +test("a spec importing a file the change adds is owed, since the trunk graph cannot have seen it", (t) => { + const repo = repository(t, "e2e-req-added-"); + const head = repo.change({ "e2e/helpers/new-flow.ts": "export const flow = 1;\n", + "e2e/existing.spec.ts": "import { flow } from \"./helpers/new-flow\";\ntest(\"existing\", () => flow);\n" }); + const web = surface(e2eLaneRequirement(repo.worktree, { base: repo.base, head, providers: PROVIDERS, graphSelection: { web: [] } }), "web"); + assert.deepEqual([web.full, web.specs], [false, ["e2e/existing.spec.ts"]]); +}); + +test("the provider is found by repository: none for another origin, the bound one in a session, and none declared is []", (t) => { + const other = repository(t, "e2e-req-other-", { remote: "git@github.com:example/other.git" }); + const otherHead = other.change(brokeMainChange()); + assert.deepEqual(e2eLaneRequirement(other.worktree, { base: other.base, head: otherHead, providers: PROVIDERS }), []); + assert.deepEqual(e2eLaneRequirement(other.worktree, { base: other.base, head: otherHead, binding: PROVIDER_BINDING }), []); + assert.deepEqual(missingE2eSpecs(other.worktree, { base: other.base, head: otherHead, providers: PROVIDERS }), []); + + const served = repository(t, "e2e-req-served-"); + const head = served.change(brokeMainChange()); + assert.deepEqual(e2eLaneRequirement(served.worktree, { base: served.base, head, binding: PROVIDER_BINDING }), + e2eLaneRequirement(served.worktree, { base: served.base, head, providers: PROVIDERS })); + const undeclared = structuredClone(CONTRACT); + delete undeclared.data.recipes.e2eRequirement; + assert.deepEqual(e2eLaneRequirement(served.worktree, { base: served.base, head, providers: [{ contract: undeclared }] }), []); + assert.deepEqual(e2eLaneRequirement(served.worktree, { base: served.base, head, providers: [] }), []); +}); + +test("uncommitted changes are read from the worktree when the caller passes its changed-file set", (t) => { + const repo = repository(t, "e2e-req-uncommitted-"); + write(repo.worktree, { [HELPER]: "export const pinnedNameStrip = 3;\n" }); + const web = surface(e2eLaneRequirement(repo.worktree, { base: repo.base, head: repo.base, providers: PROVIDERS, files: [HELPER] }), "web"); + assert.deepEqual([web.full, web.reasons], [true, [NO_GRAPH, HELPER]]); +}); + +test("missingE2eSpecs names each owed spec or the whole lane, and a passing run covers it", (t) => { + const repo = repository(t, "e2e-req-missing-"); + const head = repo.change(brokeMainChange()); + const options = { base: repo.base, head, providers: PROVIDERS, graphSelection: { web: ["e2e/existing.spec.ts"], desktop: [] } }; + assert.deepEqual(missingE2eSpecs(repo.worktree, { ...options, receipts: [{ surface: "web", full: false, specs: [NEW_SPEC, "e2e/existing.spec.ts"] }] }), + [{ surface: "web", spec: NARROW_LIST_SPEC, reason: "changed, reached by an added file, or naming a changed story (surfaces-artifacts-sessions-sessions-list)" }]); + assert.deepEqual(missingE2eSpecs(repo.worktree, { ...options, receipts: [] }).map((item) => item.spec), ["e2e/existing.spec.ts", NARROW_LIST_SPEC, NEW_SPEC]); + assert.deepEqual(missingE2eSpecs(repo.worktree, { ...options, receipts: [{ surface: "web", full: false, specs: ["e2e/existing.spec.ts", NARROW_LIST_SPEC, NEW_SPEC] }] }), []); + assert.deepEqual(missingE2eSpecs(repo.worktree, { ...options, receipts: [{ surface: "web", full: true, specs: [] }] }), []); + + // A row outside a vibe session: a provider serves the repository and no graph result exists. + const fallback = missingE2eSpecs(repo.worktree, { base: repo.base, head, providers: PROVIDERS }); + assert.deepEqual(fallback.map(({ surface: name, spec }) => [name, spec]), [["web", "full"], ["desktop", "full"]]); + assert.match(fallback[0].reason, new RegExp(`${NO_GRAPH}; ${HELPER}$`)); + assert.deepEqual(missingE2eSpecs(repo.worktree, { base: repo.base, head, providers: PROVIDERS, + receipts: [{ surface: "web", full: true }, { surface: "desktop", full: true }] }), []); +}); + +test("a lane recorded not-run satisfies nothing unless its record quotes the skip ruling that waived it", (t) => { + const repo = repository(t, "e2e-req-not-run-"); + const head = repo.change({ ...brokeMainChange(), "apps/desktop/test/e2e/home.spec.ts": "export const home = 2;\n" }); + const options = { base: repo.base, head, providers: PROVIDERS, graphSelection: { web: [], desktop: [] } }; + const desktopLane = "DESKTOP_E2E_SMOKE_TAG='' DESKTOP_E2E_CHANGED_SPECS='' pnpm --dir apps/desktop test:e2e"; + const left = { surface: "desktop", lane: desktopLane, reason: "no displayless Linux Electron harness on this machine", ruling: null }; + const owed = missingE2eSpecs(repo.worktree, { ...options, notRun: [left] }).filter((item) => item.surface === "desktop"); + assert.deepEqual(owed.map((item) => item.spec), ["apps/desktop/test/e2e/home.spec.ts"], "a not-run lane is still owed"); + assert.match(owed[0].reason, /recorded not-run here, which satisfies nothing: run it in cloud validation, which runs the whole Desktop suite, or on the heavy host/); + assert.doesNotMatch(owed[0].reason, /harness/, "the reason names where the lane runs, not what this machine lacks"); + const full = missingE2eSpecs(repo.worktree, { base: repo.base, head, providers: PROVIDERS, notRun: [left] }).find((item) => item.surface === "desktop"); + assert.equal(full.spec, "full"); + assert.match(full.reason, /satisfies nothing: run it in cloud validation/); + + const ruled = { ...left, ruling: { id: "ruling-7", source: "operator, 2026-12-02, in chat" } }; + assert.deepEqual(missingE2eSpecs(repo.worktree, { ...options, notRun: [ruled] }).filter((item) => item.surface === "desktop"), []); + assert.notDeepEqual(missingE2eSpecs(repo.worktree, { ...options, notRun: [ruled] }).filter((item) => item.surface === "web"), [], + "a ruling waives only its own surface"); + + // The ruling comes from the record itself: a not-run record with an id and a source quotes one, and one without a source does not. + const file = path.join(git(repo.worktree, ["rev-parse", "--absolute-git-dir"], repo.home), "vibe-lane-results.json"); + const record = { command: desktopLane, head, result: "not-run", reason: left.reason, at: "2026-12-02T00:00:00.000Z" }; + writeFileSync(file, JSON.stringify([{ ...record, ruling: "ruling-7", rulingSource: "operator, 2026-12-02, in chat" }])); + assert.deepEqual(recordedE2eEvidence(repo.worktree, { head }).notRun, [ruled]); + writeFileSync(file, JSON.stringify([{ ...record, ruling: "ruling-7" }])); + assert.deepEqual(recordedE2eEvidence(repo.worktree, { head }).notRun, [left]); +}); + +test("check recommends targeted E2E only for lanes that can satisfy PR create with it", (t) => { + const report = (repo) => { + const file = path.join(repo.root, "lanes.txt"); + writeFileSync(file, " pnpm test:e2e\n"); + return file; + }; + const check = (repo, file) => spawnSync(process.execPath, [PRE_PR_LANES, "check", "--worktree", repo.worktree, "--base", repo.base, "--report", file], { + encoding: "utf8", env: { ...process.env, HOME: repo.home, ...bindProvider(repo.home), [CONTRACT.data.recipes.e2e.identityKey]: "fixture" } }); + + const fullRepo = repository(t, "e2e-req-check-full-"); + fullRepo.change({ [`${STORY_DIR}/computed.stories.tsx`]: "const meta = {\n title: `Surfaces/${area}`,\n};\nexport default meta;\n" }); + const refused = check(fullRepo, report(fullRepo)); + assert.match(refused.stdout, /^MISSING-LANE pnpm test:e2e/m); + assert.match(refused.stdout, /^FULL-E2E-REQUIRED pnpm test:e2e: .*computed\.stories\.tsx: no literal Storybook title.*record it without --targeted-specs$/m); + assert.doesNotMatch(refused.stdout, /TARGETED-E2E/, "no targeted hint for a lane PR create requires in full"); + + const narrowRepo = repository(t, "e2e-req-check-narrow-"); + narrowRepo.change({ "e2e/existing.spec.ts": "import { test } from \"./test\";\ntest(\"edited\", () => {});\n" }); + const offered = check(narrowRepo, report(narrowRepo)); + assert.match(offered.stdout, /^TARGETED-E2E: this repository allows a targeted E2E lane in place of the full one for pnpm test:e2e; /m); + assert.doesNotMatch(offered.stdout, /FULL-E2E-REQUIRED/); +}); + +test("recordedE2eEvidence reads the lane records pre-pr-lanes writes, and none is empty evidence", async (t) => { + const repo = repository(t, "e2e-req-evidence-"); + const head = repo.change(brokeMainChange()); + assert.deepEqual(recordedE2eEvidence(repo.worktree), { graphSelection: null, receipts: [], notRun: [] }); + + // Witnessed passes recorded through the script itself, for the web lane and the Desktop lane. + const web = "pnpm test:e2e"; + const desktop = "DESKTOP_E2E_SMOKE_TAG='' DESKTOP_E2E_CHANGED_SPECS='' pnpm --dir apps/desktop test:e2e"; + const report = path.join(repo.root, "lanes.txt"); + writeFileSync(report, ` ${web}\n ${desktop}\n`); + const env = { ...process.env, HOME: repo.home, PATH: passingPnpmPath(repo.root), CLAUDE_CODE_SESSION_ID: "", CODEX_THREAD_ID: "" }; + const run = (...args) => spawnSync(process.execPath, [PRE_PR_LANES, ...args], { encoding: "utf8", env }); + for (const lane of [web, desktop]) { + const recorded = run("record", "--worktree", repo.worktree, "--head", head, "--command", lane, "--result", "pass", "--report", report, + ...witnessArgs(run, repo.worktree, head, lane)); + assert.equal(recorded.status, 0, recorded.stderr); + } + // The web pass carries a targeted receipt as targetedRecord returns it; the containerized web lane was left to CI. + const query = { repo: SYMPHONY_REMOTE.replace(/\.git$/, "").split("/").at(-1), files: git(repo.worktree, ["diff", "--name-only", repo.base, head], repo.home).split("\n").sort() }; + const graphItem = { type: "mcpToolCall", id: "graph-call-1", server: "graph", tool: "code_tests_for_changes", status: "completed", arguments: query, + result: { structuredContent: { repo: query.repo, desktop_e2e: { verdict: "RUN_ALL", start_here: { specs: ["apps/desktop/test/e2e/home.spec.ts"], specs_total: 1 } }, + tier2: { rows: [{ test: "e2e/existing.spec.ts" }], candidates_total: 1 } } } }; + const targeted = await targetedRecord({ worktree: repo.worktree, base: repo.base, graphSelector: "code_tests_for_changes", "graph-session": "thread-1", + "graph-turn": "turn-1", "graph-query": JSON.stringify(query), "targeted-specs": JSON.stringify(["e2e/existing.spec.ts", NEW_SPEC]) }, web, async () => ({ items: [graphItem] })); + const file = path.join(git(repo.worktree, ["rev-parse", "--absolute-git-dir"], repo.home), "vibe-lane-results.json"); + const records = JSON.parse(readFileSync(file, "utf8")); + const webRecord = records.find((record) => record.command === web); + const containerized = "E2E_SMOKE_TAG='@smoke' E2E_CHANGED_SPECS='' e2e/run-containerized.sh"; + writeFileSync(file, JSON.stringify([...records.filter((record) => record !== webRecord), { ...webRecord, targeted }, + { command: containerized, head, source: webRecord.source, laneKey: webRecord.laneKey, result: "not-run", reason: "no staging e2e identities on this machine", at: webRecord.at }, + { ...webRecord, head: repo.base, command: desktop }, + { ...webRecord, command: "pnpm --filter @repo/e2e test" }])); + + const evidence = recordedE2eEvidence(repo.worktree); + assert.deepEqual(evidence, { + graphSelection: { web: ["e2e/existing.spec.ts"], desktop: ["apps/desktop/test/e2e/home.spec.ts", "e2e/existing.spec.ts"] }, + receipts: [{ surface: "desktop", lane: desktop, result: "pass", full: true, specs: [] }, + { surface: "web", lane: web, result: "pass", full: false, specs: ["e2e/existing.spec.ts", NEW_SPEC] }], + notRun: [{ surface: "web", lane: containerized, reason: "no staging e2e identities on this machine", ruling: null }], + }); + assert.deepEqual(missingE2eSpecs(repo.worktree, { base: repo.base, head, providers: PROVIDERS, ...evidence }), + [{ surface: "web", spec: NARROW_LIST_SPEC, reason: "changed, reached by an added file, or naming a changed story (surfaces-artifacts-sessions-sessions-list)" + + "; recorded not-run here, which satisfies nothing: run it in the containerized web lane, or on the heavy host with pre-pr-lanes.mjs run --fleet-where remote" }]); + + const tampered = JSON.parse(readFileSync(file, "utf8")).map((record) => record.command === desktop && record.head === head ? { ...record, environment: { CHANGED: "1" } } : record); + writeFileSync(file, JSON.stringify(tampered)); + assert.deepEqual(recordedE2eEvidence(repo.worktree).receipts.map((receipt) => receipt.surface), ["web"], "a record that no longer matches its witness is no receipt"); + writeFileSync(file, "{not json"); + assert.throws(() => recordedE2eEvidence(repo.worktree), /JSON/); +}); + +test("pre-pr-lanes warns about the story-driven spec and keeps targeted evidence usable in flight", async (t) => { + bindProviderInProcess((cleanup) => t.after(cleanup)); + const repo = repository(t, "e2e-req-guard-"); + const head = repo.change(brokeMainChange()); + const changed = git(repo.worktree, ["diff", "--name-only", repo.base, head], repo.home).split("\n").sort(); + const repoName = SYMPHONY_REMOTE.replace(/\.git$/, "").split("/").at(-1); + const graphItem = { type: "mcpToolCall", id: "graph-call-1", server: "graph", tool: "code_tests_for_changes", status: "completed", + arguments: { repo: repoName, files: changed }, + result: { structuredContent: { repo: repoName, desktop_e2e: { verdict: "RUN_ALL", start_here: { specs: ["apps/desktop/test/e2e/home.spec.ts"], specs_total: 1 } }, + tier2: { rows: [{ test: "e2e/existing.spec.ts" }], candidates_total: 1 } } } }; + const readTurn = async () => ({ items: [graphItem] }); + const values = { worktree: repo.worktree, base: repo.base, graphSelector: "code_tests_for_changes", "graph-session": "thread-1", "graph-turn": "turn-1", + "graph-query": JSON.stringify(graphItem.arguments) }; + const lane = "pnpm test:e2e"; + const warnings = []; + const ranOnly = (specs) => targetedRecord({ ...values, "targeted-specs": JSON.stringify(specs) }, lane, readTurn, + (line) => warnings.push(line)); + + const legacy = ["e2e/existing.spec.ts", NEW_SPEC]; + const partial = await ranOnly(legacy); + assert.deepEqual(partial.specs, legacy); + assert.ok(warnings.some((line) => line.includes(NARROW_LIST_SPEC)), warnings.join("\n")); + const owed = ["e2e/existing.spec.ts", NARROW_LIST_SPEC, NEW_SPEC]; + const recorded = await ranOnly(owed); + assert.deepEqual(recorded.specs, owed); + + const selected = { laneKey: "scope-1", source: { treeSha256: "tree-1" } }; + assert.deepEqual(await targetedE2eCoverage(values, [lane], [{ command: lane, result: "pass", targeted: partial, ...selected }], selected, readTurn), [{ lane, specs: legacy }], + "the existing lane check accepts its previous proof while PR create requires the additional spec"); + assert.deepEqual(await targetedE2eCoverage(values, [lane], [{ command: lane, result: "pass", targeted: recorded, ...selected }], selected, readTurn), + [{ lane, specs: owed }]); +}); + +test("ids, titles and globs follow Storybook and the paths-filter action", () => { + assert.equal(storybookId("Surfaces/Artifacts/Sessions/Sessions List"), "surfaces-artifacts-sessions-sessions-list"); + assert.equal(storybookId("Start Here/Version History"), "start-here-version-history"); + assert.equal(metaTitle(story("A/B")), "A/B"); + assert.equal(metaTitle("export default {\n title: \"Inline/Meta\",\n};\n"), "Inline/Meta"); + assert.equal(metaTitle("const meta = {\n component: X,\n};\nexport default meta;\n"), null); + assert.equal(metaTitle("const meta = {\n title:\n \"Composites/Long Wrapped Title\",\n component: X,\n} satisfies Meta;\nexport default meta;\n"), + "Composites/Long Wrapped Title", "a title the formatter wrapped onto the next line"); + const suite = globMatcher("e2e/**/*.ts"); + assert.equal(suite.test("e2e/top.spec.ts"), true, "a globstar matches zero directories"); + assert.equal(suite.test("e2e/helpers/deep/x.ts"), true); + assert.equal(suite.test("e2e/compose.yml"), false); + assert.equal(globMatcher(".github/actions/setup/**").test(".github/actions/setup/action.yml"), true, "dotted paths match"); + assert.equal(globMatcher("apps/*").test("apps/web/x.ts"), false); + assert.throws(() => globMatcher("e2e/{a,b}.ts"), /unsupported glob/); +}); diff --git a/plugins/vibe/skills/vibe/scripts/lane-run-witness.mjs b/plugins/vibe/skills/vibe/scripts/lane-run-witness.mjs index 7c5cac1e..ee5d4843 100644 --- a/plugins/vibe/skills/vibe/scripts/lane-run-witness.mjs +++ b/plugins/vibe/skills/vibe/scripts/lane-run-witness.mjs @@ -11,12 +11,12 @@ import { evidenceFingerprint, readEvidence } from "../../../lib/handoff/scripts/ import { replayedJobStatus, WORKFLOW_WITNESS } from "../../../lib/vibe/scripts/workflow-lane-replay.mjs"; import { githubRepository } from "../../../lib/vibe/scripts/github-remote.mjs"; -import { environmentalSkipProblem, readLaneOutcomes } from "./lane-outcomes.mjs"; +import { LANE_LOG_MAX_BYTES } from "./lane-witness-check.mjs"; +export { witnessProblem } from "./lane-witness-check.mjs"; import { RUNNER_HOST } from "../../handoff/scripts/e2e-tier.mjs"; const COMMIT = /^[a-f0-9]{40}$/; const NO_DIFF = createHash("sha256").digest("hex"); -const LANE_LOG_MAX_BYTES = 100 * 1024 * 1024; /** A unique private directory even when multiple lanes start together. */ function witnessDirectory(worktree) { @@ -106,37 +106,6 @@ export async function witnessWorkflowRun({ bin, args }, worktree, source, comman return { status, signal, recorded: { witness: evidenceFingerprint(witnessPath), environment: result.environment } }; } -/** Why a lane record no longer matches its run witness, or null when its head, tree, command and environment do. */ -export function witnessProblem(record) { - if (record?.ranOn?.source === "cloud-worker" && record.result === "pass") return cloudWitnessProblem(record); - if (!record?.witness) { - if (record?.result !== "env-skip" && (record?.recordedBy !== "record" || record.result !== "pass")) return null; - return "it has no run witness"; - } - let witness; - try { - witness = JSON.parse(readEvidence(record.witness.path, record.witness).text); - const log = record.ranOn ? record.runLog : witness.log; - if (!log?.sha256 || log.sha256 !== witness.log?.sha256 || evidenceFingerprint(log.path, LANE_LOG_MAX_BYTES).sha256 !== log.sha256) { - return "its witness log changed or cannot be read"; - } - if (record.result === "env-skip") { - const { sha256, path: file } = record.envSkip.outcomes; - if (sha256 !== witness.outcomes?.sha256 || evidenceFingerprint(file).sha256 !== sha256) return "outcomes differ from its witness"; - const problem = environmentalSkipProblem(record.envSkip.timedOut, readLaneOutcomes(file)); - if (problem) return problem; - } - } catch (error) { - return `its witness or log changed or cannot be read: ${error.message}`; - } - if (witness.head !== (record.ranOn?.proofCommit ?? record.head) || record.head !== record.source?.head) return "head differs from its witness"; - if (witness.source?.treeSha256 !== record.source?.treeSha256 || (record.ranOn && witness.gitTree !== record.ranOn.gitTree)) return "tree differs from its witness"; - if (witness.command !== record.command || (record.ranOn && witness.command !== record.ranOn.command)) return "command differs from its witness"; - if (!isDeepStrictEqual(witness.environment ?? {}, record.environment ?? {})) return "environment differs from its witness"; - if (record.result === "pass" && witness.exitCode !== 0) return `the witnessed run exited ${witness.exitCode}, not a pass`; - return null; -} - /** * The fingerprint of the transported remote log. Witness verification compares it to the runner's original hash. */ @@ -147,24 +116,6 @@ export function remoteRunLog(values) { return evidenceFingerprint(values["run-log"], LANE_LOG_MAX_BYTES); } -/** A cloud workflow recipe carries its environment in the committed recipe, and its log hash in the host result. */ -function cloudWitnessProblem({ cloudEvidence, runLog, ranOn, source, head, command, environment }) { - try { - const result = JSON.parse(readEvidence(cloudEvidence.path, cloudEvidence).text); - if (result.commit !== head || head !== ranOn.proofCommit || head !== source.head) return "head differs from its witness"; - if (result.provenance?.gitTree !== ranOn.gitTree) return "tree differs from its witness"; - if (result.provenance.host !== ranOn.host || result.repository !== ranOn.repository) return "runner differs from its witness"; - const lane = result.lanes.find((item) => item.name === ranOn.lane); - if (lane?.command !== command || command !== ranOn.command) return "command differs from its witness"; - if (environment && Object.keys(environment).length) return "environment differs from its witness"; - if (lane.exitCode !== 0) return `the witnessed run exited ${lane.exitCode}, not a pass`; - const streams = [...Object.values(lane.privateStreams ?? {}), lane.combinedOutput].filter(Boolean); - if (!streams.some((stream) => stream.sha256 === runLog.sha256) || - evidenceFingerprint(runLog.path, LANE_LOG_MAX_BYTES).sha256 !== runLog.sha256) return "its log differs from the witnessed cloud output"; - return null; - } catch (error) { return `its witness or log changed or cannot be read: ${error.message}`; } -} - /** * The remote run a `record --ran-on` names, or null without it. Its proof commit is provenance only: the * binding is the clean local HEAD's Git tree, so the row's source identity is this content's. diff --git a/plugins/vibe/skills/vibe/scripts/lane-witness-check.mjs b/plugins/vibe/skills/vibe/scripts/lane-witness-check.mjs new file mode 100644 index 00000000..39645bd0 --- /dev/null +++ b/plugins/vibe/skills/vibe/scripts/lane-witness-check.mjs @@ -0,0 +1,54 @@ +import { isDeepStrictEqual } from "node:util"; +import { evidenceFingerprint, readEvidence } from "../../../lib/handoff/scripts/handoff-evidence.mjs"; +import { environmentalSkipProblem, readLaneOutcomes } from "./lane-outcomes.mjs"; + +export const LANE_LOG_MAX_BYTES = 100 * 1024 * 1024; + +/** Why a lane record no longer matches its run witness, or null when its head, tree, command and environment do. */ +export function witnessProblem(record) { + if (record?.ranOn?.source === "cloud-worker" && record.result === "pass") return cloudWitnessProblem(record); + if (!record?.witness) { + if (record?.result !== "env-skip" && (record?.recordedBy !== "record" || record.result !== "pass")) return null; + return "it has no run witness"; + } + let witness; + try { + witness = JSON.parse(readEvidence(record.witness.path, record.witness).text); + const log = record.ranOn ? record.runLog : witness.log; + if (!log?.sha256 || log.sha256 !== witness.log?.sha256 || evidenceFingerprint(log.path, LANE_LOG_MAX_BYTES).sha256 !== log.sha256) { + return "its witness log changed or cannot be read"; + } + if (record.result === "env-skip") { + const { sha256, path: file } = record.envSkip.outcomes; + if (sha256 !== witness.outcomes?.sha256 || evidenceFingerprint(file).sha256 !== sha256) return "outcomes differ from its witness"; + const problem = environmentalSkipProblem(record.envSkip.timedOut, readLaneOutcomes(file)); + if (problem) return problem; + } + } catch (error) { + return `its witness or log changed or cannot be read: ${error.message}`; + } + if (witness.head !== (record.ranOn?.proofCommit ?? record.head) || record.head !== record.source?.head) return "head differs from its witness"; + if (witness.source?.treeSha256 !== record.source?.treeSha256 || (record.ranOn && witness.gitTree !== record.ranOn.gitTree)) return "tree differs from its witness"; + if (witness.command !== record.command || (record.ranOn && witness.command !== record.ranOn.command)) return "command differs from its witness"; + if (!isDeepStrictEqual(witness.environment ?? {}, record.environment ?? {})) return "environment differs from its witness"; + if (record.result === "pass" && witness.exitCode !== 0) return `the witnessed run exited ${witness.exitCode}, not a pass`; + return null; +} + +/** A cloud workflow recipe carries its environment in the committed recipe, and its log hash in the host result. */ +function cloudWitnessProblem({ cloudEvidence, runLog, ranOn, source, head, command, environment }) { + try { + const result = JSON.parse(readEvidence(cloudEvidence.path, cloudEvidence).text); + if (result.commit !== head || head !== ranOn.proofCommit || head !== source.head) return "head differs from its witness"; + if (result.provenance?.gitTree !== ranOn.gitTree) return "tree differs from its witness"; + if (result.provenance.host !== ranOn.host || result.repository !== ranOn.repository) return "runner differs from its witness"; + const lane = result.lanes.find((item) => item.name === ranOn.lane); + if (lane?.command !== command || command !== ranOn.command) return "command differs from its witness"; + if (environment && Object.keys(environment).length) return "environment differs from its witness"; + if (lane.exitCode !== 0) return `the witnessed run exited ${lane.exitCode}, not a pass`; + const streams = [...Object.values(lane.privateStreams ?? {}), lane.combinedOutput].filter(Boolean); + if (!streams.some((stream) => stream.sha256 === runLog.sha256) || + evidenceFingerprint(runLog.path, LANE_LOG_MAX_BYTES).sha256 !== runLog.sha256) return "its log differs from the witnessed cloud output"; + return null; + } catch (error) { return `its witness or log changed or cannot be read: ${error.message}`; } +} diff --git a/plugins/vibe/skills/vibe/scripts/pre-pr-lanes.mjs b/plugins/vibe/skills/vibe/scripts/pre-pr-lanes.mjs index be76ca06..4a5286d2 100644 --- a/plugins/vibe/skills/vibe/scripts/pre-pr-lanes.mjs +++ b/plugins/vibe/skills/vibe/scripts/pre-pr-lanes.mjs @@ -63,9 +63,10 @@ // The Desktop Electron e2e lane runs only under the displayless Linux harness // (dbus, keyring and Xvfb); vibe never launches Electron natively, and the // repo's container tier has no display server. On any other machine `check` -// records it `not-run` the same way (`NOT-RUN-LANE`), and the post-merge -// desktop-e2e-validation run, which publishes `desktop-e2e/validated`, covers -// it. A passing run recorded from a remote runner still counts. +// records it `not-run` the same way (`NOT-RUN-LANE`). That record satisfies +// nothing before the pull request: the lane runs in cloud validation or on the +// heavy host (e2e-requirement.mjs). A passing run recorded from a remote runner +// counts. // // A selected lane that fails on the branch source and on captured main is // not the session's to fix (the handoff's rule for failures already on main). @@ -131,6 +132,7 @@ import { CACHED_RESULT, cachedRecord, findReusable, laneKeyFor, Provenance } fro import { storyTypecheckLane } from "./story-typecheck.mjs"; import { launchedReviewerOrVerifier } from "./agent-models.mjs"; import { E2E_SPEC, observedGraphSelection, relativePath } from "./lane-graph.mjs"; +import { E2eSurface, FULL_LANE, isDesktopE2eLane, isWebE2eLane, missingE2eSpecs, RUN_ELSEWHERE } from "./e2e-requirement.mjs"; import { declaredEnvironment, remoteRun, remoteRunLog, witnessProblem, witnessRun, witnessWorkflowRun } from "./lane-run-witness.mjs"; export { witnessProblem }; import { environmentalSkipProblem, interruptedRuns, LANE_RECORDS_FILE, laneRunOutcome, readLaneOutcomes, rerunOf, runningRecord, startLaneInBackground } from "./lane-outcomes.mjs"; @@ -148,8 +150,6 @@ const FLEET_SCRIPT = fileURLToPath(new URL("../../fleet-orchestrator/scripts/fle const LANE_LINE = /^ {4}((?:[A-Za-z_][A-Za-z0-9_]*=(?:'(?:[^']|'\\'')*'|\S+)\s+)*(?:pnpm|npm|npx|yarn|node)\s.*?)(?:\s+\(.*\))?\s*$/; const NOTHING = /nothing to cover|No paths changed/i; -// The repo's web Playwright lanes (`pnpm test:e2e`, `pnpm test:web-smoke`); a lane naming desktop is the Electron one. -const WEB_E2E = /\b(?:test:e2e|test:web-smoke)\b/; const DESKTOP = /\bdesktop\b/i; const TARGETED_POLICY = [ /An e2e lane \(`e2e`, `desktop-e2e`\) is the exception/i, @@ -165,7 +165,7 @@ export const stagingIdentity = (binding = sessionBinding()) => { }; const ENV_LINE = /^\s*(?:export\s+)?([A-Za-z_][A-Za-z0-9_]*)\s*=\s*(.*?)\s*$/; export const NOT_RUN_NO_IDENTITY = "no staging e2e identities on this machine; the containerized or CI run covers it"; -export const NOT_RUN_NO_DESKTOP_HARNESS = "no displayless Linux Electron harness on this machine and vibe never launches Electron natively; the post-merge desktop-e2e-validation run (desktop-e2e/validated) covers it"; +export const NOT_RUN_NO_DESKTOP_HARNESS = `no displayless Linux Electron harness on this machine and vibe never launches Electron natively; recorded not-run here, which satisfies nothing: run it ${RUN_ELSEWHERE[E2eSurface.Desktop]}`; const HARNESS_TOOLS = ["dbus-run-session", "xvfb-run", "gnome-keyring-daemon"]; /** The lane commands a lane report names, or null when it names none and does not say nothing changed. */ @@ -180,15 +180,7 @@ export function reportLanes(report) { return all; } -/** Whether a lane is the repo's local web e2e lane. */ -export function isWebE2eLane(lane) { - return WEB_E2E.test(lane) && !DESKTOP.test(lane); -} - -/** Whether a lane is the repo's Desktop Electron e2e lane. */ -export function isDesktopE2eLane(lane) { - return WEB_E2E.test(lane) && DESKTOP.test(lane); -} +export { isDesktopE2eLane, isWebE2eLane }; /** Whether this machine can run the Desktop lane displayless: Linux with dbus, Xvfb and the keyring daemon. */ export function hasDisplaylessElectronHarness(platform = process.platform, onPath = commandOnPath) { @@ -528,19 +520,64 @@ function assertGraphScope(values, graph, scope) { throw new Error("the observed graph query must cover the exact changed-file scope of this worktree"); } -/** The specs a targeted record of `lane` must list: its graph selection plus each changed spec on its surface. */ -function requiredTargetedSpecs(graph, scope, lane) { +/** The graph-selected and changed specs previously required for a targeted record on this lane. */ +function baselineTargetedSpecs(graph, scope, lane) { const desktop = isDesktopE2eLane(lane); - const selected = graph.result[desktop ? "desktop" : "web"]; + const surface = desktop ? E2eSurface.Desktop : E2eSurface.Web; + const selected = graph.result[surface]; if (!Array.isArray(selected)) { throw new Error(`the graph result has unread pages: read the remaining pages (${selected?.unread ?? "every page"}) in the same turn, then record again`); } - const changed = scope.changedSpecs.filter((file) => DESKTOP.test(file) === desktop); - return [...new Set([...selected, ...changed])].sort(); + return [...new Set([...selected, ...scope.changedSpecs.filter((file) => DESKTOP.test(file) === desktop)])].sort(); } +/** Compare a targeted selection with the minimum the lane used to require and the additional PR requirements. */ +function targetedSpecRequirements(values, graph, scope, lane, specs) { + const baseline = baselineTargetedSpecs(graph, scope, lane); + const surface = isDesktopE2eLane(lane) ? E2eSurface.Desktop : E2eSurface.Web; + let owed; + try { + owed = owedTargetedSpecs(values, scope, surface, graph.result[surface]); + } catch (error) { + return { accepted: sameStringList(specs, baseline), expected: baseline, + warning: `E2E-NOT-RUN ${lane}: could not check the full PR requirements: ${error.message}` }; + } + const full = owed.find((item) => item.spec === FULL_LANE); + const expected = [...new Set([...baseline, ...owed.filter((item) => item.spec !== FULL_LANE).map((item) => item.spec)])].sort(); + const missing = expected.filter((file) => !specs.includes(file)); + return { + accepted: baseline.every((file) => specs.includes(file)) && specs.every((file) => expected.includes(file)), + expected, + warning: full ? fullLaneRequired(lane, full.reason) : missing.length ? `E2E-NOT-RUN ${lane}: PR create still requires ${missing.join(", ")}` : null, + }; +} + +function owedTargetedSpecs(values, scope, surface, selected) { + return missingE2eSpecs(values.worktree, { base: scope.base, head: git(values.worktree, ["rev-parse", "HEAD"]), + binding: sessionBinding(values.worktree), files: scope.changedFiles, graphSelection: { [surface]: selected } }).filter((item) => item.surface === surface); +} -export async function targetedRecord(values, lane, readTurn) { +function fullLaneRequired(lane, reason) { + return `FULL-E2E-REQUIRED ${lane}: ${reason}; run the whole lane and record it without --targeted-specs`; +} + +/** + * The missing E2E lanes that can satisfy PR create with a targeted record, and the warning for every lane owed in full. + */ +export function targetedE2eHints(values, missing) { + const lanes = missing.filter((lane) => isWebE2eLane(lane) || isDesktopE2eLane(lane)); + if (lanes.length === 0) return { targetable: [], full: [] }; + const scope = targetedScope(values); + const verdicts = lanes.map((lane) => { + const surface = isDesktopE2eLane(lane) ? E2eSurface.Desktop : E2eSurface.Web; + return { lane, full: owedTargetedSpecs(values, scope, surface, []).find((item) => item.spec === FULL_LANE) }; + }); + return { targetable: verdicts.filter((item) => !item.full).map((item) => item.lane), + full: verdicts.filter((item) => item.full).map((item) => fullLaneRequired(item.lane, item.full.reason)) }; +} + + +export async function targetedRecord(values, lane, readTurn, warn = (line) => process.stderr.write(`${line}\n`)) { const baseSupplied = [values["targeted-specs"], values["graph-query"]]; const nativeSupplied = [values["graph-session"], values["graph-turn"]]; const launcherSupplied = values["graph-launcher-result"] !== undefined; @@ -559,8 +596,9 @@ export async function targetedRecord(values, lane, readTurn) { if (graph.query !== graphQuery) throw new Error("--graph-query must exactly match the observed graph tool arguments JSON"); const scope = targetedScope(values); assertGraphScope(values, graph, scope); - const required = requiredTargetedSpecs(graph, scope, lane); - if (!sameStringList(specs, required)) throw new Error(`--targeted-specs must exactly match graph-selected plus added or edited E2E specs: ${required.join(", ")}`); + const requirement = targetedSpecRequirements(values, graph, scope, lane, specs); + if (!requirement.accepted) throw new Error(`--targeted-specs must exactly match graph-selected plus added or edited E2E specs, with any additional specs this change requires: ${requirement.expected.join(", ")}`); + if (requirement.warning) warn(requirement.warning); return { specs, graphQuery, graph, changedFiles: scope.changedFiles }; } @@ -590,9 +628,9 @@ export async function targetedE2eCoverage(values, lanes, records, selected, read if (current.toolCallId !== record.targeted.graph?.toolCallId || current.query !== record.targeted.graphQuery || current.runtime !== record.targeted.graph?.runtime || JSON.stringify(current.result) !== JSON.stringify(record.targeted.graph?.result) || (current.runtime === "claude" && JSON.stringify(current.evidence) !== JSON.stringify(record.targeted.graph?.evidence))) continue; - let required; - try { required = requiredTargetedSpecs(current, scope, lane); } catch { continue; } - if (sameStringList(record.targeted.specs, required)) covered.push({ lane, specs: record.targeted.specs }); + let requirement; + try { requirement = targetedSpecRequirements(values, current, scope, lane, record.targeted.specs); } catch { continue; } + if (requirement.accepted) covered.push({ lane, specs: record.targeted.specs }); } return covered; } @@ -863,7 +901,11 @@ async function main(argv) { const roles = reviewRolePlan(reuse.impact, reuse.request.graphImporters ?? null); process.stdout.write(`REVIEW-ROLES ${roles.affected.join(", ") || "none"} (the delta since ${reuse.boundary.slice(0, 12)} affects these; ${roles.reused.length ? `earlier clean reviews still hold for ${roles.reused.join(", ")}` : "no earlier review still holds"})\n`); } - if (missing.length > 0 && allowsTargetedE2e(values.worktree)) process.stdout.write(`TARGETED-E2E: this repository allows a targeted E2E lane in place of the full one; ${TARGETED_RECORD}\n`); + if (missing.length > 0 && allowsTargetedE2e(values.worktree)) { + const hints = targetedE2eHints(values, missing); + for (const line of hints.full) process.stdout.write(`${line}\n`); + if (hints.targetable.length > 0) process.stdout.write(`TARGETED-E2E: this repository allows a targeted E2E lane in place of the full one for ${hints.targetable.join(", ")}; ${TARGETED_RECORD}\n`); + } process.stdout.write(`pre-pr lanes: ${lanes.length} lanes, ${missing.length} missing${notRun.length ? `, ${notRun.length} not run locally` : ""}${values["reuse-cache"] || values["reuse-unaffected"] ? `, ${covered.length + unaffected.length} cached` : ""} for changed-file scope ${selected.laneKey ?? "none"}\n`); return { exitCode: missing.length === 0 ? 0 : 1 }; })(); diff --git a/plugins/vibe/skills/vibe/scripts/test-fixtures.mjs b/plugins/vibe/skills/vibe/scripts/test-fixtures.mjs index 53cd1bef..4b29cd22 100644 --- a/plugins/vibe/skills/vibe/scripts/test-fixtures.mjs +++ b/plugins/vibe/skills/vibe/scripts/test-fixtures.mjs @@ -19,6 +19,7 @@ export function writeActiveTicketSnapshot(program, slugs) { } export const SYMPHONY_REMOTE = "git@github.com:closedloop-ai/symphony-alpha.git"; +export { SYMPHONY_REMOTE as PROVIDER_REPO_REMOTE }; // Fixture mirror of symphony-alpha/vibe-handoff-paths.json; production loads the target repository itself. export const SYMPHONY_PATH_POLICY = readFileSync(new URL("./fixtures/symphony-vibe-handoff-paths.json", import.meta.url), "utf8"); 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 e6f00117..53464014 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.121" + assert claude["version"] == codex["version"] == "1.1.122" assert codex["skills"] == "./skills/" assert skill_split.read(SKILL).startswith("---\nname: pr-takeover\n") diff --git a/plugins/vibe/tools/python/test_vibe_iss_13321_contract.py b/plugins/vibe/tools/python/test_vibe_iss_13321_contract.py index 3642436f..05be57ee 100644 --- a/plugins/vibe/tools/python/test_vibe_iss_13321_contract.py +++ b/plugins/vibe/tools/python/test_vibe_iss_13321_contract.py @@ -20,12 +20,13 @@ AGENTS = PLUGIN_ROOT / "agents" -def test_the_desktop_e2e_lane_is_left_for_the_post_merge_run_and_holds_nothing() -> None: +def test_the_desktop_e2e_lane_holds_no_assignment_and_runs_off_machine_before_a_pull_request() -> None: handoff = flat(skill_split.read(HANDOFF)) assert "comes back under `e2eLeftForCi` instead and does not hold it" in handoff assert "A Desktop lane under `e2eLeftForCi` is not such a gap." in handoff environment = flat(skill_split.read(REFERENCES / "environment.md")) - assert "publishes `desktop-e2e/validated`, and it does not hold `requiredE2eComplete`" in environment + assert "and it does not hold `requiredE2eComplete`" in environment + assert "does not cover it before a pull request" in environment writer = flat(skill_split.read(AGENTS / "vibe-change-worker.md")) assert "it does not hold `requiredE2eComplete`" in writer 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 d774e431..dd87f05a 100644 --- a/plugins/vibe/tools/python/test_vibe_ws8_load_contract.py +++ b/plugins/vibe/tools/python/test_vibe_ws8_load_contract.py @@ -150,9 +150,10 @@ 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.121", manifest - assert "Version `1.1.121`" in skill_split.read(PLUGIN_ROOT / "README.md") + assert json.loads(skill_split.read(PLUGIN_ROOT / manifest / "plugin.json"))["version"] == "1.1.122", manifest + assert "Version `1.1.122`" in skill_split.read(PLUGIN_ROOT / "README.md") changelog = skill_split.read(PLUGIN_ROOT.parents[1] / "CHANGELOG.md") + assert "### vibe v1.1.121" in changelog assert "### vibe v1.1.76" in changelog assert "### vibe v1.1.61" in changelog assert "### vibe v1.1.54" in changelog