A full-featured CRM built with React, shadcn/ui, and Supabase.
refactor: enhance agent identity checks and improve hook validations
Jerome4bcf449e3bb2
diff --git a/.claude/hooks/bash-guard.mjs b/.claude/hooks/bash-guard.mjsindex 9aff0932..beffa99f 100755--- a/.claude/hooks/bash-guard.mjs+++ b/.claude/hooks/bash-guard.mjs@@ -3,6 +3,11 @@import { readFileSync } from "node:fs";import { createHookContext } from "./lib/context.mjs";+import {+ isDeveloper,+ isOrchestrator,+ isQualityReviewer,+} from "./lib/teams.mjs";const input = JSON.parse(readFileSync(0, "utf8"));const ctx = createHookContext(input, "bash-guard");@@ -49,19 +54,23 @@ if (browserViolation) {// `rm breaker/dispatch-*` to force a merge. Reads (ls/cat) stay allowed.// Match the orchestrator the same way block-nested-orchestrator does: agent_type// when present, else the CLAUDE_AGENT_NAME-derived ctx.agentType, allowing a-// suffixed runtime name (orchestrator-…) and the chat- prefix.-const isOrchestrator = /^(chat-)?orchestrator(-|$)/.test(- agent || ctx.agentType || "",-);-if (isOrchestrator) {- const guardPath = /\/(reviews|breaker)\//;+// suffixed runtime name (orchestrator-…) and the chat- prefix. (isOrchestrator+// lives in lib/teams.mjs so both gates share one predicate.)+if (isOrchestrator(agent || ctx.agentType)) {+ // Match `reviews`/`breaker` as a path segment bounded on the left by `/` and+ // on the right by `/`, a quote, whitespace, or end-of-token. The trailing-slash+ // form alone missed the command the codebase actually teaches the reviewer to+ // use — `RD="$(dirname "$TICKET_FILE")/reviews" && touch "$RD/<flag>"` — whose+ // literal text is `…/reviews"` then `$RD/…`, never `/reviews/`. That let a+ // confused orchestrator forge a verdict flag through the documented form.+ const guardPath = /\/(reviews|breaker)(\/|["'\s]|$)/;const mutatingVerb =/(^|[;&|]|\bsudo\b|\bxargs\b)\s*(rm|touch|mkdir|mv|cp|truncate|ln)\b/.test(cmd,) ||/\bsed\s+(-[a-zA-Z]*i\b|--in-place)/.test(cmd) ||/\|\s*tee\b/.test(cmd);- const redirectToGuard = />>?\s*\S*\/(reviews|breaker)\//.test(cmd);+ const redirectToGuard = />>?\s*\S*\/(reviews|breaker)(\/|["'\s]|$)/.test(cmd);if ((mutatingVerb && guardPath.test(cmd)) || redirectToGuard) {ctx.block({reason:@@ -75,8 +84,12 @@ if (isOrchestrator) {// Validation rules — gated subagents only: the validation hooks already run// these; manual runs burn budget and can hang (vitest headed without CI=true).-const GATED_AGENTS = ["developer", "quality-reviewer"];-if (!GATED_AGENTS.includes(agent)) process.exit(0);+// Resolve identity the same robust way as the guard-state rule above: prefer the+// payload agent_type, fall back to the CLAUDE_AGENT_NAME-derived ctx.agentType,+// and match via the suffix-aware predicates — so a `developer-TASK-001` runtime+// name (or an empty agent_type) is still gated, not silently waved through.+const who = agent || ctx.agentType || "";+if (!isDeveloper(who) && !isQualityReviewer(who)) process.exit(0);const runsTypecheck = (c) =>/(make\s+typecheck|npm\s+run\s+typecheck|npx\s+tsc(\s|$)|tsc\s+--noEmit)/.test(diff --git a/.claude/hooks/block-duplicate-dispatch.mjs b/.claude/hooks/block-duplicate-dispatch.mjsindex cd614a8e..38ac7780 100755--- a/.claude/hooks/block-duplicate-dispatch.mjs+++ b/.claude/hooks/block-duplicate-dispatch.mjs@@ -69,8 +69,12 @@ if (d.subagentType === "planner") {if (existsSync(marker)) {try {- if (Date.now() - statSync(marker).mtimeMs > PLANNER_STALE_MS)- unlinkSync(marker);+ // Stale if older than the window — OR if its mtime is in the FUTURE+ // (clock skew / NFS drift): a negative age would otherwise read as "fresh"+ // forever and permanently block re-planning, with no escape (the+ // orchestrator can't rm a breaker marker — bash-guard blocks that).+ const age = Date.now() - statSync(marker).mtimeMs;+ if (age > PLANNER_STALE_MS || age < 0) unlinkSync(marker);} catch {// ignore — fall through to the existence check}@@ -98,12 +102,15 @@ if (d.subagentType === "planner") {// ---- Concern 2: debounce duplicate developer/reviewer/merger dispatches -------if (DEBOUNCE_ROLES.has(d.subagentType)) {- // Key on the ticket identity when present (TASK-001 / SIMPLE / MIGRATION /- // PROMOTE / ROLLBACK); fall back to a prompt hash for dispatches with no- // TASK_ID line (e.g. the SIMPLE inline CHANGE_REQUEST), so two identical- // prompts inside the window still collide while a genuine retry — which- // carries different prompt text (RETRY_FEEDBACK / FIX findings) — does not.- const idPart = d.taskId || `prompt:${sha(prompt)}`;+ // Key on the ticket identity AND the prompt content. The async-ack duplicate+ // re-issues the IDENTICAL dispatch prompt, so an identical (caller, role,+ // ticket, prompt) inside the window collides and is blocked. A genuine retry+ // carries different prompt text (RETRY_FEEDBACK / FIX findings) → different+ // key → allowed even inside the window (keying on the TASK id alone would+ // wrongly debounce a fast-failing ticket's legitimate re-dispatch). The+ // TASK id, when present, is kept as the human-readable label for messages.+ const label = d.taskId || `prompt:${sha(prompt)}`;+ const idPart = `${d.taskId || "_"}::${sha(prompt)}`;const marker = join(markerDir,`dispatch-${sha(`${caller}::${d.subagentType}::${idPart}`)}`,@@ -119,7 +126,7 @@ if (DEBOUNCE_ROLES.has(d.subagentType)) {if (ageMs < DEBOUNCE_WINDOW_MS) {ctx.block({reason:- `A \`${d.subagentType}\` dispatch for ${idPart} was made ${Math.round(ageMs / 1000)}s ago and is still in flight. ` ++ `A \`${d.subagentType}\` dispatch for ${label} was made ${Math.round(ageMs / 1000)}s ago and is still in flight. ` +`A dispatch can return immediately as "Async agent launched … agentId: <id>" WITHOUT blocking — that acknowledgement means "dispatched", not "done". ` +`Do NOT re-dispatch the same role for the same ticket: wait for its task-notification, then read the agent's output file and parse its contract line. ` +`Two ${d.subagentType}s on the same ticket race on one worktree/branch — that is always a bug.`,diff --git a/.claude/hooks/block-nested-orchestrator.mjs b/.claude/hooks/block-nested-orchestrator.mjsindex 34802362..569a23b3 100755--- a/.claude/hooks/block-nested-orchestrator.mjs+++ b/.claude/hooks/block-nested-orchestrator.mjs@@ -19,13 +19,13 @@import { readFileSync } from "node:fs";import { createHookContext } from "./lib/context.mjs";+import { isOrchestrator } from "./lib/teams.mjs";const input = JSON.parse(readFileSync(0, "utf8"));const ctx = createHookContext(input, "block-nested-orchestrator");const target = input.tool_input?.subagent_type || "";const caller = input.agent_type || ctx.agentType || "";-const isOrchestrator = /^(chat-)?orchestrator(-|$)/.test(caller);// Rule 1 — orchestrator allowlist.const ALLOWED = [@@ -35,7 +35,7 @@ const ALLOWED = ["merger","documentator",];-if (isOrchestrator) {+if (isOrchestrator(caller)) {if (!ALLOWED.includes(target)) {ctx.block({reason:diff --git a/.claude/hooks/cleanup-worktree.mjs b/.claude/hooks/cleanup-worktree.mjsindex 4369903f..5851ff46 100755--- a/.claude/hooks/cleanup-worktree.mjs+++ b/.claude/hooks/cleanup-worktree.mjs@@ -13,6 +13,7 @@ import {} from "node:fs";import { join } from "node:path";import { createHookContext } from "./lib/context.mjs";+import { readAgentMeta } from "./lib/agent-meta.mjs";import {getBaseBranch,getWorktreeEntries,@@ -44,19 +45,9 @@ const ctx = createHookContext(raw, "cleanup-worktree");} catch {/* proceed */}- const tp = payload.agent_transcript_path || payload.transcript_path || "";- const metaPath = tp.replace(/\.jsonl$/, ".meta.json");- if (metaPath.endsWith(".meta.json") && existsSync(metaPath)) {- try {- const at = String(- JSON.parse(readFileSync(metaPath, "utf8")).agentType || "",- );- if (at && at !== "merger") {- ctx.accept(`skip — ${at} stop (cleanup runs on merger stops)`);- }- } catch {- // proceed with the normal cleanup- }+ const meta = readAgentMeta(payload);+ if (meta && meta.agentType && meta.agentType !== "merger") {+ ctx.accept(`skip — ${meta.agentType} stop (cleanup runs on merger stops)`);}}diff --git a/.claude/hooks/lib/agent-meta.mjs b/.claude/hooks/lib/agent-meta.mjsnew file mode 100644index 00000000..98e1e95b--- /dev/null+++ b/.claude/hooks/lib/agent-meta.mjs@@ -0,0 +1,35 @@+// Read the sibling <agent>.meta.json for a SubagentStop payload.+//+// At SubagentStop the big transcript JSONL is often not flushed yet (a real+// race), but the <agent>.meta.json written at spawn already carries the+// stopping agent's identity. Three hooks (record-review-verdict, validate-on-stop,+// cleanup-worktree) need it to scope their work to the right agent/worktree, so+// the path derivation + parse lives here once instead of being copy-pasted.+//+// Returns { agentType, description } (both strings, possibly empty), or null+// when the meta is absent/unreadable — callers then fall back to transcript+// recovery.++import { existsSync, readFileSync } from "node:fs";++/**+ * @param {Record<string, unknown>} payload Parsed SubagentStop payload.+ * @returns {{ agentType: string, description: string } | null}+ */+export function readAgentMeta(payload) {+ const tp = String(+ (payload && (payload.agent_transcript_path || payload.transcript_path)) ||+ "",+ );+ const metaPath = tp.replace(/\.jsonl$/, ".meta.json");+ if (!metaPath.endsWith(".meta.json") || !existsSync(metaPath)) return null;+ try {+ const meta = JSON.parse(readFileSync(metaPath, "utf8"));+ return {+ agentType: String(meta.agentType || ""),+ description: String(meta.description || ""),+ };+ } catch {+ return null;+ }+}diff --git a/.claude/hooks/lib/teams.mjs b/.claude/hooks/lib/teams.mjsindex 5694bb92..94056d3f 100644--- a/.claude/hooks/lib/teams.mjs+++ b/.claude/hooks/lib/teams.mjs@@ -7,3 +7,8 @@ export const getFirstTaskId = (text) => (String(text ?? "").match(/TASK-[0-9]+/)// (merger-TASK-003), or an @-qualified address.export const isQualityReviewer = (name) => /^quality-reviewer([-@]|$)/.test(name || "");export const isMerger = (name) => /^merger([-@]|$)/.test(name || "");+export const isDeveloper = (name) => /^developer([-@]|$)/.test(name || "");+// The orchestrator, including the chat- web variant and any runtime suffix+// (orchestrator-…). Single source for every gate that keys on "is this the+// orchestrator" (bash-guard guard-state rule, block-nested-orchestrator).+export const isOrchestrator = (name) => /^(chat-)?orchestrator([-@]|$)/.test(name || "");diff --git a/.claude/hooks/record-review-verdict.mjs b/.claude/hooks/record-review-verdict.mjsindex 6330d232..6fea6757 100755--- a/.claude/hooks/record-review-verdict.mjs+++ b/.claude/hooks/record-review-verdict.mjs@@ -29,6 +29,7 @@ import {} from "node:fs";import { createHookContext } from "./lib/context.mjs";import { getFirstTaskId, isQualityReviewer } from "./lib/teams.mjs";+import { readAgentMeta } from "./lib/agent-meta.mjs";import { reviewFlag, reviewsDir } from "./lib/reviews.mjs";const input = JSON.parse(readFileSync(0, "utf8"));@@ -52,20 +53,12 @@ for (const n of ids) {// description. In this runtime the payload's `agent_type` is empty and// `transcript_path` can point at a not-yet-written file, so prefer the meta.if (!role || !task) {- const tp0 = input.agent_transcript_path || input.transcript_path || "";- const metaPath = tp0.replace(/\.jsonl$/, ".meta.json");- if (metaPath.endsWith(".meta.json") && existsSync(metaPath)) {- try {- const meta = JSON.parse(readFileSync(metaPath, "utf8"));- if (!role && isQualityReviewer(meta.agentType || "")) {- role = "quality-reviewer";- }- if (!task) {- const m = String(meta.description || "").match(/TASK-\d+/);- if (m) task = m[0];- }- } catch {- // best-effort — fall through to the transcript recovery below+ const meta = readAgentMeta(input);+ if (meta) {+ if (!role && isQualityReviewer(meta.agentType)) role = "quality-reviewer";+ if (!task) {+ const m = meta.description.match(/TASK-\d+/);+ if (m) task = m[0];}}}diff --git a/.claude/hooks/test/bash-guard.test.mjs b/.claude/hooks/test/bash-guard.test.mjsindex 040a145a..bd5ddfa2 100644--- a/.claude/hooks/test/bash-guard.test.mjs+++ b/.claude/hooks/test/bash-guard.test.mjs@@ -168,5 +168,26 @@ describe("bash-guard hook", () => {);expect(isBlocked(r)).toBe(true);});++ // Regression: the form the codebase teaches the reviewer uses a shell+ // variable, so the literal command text is `…/reviews"` then `$RD/…` and+ // never contains `/reviews/`. The trailing-slash-only guard missed it,+ // letting a confused orchestrator forge a verdict flag through the+ // documented form.+ test("orchestrator forging the flag via the documented variable form → blocked", () => {+ const r = runHook(+ "orchestrator",+ `RD="$(dirname "$TICKET_FILE")/reviews" && mkdir -p "$RD" && touch "$RD/TASK-002-quality-reviewer"`,+ );+ expect(isBlocked(r)).toBe(true);+ });++ test("orchestrator cd-ing into the reviews dir then touching a flag → blocked", () => {+ const r = runHook(+ "orchestrator",+ `cd ${SD}/reviews && touch TASK-002-quality-reviewer`,+ );+ expect(isBlocked(r)).toBe(true);+ });});});diff --git a/.claude/hooks/test/block-nested-orchestrator.test.mjs b/.claude/hooks/test/block-nested-orchestrator.test.mjsnew file mode 100644index 00000000..ac6faf39--- /dev/null+++ b/.claude/hooks/test/block-nested-orchestrator.test.mjs@@ -0,0 +1,90 @@+// Tests for block-nested-orchestrator.mjs — the PreToolUse(Agent) gate that+// enforces the harness dispatch topology. Two rules:+// 1. the orchestrator may dispatch ONLY the typed harness agents+// (planner, developer, quality-reviewer, merger, documentator).+// 2. a subagent (has agent_id) must NOT dispatch an orchestrator.+// A block is emitted via decisionBlock: exit 0 with {"decision":"block"} on+// stdout. An allowed dispatch exits 0 with no decision JSON.++import { mkdtempSync, rmSync } from "node:fs";+import { tmpdir } from "node:os";+import { dirname, join } from "node:path";+import { fileURLToPath } from "node:url";+import { spawnSync } from "node:child_process";+import { afterAll, describe, test, expect } from "vitest";++const HERE = dirname(fileURLToPath(import.meta.url));+const HOOK = join(HERE, "..", "block-nested-orchestrator.mjs");+const TMP = mkdtempSync(join(tmpdir(), "block-nested-orch-test-"));+const env = { ...process.env, APP_DIR: TMP, CRM_TMP_ROOT: TMP };+delete env.CLAUDE_AGENT_NAME;++afterAll(() => rmSync(TMP, { recursive: true, force: true }));++// callerType = the dispatching agent's agent_type; agentId distinguishes the+// main thread ("") from a subagent (non-empty).+const run = (callerType, target, agentId = "") => {+ const r = spawnSync("node", [HOOK], {+ input: JSON.stringify({+ session_id: "td-nested-1",+ agent_type: callerType,+ agent_id: agentId,+ tool_input: { subagent_type: target },+ }),+ env,+ encoding: "utf8",+ });+ return {+ blocked: /"decision":"block"/.test(r.stdout || ""),+ status: r.status,+ };+};++describe("block-nested-orchestrator — Rule 1 (orchestrator allowlist)", () => {+ for (const t of [+ "planner",+ "developer",+ "quality-reviewer",+ "merger",+ "documentator",+ ]) {+ test(`orchestrator dispatching ${t} → allowed`, () => {+ expect(run("orchestrator", t, "orch-1").blocked).toBe(false);+ });+ }++ test("orchestrator dispatching general-purpose → blocked", () => {+ expect(run("orchestrator", "general-purpose", "orch-1").blocked).toBe(true);+ });++ test("orchestrator dispatching another orchestrator → blocked", () => {+ expect(run("orchestrator", "orchestrator", "orch-1").blocked).toBe(true);+ });++ test("a suffixed orchestrator-name caller is still gated by the allowlist", () => {+ expect(run("orchestrator-abc12", "Explore", "orch-1").blocked).toBe(true);+ expect(run("orchestrator-abc12", "planner", "orch-1").blocked).toBe(false);+ });++ test("chat-orchestrator dispatching planner → allowed", () => {+ expect(run("chat-orchestrator", "planner", "chat-1").blocked).toBe(false);+ });+});++describe("block-nested-orchestrator — Rule 2 (no nested orchestrator)", () => {+ test("a subagent dispatching orchestrator → blocked", () => {+ expect(run("general-purpose", "orchestrator", "gp-1").blocked).toBe(true);+ });++ test("a subagent dispatching chat-orchestrator → blocked", () => {+ expect(run("developer", "chat-orchestrator", "dev-1").blocked).toBe(true);+ });++ test("the main thread (no agent_id) dispatching orchestrator → allowed", () => {+ expect(run("", "orchestrator", "").blocked).toBe(false);+ });++ test("a subagent dispatching a non-orchestrator agent → allowed", () => {+ expect(run("developer", "general-purpose", "dev-1").blocked).toBe(false);+ });+});diff --git a/.claude/hooks/test/session-bootstrap.test.mjs b/.claude/hooks/test/session-bootstrap.test.mjsnew file mode 100644index 00000000..47eabf36--- /dev/null+++ b/.claude/hooks/test/session-bootstrap.test.mjs@@ -0,0 +1,69 @@+// Tests for session-bootstrap.mjs — the SessionStart hook that injects+// <session_dir> via hookSpecificOutput.additionalContext so the harness can run+// on any surface without a launch script. Key invariant: the injected dir is+// ctx.sessionDir = <TMP_ROOT>/<sanitized repo>/<session_id>, so its basename is+// the real session id (what setup-worktree and the orchestrator also key off).++import { mkdtempSync, rmSync } from "node:fs";+import { tmpdir } from "node:os";+import { dirname, join } from "node:path";+import { fileURLToPath } from "node:url";+import { spawnSync } from "node:child_process";+import { afterAll, describe, test, expect } from "vitest";+import { sanitizePath } from "../lib/paths.mjs";++const HERE = dirname(fileURLToPath(import.meta.url));+const HOOK = join(HERE, "..", "session-bootstrap.mjs");+const TMP = mkdtempSync(join(tmpdir(), "session-bootstrap-test-"));+const APP_DIR = join(TMP, "repo");+const CRM_TMP_ROOT = join(TMP, "scratch");+const SESSION_ID = "abcd1234-1111-2222-3333-444455556666";++const baseEnv = { ...process.env, APP_DIR, CRM_TMP_ROOT };+delete baseEnv.CHAT_SESSION_DIR;+delete baseEnv.CLAUDE_CODE_SESSION_ID;++afterAll(() => rmSync(TMP, { recursive: true, force: true }));++const run = (payload, extraEnv = {}) =>+ spawnSync("node", [HOOK], {+ input: payload === undefined ? "" : JSON.stringify(payload),+ env: { ...baseEnv, ...extraEnv },+ encoding: "utf8",+ });++describe("session-bootstrap", () => {+ test("injects <session_dir> built from the real session id", () => {+ const r = run({ session_id: SESSION_ID });+ expect(r.status).toBe(0);+ const expectedDir = join(CRM_TMP_ROOT, sanitizePath(APP_DIR), SESSION_ID);+ expect(r.stdout).toContain(`<session_dir>${expectedDir}</session_dir>`);+ // Alignment invariant: basename(session_dir) === session_id.+ const m = r.stdout.match(/<session_dir>(.+?)<\/session_dir>/);+ expect(m && m[1].split("/").pop()).toBe(SESSION_ID);+ });++ test("emits valid additionalContext JSON for SessionStart", () => {+ const r = run({ session_id: SESSION_ID });+ const parsed = JSON.parse(r.stdout.trim());+ expect(parsed.hookSpecificOutput.hookEventName).toBe("SessionStart");+ expect(parsed.hookSpecificOutput.additionalContext).toContain(+ "<session_dir>",+ );+ });++ test("stays out of the way when a managed launcher owns the session", () => {+ const r = run(+ { session_id: SESSION_ID },+ { CHAT_SESSION_DIR: "/tmp/atomic-crm-harness/managed" },+ );+ expect(r.status).toBe(0);+ expect(r.stdout).not.toContain("<session_dir>");+ });++ test("exits cleanly with no output when there is no payload", () => {+ const r = run(undefined);+ expect(r.status).toBe(0);+ expect(r.stdout).not.toContain("<session_dir>");+ });+});diff --git a/.claude/hooks/validate-on-stop.mjs b/.claude/hooks/validate-on-stop.mjsindex 613521ba..2419f6f7 100755--- a/.claude/hooks/validate-on-stop.mjs+++ b/.claude/hooks/validate-on-stop.mjs@@ -5,6 +5,7 @@ import { existsSync, readFileSync } from "node:fs";import { createHookContext } from "./lib/context.mjs";import { git } from "./lib/git.mjs";import { getFirstTaskId } from "./lib/teams.mjs";+import { readAgentMeta } from "./lib/agent-meta.mjs";import {sessionBranch,simpleWorktreePath,@@ -39,16 +40,10 @@ let isSimple = false;// TASK-002: …"). Use it to scope validation to THIS dev's worktree instead of// re-validating every session worktree (wt=all) on every stop.if (!taskId) {- const tp0 = payload.agent_transcript_path || payload.transcript_path || "";- const metaPath = tp0.replace(/\.jsonl$/, ".meta.json");- if (metaPath.endsWith(".meta.json") && existsSync(metaPath)) {- try {- const meta = JSON.parse(readFileSync(metaPath, "utf8"));- const m = String(meta.description || "").match(/TASK-\d+/);- if (m) taskId = m[0];- } catch {- // best-effort — fall through to transcript recovery below- }+ const meta = readAgentMeta(payload);+ if (meta) {+ const m = meta.description.match(/TASK-\d+/);+ if (m) taskId = m[0];}}diff --git a/.claude/scripts/apply-migrations.mjs b/.claude/scripts/apply-migrations.mjsindex f48e6858..823d7bdc 100755--- a/.claude/scripts/apply-migrations.mjs+++ b/.claude/scripts/apply-migrations.mjs@@ -39,13 +39,18 @@ import { setTimeout as sleep } from "node:timers/promises";// without relying on CLAUDE_PROJECT_DIR being EXPORTED to this node process. The// old "/app" hardcoded fallback was a CRM-Builder-ism: on a bare checkout where the// env var wasn't exported, it chdir'd into a non-writable /app → EACCES on mkdir.-const gitTop = spawnSync("git", ["rev-parse", "--show-toplevel"], {- encoding: "utf8",-});+// git is only spawned as the fallback — when an env var is set (the common harness+// case) we never shell out.+const gitToplevel = () => {+ const r = spawnSync("git", ["rev-parse", "--show-toplevel"], {+ encoding: "utf8",+ });+ return (r.status === 0 && r.stdout.trim()) || "";+};const APP_DIR =process.env.APP_DIR ||process.env.CLAUDE_PROJECT_DIR ||- (gitTop.status === 0 && gitTop.stdout.trim()) ||+ gitToplevel() ||process.cwd();const GREEN = "\x1b[0;32m";diff --git a/scripts/harness-revert.mjs b/scripts/harness-revert.mjsindex 000f9e77..cd4ff05e 100755--- a/scripts/harness-revert.mjs+++ b/scripts/harness-revert.mjs@@ -157,16 +157,25 @@ if (HARD) {} else {requireOnBase();stashDirty();+ // All-or-nothing: capture HEAD before the first revert so that if a later+ // merge conflicts we can roll the already-applied reverts back. Otherwise a+ // partial run leaves some reverts committed while the original merges still+ // match the subject filter, and a naive "resolve and re-run" would re-revert+ // the already-reverted merges (revert-of-revert re-applies the session's+ // changes). Resetting to preRevertHead keeps re-run idempotent.+ const preRevertHead = DRY_RUN ? "" : git(["rev-parse", "HEAD"]).out;for (const sha of merges) {log(`==> Reverting promotion merge ${sha.slice(0, 12)}`);const r = gitRun(["revert", "--no-edit", "-m", "1", sha]);if (r.code !== 0) {- git(["revert", "--abort"]);+ gitRun(["revert", "--abort"]);+ if (!DRY_RUN && preRevertHead)+ gitRun(["reset", "--hard", preRevertHead]);err(`!! Revert hit a conflict on ${sha.slice(0, 12)} (another session may have touched the same files).`,);err(- " Resolve it manually, then re-run. Aborted before cleanup — nothing was removed.",+ " Rolled back to the pre-revert state — nothing was reverted or removed. Resolve the conflict source, then re-run.",);process.exit(1);}@@ -219,12 +228,14 @@ log(`==> Removing config sessionbase.${SHORT}`);gitRun(["config", "--local", "--remove-section", `sessionbase.${SHORT}`]);// 6. Remove this session's /tmp dir(s). Worktree base is /tmp/<slug>/<full-id>;-// the full id starts with the short id, so match on it.+// the full id is <short>-<rest>, so match on the short id at the UUID-segment+// boundary (exact, or followed by "-"). A bare startsWith(SHORT) would also+// swallow another session whose id merely shares the leading hex block.const slug = REPO_ROOT.replace(/\//g, "_");const tmpBase = `/tmp/${slug}`;if (existsSync(tmpBase)) {for (const name of readdirSync(tmpBase)) {- if (!name.startsWith(SHORT)) continue;+ if (name !== SHORT && !name.startsWith(`${SHORT}-`)) continue;const dir = join(tmpBase, name);log(`==> Removing session dir ${dir}`);if (DRY_RUN) log(`[dry-run] rm -rf ${dir}`);