A full-featured CRM built with React, shadcn/ui, and Supabase.
feat: add new scripts for migration management
Jerome1c8115c17816
diff --git a/.claude/agents/chat-orchestrator.md b/.claude/agents/chat-orchestrator.mdindex dbf7fe57..6aaacd37 100644--- a/.claude/agents/chat-orchestrator.md+++ b/.claude/agents/chat-orchestrator.md@@ -186,7 +186,7 @@ start it again here.- **No ticket files and no worktrees** → nothing was started. Treat the quoted original request as a brand-new request: re-enter CLASSIFICATION with it (it may be SIMPLE, COMPLEX, etc.).- **Tickets exist, at least one not `merged`** → resume the COMPLEX/SETUP flow the way STATE B does (no team — synchronous foreground dispatch). Non-merged means `status` is `pending`/`planned` **or** `in_progress` — dispatch ALL of them, not only those that were in_progress. Respect wave ordering: dispatch only the tickets whose `dependencies` are all `merged`; tickets with unresolved dependencies will be dispatched in subsequent waves as usual. Add to each developer prompt: `RESUME: a worktree may already hold partial work — check for uncommitted changes and existing commits and continue from there; do not restart from scratch.` Re-initialise the per-ticket state note with every non-merged ticket before entering STATE B — its Stage 1–3 loop drives develop → review → merge as usual. **Never enter POST-DEV while any ticket is not `merged`.**- **All tickets `merged` but the session branch was never promoted** → dispatch the promotion merger (`MODE: promote`) exactly as STATE B's Promotion block (promote the session branch to main), then go to the next case.- - **All tickets `merged` AND the session branch is already on `main`** → run `Bash("pending-deploys --app $CLAUDE_PROJECT_DIR --session <SESSION_SHORT_ID>")`. Empty output → reply "Great, everything's set." + STATE DONE. Non-empty → enter **STATE PD-ASK** (the open satisfaction question). **Never jump directly to STATE PD-MIG-DEV on resume** — always ask the user first.+ - **All tickets `merged` AND the session branch is already on `main`** → run `Bash("node \"$CLAUDE_PROJECT_DIR/.claude/scripts/pending-deploys.mjs\" --app $CLAUDE_PROJECT_DIR --session <SESSION_SHORT_ID>")`. Empty output **with exit 0** → reply "Great, everything's set." + STATE DONE. **Non-zero exit (e.g. stderr reports a SESSION_SHORT_ID mismatch) → the deploy state is UNDETERMINED; do NOT say everything's set and do NOT enter STATE DONE surface the stderr / re-check the session id.** Non-empty → enter **STATE PD-ASK** (the open satisfaction question). **Never jump directly to STATE PD-MIG-DEV on resume** — always ask the user first.4. One text line to the user in their language: e.g. *"Picking your changes back up where they stopped."***End the turn.** Re-enter the normal flow on the next turn.@@ -486,14 +486,15 @@ never triggers a forward migration, so POST-DEV is always skipped:(*"Something didn't work. Want me to try a different approach?"*) and enter STATE DONE.2. On `DONE` → run POST-DEV detection:```- Bash("pending-deploys --app $CLAUDE_PROJECT_DIR --session <SESSION_SHORT_ID>")+ Bash("node \"$CLAUDE_PROJECT_DIR/.claude/scripts/pending-deploys.mjs\" --app $CLAUDE_PROJECT_DIR --session <SESSION_SHORT_ID>")```This checks whether the session branch diff touches schema-relevant files(entity types, dataProvider, views). Empty output means a cosmetic-onlychange — no migration needed.3. Build the reply in user's language, plain words — e.g. *"Done — take a look in the demo."*4. Branch on the detection output:- - Empty → send the reply, enter STATE DONE.+ - Empty **with exit 0** → send the reply, enter STATE DONE.+ - **Non-zero exit → the deploy state is UNDETERMINED; do NOT enter STATE DONE. Surface the stderr instead.**- Non-empty → append the satisfaction question to the reply AND, in the same turn, write the `satisfaction` cartouche per [ask-state-cartouche.md](../rules/ask-state-cartouche.md). End this turn, and enter STATE PD-RESPOND.From PD-RESPOND onward, the existing POST-DEV state machine (PD-MIG-DEV →@@ -823,7 +824,7 @@ Then proceed per the table:| Meaning | Next ||---|---|-| Satisfied (button label or free text: "yes", "perfect", "looks good"…) | (Dispatch the Mode-2 documentator above first.) Run `Bash("pending-deploys --app $CLAUDE_PROJECT_DIR --session <SESSION_SHORT_ID>")`. Empty output → reply "Great, everything's set." and STATE DONE. Non-empty → emit "Saving your changes — this can take a moment." and enter STATE PD-MIG-DEV. |+| Satisfied (button label or free text: "yes", "perfect", "looks good"…) | (Dispatch the Mode-2 documentator above first.) Run `Bash("node \"$CLAUDE_PROJECT_DIR/.claude/scripts/pending-deploys.mjs\" --app $CLAUDE_PROJECT_DIR --session <SESSION_SHORT_ID>")`. Empty output **with exit 0** → reply "Great, everything's set." and STATE DONE. **Non-zero exit → UNDETERMINED; do NOT claim done — surface the error.** Non-empty → emit "Saving your changes — this can take a moment." and enter STATE PD-MIG-DEV. || Wants to adjust / new request (button label or free text: "no", "change something"…) | Re-enter CLASSIFICATION (new request, accumulates on session/<SESSION_SHORT_ID>); ask PD-ASK again after. || Ambiguous | Re-ask the open question once; stay in PD-RESPOND. |@@ -865,7 +866,7 @@ Agent({### STATE PD-DEPLOY — applyOne line: *"Applying your changes — this can take a moment on first run."*-`Bash("apply-migrations")` (timeout 240000 ms).+`Bash("node \"$CLAUDE_PROJECT_DIR/.claude/scripts/apply-migrations.mjs\"")` (timeout 240000 ms).→ exit 0: demo mode → STATE PD-LIVE-ASK; full mode → STATE PD-DONE ("Your changes are saved."). Non-zero → PD-DONE with a non-technical failure line.### STATE PD-LIVE-ASK — offer to switch the app to real data@@ -930,6 +931,7 @@ Already wraps every successful PD branch with the user-facing reply. After reply## Environment- **MODE:** Read `<mode>demo</mode>` or `<mode>full</mode>` from your own system prompt. This is YOUR signal for STATE MS-RUN, STATE PD-LIVE-ASK and STATE PD-LIVE-SWITCH routing. Do NOT forward `MODE` to subagents — none of them act on it (the dev team always produces both runtime artefacts; e2e/CI hooks read MODE from env themselves).+ **When `<mode>` tag is ABSENT**, the data-mode concept and the `switch-mode` command do not exist here: the MODE-SWITCH classification, STATE MS-RUN, STATE PD-LIVE-ASK and STATE PD-LIVE-SWITCH are all unavailable, never enter them and never call `switch-mode`. Treat STATE PD-DEPLOY (apply-migrations) as the terminal POST-DEV step in that case.- **TICKETS_DIR:** Read `<session_dir>/...</session_dir>` from system prompt. Pass literal absolute path to every agent (e.g. `/chat-service/logs/<uuid>`). Do not use `${session_dir}` syntax.- **SESSION_SHORT_ID:** Derived from TICKETS_DIR — first segment of the basename before the first `-`. Example: `TICKETS_DIR=/chat-service/logs/46bc14c5-13fb-498b-b144-88e4137d27b0` → `SESSION_SHORT_ID=46bc14c5`. Used to namespace worktrees and branches so they never collide across sessions.- **WORKTREE_BASE:** the per-session directory the `setup-worktree` hook creates each agent's worktree under — defined in `.claude/rules/worktree-scope.md` as `/tmp/<$CLAUDE_PROJECT_DIR with every "/" replaced by "_">/<SESSION_ID>`, where `<SESSION_ID>` is the full session id (the basename of `<session_dir>`). Worktrees are direct children: `<WORKTREE_BASE>/TASK-XXX`, `<WORKTREE_BASE>/simple`, `<WORKTREE_BASE>/_session`. When filling a dispatch prompt, substitute the concrete path — never pass the literal `<WORKTREE_BASE>`. The repository itself stays at `$CLAUDE_PROJECT_DIR`, never `/app`.diff --git a/.claude/scripts/apply-migrations.mjs b/.claude/scripts/apply-migrations.mjsnew file mode 100755index 00000000..6f5af43c--- /dev/null+++ b/.claude/scripts/apply-migrations.mjs@@ -0,0 +1,150 @@+#!/usr/bin/env node+// ─────────────────────────────────────────────────────────────+// apply-migrations — Apply committed migrations to the local+// Supabase instance.+//+// Usage:+// node apply-migrations.mjs+//+// Behaviour:+// Migrations are already committed to supabase/migrations/ on+// main (written by the deploy-time migration round and merged+// by the merger) before this script runs. There is nothing to+// promote — this script only applies what is already there.+//+// If Supabase is not running: start it (initial start applies+// every migration in supabase/migrations/).+// If Supabase is already running: run `npx supabase migration up`.+//+// After applying, the PostgREST schema cache is reloaded so+// new columns/tables are visible immediately.+//+// Portability (works on both crm-builder and a bare AtomicCRM checkout):+// APP_DIR — repo root. Defaults to $CLAUDE_PROJECT_DIR, then /app.+// MODE — crm-builder sets demo|full; when unset (AtomicCRM+// standalone) we proceed (treated as full).+// Supabase is driven via the `supabase` CLI, which manages its own+// Docker containers — we do NOT gate on /var/run/docker.sock so the+// same script works wherever the CLI is available (e.g. `make`).+// ─────────────────────────────────────────────────────────────+import { spawnSync } from "node:child_process";+import { mkdirSync } from "node:fs";+import { setTimeout as sleep } from "node:timers/promises";++const APP_DIR = process.env.APP_DIR || process.env.CLAUDE_PROJECT_DIR || "/app";+const MODE = process.env.MODE || "full";++const GREEN = "\x1b[0;32m";+const YELLOW = "\x1b[1;33m";+const RED = "\x1b[0;31m";+const BOLD = "\x1b[1m";+const NC = "\x1b[0m";++const log = (msg) => process.stdout.write(`${msg}\n`);+const err = (msg) => process.stderr.write(`${msg}\n`);++if (MODE === "demo") {+ log(+ `${YELLOW}Demo mode (FakeRest) — no Supabase instance to migrate. Migration files are committed and will be applied on deploy.${NC}`,+ );+ process.exit(0);+}++process.chdir(APP_DIR);+mkdirSync("supabase/migrations", { recursive: true });++// Run a command, capturing combined stdout+stderr as text.+function run(cmd, args) {+ const res = spawnSync(cmd, args, { encoding: "utf8" });+ const out = (res.stdout || "") + (res.stderr || "");+ return { out, code: res.status ?? (res.error ? 1 : 0) };+}++async function isSupabaseUp() {+ try {+ await fetch("http://localhost:54321", {+ signal: AbortSignal.timeout(2000),+ });+ return true;+ } catch {+ return false;+ }+}++function reloadSchemaCache() {+ const { code } = run("npx", [+ "supabase",+ "db",+ "execute",+ "--sql",+ "SELECT pg_notify('pgrst', 'reload schema');",+ ]);+ if (code === 0) {+ log(`${GREEN}PostgREST schema cache reloaded.${NC}`);+ } else {+ log(`${YELLOW}Could not reload PostgREST schema cache (non-fatal).${NC}`);+ }+}++if (await isSupabaseUp()) {+ // ── Apply migrations to running Supabase ──+ log(`${BOLD}Applying pending migrations to running Supabase...${NC}`);+ let { out, code } = run("npx", ["supabase", "migration", "up"]);++ if (code !== 0) {+ // Auto-repair phantom versions that are recorded in Supabase but absent from+ // the local migrations/ directory (happens when a prior session's worktree was+ // cleaned up after applying the migration but before it landed in git).+ if (+ out.includes(+ "Remote migration versions not found in local migrations directory",+ )+ ) {+ const phantomVersions = [...new Set(out.match(/\d{14}/g) ?? [])];+ if (phantomVersions.length > 0) {+ log(+ `${YELLOW}Auto-repairing phantom migration versions: ${phantomVersions.join(" ")}${NC}`,+ );+ run("npx", [+ "supabase",+ "migration",+ "repair",+ "--status",+ "reverted",+ ...phantomVersions,+ ]);+ ({ out, code } = run("npx", ["supabase", "migration", "up"]));+ }+ }+ if (code !== 0) {+ err(out);+ err(`${RED}Migration up failed.${NC}`);+ process.exit(1);+ }+ }+ log(`${GREEN}Migrations applied.${NC}`);+ reloadSchemaCache();+} else {+ // ── Initial start applies all migrations ──+ log(+ `${BOLD}Starting Supabase (initial start applies all migrations)...${NC}`,+ );+ log(`${YELLOW}First run can take up to ~2 min to pull images.${NC}`);+ const { out } = run("npx", ["supabase", "start"]);+ for (const line of out.split("\n")) {+ if (/✓|✗|Error|Started|API URL/.test(line)) log(line);+ }++ log(`${BOLD}Waiting for Supabase API (localhost:54321)...${NC}`);+ let retries = 120;+ while (!(await isSupabaseUp())) {+ retries -= 1;+ if (retries <= 0) {+ err(`${RED}Supabase did not respond after 120s.${NC}`);+ process.exit(1);+ }+ await sleep(1000);+ }+ log(`${GREEN}Supabase ready and all migrations applied.${NC}`);+ reloadSchemaCache();+}diff --git a/.claude/scripts/pending-deploys.mjs b/.claude/scripts/pending-deploys.mjsnew file mode 100755index 00000000..ab4fa18d--- /dev/null+++ b/.claude/scripts/pending-deploys.mjs@@ -0,0 +1,109 @@+#!/usr/bin/env node+// pending-deploys — decide whether the session has schema-relevant changes+// not yet covered by supabase/migrations/.+//+// pending-deploys --app <APP_DIR> --session <SESSION_SHORT>+//+// Prints a non-empty marker (the changed schema-relevant paths) when a deploy+// is worth offering; prints nothing otherwise.+//+// Exit codes:+// 0 — decision made (stdout empty = nothing to deploy, non-empty = paths).+// 3 — could NOT decide: the passed <SESSION_SHORT> has no session refs.+import { execFileSync } from "node:child_process";++const args = process.argv.slice(2);+const get = (flag, def) => {+ const i = args.indexOf(flag);+ return i >= 0 ? args[i + 1] : def;+};+const APP = get("--app", process.env.CLAUDE_PROJECT_DIR || "/app");+const SESSION = get("--session", "");+if (!SESSION) {+ process.stderr.write("--session <SESSION_SHORT> required\n");+ process.exit(0);+}++const refExists = (ref) => {+ try {+ execFileSync("git", ["-C", APP, "show-ref", "--verify", "--quiet", ref], {+ stdio: "ignore",+ });+ return true;+ } catch {+ return false;+ }+};++// Guard against the SESSION_SHORT_ID mismatch. The session topology+// (session-base/<id> + session/<id>) is created at session start, so missing+// refs for the requested id are suspicious. Distinguish two cases:+// - NO session-base/* branch exists at all → no topology (e.g. hooks never+// ran, or a non-session context) → genuinely nothing to deploy → exit 0.+// - session-base/* branches exist but NOT for <SESSION> → the caller passed+// the wrong short id → fail loudly so the deploy isn't silently skipped.+if (+ !refExists(`refs/heads/session-base/${SESSION}`) ||+ !refExists(`refs/heads/session/${SESSION}`)+) {+ let bases = "";+ try {+ bases = execFileSync(+ "git",+ [+ "-C",+ APP,+ "for-each-ref",+ "--format=%(refname:short)",+ "refs/heads/session-base/",+ ],+ { stdio: ["pipe", "pipe", "pipe"] },+ )+ .toString()+ .trim();+ } catch {+ /* not a git repo / no refs — treated as no topology below */+ }+ if (bases) {+ process.stderr.write(+ `pending-deploys: no session refs for '${SESSION}', but found: ${bases.split("\n").join(", ")}. ` ++ `Likely a SESSION_SHORT_ID mismatch — refusing to report "nothing to deploy".\n`,+ );+ process.exit(3);+ }+ process.exit(0); // no session topology anywhere → nothing to deploy+}++// Schema-relevant path heuristic: entity types, fake-data generators, resource+// registrations, and SQL schema files modified by simple-developer.+// Anchored to avoid matching arbitrary paths with "fake" substrings.+const SCHEMA_RE =+ /(\/types?\.ts$|dataProvider|\/dataGenerator\/|supabase\/schemas\/|resources?\/.*\.(ts|tsx)$)/i;++let changed = "";+try {+ changed = execFileSync(+ "git",+ [+ "-C",+ APP,+ "diff",+ "--name-only",+ `session-base/${SESSION}..session/${SESSION}`,+ ],+ { stdio: ["pipe", "pipe", "pipe"] },+ ).toString();+} catch (e) {+ process.stderr.write(+ `pending-deploys: git diff failed for '${SESSION}': ${e.message}\n`,+ );+ process.exit(3);+}++const relevant = changed+ .split("\n")+ .filter(Boolean)+ .filter((p) => SCHEMA_RE.test(p));+// (Idempotency against already-applied schema is enforced later by the+// migration round, which cross-checks supabase/migrations/ and may no-op.)+if (relevant.length) process.stdout.write(`${relevant.join("\n")}\n`);diff --git a/.claude/scripts/test/pending-deploys.test.mjs b/.claude/scripts/test/pending-deploys.test.mjsnew file mode 100644index 00000000..e35cc145--- /dev/null+++ b/.claude/scripts/test/pending-deploys.test.mjs@@ -0,0 +1,111 @@+// Tests for .claude/scripts/pending-deploys.mjs — decides whether a session has+// schema-relevant changes worth a migration round.+import { describe, test, expect } from "vitest";+import { execFileSync } from "node:child_process";+import { mkdtempSync, writeFileSync, mkdirSync, rmSync } from "node:fs";+import { tmpdir } from "node:os";+import { join } from "node:path";++const SCRIPT = new URL("../pending-deploys.mjs", import.meta.url).pathname;++function git(cwd, ...args) {+ return execFileSync("git", args, { cwd }).toString();+}++function setupRepo() {+ const dir = mkdtempSync(join(tmpdir(), "pd-"));+ git(dir, "init", "-q", "-b", "main");+ git(dir, "config", "user.email", "[email protected]");+ git(dir, "config", "user.name", "t");+ mkdirSync(join(dir, "src"), { recursive: true });+ mkdirSync(join(dir, "supabase/migrations"), { recursive: true });+ writeFileSync(+ join(dir, "src/types.ts"),+ "export type Contact = { id: string };\n",+ );+ git(dir, "add", ".");+ git(dir, "commit", "-qm", "seed");+ git(dir, "branch", "session-base/ab12cd34", "main");+ git(dir, "branch", "session/ab12cd34", "main");+ return dir;+}++describe("pending-deploys", () => {+ test("empty when session branch made no schema-relevant change", () => {+ const dir = setupRepo();+ const out = execFileSync("node", [+ SCRIPT,+ "--app",+ dir,+ "--session",+ "ab12cd34",+ ])+ .toString()+ .trim();+ expect(out).toBe("");+ rmSync(dir, { recursive: true, force: true });+ });++ test("non-empty when the session branch adds an entity field", () => {+ const dir = setupRepo();+ git(dir, "checkout", "-q", "session/ab12cd34");+ writeFileSync(+ join(dir, "src/types.ts"),+ "export type Contact = { id: string; priority: number };\n",+ );+ git(dir, "add", ".");+ git(dir, "commit", "-qm", "add priority");+ git(dir, "checkout", "-q", "main");+ const out = execFileSync("node", [+ SCRIPT,+ "--app",+ dir,+ "--session",+ "ab12cd34",+ ])+ .toString()+ .trim();+ expect(out).not.toBe("");+ rmSync(dir, { recursive: true, force: true });+ });++ test("empty and exit 0 when NO session topology exists at all (hooks never ran)", () => {+ const dir = mkdtempSync(join(tmpdir(), "pd-"));+ git(dir, "init", "-q", "-b", "main");+ git(dir, "config", "user.email", "[email protected]");+ git(dir, "config", "user.name", "t");+ writeFileSync(join(dir, "x.ts"), "export const x = 1;\n");+ git(dir, "add", ".");+ git(dir, "commit", "-qm", "seed");+ // No session-base/* branches at all.+ const out = execFileSync("node", [+ SCRIPT,+ "--app",+ dir,+ "--session",+ "xx99yy00",+ ])+ .toString()+ .trim();+ expect(out).toBe("");+ rmSync(dir, { recursive: true, force: true });+ });++ test("fails loudly (exit 3 + stderr) on SESSION_SHORT_ID mismatch", () => {+ const dir = setupRepo(); // creates session-base/ab12cd34 + session/ab12cd34+ let code = 0,+ stderr = "";+ try {+ execFileSync("node", [SCRIPT, "--app", dir, "--session", "xx99yy00"], {+ encoding: "utf8",+ stdio: ["pipe", "pipe", "pipe"],+ });+ } catch (e) {+ code = e.status;+ stderr = (e.stderr || "").toString();+ }+ expect(code).toBe(3);+ expect(stderr).toMatch(/mismatch/i);+ rmSync(dir, { recursive: true, force: true });+ });+});