Skip to content

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

Minor fixes agent naming in hooks, add launch harness scripts, add harness monitoring and cleanup scripts

Jerome4fd62e6dcb78
diff --git a/.claude/hooks/lib/context.mjs b/.claude/hooks/lib/context.mjs
index b4339925..d167b5b4 100644
--- a/.claude/hooks/lib/context.mjs
+++ b/.claude/hooks/lib/context.mjs
@@ -20,9 +20,10 @@ export function createHookContext(input, name = "hook") {
const clean = (s) => String(s ?? "").replace(/[\t\n]/g, " ");
const agentId = clean(i.agent_id);
- // agentName is the runtime-assigned (possibly TASK-suffixed) name from the
- // environment; agentType prefers the payload's agent_type and falls back to it.
- const agentName = process.env.CLAUDE_AGENT_NAME || "";
+ // agentName: env var carries the suffixed runtime name (e.g. developer-TASK-001)
+ // in PostToolUse/PreToolUse contexts; for SubagentStart the env is the parent's,
+ // so fall back to i.agent_name which Claude Code populates with the child's name.
+ const agentName = process.env.CLAUDE_AGENT_NAME || clean(i.agent_name) || "";
const chatSessionId = process.env.CHAT_SESSION_DIR ? basename(process.env.CHAT_SESSION_DIR) : "";
const sessionId =
diff --git a/.claude/hooks/lib/validation.mjs b/.claude/hooks/lib/validation.mjs
index 43a2323c..e59238bb 100644
--- a/.claude/hooks/lib/validation.mjs
+++ b/.claude/hooks/lib/validation.mjs
@@ -98,7 +98,7 @@ export function runValidationSteps(ctx, { worktree = "" } = {}) {
for (const wt of worktrees) {
const failed = (step, output) => {
- ctx.log(`FAIL step=${step} wt=${wt}`);
+ ctx.log(`FAIL step=${step} wt=${wt}\n${output}`);
return { ok: false, step, output: `=== ${step} failed in ${wt} ===\n${output}\n` };
};
diff --git a/.claude/hooks/setup-worktree.mjs b/.claude/hooks/setup-worktree.mjs
index a4a0ec7b..67bc77f0 100755
--- a/.claude/hooks/setup-worktree.mjs
+++ b/.claude/hooks/setup-worktree.mjs
@@ -19,7 +19,8 @@ import {
const ctx = createHookContext(readFileSync(0, "utf8"), "setup-worktree");
const agentType = ctx.agentType || "";
-const taskId = getFirstTaskId(agentType);
+const agentName = ctx.agentName || "";
+const taskId = getFirstTaskId(agentName) || getFirstTaskId(agentType);
let worktreePath;
let branchName;
@@ -54,9 +55,7 @@ if (!existsSync(join(sessionWt, ".git"))) {
const add = git(["worktree", "add", sessionWt, integrationBranch]);
if (add.status === 0) {
ctx.linkNodeModules(sessionWt);
- ctx.log(
- `SESSION-BRANCH created ${integrationBranch} from ${base}`,
- );
+ ctx.log(`SESSION-BRANCH created ${integrationBranch} from ${base}`);
} else {
ctx.log(
`SESSION-BRANCH FAILED _session worktree ${integrationBranch} err=${add.stderr.replace(/\n/g, " ")}`,
@@ -64,9 +63,7 @@ if (!existsSync(join(sessionWt, ".git"))) {
}
}
-ctx.log(
- `START agent=${agentType} path=${worktreePath} branch=${branchName}`,
-);
+ctx.log(`START agent=${agentType} path=${worktreePath} branch=${branchName}`);
if (getWorktreePaths().includes(worktreePath)) {
ctx.accept(`already registered (${worktreePath})`);
diff --git a/makefile b/makefile
index 1361d9d3..2852d11a 100644
--- a/makefile
+++ b/makefile
@@ -158,3 +158,18 @@ update-changelog: ## Update the changelog with the unreleased changes (ran autom
storybook: ## start storybook
npm run storybook
+
+harness: ## run the agent harness interactively (pass REQUEST="..." to pre-fill)
+ scripts/test-harness.sh "$(REQUEST)"
+
+clean-harness: ## clean up the agent harness session
+ scripts/clean-harness.sh
+
+watch: ## live monitor of the most recent agent session (agents, hooks, diagnosis)
+ node scripts/harness-monitor.mjs --watch
+
+monitor: ## one-shot summary of the most recent agent session (pass SESSION=<id> to pick one)
+ @node scripts/harness-monitor.mjs $(if $(SESSION),--session $(SESSION),)
+
+sessions: ## list known agent sessions, newest first
+ @node scripts/harness-monitor.mjs --list
diff --git a/scripts/clean-harness.sh b/scripts/clean-harness.sh
new file mode 100755
index 00000000..b1841873
--- /dev/null
+++ b/scripts/clean-harness.sh
@@ -0,0 +1,198 @@
+#!/usr/bin/env bash
+#
+# Clean up Atomic CRM agent-workflow session artifacts.
+#
+# Removes everything the SIMPLE/COMPLEX agent pipeline leaves behind:
+# - session git worktrees under /tmp/<repo-slug>/
+# - branches checked out in those worktrees, plus session/* and session-base/*
+# - the .promote.lock promotion lock file
+# - the /tmp/<repo-slug> session directory tree
+#
+# It NEVER deletes the current branch, main, or any branch not tied to a
+# session worktree.
+#
+# By default it also lands you back where you launched the harness from:
+# - checks out the branch you started on (the harness checks out main to
+# promote, which would otherwise strand you there),
+# - hard-resets that branch to the pre-harness commit (dropping every commit
+# the harness made on top),
+# - restores main to origin/main (undoing the merge the harness made on main).
+#
+# The start branch + commit are read from .git/clean-harness-return, written by
+# launch-harness.sh at launch (it survives the /tmp cleanup). If that record is
+# missing, it falls back to the most recent session-base anchor and resets the
+# current branch in place.
+#
+# Usage:
+# scripts/clean-harness.sh # clean + reset to latest harness-start anchor
+# scripts/clean-harness.sh --no-reset # clean session artifacts only, no reset
+# scripts/clean-harness.sh --dry-run # print what would happen, change nothing
+#
+set -euo pipefail
+
+REPO_ROOT="$(git rev-parse --show-toplevel)"
+cd "$REPO_ROOT"
+
+DRY_RUN=false
+NO_RESET=false
+RESET_REF=""
+for arg in "$@"; do
+ case "$arg" in
+ --dry-run|-n) DRY_RUN=true ;;
+ --no-reset) NO_RESET=true ;;
+ *) echo "Unknown argument: $arg" >&2; exit 2 ;;
+ esac
+done
+
+CURRENT_BRANCH="$(git rev-parse --abbrev-ref HEAD)"
+HEAD_SHA="$(git rev-parse HEAD)"
+
+# Preferred target: the launch record written by launch-harness.sh, which captures
+# the branch + commit you started from (the exact pre-harness anchor). It lives
+# under .git/ so it survives the /tmp cleanup below.
+RETURN_FILE="$REPO_ROOT/.git/clean-harness-return"
+START_BRANCH=""
+if [[ -z "$RESET_REF" ]] && ! $NO_RESET && [[ -f "$RETURN_FILE" ]]; then
+ IFS=$'\t' read -r START_BRANCH RESET_REF < "$RETURN_FILE" || true
+ if [[ -n "$RESET_REF" ]] && ! git rev-parse --verify --quiet "${RESET_REF}^{commit}" >/dev/null; then
+ echo "Warning: recorded start commit ${RESET_REF:0:12} no longer exists; ignoring record." >&2
+ RESET_REF=""
+ START_BRANCH=""
+ fi
+fi
+
+# Fallback target: the most recent harness-start anchor.
+#
+# setup-worktree.mjs records each harness run's starting point as a
+# `session-base/<id>` branch pointing at HEAD before any agent work. We pick the
+# anchor with the most commits in its history (= started latest) among those
+# that are a STRICT ancestor of HEAD, so the agent commits stacked on top get
+# dropped while pre-run history is kept.
+if [[ -z "$RESET_REF" ]] && ! $NO_RESET; then
+ best_count=-1
+ while IFS= read -r ref; do
+ [[ -z "$ref" ]] && continue
+ sha="$(git rev-parse "$ref")"
+ [[ "$sha" == "$HEAD_SHA" ]] && continue # not strict
+ git merge-base --is-ancestor "$sha" "$HEAD_SHA" || continue # must be ancestor
+ count="$(git rev-list --count "$sha")"
+ if (( count > best_count )); then
+ best_count=$count
+ RESET_REF="$sha"
+ fi
+ done < <(git for-each-ref --format='%(refname:short)' 'refs/heads/session-base/*')
+
+ if [[ -z "$RESET_REF" ]]; then
+ echo "Warning: no session-base anchor (strict ancestor of HEAD) found; skipping reset." >&2
+ echo " Use --no-reset to silence this." >&2
+ fi
+fi
+
+# /tmp base: repo path with every "/" replaced by "_" (see worktree-scope rule).
+SLUG="${REPO_ROOT//\//_}"
+TMP_BASE="/tmp/${SLUG}"
+
+say() { printf '%s\n' "$*"; }
+do_run() {
+ if $DRY_RUN; then
+ say "[dry-run] $*"
+ else
+ "$@"
+ fi
+}
+
+say "==> Repo: $REPO_ROOT"
+say "==> Tmp base: $TMP_BASE"
+say "==> Branch: $CURRENT_BRANCH"
+$DRY_RUN && say "==> Mode: DRY-RUN (no changes)"
+
+# 1. Collect branches checked out in /tmp session worktrees (before removal).
+mapfile -t SESSION_WT_BRANCHES < <(
+ git worktree list --porcelain | awk -v base="$TMP_BASE/" '
+ /^worktree / { wt = $2 }
+ /^branch / { sub("refs/heads/", "", $2); if (index(wt, base) == 1) print $2 }
+ '
+)
+
+# 2. Remove every worktree under the tmp base.
+say "==> Removing session worktrees..."
+while IFS= read -r wt; do
+ [[ -z "$wt" ]] && continue
+ say " - $wt"
+ do_run git worktree remove --force "$wt"
+done < <(git worktree list --porcelain | awk -v base="$TMP_BASE/" '/^worktree / && index($2, base) == 1 { print $2 }')
+do_run git worktree prune
+
+# 3. Delete session branches: those from /tmp worktrees + session/* + session-base/*.
+say "==> Deleting session branches..."
+{
+ printf '%s\n' "${SESSION_WT_BRANCHES[@]:-}"
+ git for-each-ref --format='%(refname:short)' refs/heads/session refs/heads/session-base 2>/dev/null || true
+ git for-each-ref --format='%(refname:short)' 'refs/heads/session/*' 'refs/heads/session-base/*'
+} | sort -u | while IFS= read -r br; do
+ [[ -z "$br" ]] && continue
+ [[ "$br" == "$CURRENT_BRANCH" ]] && { say " ! skip current branch: $br"; continue; }
+ if git show-ref --verify --quiet "refs/heads/$br"; then
+ say " - $br"
+ do_run git branch -D "$br"
+ fi
+done
+
+# 4. Remove the promotion lock.
+if [[ -f "$REPO_ROOT/.promote.lock" ]]; then
+ say "==> Removing .promote.lock"
+ do_run rm -f "$REPO_ROOT/.promote.lock"
+fi
+
+# 5. Remove the /tmp session directory tree.
+if [[ -d "$TMP_BASE" ]]; then
+ say "==> Removing $TMP_BASE"
+ do_run rm -rf "$TMP_BASE"
+fi
+
+# 6. Land back on the start branch + commit, and restore main.
+if [[ -n "$RESET_REF" ]]; then
+ # 6-pre. Safety net: never let the hard reset destroy uncommitted work. If the
+ # working tree has tracked changes, stash them first so a surprise is always
+ # recoverable with `git stash pop`. Untracked files are left alone (reset does
+ # not touch them).
+ if [[ -n "$(git status --porcelain --untracked-files=no)" ]]; then
+ say "==> Stashing uncommitted changes before reset (recover with: git stash pop)"
+ do_run git stash push -m "clean-harness safety stash"
+ fi
+
+ # 6a. Switch off whatever the harness left us on (e.g. main) onto the branch
+ # we started from.
+ if [[ -n "$START_BRANCH" && "$START_BRANCH" != "$CURRENT_BRANCH" ]]; then
+ if git show-ref --verify --quiet "refs/heads/$START_BRANCH"; then
+ say "==> Checking out $START_BRANCH"
+ do_run git checkout "$START_BRANCH"
+ else
+ say " ! start branch '$START_BRANCH' no longer exists; staying on $CURRENT_BRANCH"
+ START_BRANCH=""
+ fi
+ fi
+ TARGET_BRANCH="${START_BRANCH:-$CURRENT_BRANCH}"
+
+ # 6b. Restore main to origin/main (undo the merge the harness made on main),
+ # unless main is the branch we are landing on.
+ if [[ "$TARGET_BRANCH" != "main" ]] && git show-ref --verify --quiet refs/heads/main; then
+ if git rev-parse --verify --quiet "origin/main^{commit}" >/dev/null; then
+ say "==> Restoring main to origin/main"
+ do_run git branch -f main origin/main
+ else
+ say " ! origin/main not found; leaving main untouched"
+ fi
+ fi
+
+ # 6c. Reset the start branch to the pre-harness commit.
+ say "==> Resetting $TARGET_BRANCH to $RESET_REF"
+ do_run git reset --hard "$RESET_REF"
+
+ # 6d. Consume the launch record.
+ if [[ -f "$RETURN_FILE" ]]; then
+ do_run rm -f "$RETURN_FILE"
+ fi
+fi
+
+say "==> Done."
diff --git a/scripts/harness-monitor.mjs b/scripts/harness-monitor.mjs
new file mode 100755
index 00000000..b97e7e21
--- /dev/null
+++ b/scripts/harness-monitor.mjs
@@ -0,0 +1,636 @@
+#!/usr/bin/env node
+//
+// Harness monitor — a terminal view of an agent-workflow session.
+//
+// Gather informations from three places, all keyed by the session id:
+//
+// 1. hooks.log <TMP_ROOT>/<sanitized-repo>/<id>/hooks.log
+// 2. subagent transcripts ~/.claude/projects/<slug>/<id>/subagents/*.jsonl
+// 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
+
+import { readFileSync, readdirSync, existsSync, statSync } from "node:fs";
+import { join, basename } from "node:path";
+import { homedir } from "node:os";
+import { execSync } from "node:child_process";
+
+// ─── paths & session discovery ──────────────────────────────────────────────
+
+const REPO = (() => {
+ if (process.env.CLAUDE_PROJECT_DIR) return process.env.CLAUDE_PROJECT_DIR;
+ try {
+ return execSync("git rev-parse --show-toplevel", {
+ encoding: "utf8",
+ }).trim();
+ } catch {
+ return process.cwd();
+ }
+})();
+
+const TMP_ROOT = process.env.CRM_TMP_ROOT || "/tmp";
+const sanitize = (p) => String(p).replace(/\//g, "_");
+const WORKTREE_ROOT = join(TMP_ROOT, sanitize(REPO)); // /tmp/_workspaces_atomic-crm
+const CLAUDE_PROJ = join(
+ homedir(),
+ ".claude",
+ "projects",
+ REPO.replace(/\//g, "-"),
+);
+const HARNESS_ROOT = "/tmp/atomic-crm-harness";
+
+// A session id is a worktree-base subdir that has a hooks.log. Test fixtures
+// (td-1, td-2, …) are skipped — they are not real sessions.
+function listSessions() {
+ if (!existsSync(WORKTREE_ROOT)) return [];
+ return readdirSync(WORKTREE_ROOT)
+ .filter((name) => !/^td-/.test(name))
+ .map((id) => ({ id, log: join(WORKTREE_ROOT, id, "hooks.log") }))
+ .filter((s) => existsSync(s.log))
+ .map((s) => ({ ...s, mtime: statSync(s.log).mtimeMs }))
+ .sort((a, b) => b.mtime - a.mtime);
+}
+
+function sessionPaths(id) {
+ const base = join(WORKTREE_ROOT, id);
+ return {
+ id,
+ base,
+ hooksLog: join(base, "hooks.log"),
+ mainTranscript: join(CLAUDE_PROJ, `${id}.jsonl`),
+ subagentsDir: join(CLAUDE_PROJ, id, "subagents"),
+ ticketDirs: [join(HARNESS_ROOT, id), join(base, "tickets")],
+ };
+}
+
+// A worktree path → a short, human label. `simple` is the simple-developer's
+// worktree; `_session` is the shared integration worktree the merger merges
+// into before promoting to the base branch.
+function wtLabel(path) {
+ if (!path) return "";
+ const b = basename(path);
+ if (b === "_session") return "_session (integration)";
+ if (b === "simple") return "simple (dev worktree)";
+ return b; // TASK-XXX
+}
+
+// ─── colour helpers ─────────────────────────────────────────────────────────
+
+const COLOR = process.stdout.isTTY && !process.env.NO_COLOR;
+const c = (code, s) => (COLOR ? `\x1b[${code}m${s}\x1b[0m` : s);
+const dim = (s) => c("2", s);
+const bold = (s) => c("1", s);
+const red = (s) => c("31", s);
+const green = (s) => c("32", s);
+const yellow = (s) => c("33", s);
+const blue = (s) => c("36", s);
+const mag = (s) => c("35", s);
+
+const hhmmss = (iso) => {
+ const d = new Date(iso);
+ return Number.isNaN(d.getTime()) ? iso : d.toISOString().slice(11, 19);
+};
+
+// ─── hooks.log parsing ──────────────────────────────────────────────────────
+// Line shape: `[<iso-ts>] [<hook>] <rest...>`. Lines without that prefix are
+// continuation output (e.g. a multi-line validation failure) and attach to the
+// previous event as detail.
+
+const LINE_RE = /^\[([^\]]+)\]\s+\[([^\]]+)\]\s+(.*)$/;
+
+function parseHooksLog(path) {
+ if (!existsSync(path)) return [];
+ const events = [];
+ for (const line of readFileSync(path, "utf8").split("\n")) {
+ if (!line) continue;
+ const m = line.match(LINE_RE);
+ if (!m) {
+ if (events.length) events[events.length - 1].detail.push(line);
+ continue;
+ }
+ const [, ts, hook, rest] = m;
+ const fields = {};
+ for (const f of rest.matchAll(/(\w+)=(\S+)/g)) fields[f[1]] = f[2];
+ const state = rest.split(/\s+/)[0];
+ events.push({ ts, hook, state, rest, fields, detail: [] });
+ }
+ return events;
+}
+
+// ─── subagent transcripts ───────────────────────────────────────────────────
+
+function readJsonl(path) {
+ if (!existsSync(path)) return [];
+ const out = [];
+ for (const line of readFileSync(path, "utf8").split("\n")) {
+ if (!line.trim()) continue;
+ try {
+ out.push(JSON.parse(line));
+ } catch {
+ /* skip malformed line */
+ }
+ }
+ return out;
+}
+
+function readAgents(dir) {
+ if (!existsSync(dir)) return [];
+ const agents = [];
+ for (const file of readdirSync(dir)) {
+ if (!file.endsWith(".jsonl")) continue;
+ const agentId = basename(file, ".jsonl");
+ const meta = (() => {
+ const p = join(dir, `${agentId}.meta.json`);
+ try {
+ return JSON.parse(readFileSync(p, "utf8"));
+ } catch {
+ return {};
+ }
+ })();
+
+ const records = readJsonl(join(dir, file));
+ const toolCounts = {};
+ const messages = []; // SendMessage payloads, timestamped
+ let lastText = "";
+ let firstTs = null;
+ let lastTs = null;
+ for (const rec of records) {
+ if (rec.timestamp) {
+ if (!firstTs) firstTs = rec.timestamp;
+ lastTs = rec.timestamp;
+ }
+ const content = rec.message?.content;
+ if (!Array.isArray(content)) continue;
+ for (const block of content) {
+ if (block.type === "tool_use") {
+ toolCounts[block.name] = (toolCounts[block.name] || 0) + 1;
+ if (block.name === "SendMessage") {
+ const to = block.input?.to ?? "?";
+ const msg = block.input?.message;
+ messages.push({
+ to,
+ text: typeof msg === "string" ? msg : JSON.stringify(msg),
+ ts: rec.timestamp,
+ });
+ }
+ } else if (block.type === "text" && block.text.trim()) {
+ lastText = block.text.trim();
+ }
+ }
+ }
+ agents.push({
+ agentId,
+ type: meta.agentType || "?",
+ description: meta.description || "",
+ toolCounts,
+ messages,
+ lastText,
+ firstTs,
+ lastTs,
+ verdict: classifyVerdict(lastText),
+ });
+ }
+ // Chronological by last activity so repeated dispatches of the same agent
+ // (retries / resumes) read top-to-bottom in the order they ran.
+ return agents.sort((a, b) =>
+ String(a.lastTs || "").localeCompare(String(b.lastTs || "")),
+ );
+}
+
+// The orchestrator is the main session transcript, NOT a subagent.
+function readOrchestrator(path) {
+ const records = readJsonl(path);
+ if (!records.length) return null;
+ let lastText = "";
+ let lastTs = null;
+ const dispatches = []; // { ts, type } — when the orchestrator spawned each agent
+ for (const rec of records) {
+ if (rec.timestamp) lastTs = rec.timestamp;
+ const content = rec.message?.content;
+ if (!Array.isArray(content)) continue;
+ for (const block of content) {
+ if (
+ block.type === "tool_use" &&
+ (block.name === "Agent" || block.name === "Task")
+ )
+ dispatches.push({
+ ts: rec.timestamp,
+ type:
+ block.input?.subagent_type || block.input?.description || "agent",
+ });
+ else if (block.type === "text" && block.text.trim())
+ lastText = block.text.trim();
+ }
+ }
+ return { lastText, lastTs, dispatches };
+}
+
+// Merge every timestamped signal — orchestrator spawns, agent SendMessages,
+// agent completions, and the key hook milestones — into one chronological
+// stream. This is the "what happened, in order" view: dev → merger, etc.
+function buildEventTimeline(orchestrator, agents, events) {
+ const items = [];
+ const push = (ts, color, icon, text) =>
+ ts && items.push({ ts, color, icon, text });
+
+ for (const d of orchestrator?.dispatches ?? [])
+ push(d.ts, blue, "▶", `orchestrator spawned ${bold(d.type)}`);
+
+ for (const a of agents) {
+ for (const m of a.messages)
+ push(
+ m.ts,
+ mag,
+ "→",
+ `${a.type} → ${bold(m.to)}: ${m.text.split("\n")[0].slice(0, 80)}`,
+ );
+ const mark =
+ a.verdict.kind === "done"
+ ? green("✓")
+ : a.verdict.kind === "fail"
+ ? red("✗")
+ : dim("■");
+ const vcolor =
+ a.verdict.kind === "fail" ? red : a.verdict.kind === "done" ? green : dim;
+ push(
+ a.lastTs,
+ vcolor,
+ mark,
+ `${a.type} finished — ${a.verdict.label.slice(0, 80)}`,
+ );
+ }
+
+ for (const e of events) {
+ if (e.hook === "setup-worktree" && e.state === "CREATED")
+ push(e.ts, blue, "⊕", `worktree created ${dim(wtLabel(e.fields.path))}`);
+ else if (e.hook === "validate" && e.state === "OK")
+ push(e.ts, green, "✓", `validation OK ${dim(wtLabel(e.fields.wt))}`);
+ else if (e.hook === "validate" && e.state === "FAIL")
+ push(
+ e.ts,
+ red,
+ "✗",
+ `validation FAIL ${e.fields.step || ""}${e.detail.length ? dim(" — " + e.detail.join(" ").slice(0, 60)) : ""}`,
+ );
+ else if (e.hook === "circuit-breaker" && /^BLOCK/.test(e.rest))
+ push(e.ts, red, "⛔", `circuit-breaker BLOCK (count=${e.fields.count})`);
+ }
+
+ if (orchestrator?.lastTs)
+ push(
+ orchestrator.lastTs,
+ dim,
+ "▣",
+ `orchestrator last said: ${orchestrator.lastText.split("\n").pop().slice(0, 80)}`,
+ );
+
+ return items.sort((a, b) => String(a.ts).localeCompare(String(b.ts)));
+}
+
+// Synthesize a single completion verdict for the whole session from the
+// strongest available signal: the merger's DONE line, then a clean
+// no-dirty-worktree finish, else still-running / unknown.
+function sessionStatus(agents, events) {
+ const merger = agents.find((a) => a.type === "merger");
+ if (merger) {
+ const m = merger.lastText.match(/DONE:\s*commit=(\S+)/i);
+ if (m)
+ return green(
+ `✓ COMPLETE — merger promoted to main (commit ${m[1].replace(/[.,]$/, "")})`,
+ );
+ if (/promotion merged|merged .*into main/i.test(merger.lastText))
+ return green("✓ COMPLETE — merger reported the session merged into main");
+ if (merger.verdict.kind === "fail")
+ return red(`✗ merger FAILED — ${merger.verdict.label.slice(0, 120)}`);
+ }
+ if (agents.some((a) => a.verdict.kind === "fail"))
+ return red("✗ FAILED — an agent ended in failure (see DIAGNOSIS)");
+ const lastValidate = [...events]
+ .reverse()
+ .find((e) => e.hook === "validate" && e.state === "ACCEPT");
+ if (lastValidate && /no_dirty_worktree/.test(lastValidate.rest))
+ return yellow(
+ "… likely done — last validation found nothing left to do, but no merger DONE was seen",
+ );
+ return yellow("… in progress / outcome unclear");
+}
+
+// The structured-text contract: agents end with DONE / FAILED / BLOCKED, or a
+// reviewer verdict.
+function classifyVerdict(text) {
+ if (!text) return { kind: "running", label: "running / no final message" };
+ const head =
+ text
+ .split("\n")
+ .find((l) => l.trim())
+ ?.slice(0, 200) ?? "";
+ if (/^FAILED\b|permanently deadlocked|\bBLOCKED\b/im.test(text))
+ return { kind: "fail", label: head };
+ if (
+ /^DONE:|merged\s+TASK|merged successfully|promotion merged|completed successfully|^Verdict:\s*(APPROVED|GREEN)/im.test(
+ text,
+ )
+ )
+ return { kind: "done", label: head };
+ return { kind: "info", label: head };
+}
+
+// ─── tickets ────────────────────────────────────────────────────────────────
+
+function readTickets(dirs) {
+ for (const dir of dirs) {
+ if (!existsSync(dir)) continue;
+ const files = readdirSync(dir).filter((f) => /^TASK-\d+\.json$/.test(f));
+ if (!files.length) continue;
+ return files.sort().map((f) => {
+ try {
+ const t = JSON.parse(readFileSync(join(dir, f), "utf8"));
+ return {
+ id: t.id || basename(f, ".json"),
+ status: t.status || "?",
+ title: t.title || t.description || "",
+ };
+ } catch {
+ return { id: basename(f, ".json"), status: "unreadable", title: "" };
+ }
+ });
+ }
+ return [];
+}
+
+// ─── diagnosis ──────────────────────────────────────────────────────────────
+// Turn the raw event stream into named pathologies.
+
+function diagnose(events, agents) {
+ const findings = [];
+
+ // 1. A validation step that keeps failing on the same worktree.
+ const validFails = events.filter(
+ (e) => e.hook === "validate" && e.state === "FAIL" && e.fields.step,
+ );
+ const byStep = {};
+ for (const e of validFails)
+ byStep[e.fields.step] = (byStep[e.fields.step] || 0) + 1;
+ for (const [step, n] of Object.entries(byStep)) {
+ if (n >= 2)
+ findings.push(
+ red(
+ `✗ validation never passes: '${step}' failed ${n}× — the flow cannot complete until this is green.`,
+ ),
+ );
+ }
+
+ // 2. Circuit-breaker blocks → an agent is re-submitting an identical action.
+ const blocks = events.filter(
+ (e) => e.hook === "circuit-breaker" && /^BLOCK/.test(e.rest),
+ );
+ if (blocks.length) {
+ const maxCount = Math.max(
+ ...blocks.map((b) => Number(b.fields.count) || 0),
+ );
+ findings.push(
+ red(
+ `✗ retry loop: circuit-breaker BLOCKED ${blocks.length}× (up to ${maxCount} identical attempts) — the agent is stuck repeating the same call.`,
+ ),
+ );
+ }
+
+ // 3. bash-guard blocks → agent fighting the validation/permission rules.
+ const guard = events.filter(
+ (e) => e.hook === "bash-guard" && /BLOCK/.test(e.rest),
+ );
+ if (guard.length >= 3)
+ findings.push(
+ yellow(
+ `⚠ ${guard.length} bash-guard blocks — the agent tried to run forbidden commands (often a sign it's flailing).`,
+ ),
+ );
+
+ // 4. Agents that reported failure
+ const seen = new Set();
+ for (const a of agents) {
+ const signals = [
+ a.verdict.kind === "fail" ? a.verdict.label : "",
+ ...a.messages.map((m) => m.text),
+ ];
+ for (const s of signals) {
+ const head = s.split("\n")[0];
+ if (
+ !/FAILED|BLOCKED|worktree not found|cannot create worktree/i.test(head)
+ )
+ continue;
+ const key = `${a.type}:${head.slice(0, 60)}`;
+ if (seen.has(key)) continue;
+ seen.add(key);
+ findings.push(red(`✗ ${a.type}: ${head.slice(0, 140)}`));
+ }
+ }
+
+ // 4b. A TASK developer ran but its worktree was never created.
+ const createdTasks = new Set(
+ events
+ .filter(
+ (e) =>
+ e.hook === "setup-worktree" &&
+ /CREATED/.test(e.rest) &&
+ e.fields.branch,
+ )
+ .map((e) => (e.fields.branch.match(/TASK-\d+/) || [])[0])
+ .filter(Boolean),
+ );
+ for (const a of agents) {
+ const task = (a.type.match(/TASK-\d+/) || [])[0];
+ if (task && !createdTasks.has(task) && /developer/.test(a.type))
+ findings.push(
+ red(
+ `✗ ${task}: worktree never created (no setup-worktree CREATED entry) — the developer has nowhere to work.`,
+ ),
+ );
+ }
+
+ // 5. Worktree setup failure.
+ if (
+ events.some(
+ (e) => e.hook === "setup-worktree" && /FAILED|EXIT=2/.test(e.rest),
+ )
+ )
+ findings.push(
+ red("✗ setup-worktree failed — no usable worktree was created."),
+ );
+
+ if (!findings.length) findings.push(green("✓ no known pathology detected."));
+ return findings;
+}
+
+// ─── rendering ──────────────────────────────────────────────────────────────
+
+function render(id, limit = 0) {
+ const p = sessionPaths(id);
+ const events = parseHooksLog(p.hooksLog);
+ const agents = readAgents(p.subagentsDir);
+ const orchestrator = readOrchestrator(p.mainTranscript);
+ const tickets = readTickets(p.ticketDirs);
+ const out = [];
+ const line = (s = "") => out.push(s);
+
+ line(bold(blue(`━━━ harness session ${id} ━━━`)));
+ line(dim(`repo: ${REPO}`));
+ line(dim(`base: ${p.base}`));
+ if (existsSync(p.hooksLog))
+ line(
+ dim(
+ `hooks.log: ${events.length} events, updated ${hhmmss(new Date(statSync(p.hooksLog).mtime).toISOString())}`,
+ ),
+ );
+ else line(red("hooks.log: missing"));
+ line();
+
+ // Headline: did the session complete?
+ line(bold("STATUS ") + sessionStatus(agents, events));
+ if (orchestrator)
+ line(
+ ` ${dim("orchestrator last said:")} ${orchestrator.lastText.split("\n").pop().slice(0, 140) || dim("(none)")}`,
+ );
+ else line(` ${dim("orchestrator: main transcript not found")}`);
+ line();
+
+ // Agents
+ line(bold("AGENTS"));
+ if (!agents.length) line(dim(" (no subagent transcripts found)"));
+ for (const a of agents) {
+ const mark =
+ a.verdict.kind === "done"
+ ? green("✓")
+ : a.verdict.kind === "fail"
+ ? red("✗")
+ : yellow("…");
+ const tools = Object.entries(a.toolCounts)
+ .map(([n, k]) => `${n}:${k}`)
+ .join(" ");
+ line(` ${mark} ${bold(a.type)} ${dim(a.description)}`);
+ if (tools) line(` ${dim("tools")} ${tools}`);
+ for (const m of a.messages)
+ line(` ${mag("→ " + m.to)} ${m.text.split("\n")[0].slice(0, 100)}`);
+ if (a.verdict.label)
+ line(
+ ` ${a.verdict.kind === "fail" ? red(a.verdict.label) : dim(a.verdict.label)}`,
+ );
+ }
+ line();
+
+ // Tickets
+ if (tickets.length) {
+ line(bold("TICKETS"));
+ for (const t of tickets) {
+ const cl =
+ t.status === "merged"
+ ? green
+ : t.status === "in_progress"
+ ? yellow
+ : dim;
+ line(` ${cl(t.status.padEnd(12))} ${t.id} ${dim(t.title.slice(0, 80))}`);
+ }
+ line();
+ }
+
+ // Unified event timeline: orchestrator spawns + agent messages + completions
+ // + key hook milestones, in chronological order. Consecutive identical rows
+ // (e.g. the same validation failing 40×) are run-length collapsed to `×N`.
+ let timeline = buildEventTimeline(orchestrator, agents, events);
+ const total = timeline.length;
+ if (limit && total > limit) timeline = timeline.slice(total - limit);
+ line(
+ bold("EVENT TIMELINE") +
+ dim(
+ ` (chronological${limit && total > limit ? `, last ${limit} of ${total}` : ""})`,
+ ),
+ );
+ let i = 0;
+ while (i < timeline.length) {
+ let j = i;
+ while (j + 1 < timeline.length && timeline[j + 1].text === timeline[i].text)
+ j++;
+ const n = j - i + 1;
+ const ev = timeline[i];
+ const span = n > 1 ? dim(` ×${n} (until ${hhmmss(timeline[j].ts)})`) : "";
+ line(` ${dim(hhmmss(ev.ts))} ${ev.color(ev.icon)} ${ev.text}${span}`);
+ i = j + 1;
+ }
+ line();
+
+ // Diagnosis
+ line(bold("DIAGNOSIS"));
+ for (const f of diagnose(events, agents)) line(` ${f}`);
+
+ return out.join("\n");
+}
+
+// ─── main ───────────────────────────────────────────────────────────────────
+
+const args = process.argv.slice(2);
+const has = (f) => args.includes(f);
+const valueOf = (f) => {
+ const i = args.indexOf(f);
+ return i >= 0 ? args[i + 1] : null;
+};
+
+// This is a CLI tool: its whole job is to write a report to stdout. ESLint's
+// no-console rule only permits warn/error, so write to stdout directly.
+const print = (s = "") => process.stdout.write(s + "\n");
+
+if (has("--list")) {
+ const sessions = listSessions();
+ if (!sessions.length) {
+ print("No sessions found under " + WORKTREE_ROOT);
+ process.exit(0);
+ }
+ print(bold("Sessions (newest first):"));
+ for (const s of sessions)
+ print(
+ ` ${s.id} ${dim(new Date(s.mtime).toISOString().slice(0, 19).replace("T", " "))}`,
+ );
+ process.exit(0);
+}
+
+const sessionId = valueOf("--session") || listSessions()[0]?.id;
+if (!sessionId) {
+ console.error(
+ red(
+ `No session found under ${WORKTREE_ROOT}. Start the harness first (make harness).`,
+ ),
+ );
+ process.exit(1);
+}
+
+if (has("--watch")) {
+ // Use the terminal's alternate screen buffer (like top/htop/less): the view
+ // redraws in place and never pollutes the scrollback. We restore the normal
+ // screen on exit. The timeline is capped to the visible height so the newest
+ // events are always on screen instead of scrolling off the top.
+ const enter = () => process.stdout.write("\x1b[?1049h\x1b[?25l");
+ const leave = () => process.stdout.write("\x1b[?1049l\x1b[?25h");
+ const tick = () => {
+ const limit = Math.max(8, (process.stdout.rows || 40) - 18); // leave room for header/agents
+ process.stdout.write("\x1b[H\x1b[J"); // home + clear to end
+ process.stdout.write(render(sessionId, limit));
+ process.stdout.write(
+ "\n" + dim(`watching ${sessionId} — refresh 1.5s — Ctrl-C to quit`),
+ );
+ };
+ enter();
+ tick();
+ const iv = setInterval(tick, 1500);
+ const quit = () => {
+ clearInterval(iv);
+ leave();
+ process.exit(0);
+ };
+ process.on("SIGINT", quit);
+ process.on("SIGTERM", quit);
+} else {
+ print(render(sessionId));
+}
diff --git a/scripts/launch-harness.sh b/scripts/launch-harness.sh
new file mode 100755
index 00000000..8a2e28e0
--- /dev/null
+++ b/scripts/launch-harness.sh
@@ -0,0 +1,70 @@
+#!/usr/bin/env bash
+#
+# Launch the chat-orchestrator agent locally
+#
+#
+# Usage:
+# scripts/launch-harness.sh ["CRM change request"]
+# MODE=full scripts/launch-harness.sh "..." # real backend (needs local Supabase up)
+#
+# The request is optional: pass it to pre-fill the first message, or omit it and
+# type your request once the session opens.
+
+set -euo pipefail
+
+# Capture the optional request before we touch the positional parameters.
+REQUEST="$*"
+
+# Run from the repo root so CLAUDE_PROJECT_DIR and the hook-computed worktree
+# paths line up.
+REPO="$(git rev-parse --show-toplevel)"
+cd "$REPO"
+
+# Record the branch + commit we start from so `make clean-harness` can land us
+# back here afterwards. The harness checks out main to promote merged work, which
+# would otherwise leave you stranded on main with your branch behind. Stored
+# under .git/ so it survives the /tmp session cleanup. Detached HEAD → empty
+# branch field (clean-harness then just resets in place).
+START_BRANCH="$(git symbolic-ref --short HEAD 2>/dev/null || true)"
+START_SHA="$(git rev-parse HEAD)"
+printf '%s\t%s\n' "$START_BRANCH" "$START_SHA" > "$REPO/.git/clean-harness-return"
+
+# Mint a fresh session id and build the session dir from it. The hooks
+# (setup-worktree, merger, ...) derive the worktree base from the process's real
+# session id, while the orchestrator derives WORKTREE_BASE from
+# basename(session_dir) -- they only agree when basename(session_dir) == the
+# session id, hence --session-id below points at the same UUID.
+UUID="$(uuidgen 2>/dev/null | tr 'A-Z' 'a-z' || cat /proc/sys/kernel/random/uuid)"
+SAN="$(printf '%s' "$REPO" | sed 's#/#_#g')"
+SESSION_DIR="/tmp/atomic-crm-harness/${UUID}"
+mkdir -p "$SESSION_DIR"
+
+MODE="${MODE:-demo}"
+
+echo "Harness session"
+echo " mode: $MODE"
+echo " session id: $UUID"
+echo " session dir: $SESSION_DIR"
+echo " worktree base: /tmp/${SAN}/${UUID} (created lazily by the setup-worktree hook)"
+echo " hooks log: /tmp/${SAN}/${UUID}/hooks.log"
+echo
+
+# Build the claude argument list. The request, if any, is passed as the first
+# message (positional prompt); otherwise the session starts blank.
+ARGS=(
+ --agent chat-orchestrator
+ --session-id "$UUID"
+ --permission-mode auto
+ --append-system-prompt "<mode>${MODE}</mode>
+<session_dir>${SESSION_DIR}</session_dir>"
+)
+if [ -n "$REQUEST" ]; then
+ ARGS+=("$REQUEST")
+fi
+
+exec env \
+ CLAUDE_PROJECT_DIR="$REPO" \
+ CHAT_SESSION_DIR="$SESSION_DIR" \
+ MODE="$MODE" \
+ DISABLE_AUTOUPDATER=1 \
+ claude "${ARGS[@]}"