Skip to content

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

feat(harness): resume an interrupted session after an editor restart

Jeromedce86724d19c
diff --git a/.claude/agents/orchestrator.md b/.claude/agents/orchestrator.md
index c2920b0f..cd3a35d6 100644
--- a/.claude/agents/orchestrator.md
+++ b/.claude/agents/orchestrator.md
@@ -113,6 +113,7 @@ The previous process was interrupted (crash or usage limit). **This is a fresh p
1. Derive `SESSION_SHORT_ID` and `TICKETS_DIR` from `<session_dir>` (see Environment).
2. Re-evaluate the real state with read-only Bash inspection:
+ - `git -C $CLAUDE_PROJECT_DIR worktree prune` FIRST — a machine restart can wipe `/tmp` (where worktrees live) while the branches survive in `.git`, leaving stale worktree admin refs that would make `setup-worktree`'s `worktree add` fail. Pruning them is safe and idempotent; the branches (the real work) are untouched.
- `ls ${TICKETS_DIR}/TASK-*.json 2>/dev/null` — were tickets ever created?
- For each ticket, `Read` it and note its `status` (planned / in_progress / merged).
- `git -C $CLAUDE_PROJECT_DIR log --oneline session-base/<SESSION_SHORT_ID>..session/<SESSION_SHORT_ID>` — what's merged on the session branch.
diff --git a/.claude/hooks/cleanup-session.mjs b/.claude/hooks/cleanup-session.mjs
index f08e18fd..1866e890 100755
--- a/.claude/hooks/cleanup-session.mjs
+++ b/.claude/hooks/cleanup-session.mjs
@@ -13,6 +13,11 @@
// exclusion (same reasoning as harness-revert.mjs). It is gitignored, so it does
// not show as untracked either way.
//
+// Resume guard: if the session is still mid-harness at end (plan gate, mid-wave,
+// awaiting promotion, or a pending deploy migration), teardown is SKIPPED so the
+// same session id can resume from disk later (STATE RECOVERY). Only a finished /
+// idle session is torn down. See lib/session-state.mjs.
+//
// Only the CURRENT session's paths are touched, never another session's (a
// second VS Code window is its own session and may be running concurrently).
// No-op under a managed launcher (CHAT_SESSION_DIR owns its own lifecycle).
@@ -24,6 +29,7 @@ import { join } from "node:path";
import { createHookContext } from "./lib/context.mjs";
import { REPO } from "./lib/paths.mjs";
import { removeWorktreesUnder } from "./lib/worktree.mjs";
+import { detectInflight } from "./lib/session-state.mjs";
import { removeWorktreeFolders } from "./lib/workspace-folders.mjs";
if (process.env.CHAT_SESSION_DIR) process.exit(0);
@@ -36,6 +42,25 @@ try {
}
const ctx = createHookContext(raw, "cleanup-session");
+// Resume safety: if THIS session is mid-harness (plan gate, mid-wave, awaiting
+// promotion, or a pending deploy migration), a clean SessionEnd must NOT destroy
+// its state - the same session id resumes later and STATE RECOVERY needs the
+// tickets and partial worktrees on disk. Preserve everything and bail. `null`
+// (undetermined) also preserves: never delete resumable work on a probe error.
+// Keyed on this session's own namespace, so a concurrent session is unaffected.
+try {
+ const { inflight, phase } = detectInflight(ctx);
+ if (inflight !== false) {
+ ctx.error(
+ `preserved for resume (phase=${phase ?? "undetermined"}); state kept for STATE RECOVERY`,
+ );
+ process.exit(0);
+ }
+} catch {
+ // Detection failed entirely: fail safe (preserve), do not risk deleting work.
+ process.exit(0);
+}
+
try {
// All worktrees under this session's base (_session, simple, leftover TASK-XXX)
// + prune, then the base dir itself (worktrees, tickets, logs; scratch once the
diff --git a/.claude/hooks/lib/session-state.mjs b/.claude/hooks/lib/session-state.mjs
new file mode 100644
index 00000000..c27c4d56
--- /dev/null
+++ b/.claude/hooks/lib/session-state.mjs
@@ -0,0 +1,121 @@
+// In-flight detection for a harness session, keyed STRICTLY off the current
+// session's own id (ctx.sessionShort / ctx.sessionDir). Because Claude Code
+// reuses the same session id when a conversation is resumed (verified: a single
+// transcript spans multi-hour close/reopen gaps under one id), the same session
+// recomputes the same namespace on resume — so "is THIS session mid-harness?"
+// is answerable from disk + git alone, with no global state. Two concurrent
+// sessions have distinct ids => distinct namespaces => this never crosses them,
+// which is what makes the resume machinery multi-session safe by construction.
+//
+// Consumers: session-bootstrap (SessionStart banner offering resume) and
+// cleanup-session (SessionEnd guard that preserves an in-flight session's state
+// instead of deleting it). STATE RECOVERY in the orchestrator does the precise
+// re-classification; this only answers "worth resuming, and roughly where".
+
+import { existsSync, readFileSync, readdirSync } from "node:fs";
+import { join } from "node:path";
+import { REPO } from "./paths.mjs";
+import { exec } from "./process.mjs";
+import { getBaseBranch, git } from "./git.mjs";
+import { sessionBranch } from "./topology.mjs";
+
+const TICKET_RE = /^TASK-\d+\.json$/;
+
+// Tickets live in the session dir itself or a `tickets/` subdir - try both, same
+// as render-status.mjs. Unreadable JSON counts as a ticket (status "unreadable"),
+// so a corrupt file never silently downgrades an in-flight session to "done".
+function readTickets(ctx) {
+ for (const dir of [ctx.ticketsDir, ctx.sessionDir]) {
+ if (!existsSync(dir)) continue;
+ let files;
+ try {
+ files = readdirSync(dir).filter((f) => TICKET_RE.test(f));
+ } catch {
+ continue;
+ }
+ if (!files.length) continue;
+ return files.map((f) => {
+ try {
+ return JSON.parse(readFileSync(join(dir, f), "utf8"));
+ } catch {
+ return { status: "unreadable" };
+ }
+ });
+ }
+ return [];
+}
+
+const verifyRef = (ref) =>
+ git(["rev-parse", "--verify", "--quiet", ref]).status === 0;
+
+// The base branch this session forked from: setup-worktree records it in
+// .git/config (sessionbase.<short>.branch); fall back to the repo's base branch.
+function forkBaseBranch(ctx) {
+ const r = git(["config", "--get", `sessionbase.${ctx.sessionShort}.branch`]);
+ return (r.status === 0 && r.stdout.trim()) || getBaseBranch();
+}
+
+// A deploy-time migration still pending after promotion. Best-effort: any
+// non-zero exit (including 3 = undetermined) is read as "nothing pending", so a
+// missing deploy adapter or an odd state never fabricates a migration gate.
+function pendingDeploy(ctx) {
+ const script = join(REPO, ".claude", "scripts", "pending-deploys.mjs");
+ if (!existsSync(script)) return false;
+ // Bounded: a hung probe must never wedge the SessionStart/SessionEnd hooks.
+ // On timeout spawnSync sets an error → non-zero status → read as "nothing
+ // pending" (the pre-promotion preserve conditions already covered the risky
+ // windows; a promoted branch is git-recoverable regardless).
+ const r = exec(
+ "node",
+ [script, "--app", REPO, "--session", ctx.sessionShort],
+ { timeout: 10000 },
+ );
+ return r.status === 0 && Boolean(r.stdout.trim());
+}
+
+/**
+ * @param {object} ctx hook context (createHookContext)
+ * @param {{ checkDeploy?: boolean }} [opts] run the deploy-gate probe (default true)
+ * @returns {{ inflight: boolean|null, phase: string|null }}
+ * inflight true = resume it; false = nothing/finished; null = undetermined
+ * (an error mid-probe) so callers can fail safe. `phase` is a human hint.
+ */
+export function detectInflight(ctx, { checkDeploy = true } = {}) {
+ try {
+ const short = ctx.sessionShort;
+ if (!short || short === "default") return { inflight: false, phase: null };
+
+ const tickets = readTickets(ctx);
+ const hasTickets = tickets.length > 0;
+ const allMerged =
+ hasTickets && tickets.every((t) => t.status === "merged");
+ const sessRef = sessionBranch(ctx); // session/<short>
+ const branchExists = verifyRef(`refs/heads/${sessRef}`);
+
+ // Tickets created but not all merged: plan gate leaves ONLY the tickets on
+ // disk (no session branch yet); once dev started it is a mid-wave stop.
+ if (hasTickets && !allMerged) {
+ return { inflight: true, phase: branchExists ? "mid-wave" : "plan gate" };
+ }
+
+ // No session branch and nothing unmerged: nothing was forked yet.
+ if (!branchExists) return { inflight: false, phase: null };
+
+ // Session branch exists. Promoted into its fork base yet?
+ const base = forkBaseBranch(ctx);
+ const promoted =
+ verifyRef(`refs/heads/${base}`) &&
+ git(["merge-base", "--is-ancestor", sessRef, base]).status === 0;
+ if (!promoted) {
+ return { inflight: true, phase: "waves done, awaiting promotion" };
+ }
+
+ // Promoted: only the deploy-time migration can still be pending.
+ if (checkDeploy && pendingDeploy(ctx)) {
+ return { inflight: true, phase: "migration gate" };
+ }
+ return { inflight: false, phase: null };
+ } catch {
+ return { inflight: null, phase: null };
+ }
+}
diff --git a/.claude/hooks/session-bootstrap.mjs b/.claude/hooks/session-bootstrap.mjs
index c7a4891b..1a5a9024 100755
--- a/.claude/hooks/session-bootstrap.mjs
+++ b/.claude/hooks/session-bootstrap.mjs
@@ -15,6 +15,7 @@
import { readFileSync, mkdirSync } from "node:fs";
import { createHookContext } from "./lib/context.mjs";
+import { detectInflight } from "./lib/session-state.mjs";
// A managed launcher owns the session context — stay out of its way.
if (process.env.CHAT_SESSION_DIR) process.exit(0);
@@ -43,11 +44,34 @@ try {
ctx.log(`SESSION-BOOTSTRAP session_dir=${sessionDir}`);
+// Resume banner: on a RESUMED session (same id → same namespace), the previous
+// orchestrator process is gone and nothing re-launches it, so an interrupted
+// harness would otherwise sit dead. If THIS session has in-flight harness state
+// on disk/git, tell the main thread to re-dispatch a FRESH recovery orchestrator
+// (never SendMessage the dead one). Keyed only on this session id — a fresh or
+// unrelated concurrent session has no state under its id and gets no banner.
+let resume = "";
+try {
+ const { inflight, phase } = detectInflight(ctx);
+ if (inflight === true) {
+ ctx.log(`SESSION-BOOTSTRAP resume-available phase=${phase}`);
+ resume =
+ `\n<harness_resume>` +
+ `An interrupted harness session was detected for THIS session (short id \`${ctx.sessionShort}\`), paused at: ${phase}. ` +
+ `Its orchestrator process ended when the window last closed; nothing is running now. ` +
+ `To resume, dispatch a FRESH orchestrator with <intent>recovery</intent> and this same session_dir. ` +
+ `Do NOT SendMessage a previous orchestrator (it is dead). See CLAUDE.md "Resuming after a restart".` +
+ `</harness_resume>`;
+ }
+} catch {
+ // detection must never break bootstrap
+}
+
process.stdout.write(
JSON.stringify({
hookSpecificOutput: {
hookEventName: "SessionStart",
- additionalContext: `<session_dir>${sessionDir}</session_dir>`,
+ additionalContext: `<session_dir>${sessionDir}</session_dir>${resume}`,
},
}) + "\n",
);
diff --git a/.claude/hooks/test/cleanup-session.test.mjs b/.claude/hooks/test/cleanup-session.test.mjs
index 0010d341..a200851d 100644
--- a/.claude/hooks/test/cleanup-session.test.mjs
+++ b/.claude/hooks/test/cleanup-session.test.mjs
@@ -106,6 +106,32 @@ describe("cleanup-session", () => {
expect(worktreeList()).toContain(app);
});
+ test("preserves state for resume when a ticket is not yet merged (in-flight)", () => {
+ const { base, run } = setup();
+ writeFileSync(
+ join(base, "TASK-001.json"),
+ JSON.stringify({ id: "TASK-001", status: "planned" }),
+ );
+ const r = run();
+ expect(r.status).toBe(0);
+ // Teardown SKIPPED: the same session id must resume from disk later.
+ expect(existsSync(base)).toBe(true);
+ expect(existsSync(join(base, "TASK-001.json"))).toBe(true);
+ });
+
+ test("preserves state when the session branch has unpromoted commits", () => {
+ const { base, run } = setup();
+ const sessWt = join(base, "_session");
+ writeFileSync(join(sessWt, "wave.txt"), "x\n");
+ const gw = (...a) =>
+ spawnSync("git", ["-C", sessWt, ...a], { encoding: "utf8" });
+ gw("add", ".");
+ gw("commit", "-qm", "wave work");
+ const r = run();
+ expect(r.status).toBe(0);
+ expect(existsSync(base)).toBe(true);
+ });
+
test("is a no-op under a managed launcher (CHAT_SESSION_DIR set)", () => {
const { base, promoteLock, run } = setup();
const r = run({ CHAT_SESSION_DIR: "/tmp/managed-session-xyz" });
diff --git a/.claude/hooks/test/session-bootstrap.test.mjs b/.claude/hooks/test/session-bootstrap.test.mjs
index 47eabf36..ece69932 100644
--- a/.claude/hooks/test/session-bootstrap.test.mjs
+++ b/.claude/hooks/test/session-bootstrap.test.mjs
@@ -4,7 +4,7 @@
// 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 { mkdirSync, mkdtempSync, rmSync, writeFileSync } from "node:fs";
import { tmpdir } from "node:os";
import { dirname, join } from "node:path";
import { fileURLToPath } from "node:url";
@@ -66,4 +66,35 @@ describe("session-bootstrap", () => {
expect(r.status).toBe(0);
expect(r.stdout).not.toContain("<session_dir>");
});
+
+ test("emits no resume banner for a fresh session with no harness state", () => {
+ const r = run({ session_id: SESSION_ID });
+ expect(r.stdout).not.toContain("<harness_resume>");
+ });
+
+ test("injects a resume banner when THIS session has in-flight harness state", () => {
+ // An unmerged ticket in the session dir = an interrupted plan-gate session.
+ // Isolated app/scratch so the shared module-level dirs stay banner-free.
+ const app = mkdtempSync(join(tmpdir(), "sb-inflight-app-"));
+ const scratch = mkdtempSync(join(tmpdir(), "sb-inflight-scratch-"));
+ const sid = "beef1234-aaaa-bbbb-cccc-ddddeeeeffff";
+ const sessionDir = join(scratch, sanitizePath(app), sid);
+ mkdirSync(sessionDir, { recursive: true });
+ writeFileSync(
+ join(sessionDir, "TASK-001.json"),
+ JSON.stringify({ id: "TASK-001", status: "planned" }),
+ );
+ const r = spawnSync("node", [HOOK], {
+ input: JSON.stringify({ session_id: sid }),
+ env: { ...baseEnv, APP_DIR: app, CRM_TMP_ROOT: scratch },
+ encoding: "utf8",
+ });
+ rmSync(app, { recursive: true, force: true });
+ rmSync(scratch, { recursive: true, force: true });
+ expect(r.status).toBe(0);
+ expect(r.stdout).toContain("<harness_resume>");
+ expect(r.stdout).toContain("plan gate");
+ // The banner is appended, not a replacement: <session_dir> is still present.
+ expect(r.stdout).toContain("<session_dir>");
+ });
});
diff --git a/CLAUDE.md b/CLAUDE.md
index 0fc8d0ae..b91388d8 100644
--- a/CLAUDE.md
+++ b/CLAUDE.md
@@ -8,6 +8,8 @@ Code-change requests can run through the **agent harness**: subagents (planner,
**"Launched" is NOT "done".** The dispatch is meant to block, but some runtimes (interactive Claude Code / the VS Code extension) return immediately with `Async agent launched … agentId: <id>` and deliver the result later as a `task-notification`. That ack means dispatched, not finished: do NOT fill the silence by implementing the feature yourself or re-dispatching (that duplicates the developer's work). While it runs, only surface progress, then relay the final report. On completion, before relaying, check `<session_dir>/needs-recovery` (written by `completion-invariant` when the orchestrator stopped with APPROVED-but-unmerged work): if present, dispatch a FRESH `orchestrator` with `<intent>recovery</intent>` and the same `<session_dir>` (never `SendMessage` the old one), wait, then relay.
+**Resuming after a restart.** Closing the VS Code window / editor (or rebooting) between two harness steps kills the orchestrator's background process, but Claude Code reuses the SAME session id when you reopen the conversation, so the harness namespace (`<session_dir>`, `session/<short>` branch, worktrees) is unchanged. The gate pauses (plan gate, migration gate) are the exposed windows: the orchestrator has ended its turn and this thread is idle awaiting you, so a `task-notification` for the old (now dead) process will never arrive. Two things make resume work: (1) `cleanup-session` no longer deletes an in-flight session's state on a clean close, and (2) the `session-bootstrap` SessionStart hook detects in-flight state for the current session and injects a `<harness_resume>` banner naming the phase. When you see that banner (or the user asks to continue an interrupted harness), dispatch a FRESH `orchestrator` with `<intent>recovery</intent>` and the same `<session_dir>` (from the banner / the earlier turns), wait, then relay. NEVER `SendMessage` the previous orchestrator (it is dead) and never re-implement the work yourself. This is keyed on the current session id only, so a second concurrent window (its own session id) is never offered another session's work.
+
**PD-ASK round-trip (migration confirmation).** The orchestrator may end its turn asking *"apply the database migration now?"* (it does not under `gate=none`, which auto-applies; see "Gate level"). Relay it to the user; do NOT `SendMessage` the old orchestrator to relay the answer (relayed approvals carry no user authority, so it loops re-asking). On the reply:
- **Approved**: FIRST write `<session_dir>/migration-approval.json` = `{"kind":"migration-approval","session_id":"<id>","question":"<asked>","answer":"<user's verbatim reply>","approved_at":"<ISO-8601>","via":"AskUserQuestion"}` (the durable audit trail). THEN dispatch a FRESH `orchestrator` whose prompt begins `<intent>apply-migration</intent>`, states the approval, references that record, and passes the same `<session_dir>`. The built-in security warning on a relayed approval is expected.
- **Wants changes**: dispatch a fresh `orchestrator` with the new request.