Skip to content

A full-featured CRM built with React, shadcn/ui, and Supabase.

Reject the orchestrator's stop once when the e2e suite failed

Jeromeb9dcdcb87de8
diff --git a/.claude/agents/orchestrator.md b/.claude/agents/orchestrator.md
index b4d75621..a699c709 100644
--- a/.claude/agents/orchestrator.md
+++ b/.claude/agents/orchestrator.md
@@ -501,7 +501,7 @@ After feature-review passes, confirm the integrated feature RUNS before promotio
- **Demo smoke** (when the diff changes UI under `src/components/`): dispatch the quality-reviewer with `MODE: feature-smoke` (foreground, `run_in_background: false`) to drive the feature's key user flows in demo mode via the Playwright MCP and report PASS/FAIL. Runs for any UI change; needs no Supabase.
- **e2e suite**: you do NOT launch it, and `bash-guard` refuses the command if you try. The `e2e-on-feature-review` SubagentStop hook runs it for you, on the integrated `_session` worktree, and ONLY when the feature review above APPROVED (it keys off the reviewer's own `FEATURE-quality-reviewer` verdict flag), so a `BLOCKED` review never pays for the suite. It uses an ISOLATED, slot-leased Supabase instance and tears it down. Read the outcome from `<session_dir>/e2e-result.json` (`status`: `passed` | `skipped` | `failed`, plus the last 40 output lines) after the reviewer returns; the same outcome is appended to `harness-progress.log`. A missing file means the hook did not run the suite (no session worktree, or the review did not approve).
-Reading `e2e-result.json` is MANDATORY before promotion / handoff: it is the only place the suite's verdict exists, and skipping the read is what would make a red suite "silently swallowed".
+Reading `e2e-result.json` is MANDATORY before promotion / handoff: it is the only place the suite's verdict exists, and skipping the read is what would make a red suite "silently swallowed". Enforced, not just asked: if you stop while it says `failed`, the `completion-invariant` hook rejects the stop once so you have to act on it or state it in the report.
On a demo-smoke FAIL or `status: "failed"`, take the SAME action as a `BLOCKED:` feature review, with the findings replaced by the failing spec output: dispatch ONE `developer` with the SIMPLE template (`CHANGE_REQUEST` = the failing output verbatim, `BRANCH_NAME: <SESSION_SHORT_ID>/simple`, `WORKTREE_PATH: <WORKTREE_BASE>/simple`, `run_in_background: false`), merge it into `session/<SESSION_SHORT_ID>` with a SIMPLE-mode merger carrying `STAGE: a-only`, then re-run feature-review. Re-running it is what re-runs the suite: the reviewer rewrites its `FEATURE-quality-reviewer` flag, which re-triggers the hook on the fixed code. **The 2-round bound is shared with the feature-review rounds above** (2 fix rounds for the whole end-of-feature loop, review and e2e combined): past that, report the remaining failure in the handoff and proceed, never wedge the pipeline. A skip is fine (deferred to a human `make test-e2e-ci`, the headless target; `make test-e2e` opens the Playwright UI and needs a display). `#technical-harness` runs feature-smoke before its stop and reports the result; it does not promote.
diff --git a/.claude/hooks/completion-invariant.mjs b/.claude/hooks/completion-invariant.mjs
index f0ae6e5c..fc13d402 100755
--- a/.claude/hooks/completion-invariant.mjs
+++ b/.claude/hooks/completion-invariant.mjs
@@ -7,6 +7,11 @@
// `needs-recovery` marker so the LAUNCHING SURFACE (main thread / chat-service, which IS
// re-invokable) re-runs <intent>recovery</intent>. Fail-open: any doubt or error accepts
// the stop, so this never wedges a legitimate completion.
+//
+// Second invariant, same spirit: stopping while <session_dir>/e2e-result.json says the
+// end-of-feature suite FAILED. Reading that file is only a prompt-level instruction, so
+// this is the deterministic backstop that a red suite cannot be swallowed in silence.
+// One reject (own budget, no recovery marker), then the stop is allowed.
import {
existsSync,
@@ -22,6 +27,11 @@ import { getUnmergedTaskBranches, git } from "./lib/git.mjs";
import { sessionBranch, simpleBranch } from "./lib/topology.mjs";
const REJECT_LIMIT = 2; // reject at most twice, then allow + mark for recovery
+// A red e2e is not an orphaned pipeline, so it gets its own single-shot budget and no
+// recovery marker: reject once to force the orchestrator to actually react to the result
+// it was supposed to read, then let the stop through. Its own 2-round fix bound takes it
+// from there, and "never wedge the pipeline" still holds.
+const E2E_REJECT_LIMIT = 1;
let ctx;
try {
@@ -67,6 +77,7 @@ try {
if (orphaned.length === 0) {
clearRejects();
+ rejectOnceOnRedE2e();
ctx.accept("no approved-but-unmerged work");
}
@@ -95,6 +106,43 @@ try {
process.exit(0);
}
+// --- red e2e ------------------------------------------------------------------
+// The e2e verdict only exists in <session_dir>/e2e-result.json, written by
+// e2e-on-feature-review.mjs. Reading it is a prompt-level instruction, so an
+// orchestrator that never reads it would swallow a red suite in silence. Returns
+// normally (caller accepts) unless it decided to reject this stop.
+function rejectOnceOnRedE2e() {
+ let result;
+ try {
+ const p = join(
+ process.env.CHAT_SESSION_DIR || ctx.sessionDir,
+ "e2e-result.json",
+ );
+ if (!existsSync(p)) return; // not run this round -> nothing to react to
+ result = JSON.parse(readFileSync(p, "utf8"));
+ } catch {
+ return; // unreadable / malformed -> fail-open, same as the rest of this hook
+ }
+ if (result?.status !== "failed") return;
+
+ const rejects = readE2eRejects();
+ if (rejects >= E2E_REJECT_LIMIT) {
+ clearE2eRejects();
+ ctx.log(`red e2e persists after ${rejects} reject(s), allowing the stop`);
+ return;
+ }
+ writeE2eRejects(rejects + 1);
+ ctx.fail(
+ `Completion invariant: the end-of-feature e2e suite FAILED and you are stopping without ` +
+ `acting on it. Read <session_dir>/e2e-result.json, then either fix it (ONE developer on ` +
+ `<SESSION_SHORT_ID>/simple with the failing output as CHANGE_REQUEST, a STAGE: a-only ` +
+ `merger, then re-run feature-review, which re-runs the suite) or, if you have already used ` +
+ `the 2 fix rounds, state the failure explicitly in your final report. Do not end your turn ` +
+ `leaving it unmentioned. (attempt ${rejects + 1}/${E2E_REJECT_LIMIT})`,
+ { log: `reject ${rejects + 1}/${E2E_REJECT_LIMIT} red-e2e` },
+ );
+}
+
// --- markers -----------------------------------------------------------------
function breakerFile() {
const dir = join(ctx.sessionDir, "breaker");
@@ -126,6 +174,38 @@ function clearRejects() {
/* absent - fine */
}
}
+// Separate budget from the orphan one: a red e2e must not spend the merge-stall
+// attempts, and a merge stall must not spend the e2e attempt.
+function e2eBreakerFile() {
+ const dir = join(ctx.sessionDir, "breaker");
+ try {
+ mkdirSync(dir, { recursive: true });
+ } catch {
+ /* best effort */
+ }
+ return join(dir, "completion-invariant-e2e-rejects");
+}
+function readE2eRejects() {
+ try {
+ return parseInt(readFileSync(e2eBreakerFile(), "utf8"), 10) || 0;
+ } catch {
+ return 0;
+ }
+}
+function writeE2eRejects(n) {
+ try {
+ writeFileSync(e2eBreakerFile(), String(n));
+ } catch {
+ /* best effort */
+ }
+}
+function clearE2eRejects() {
+ try {
+ unlinkSync(e2eBreakerFile());
+ } catch {
+ /* absent - fine */
+ }
+}
function writeRecoveryMarker(branches) {
try {
writeFileSync(
diff --git a/.claude/hooks/test/completion-invariant.test.mjs b/.claude/hooks/test/completion-invariant.test.mjs
new file mode 100644
index 00000000..4b8c83d0
--- /dev/null
+++ b/.claude/hooks/test/completion-invariant.test.mjs
@@ -0,0 +1,120 @@
+import { spawnSync } from "node:child_process";
+import { mkdirSync, mkdtempSync, rmSync, writeFileSync } from "node:fs";
+import { tmpdir } from "node:os";
+import { dirname, join } from "node:path";
+import { fileURLToPath } from "node:url";
+import { afterEach, beforeEach, describe, expect, test } from "vitest";
+import { sanitizePath } from "../lib/paths.mjs";
+
+const HERE = dirname(fileURLToPath(import.meta.url));
+const HOOK = join(HERE, "..", "completion-invariant.mjs");
+const SESSION_ID = "ci9f0a1b-1111-2222-3333-444455556666";
+const SHORT = "ci9f0a1b";
+
+let TMP, APP_DIR, sessionDir, env;
+
+const g = (...args) =>
+ spawnSync("git", ["-C", APP_DIR, ...args], { encoding: "utf8" });
+
+const writeE2eResult = (status) =>
+ writeFileSync(
+ join(sessionDir, "e2e-result.json"),
+ JSON.stringify({ kind: "e2e-result", status, output: "1 failed" }),
+ );
+
+const transcriptWithMeta = (agentType) => {
+ const tp = join(TMP, `agent-${Math.random().toString(36).slice(2)}.jsonl`);
+ writeFileSync(tp, "");
+ writeFileSync(
+ tp.replace(/\.jsonl$/, ".meta.json"),
+ JSON.stringify({ agentType, description: "orchestrate the feature" }),
+ );
+ return tp;
+};
+
+const run = (transcriptPath) =>
+ spawnSync("node", [HOOK], {
+ input: JSON.stringify({
+ session_id: SESSION_ID,
+ hook_event_name: "SubagentStop",
+ transcript_path: transcriptPath,
+ }),
+ env,
+ encoding: "utf8",
+ });
+
+beforeEach(() => {
+ TMP = mkdtempSync(join(tmpdir(), "completion-invariant-"));
+ APP_DIR = join(TMP, "app");
+ const TMP_ROOT = join(TMP, "scratch");
+ sessionDir = join(TMP_ROOT, sanitizePath(APP_DIR), SESSION_ID);
+ mkdirSync(sessionDir, { recursive: true });
+ mkdirSync(APP_DIR, { recursive: true });
+
+ g("init", "-q", "-b", "main");
+ g("config", "user.email", "[email protected]");
+ g("config", "user.name", "t");
+ writeFileSync(join(APP_DIR, "f.txt"), "seed");
+ g("add", "-A");
+ g("commit", "-q", "-m", "seed");
+ g("branch", `session/${SHORT}`);
+
+ env = { ...process.env, APP_DIR, HARNESS_TMP_ROOT: TMP_ROOT };
+ delete env.CHAT_SESSION_DIR;
+ delete env.CLAUDE_AGENT_NAME;
+});
+
+afterEach(() => rmSync(TMP, { recursive: true, force: true }));
+
+describe("completion-invariant — red e2e", () => {
+ test("rejects the orchestrator's stop once when the e2e suite failed", () => {
+ writeE2eResult("failed");
+ const r = run(transcriptWithMeta("orchestrator"));
+ expect(r.status).toBe(2);
+ expect(r.stderr).toContain("e2e suite FAILED");
+ });
+
+ test("allows the stop on the next attempt, never wedging the pipeline", () => {
+ writeE2eResult("failed");
+ const tp = transcriptWithMeta("orchestrator");
+ expect(run(tp).status).toBe(2);
+ expect(run(tp).status).toBe(0);
+ });
+
+ test("accepts a passing suite", () => {
+ writeE2eResult("passed");
+ expect(run(transcriptWithMeta("orchestrator")).status).toBe(0);
+ });
+
+ test("accepts a gracefully skipped suite", () => {
+ writeE2eResult("skipped");
+ expect(run(transcriptWithMeta("orchestrator")).status).toBe(0);
+ });
+
+ test("accepts when no suite ran this round", () => {
+ expect(run(transcriptWithMeta("orchestrator")).status).toBe(0);
+ });
+
+ test("ignores a red suite on a non-orchestrator stop", () => {
+ writeE2eResult("failed");
+ expect(run(transcriptWithMeta("developer")).status).toBe(0);
+ });
+
+ test("keeps the e2e budget separate from the orphan-branch budget", () => {
+ writeE2eResult("failed");
+ const tp = transcriptWithMeta("orchestrator");
+ run(tp);
+ const orphanBudget = join(
+ sessionDir,
+ "breaker",
+ "completion-invariant-rejects",
+ );
+ const e2eBudget = join(
+ sessionDir,
+ "breaker",
+ "completion-invariant-e2e-rejects",
+ );
+ expect(spawnSync("test", ["-f", e2eBudget]).status).toBe(0);
+ expect(spawnSync("test", ["-f", orphanBudget]).status).not.toBe(0);
+ });
+});
diff --git a/.claude/rules/validation-commands.md b/.claude/rules/validation-commands.md
index a8aac08e..3c7eb7e7 100644
--- a/.claude/rules/validation-commands.md
+++ b/.claude/rules/validation-commands.md
@@ -24,7 +24,13 @@ guard, so they can never drift:
isolated slot-leased Supabase. The outcome lands in
`<session_dir>/e2e-result.json` for the orchestrator to read. **No agent launches
the suite, the orchestrator included**, and `bash-guard` enforces that for every
- caller.
+ caller. A stale result from an earlier round is dropped as soon as a feature review
+ stops, so a missing file means "not run this round", never "passed earlier".
+- `completion-invariant.mjs` (SubagentStop, `orchestrator`) is the backstop on the
+ other end: reading that result is a prompt-level instruction, so stopping while it
+ says `failed` gets the stop rejected once. Then it is allowed through, on its own
+ budget and with no recovery marker, because a red suite is not an orphaned pipeline
+ and "never wedge the pipeline" still holds.
- `bash-guard.mjs` (PreToolUse Bash) blocks `developer` / `quality-reviewer` from
running those same commands manually, plus `validation.extraForbidden` (build,
e2e). The forbidden set is DERIVED from `validation.steps`, not hardcoded here.