A full-featured CRM built with React, shadcn/ui, and Supabase.
feat(harness): session visibility + end-of-session cleanup
Jerome568037a4d327
diff --git a/.claude/commands/harness-revert.md b/.claude/commands/harness-revert.mdindex 968b8581..6d985dde 100644--- a/.claude/commands/harness-revert.md+++ b/.claude/commands/harness-revert.md@@ -19,7 +19,7 @@ Revert everything a harness session merged into your branch, then remove its tem3. **On confirmation, run the script** from the repo root (append `--hard` for the clean-history strategy):```- node "$(git rev-parse --show-toplevel)/scripts/harness-revert.mjs" <short> [--hard]+ node "$(git rev-parse --show-toplevel)/.claude/scripts/harness-revert.mjs" <short> [--hard]```(Run it once with `--dry-run` appended first if you want to preview the exact git actions.) Relay the script's output. Default mode reverts this session's promotion merge commit(s) (safe even if other sessions landed on the same branch); `--hard` resets the base branch to the fork point (refuses if history diverged). Either way it then removes the session's worktrees, branches, `sessionbase.<short>` config, and `/tmp` dir.diff --git a/.claude/hooks/cleanup-session.mjs b/.claude/hooks/cleanup-session.mjsnew file mode 100755index 00000000..9b7f2aed--- /dev/null+++ b/.claude/hooks/cleanup-session.mjs@@ -0,0 +1,50 @@+#!/usr/bin/env node+// SessionEnd: tear down THIS session's harness scratch state when the Claude+// session ends: remove every git worktree under <WORKTREE_BASE> (_session,+// simple, any leftover TASK-XXX), prune the admin refs, drop the base dir, and+// remove the Playwright test-results left in the repo.+//+// Branches are left intact: they are cheap, do not clutter the editor's Source+// Control view (only worktrees do), and deleting them could drop work stopped at+// the session branch and not yet promoted.+//+// `.promote.lock` is deliberately NOT removed: it is the shared promotion mutex+// (flock), and unlinking it mid-run would break a concurrent session's mutual+// exclusion (same reasoning as harness-revert.mjs). It is gitignored, so it does+// not show as untracked either way.+//+// 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).+// Never throws. No file logging: this hook's log file lives inside the base dir+// it deletes, so writing after removal would recreate the dir we tear down.++import { readFileSync, rmSync } from "node:fs";+import { join } from "node:path";+import { createHookContext } from "./lib/context.mjs";+import { REPO } from "./lib/paths.mjs";+import { removeWorktreesUnder } from "./lib/worktree.mjs";++if (process.env.CHAT_SESSION_DIR) process.exit(0);++let raw = "";+try {+ raw = readFileSync(0, "utf8");+} catch {+ process.exit(0);+}+const ctx = createHookContext(raw, "cleanup-session");++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+ // session ends). Base removal is last: nothing may log after it (this hook's log+ // file lives inside it and logging would recreate it).+ removeWorktreesUnder(ctx.worktreeBase);+ rmSync(join(REPO, "test-results"), { recursive: true, force: true });+ rmSync(ctx.worktreeBase, { recursive: true, force: true });+} catch (e) {+ ctx.error(`skipped: ${e?.message ?? e}`);+}++process.exit(0);diff --git a/.claude/hooks/cleanup-worktree.mjs b/.claude/hooks/cleanup-worktree.mjsindex 5851ff46..15762227 100755--- a/.claude/hooks/cleanup-worktree.mjs+++ b/.claude/hooks/cleanup-worktree.mjs@@ -28,6 +28,7 @@ import {sessionBaseBranch,sessionBranch,} from "./lib/topology.mjs";+import { removeWorktree } from "./lib/worktree.mjs";const raw = readFileSync(0, "utf8");const ctx = createHookContext(raw, "cleanup-worktree");@@ -108,15 +109,6 @@ const shouldRemove = ({ path: wtPath, branch }) => {return true;};-const removeWorktree = (wtPath) => {- if (git(["worktree", "remove", "--force", wtPath]).status === 0) {- ctx.log(`REMOVED ${wtPath}`);- return;- }- rmSync(wtPath, { recursive: true, force: true });- ctx.log(`RM-RF ${wtPath}`);-};-const deleteBranch = (branch) => {if (!branch) return;if (isProtectedBranch(branch)) {@@ -132,7 +124,10 @@ const deleteBranch = (branch) => {const ourWorktrees = getWorktreeEntries().filter((e) => isUnderBase(e.path));const toRemove = ourWorktrees.filter(shouldRemove);-toRemove.forEach((e) => removeWorktree(e.path));+toRemove.forEach((e) => {+ removeWorktree(e.path);+ ctx.log(`REMOVED ${e.path}`);+});toRemove.map((e) => e.branch).forEach(deleteBranch);git(["worktree", "prune"]);diff --git a/.claude/hooks/lib/worktree.mjs b/.claude/hooks/lib/worktree.mjsnew file mode 100644index 00000000..37e1305e--- /dev/null+++ b/.claude/hooks/lib/worktree.mjs@@ -0,0 +1,28 @@+// Worktree teardown primitives shared by the cleanup hooks (cleanup-worktree,+// cleanup-session). Mutations live here, kept separate from git.mjs's read-only+// queries. The harness-revert script reuses getWorktreeEntries (read) directly+// but keeps its own mutations because it honours --dry-run.++import { rmSync } from "node:fs";+import { getWorktreeEntries, git } from "./git.mjs";++// Remove one worktree: `git worktree remove --force`, falling back to a plain+// recursive rm when git refuses (e.g. the admin entry is already gone). Callers+// prune afterwards (removeWorktreesUnder does; a lone caller should too).+export function removeWorktree(path) {+ if (git(["worktree", "remove", "--force", path]).status !== 0) {+ rmSync(path, { recursive: true, force: true });+ }+}++// Remove every registered worktree at or under `base`, then prune the admin+// refs. Returns the count removed. The main repo worktree is never under a+// session base, so it is excluded naturally.+export function removeWorktreesUnder(base) {+ const under = getWorktreeEntries().filter(+ (e) => e.path === base || e.path.startsWith(base + "/"),+ );+ under.forEach((e) => removeWorktree(e.path));+ git(["worktree", "prune"]);+ return under.length;+}diff --git a/.claude/hooks/link-session-workspace.mjs b/.claude/hooks/link-session-workspace.mjsnew file mode 100755index 00000000..cb60673c--- /dev/null+++ b/.claude/hooks/link-session-workspace.mjs@@ -0,0 +1,92 @@+#!/usr/bin/env node+// SessionStart: maintain a stable ".harness-session" symlink in the VS Code+// multi-root workspace, pointing at the CURRENT session dir. The harness+// tickets live in that dir (TICKETS_DIR), so this keeps them visible in the+// editor for plan-gate validation. The session dir path carries the+// per-session id, so a static workspace folder entry would go stale every+// session; the .code-workspace references the stable symlink name instead and+// this hook repoints the symlink at each session start.+//+// No-op when a managed launcher owns the session (CHAT_SESSION_DIR set, it has+// its own UI) or when the repo's parent is not a VS Code multi-root workspace+// (no *.code-workspace file beside it). Never throws: a convenience feature+// must not break a session.++import {+ existsSync,+ lstatSync,+ mkdirSync,+ readdirSync,+ readFileSync,+ readlinkSync,+ rmSync,+ symlinkSync,+} from "node:fs";+import { dirname, join } from "node:path";+import { createHookContext } from "./lib/context.mjs";++const LINK_NAME = ".harness-session";++// A managed launcher (chat-service) owns the session and its own UI; there is+// no VS Code workspace to manage.+if (process.env.CHAT_SESSION_DIR) process.exit(0);++let input = {};+try {+ input = JSON.parse(readFileSync(0, "utf8"));+} catch {+ // no payload, nothing to do+ process.exit(0);+}++const ctx = createHookContext(input, "link-session-workspace");++const isSymlink = (p) => {+ try {+ return lstatSync(p).isSymbolicLink();+ } catch {+ return false;+ }+};++try {+ // The .code-workspace file sits beside the repo (its parent dir is the+ // multi-root workspace root). Only act when that layout is present.+ const workspaceRoot = dirname(ctx.repo);+ const inWorkspace =+ existsSync(workspaceRoot) &&+ readdirSync(workspaceRoot).some((f) => f.endsWith(".code-workspace"));+ if (!inWorkspace) {+ ctx.log(`no .code-workspace beside ${ctx.repo}, skip`);+ process.exit(0);+ }++ // Never leave a dangling link: ensure the target exists first.+ mkdirSync(ctx.sessionDir, { recursive: true });++ const linkPath = join(workspaceRoot, LINK_NAME);+ if (existsSync(linkPath) || isSymlink(linkPath)) {+ if (!isSymlink(linkPath)) {+ // A real file/dir is sitting there, do not clobber it.+ ctx.log(`${linkPath} exists and is not a symlink, skip`);+ process.exit(0);+ }+ let current = "";+ try {+ current = readlinkSync(linkPath);+ } catch {+ // unreadable link, replace it+ }+ if (current === ctx.sessionDir) {+ ctx.log(`already linked to ${ctx.sessionDir}`);+ process.exit(0);+ }+ rmSync(linkPath, { force: true });+ }+ symlinkSync(ctx.sessionDir, linkPath);+ ctx.log(`linked ${LINK_NAME} -> ${ctx.sessionDir}`);+} catch (e) {+ ctx.log(`skipped: ${e?.message ?? e}`);+}++process.exit(0);diff --git a/.claude/hooks/test/cleanup-session.test.mjs b/.claude/hooks/test/cleanup-session.test.mjsnew file mode 100644index 00000000..3bdeae42--- /dev/null+++ b/.claude/hooks/test/cleanup-session.test.mjs@@ -0,0 +1,103 @@+// Tests for cleanup-session.mjs: the SessionEnd hook that tears down this+// session's worktrees (_session, simple, TASK-XXX) under <WORKTREE_BASE> and+// removes the promotion lock + Playwright test-results. Builds a throwaway repo+// with real worktrees ("claude" Node project, real git/worktree work).++import { spawnSync } from "node:child_process";+import {+ existsSync,+ 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, describe, expect, test } from "vitest";++const HERE = dirname(fileURLToPath(import.meta.url));+const HOOK = join(HERE, "..", "cleanup-session.mjs");+const SESSION_ID = "cafe1234-1111-2222-3333-444455556666";+const SHORT = SESSION_ID.split("-")[0];+const sanitize = (p) => p.replace(/\//g, "_");++let TMP = null;+afterEach(() => {+ if (TMP) rmSync(TMP, { recursive: true, force: true });+ TMP = null;+});++// A throwaway repo with a session branch + a _session and a simple worktree, plus+// the leftover files. Returns paths and a run() that fires the SessionEnd hook.+const setup = () => {+ TMP = mkdtempSync(join(tmpdir(), "cleanup-session-test-"));+ const app = join(TMP, "app");+ const tmpRoot = join(TMP, "wtroot");+ mkdirSync(app, { recursive: true });+ const base = join(tmpRoot, sanitize(app), SESSION_ID);+ mkdirSync(base, { recursive: true });++ const g = (...a) => spawnSync("git", ["-C", app, ...a], { encoding: "utf8" });+ g("init", "-q", "-b", "main");+ g("config", "user.email", "[email protected]");+ g("config", "user.name", "t");+ writeFileSync(join(app, "seed.txt"), "seed\n");+ g("add", ".");+ g("commit", "-qm", "seed");+ g("branch", `session/${SHORT}`, "main");+ g("branch", `${SHORT}/simple`, "main");+ g("worktree", "add", "-q", join(base, "_session"), `session/${SHORT}`);+ g("worktree", "add", "-q", join(base, "simple"), `${SHORT}/simple`);++ const promoteLock = join(app, ".promote.lock");+ const testResults = join(app, "test-results");+ writeFileSync(promoteLock, "");+ mkdirSync(testResults, { recursive: true });+ writeFileSync(join(testResults, ".last-run.json"), "{}");++ const env = { ...process.env, APP_DIR: app, HARNESS_TMP_ROOT: tmpRoot };+ delete env.CHAT_SESSION_DIR;+ const run = (extraEnv = {}) =>+ spawnSync("node", [HOOK], {+ input: JSON.stringify({ session_id: SESSION_ID }),+ env: { ...env, ...extraEnv },+ encoding: "utf8",+ });+ const worktreeList = () => g("worktree", "list", "--porcelain").stdout;+ return { app, base, promoteLock, testResults, run, worktreeList };+};++describe("cleanup-session", () => {+ test("removes the session worktrees, base dir and test-results", () => {+ const { base, testResults, run, worktreeList } = setup();+ const r = run();+ expect(r.status).toBe(0);+ expect(existsSync(base)).toBe(false);+ expect(existsSync(testResults)).toBe(false);+ // Only the main worktree remains registered.+ expect(worktreeList()).not.toContain("_session");+ expect(worktreeList()).not.toContain("/simple");+ });++ test("leaves the shared .promote.lock in place (concurrent-promotion mutex)", () => {+ const { promoteLock, run } = setup();+ run();+ expect(existsSync(promoteLock)).toBe(true);+ });++ test("leaves the main repo worktree intact", () => {+ const { app, run, worktreeList } = setup();+ run();+ expect(existsSync(join(app, "seed.txt"))).toBe(true);+ expect(worktreeList()).toContain(app);+ });++ 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" });+ expect(r.status).toBe(0);+ expect(existsSync(base)).toBe(true);+ expect(existsSync(promoteLock)).toBe(true);+ });+});diff --git a/.claude/hooks/test/link-session-workspace.test.mjs b/.claude/hooks/test/link-session-workspace.test.mjsnew file mode 100644index 00000000..c22d0d6f--- /dev/null+++ b/.claude/hooks/test/link-session-workspace.test.mjs@@ -0,0 +1,101 @@+// Tests for link-session-workspace.mjs: the SessionStart hook that keeps a+// stable ".harness-session" symlink in the VS Code multi-root workspace+// pointing at the current session dir (where the harness tickets live).++import {+ mkdtempSync,+ mkdirSync,+ writeFileSync,+ lstatSync,+ readlinkSync,+ existsSync,+ 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 { afterEach, describe, test, expect } from "vitest";++const HERE = dirname(fileURLToPath(import.meta.url));+const HOOK = join(HERE, "..", "link-session-workspace.mjs");+const LINK_NAME = ".harness-session";+// Mirror lib/paths.mjs sanitizePath: every "/" becomes "_".+const sanitize = (p) => p.replace(/\//g, "_");++let TMP = null;+afterEach(() => {+ if (TMP) rmSync(TMP, { recursive: true, force: true });+ TMP = null;+});++// Build an isolated layout: <root>/ws/repo is the repo, <root>/ws holds the+// .code-workspace file (the workspace root), and <root>/sessions is the session+// dir root. run() spawns the hook with APP_DIR/HARNESS_TMP_ROOT pointing there.+const setup = ({ withWorkspaceFile = true } = {}) => {+ TMP = mkdtempSync(join(tmpdir(), "link-session-ws-test-"));+ const workspaceRoot = join(TMP, "ws");+ const repo = join(workspaceRoot, "repo");+ const tmpRoot = join(TMP, "sessions");+ mkdirSync(repo, { recursive: true });+ mkdirSync(tmpRoot, { recursive: true });+ if (withWorkspaceFile) {+ writeFileSync(join(workspaceRoot, "proj.code-workspace"), "{}");+ }+ const linkPath = join(workspaceRoot, LINK_NAME);+ const sessionDirFor = (id) => join(tmpRoot, sanitize(repo), id);+ const run = (sessionId, extraEnv = {}) => {+ const env = { ...process.env, APP_DIR: repo, HARNESS_TMP_ROOT: tmpRoot };+ delete env.CHAT_SESSION_DIR;+ delete env.CLAUDE_AGENT_NAME;+ Object.assign(env, extraEnv);+ return spawnSync("node", [HOOK], {+ input: JSON.stringify({ session_id: sessionId }),+ env,+ encoding: "utf8",+ });+ };+ return { workspaceRoot, repo, linkPath, sessionDirFor, run };+};++describe("link-session-workspace", () => {+ test("creates the symlink to the current session dir", () => {+ const { linkPath, sessionDirFor, run } = setup();+ const r = run("sess-1");+ expect(r.status).toBe(0);+ expect(lstatSync(linkPath).isSymbolicLink()).toBe(true);+ expect(readlinkSync(linkPath)).toBe(sessionDirFor("sess-1"));+ // target materialised so the link is never dangling+ expect(existsSync(sessionDirFor("sess-1"))).toBe(true);+ });++ test("repoints an existing harness symlink to the new session dir", () => {+ const { linkPath, sessionDirFor, run } = setup();+ run("sess-1");+ run("sess-2");+ expect(readlinkSync(linkPath)).toBe(sessionDirFor("sess-2"));+ });++ test("does nothing when there is no .code-workspace file", () => {+ const { linkPath, run } = setup({ withWorkspaceFile: false });+ const r = run("sess-1");+ expect(r.status).toBe(0);+ expect(existsSync(linkPath)).toBe(false);+ });++ test("does not clobber a real directory sitting at the link path", () => {+ const { linkPath, run } = setup();+ mkdirSync(linkPath);+ writeFileSync(join(linkPath, "keep.txt"), "important");+ run("sess-1");+ expect(lstatSync(linkPath).isSymbolicLink()).toBe(false);+ expect(existsSync(join(linkPath, "keep.txt"))).toBe(true);+ });++ test("is a no-op under a managed launcher (CHAT_SESSION_DIR set)", () => {+ const { linkPath, run } = setup();+ const r = run("sess-1", { CHAT_SESSION_DIR: "/tmp/managed-session-xyz" });+ expect(r.status).toBe(0);+ expect(existsSync(linkPath)).toBe(false);+ });+});diff --git a/scripts/harness-monitor.mjs b/.claude/scripts/harness-monitor.mjssimilarity index 98%rename from scripts/harness-monitor.mjsrename to .claude/scripts/harness-monitor.mjsindex 7cebe10c..ad6f2885 100755--- a/scripts/harness-monitor.mjs+++ b/.claude/scripts/harness-monitor.mjs@@ -9,10 +9,10 @@// 3. tickets <CHAT_SESSION_DIR or TICKETS_DIR>/TASK-*.json//// Usage:-// scripts/harness-monitor.mjs # latest session, one-shot summary-// scripts/harness-monitor.mjs --watch # latest session, live (re-renders)-// scripts/harness-monitor.mjs --session <id> # a specific session id-// scripts/harness-monitor.mjs --list # list known sessions, newest first+// .claude/scripts/harness-monitor.mjs # latest session, one-shot summary+// .claude/scripts/harness-monitor.mjs --watch # latest session, live (re-renders)+// .claude/scripts/harness-monitor.mjs --session <id> # a specific session id+// .claude/scripts/harness-monitor.mjs --list # list known sessions, newest firstimport { readFileSync, readdirSync, existsSync, statSync } from "node:fs";import { join, basename } from "node:path";diff --git a/scripts/harness-revert.mjs b/.claude/scripts/harness-revert.mjssimilarity index 98%rename from scripts/harness-revert.mjsrename to .claude/scripts/harness-revert.mjsindex cd4ff05e..dd350f36 100755--- a/scripts/harness-revert.mjs+++ b/.claude/scripts/harness-revert.mjs@@ -18,8 +18,8 @@// branch is exactly the merge commits whose subject is "merge(session): <short>".//// Usage:-// scripts/harness-revert.mjs <SESSION_SHORT_ID> # revert + clean up-// scripts/harness-revert.mjs <SESSION_SHORT_ID> --dry-run # print, change nothing+// .claude/scripts/harness-revert.mjs <SESSION_SHORT_ID> # revert + clean up+// .claude/scripts/harness-revert.mjs <SESSION_SHORT_ID> --dry-run # print, change nothing//import { spawnSync } from "node:child_process";import { existsSync, readdirSync, rmSync } from "node:fs";diff --git a/.claude/settings.json b/.claude/settings.jsonindex 669ed0d0..c02b3819 100644--- a/.claude/settings.json+++ b/.claude/settings.json@@ -23,7 +23,19 @@"Bash(npm install *)","Bash(npm i *)","Bash(pnpm add *)",- "Bash(yarn add *)"+ "Bash(yarn add *)",+ "mcp__github__merge_pull_request",+ "mcp__github__create_or_update_file",+ "mcp__github__push_files",+ "mcp__github__delete_file",+ "mcp__github__create_repository",+ "mcp__github__fork_repository",+ "mcp__plugin_github_github__merge_pull_request",+ "mcp__plugin_github_github__create_or_update_file",+ "mcp__plugin_github_github__push_files",+ "mcp__plugin_github_github__delete_file",+ "mcp__plugin_github_github__create_repository",+ "mcp__plugin_github_github__fork_repository"]},"attribution": {@@ -43,6 +55,22 @@"type": "command","command": "$CLAUDE_PROJECT_DIR/.claude/hooks/ensure-playwright-mcp.mjs","timeout": 10+ },+ {+ "type": "command",+ "command": "$CLAUDE_PROJECT_DIR/.claude/hooks/link-session-workspace.mjs",+ "timeout": 10+ }+ ]+ }+ ],+ "SessionEnd": [+ {+ "hooks": [+ {+ "type": "command",+ "command": "$CLAUDE_PROJECT_DIR/.claude/hooks/cleanup-session.mjs",+ "timeout": 30}]}diff --git a/.gitignore b/.gitignoreindex 8df74f62..168883cf 100644--- a/.gitignore+++ b/.gitignore@@ -42,6 +42,9 @@ public/r/!supabase/functions/.env.claude/settings.local.json+# Harness scratch (promotion lock; worktrees + test-results also cleaned at SessionEnd)+.promote.lock+# Playwrightnode_modules//test-results/diff --git a/CLAUDE.md b/CLAUDE.mdindex 8c0d45e9..9c0386de 100644--- a/CLAUDE.md+++ b/CLAUDE.md@@ -14,7 +14,7 @@ Code-change requests can run through the **agent harness**: subagents (planner,While a fresh dispatch runs, don't start a parallel plan B; wait, then relay.-**Gate level.** A request may carry `gate=none|plan|waves` (default **`plan`**); ALWAYS pass an explicit `GATE: <level>` line (the orchestrator also fails closed to `plan` on a missing/unknown value). `plan` pauses after planning for ticket review; `none` runs autonomously; `waves` also pauses at each wave. On a plan pause, relay the plan + question; on approval dispatch a FRESH `orchestrator` with `<intent>execute-plan</intent>` and the same `<session_dir>` (never `SendMessage`); on "wants changes" dispatch a fresh one. CRM Builder's launcher sets `gate=none`.+**Gate level.** A request may carry `gate=none|plan|waves` (default **`plan`**); ALWAYS pass an explicit `GATE: <level>` line (the orchestrator also fails closed to `plan` on a missing/unknown value). `plan` pauses after planning for ticket review; `none` runs autonomously; `waves` also pauses at each wave. On a plan pause, relay the plan + question **and a clickable link to the actual ticket JSONs** so the user reviews the real tickets, not just your summary: the `link-session-workspace` hook maintains a `.harness-session` symlink at the workspace root pointing at `<session_dir>`, so link `[tickets](.harness-session/tickets/)` (or the specific `TASK-XXX.json` files) with a relative markdown path. On approval dispatch a FRESH `orchestrator` with `<intent>execute-plan</intent>` and the same `<session_dir>` (never `SendMessage`); on "wants changes" dispatch a fresh one. CRM Builder's launcher sets `gate=none`.## Opting in