Skip to content

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

feat(harness): Phase B pluggable Supabase deploy adapter

Jeromed6d38a036d0c
diff --git a/.claude/adapters/supabase/README.md b/.claude/adapters/supabase/README.md
new file mode 100644
index 00000000..bde8584c
--- /dev/null
+++ b/.claude/adapters/supabase/README.md
@@ -0,0 +1,31 @@
+# Supabase deploy adapter
+
+This adapter provides the harness's optional **deploy phase**: the deploy-time SQL
+migration round (STATE PD-* in the orchestrator). It is a pluggable capability
+under the optionality model (see `adr/harness-action-plan.md`):
+
+- The phase exists **iff** `harness.config.json` has a `deploy` block whose
+ `adapter` is `supabase`. Remove that block and a schema-free feature runs end
+ to end with no PD state and no migration mention (the orchestrator terminates
+ at promotion; `pending-deploys.mjs` short-circuits to "nothing to deploy").
+- What the adapter provides is declared in `manifest.json`: the detection script,
+ the generate skill, the apply script, the review mode, the write-guard hook, and
+ the e2e-smoke script.
+
+## Deploy-relevance
+
+`config.deploy.relevantGlobs` (`supabase/**`) is the single definition of a
+deploy-relevant path, shared by `pending-deploys.mjs`, the orchestrator's
+SIMPLE-review gate, and the planner's schema wording. A real migration always
+requires a change under these globs (that is where the declarative DDL lives, and
+`supabase db diff` only fires on it), so the globs are both necessary and
+sufficient to decide whether to offer the migration round.
+
+## File locations (Phase B)
+
+The adapter's files still live at their discoverable locations
+(`.claude/skills/writing-migrations`, `.claude/scripts/*`, `.claude/hooks/block-migration-writes.mjs`)
+because Claude Code discovers skills only under `.claude/skills/`. `manifest.json`
+declares the boundary by pointing at them. The physical relocation under this
+directory happens in Phase C (TC.1), together with the renderer's symlink
+mechanism that keeps the skill discoverable after the move.
diff --git a/.claude/adapters/supabase/manifest.json b/.claude/adapters/supabase/manifest.json
new file mode 100644
index 00000000..8c83b2fd
--- /dev/null
+++ b/.claude/adapters/supabase/manifest.json
@@ -0,0 +1,30 @@
+{
+ "adapter": "supabase",
+ "provides": "deploy",
+ "description": "Supabase deploy adapter: the deploy-time SQL migration round. Active iff harness.config.json has a `deploy` block with adapter=supabase.",
+ "detection": {
+ "relevantGlobsFrom": "harness.config.json:deploy.relevantGlobs",
+ "pendingDeploysScript": ".claude/scripts/pending-deploys.mjs"
+ },
+ "generate": {
+ "skill": "writing-migrations",
+ "note": "developer-dispatched skill that generates SQL under supabase/migrations/ from the session-branch schema diff"
+ },
+ "apply": {
+ "script": ".claude/scripts/apply-migrations.mjs"
+ },
+ "review": {
+ "mode": "migration-review",
+ "agent": "quality-reviewer",
+ "note": "single-shot migration-review mode gates the generated SQL before merge"
+ },
+ "writeGuard": {
+ "hook": ".claude/hooks/block-migration-writes.mjs",
+ "note": "blocks migration SQL writes outside the deploy-time round"
+ },
+ "e2eSmoke": {
+ "script": ".claude/scripts/e2e-smoke.sh"
+ },
+ "locations": "in-place",
+ "note": "Files are referenced at their current discoverable locations (.claude/skills, .claude/scripts, .claude/hooks). The physical relocation under adapters/supabase/ happens in Phase C (TC.1), which also gives the renderer the symlink mechanism that keeps the skill discoverable. This manifest is the adapter-boundary declaration in the meantime."
+}
diff --git a/.claude/agents/developer.md b/.claude/agents/developer.md
index 9d6f9b97..def5abb7 100644
--- a/.claude/agents/developer.md
+++ b/.claude/agents/developer.md
@@ -71,6 +71,12 @@ Your very last line of output MUST be exactly one of:
- `DONE: branch=<BRANCH_NAME> commit=<short_sha> files=[<comma-separated modified paths, relative to repo root>]`
- `FAILED: <one-line reason>`
+Optionally, on the single line IMMEDIATELY BEFORE that final line, you may emit one hesitation:
+
+- `HESITATIONS: <one line: the riskiest spot in this diff, or a decision you were unsure about>`
+
+Omit it when you have none. The contract line always stays LAST (the orchestrator parses it by regex); the reviewer reads `HESITATIONS` to prioritize where a human should look.
+
Nothing else after the contract line — no pleasantries, no markdown trailer.
The orchestrator parses this line by regex. Any other format is treated as `FAILED`.
@@ -252,8 +258,8 @@ Implement the plan. Stick to ticket scope.
- Atomic commits per logical step. Every subject includes `TASK-XXX`: `feat(TASK-XXX): <what>`.
- TypeScript strict: no `any`, no `@ts-ignore` without JSDoc.
- JSDoc on every non-trivial exported function.
-- No features outside ticket scope.
+- No features outside ticket scope. An adjacent problem you notice (a nearby bug, a tempting refactor) is REPORTED in your final message, never fixed silently in this diff (`coding-style.md` scope discipline).
- e2e tests in `e2e/` if ticket touches UI/filters/forms/interactions, unless acceptance criteria say otherwise. Call `Skill({skill: "e2e-conventions"})` and `Skill({skill: "playwright-testing"})` before writing e2e tests. Don't run them — ship the spec, CI executes.
- Silent mode: Playwright `--headless`, Vite without `--open`, Vitest without `browser.ui`.
-- **Self-verification in the browser (optional, before commit).** When a change is behavior-visible and you want to confirm it renders before handing off to review, drive it via the Playwright MCP against a demo-mode server you start **inside your own worktree** (never `$REPO`): `cd <WORKTREE_PATH> && npm run dev:demo -- --port <PORT> --strictPort` (run in background; pick a port unique to this task, e.g. `5300` + the TASK number). Demo mode is FakeRest + auto-authenticated (no Supabase, no login); the app uses hash routing, so navigate to `http://localhost:<PORT>/#/<route>`. Prefer `browser_snapshot` (accessibility tree, token-cheap) over `browser_take_screenshot` (reserve pixels for visual/legibility checks). **Always tear down** — `browser_close` and kill the server — before you stop, or the SubagentStop validation chain stalls. This is for your own confidence; the quality-reviewer re-verifies in its Part C. It does **not** replace the required e2e spec.
+- **Self-verification in the browser (optional, before commit).** When a change is behavior-visible and you want to confirm it renders before handing off to review, drive it via the Playwright MCP against a demo-mode server you start **inside your own worktree** (never `$REPO`). The launch command and port base come from `config.app` (`smokeCommand` + `portBase`, currently `npm run dev:demo` and `5300`): `cd <WORKTREE_PATH> && npm run dev:demo -- --port <PORT> --strictPort` (run in background; pick a port unique to this task, e.g. `5300` + the TASK number). Demo mode is FakeRest + auto-authenticated (no Supabase, no login); with `config.app.hashRouting` the app uses hash routing, so navigate to `http://localhost:<PORT>/#/<route>`. Prefer `browser_snapshot` (accessibility tree, token-cheap) over `browser_take_screenshot` (reserve pixels for visual/legibility checks). **Always tear down** — `browser_close` and kill the server — before you stop, or the SubagentStop validation chain stalls. This is for your own confidence; the quality-reviewer re-verifies in its Part C. It does **not** replace the required e2e spec.
- Architecture Decision Records: load `Skill({skill: "adr-writing"})` only when the change introduces a structural decision (see WORKFLOW step 3). Skip by default.
diff --git a/.claude/agents/orchestrator.md b/.claude/agents/orchestrator.md
index 1e528fda..0aa7ddc7 100644
--- a/.claude/agents/orchestrator.md
+++ b/.claude/agents/orchestrator.md
@@ -88,7 +88,7 @@ SIMPLE: S-DEV (turn N) → (S-REVIEW if diff touched supabase/ → BLOCKED?
COMPLEX: STATE A (turn N) → STATE B (same turn: Stage 1 develop → Stage 2 review → Stage 3 merge, per wave,
all foreground; then promotion to the base branch) → (POST-DEV) → STATE DONE
-POST-DEV (end of COMPLEX, SETUP, schema-touching SIMPLE), conditional on a schema-relevant diff:
+POST-DEV runs ONLY if the project configures a deploy adapter (`config.deploy` in `harness.config.json`). With no deploy adapter, `pending-deploys.mjs` returns empty for every run, so each flow terminates at promotion / STATE DONE with NO PD state and no migration mention (the pluggable deploy phase, TB.1). When configured, it is (end of COMPLEX, SETUP, schema-touching SIMPLE), conditional on a deploy-relevant diff:
PD-ASK (turn N, then END the turn) → resume one of two ways:
• chat surface: user's own next message → PD-RESPOND (turn N+1)
• dev surface: coordinator re-dispatches you FRESH —
@@ -257,16 +257,16 @@ Agent({
One progress line, e.g. *"Working on it..."* **End this turn.** SubagentStop hooks run validation automatically.
-→ Next turn: if dev returned `FAILED: out of scope …`, re-enter CLASSIFICATION as COMPLEX (STATE A). Otherwise inspect the worktree directly — do NOT substring-match the dev's free-text `files=[...]`:
+→ Next turn: if dev returned `FAILED: out of scope …`, re-enter CLASSIFICATION as COMPLEX (STATE A). Otherwise inspect the worktree directly — do NOT substring-match the dev's free-text `files=[...]`. Grep for **deploy-relevant paths** (`config.deploy.relevantGlobs`, currently `^supabase/`; the same single definition `pending-deploys.mjs` uses). A project with no deploy adapter has none of these paths, so the grep is empty and the schema review is naturally skipped:
```
Bash("cd <WORKTREE_BASE>/simple && git diff --name-only session-base/<SESSION_SHORT_ID>..HEAD | grep -E '^supabase/' || true")
```
-- Non-empty (`supabase/` paths) → STATE S-REVIEW.
+- Non-empty (deploy-relevant paths) → STATE S-REVIEW.
- Empty → STATE S-MERGE.
### STATE S-REVIEW — SIMPLE: dispatch quality-reviewer (conditional, next turn)
-Only when the diff touched `supabase/` (schema, view, RLS) — the hooks can't judge schema-shape or injection risk.
+Only when the diff touched deploy-relevant paths (`config.deploy.relevantGlobs`, e.g. `supabase/` schema, view, RLS) — the hooks can't judge schema-shape or injection risk.
1. If dev returned `FAILED:` → skip review, go to S-DONE with failure.
2. Dispatch ONE `quality-reviewer`:
@@ -402,6 +402,19 @@ When all developers return, parse each last line:
If an `Agent` dispatch *call itself* errors, mark that ticket `{stage: "FAILED", failure_reason: "dispatch error: <message>"}` and keep the others — one dispatch failure never hangs the wave. Same for reviewer/merger dispatch errors.
+#### Stage 1b: TEST-WRITER (conditional, OFF by default)
+
+Only for a ticket that reached `REVIEW` **and** whose ticket JSON has `"separate_test_writer": true` (the planner sets this only on structural / high-risk tickets). Every other ticket skips this stage, so the default path is unchanged. Dispatch runs BEFORE that ticket's Stage 2 review, FOREGROUND, on the developer's OWN worktree (batch all flagged tickets into one message — separate worktrees):
+```
+Agent({
+ subagent_type: "test-writer",
+ description: "Strengthen tests for TASK-XXX",
+ prompt: "ROLE: test-writer\nTASK_ID: TASK-XXX\nTICKET_FILE: <TICKETS_DIR>/TASK-XXX.json\nWORKTREE_PATH: <WORKTREE_BASE>/TASK-XXX\nBRANCH_NAME: <SESSION_SHORT_ID>/TASK-XXX",
+ run_in_background: false
+})
+```
+The `TASK_ID` + `WORKTREE_PATH` lines let the SubagentStop validation chain scope to this worktree (its committed tests are typechecked + run, same as the developer's). Parse the last line: `DONE: …` → proceed to Stage 2 review as usual. `FAILED: <reason>` → do NOT silently absorb it (it usually means the new tests exposed a real bug, or the ticket needs an app-code change the test-writer may not make): feed the reason to the developer as a Stage-2-style retry (`RETRY_FEEDBACK=<the test-writer's FAILED reason>`), re-develop, then re-run the test-writer, before review.
+
#### Stage 2 — REVIEW + bounded retry (concurrent reviews, looped)
For every ticket in `REVIEW`, dispatch the quality-reviewer in the foreground. Batch all review-ready tickets into ONE message (reviewers are read-only on separate worktrees):
@@ -462,7 +475,7 @@ Agent({
run_in_background: false
})
```
-- `APPROVED` → forward any non-blocking notes (nits, ponytail `net: -N`) to the final report; proceed to promotion.
+- `APPROVED` → forward any non-blocking notes (nits, ponytail `net: -N`) to the final report; proceed to promotion. **`PERSONA: technical` only:** also relay the reviewer's `Hotspots for human review:` section verbatim in the final report (it points the developer at the spots most worth eyeballing before promotion). Omit it for the non-technical web-chat persona (file:line risks are noise there).
- `BLOCKED:` <imperative findings> → fix them on the shared `<SESSION_SHORT_ID>/simple` worktree, which `setup-worktree` forks from the session branch (so the fix lands on top of the merged work). Do NOT invent a `featurefix` branch: `setup-worktree` / `enforce-dev-dispatch` only recognize `TASK-XXX` and `<SESSION_SHORT_ID>/simple`, so a bespoke branch is rejected (fail-closed) and the fix cannot get a worktree. Dispatch ONE `developer` with the SIMPLE template: `CHANGE_REQUEST` = the findings verbatim, `BRANCH_NAME: <SESSION_SHORT_ID>/simple`, `WORKTREE_PATH: <WORKTREE_BASE>/simple`, `run_in_background: false`. Then merge it into `session/<SESSION_SHORT_ID>` with a SIMPLE-mode merger carrying `STAGE: a-only` (Stage A only, no promotion), and re-run feature-review. **Bound to 2 rounds**: if still `BLOCKED` after 2, report the remaining findings in the handoff and proceed anyway (never wedge the pipeline on review). `#technical-harness` runs feature-review before its stop (no promotion after).
#### Feature-smoke (does it actually run? audit D5)
diff --git a/.claude/agents/planner.md b/.claude/agents/planner.md
index 1b0f9c59..a0ce34c1 100644
--- a/.claude/agents/planner.md
+++ b/.claude/agents/planner.md
@@ -90,6 +90,7 @@ Rules:
"parallel_safe": true,
"branch_name": "TASK-001-company-importance-type",
"visual_customization": false,
+ "separate_test_writer": false,
"status": "pending"
}
```
@@ -112,6 +113,8 @@ Normal feature tickets (type / component / config prop) → `parallel_safe: true
**`visual_customization`**: set `true` when the ticket touches colors, theme, component styling, dark/light mode, or layout preferences. The developer loads `Skill({skill: "shadcn-customization"})` as its first action on such tickets.
+**`separate_test_writer`** (default `false`): set `true` ONLY on a structural or high-risk ticket (`risk_level: "high"`, auth/RLS, migrations, money, data deletion, a widely-reused shared module) where an independent test author adds value. When set, the orchestrator dispatches a dedicated `test-writer` on the developer's worktree between implementation and review. Leave `false` for ordinary tickets: the extra pass is not free and most tickets do not need it.
+
### Dependency rules
- B uses a type/hook/component from A → `B.dependencies = ["A"]`.
@@ -213,9 +216,13 @@ Default to one combined ticket (types + fake data) for field additions on existi
### Banned acceptance criteria — NEVER WRITE THESE
-Migrations are generated at deploy time, not during feature tickets. Any AC that
-implies the developer must write a migration is a bug that produces a 7+ min
-reviewer-arbitration loop (observed in session 3f810745). NEVER write:
+Deploy-relevant schema files (the `config.deploy` adapter's source of truth, e.g.
+`supabase/schemas/` for the Supabase adapter) are edited by feature tickets;
+deploy artifacts (migrations) are generated at deploy time, not during tickets. A
+project with no deploy adapter has no such distinction, so this whole section is
+inert there. For the Supabase adapter: any AC that implies the developer must
+write a migration is a bug that produces a 7+ min reviewer-arbitration loop
+(observed in session 3f810745). NEVER write:
- *"A Supabase migration is generated"* / *"… is applied locally"* / *"… is committed"*
- *"Run `supabase db diff`"* / *"Run `npx supabase migration up`"*
diff --git a/.claude/agents/quality-reviewer.md b/.claude/agents/quality-reviewer.md
index 70d75115..48d2af41 100644
--- a/.claude/agents/quality-reviewer.md
+++ b/.claude/agents/quality-reviewer.md
@@ -78,10 +78,20 @@ Discipline (keep signal high, noise low):
cross-ticket over-engineering (duplicated helpers, etc.). Its findings are ALWAYS non-blocking
(report only), never a fix trigger.
+**Hotspots for human review (required section, ABOVE the contract line).** Regardless of the
+verdict, compile a `Hotspots for human review:` section that targets a human's attention where a
+mistake would be most costly. Rules:
+- 1 to 5 entries, hard cap at 5. Each is `file:line - one sentence naming the concrete risk`.
+- Prioritize any `HESITATIONS:` the developers flagged, then irreversible / high-blast-radius spots
+ (auth, RLS, migrations, money, data deletion, shared config).
+- These are NOT findings to fix: a hotspot can coexist with `APPROVED`. Never list linter-style
+ items (style, naming, things the hooks already catch).
+- `Hotspots for human review: none identified` is a valid, complete section.
+
OUTPUT CONTRACT (text, no `SendMessage`), last line exactly one of:
- `APPROVED`: no imperative findings. Put any non-blocking notes (nits, cleanliness, ponytail
- `net: -N lines`) ABOVE the line; the orchestrator forwards them to the handoff report and does
- not act on them.
+ `net: -N lines`) and the Hotspots section ABOVE the line; the orchestrator forwards them to the
+ handoff report and does not act on them.
- `BLOCKED:` followed by a bulleted list of the IMPERATIVE findings ONLY, one per line, each
`file:line - failure scenario - what to change`. The orchestrator dispatches a fix for these,
then re-runs you.
@@ -420,9 +430,11 @@ that CI will cover it. Do NOT run `npx playwright install`.
interactively via the Playwright MCP against a demo-mode server you start inside
**your own worktree** (never `$REPO` — that serves the wrong branch):
-1. **Start the server (background, from the worktree).** Pick a port unique to
- this task to avoid collisions with parallel reviewers — `5300` + the TASK
- number (e.g. TASK-006 → `5306`):
+1. **Start the server (background, from the worktree).** The launch command and
+ port base come from `config.app` (`smokeCommand` + `portBase`, currently
+ `npm run dev:demo` and `5300`). Pick a port unique to this task to avoid
+ collisions with parallel reviewers: `config.app.portBase` + the TASK number
+ (e.g. TASK-006 → `5306`):
```bash
cd <WORKTREE_PATH> && npm run dev:demo -- --port <PORT> --strictPort
```
diff --git a/.claude/scripts/e2e-smoke.sh b/.claude/scripts/e2e-smoke.sh
index 4a0b13e9..848becff 100755
--- a/.claude/scripts/e2e-smoke.sh
+++ b/.claude/scripts/e2e-smoke.sh
@@ -109,6 +109,38 @@ export VITE_SUPABASE_URL="http://127.0.0.1:$api_port"
export VITE_SUPABASE_ANON_KEY="$ANON_KEY"
export SERVICE_ROLE_KEY
+# --- P-001: materialize the session schema the deploy-time migration will carry -
+# Ticket developers never write migrations, so a schema-touching session has
+# supabase/schemas/ ahead of supabase/migrations/. The CLI builds the DB from
+# migrations/ only, so without this the isolated stack lacks the new columns and
+# schema-exercising specs 400 against PostgREST - a false FAIL (P-001). When the
+# session changed supabase/schemas/, generate a THROWAWAY migration from the delta
+# INTO THE WORKDIR (never $SRC) and apply it. Best-effort: on any failure SKIP the
+# leg rather than emit a false FAIL (the real migration lands in the deploy round).
+schema_changed=0
+branch="$(git -C "$SRC" rev-parse --abbrev-ref HEAD 2>/dev/null || echo "")"
+case "$branch" in
+ session/*)
+ base="session-base/${branch#session/}"
+ if git -C "$SRC" rev-parse --verify -q "$base" >/dev/null 2>&1 \
+ && git -C "$SRC" diff --name-only "$base"...HEAD 2>/dev/null | grep -q '^supabase/schemas/'; then
+ schema_changed=1
+ fi
+ ;;
+esac
+if [ "$schema_changed" = "1" ] && [ -d "$workdir/supabase/schemas" ]; then
+ echo "e2e-smoke: session changed supabase/schemas/, materializing a throwaway migration..."
+ if npx supabase db diff --workdir "$workdir" --local -f _e2e_throwaway >"$workroot/dbdiff.log" 2>&1; then
+ if ls "$workdir"/supabase/migrations/*_e2e_throwaway.sql >/dev/null 2>&1; then
+ npx supabase migration up --workdir "$workdir" --local >"$workroot/migup.log" 2>&1 \
+ || { cat "$workroot/migup.log" >&2; skip "schema pending migration round (throwaway apply failed); deferring the Supabase e2e leg to the deploy-time migration."; }
+ fi
+ else
+ cat "$workroot/dbdiff.log" >&2
+ skip "schema pending migration round (throwaway diff failed); deferring the Supabase e2e leg to the deploy-time migration."
+ fi
+fi
+
# --- serve the app (dev server reads env at start, so no per-slot build) ----
( cd "$SRC" && VITE_SUPABASE_URL="$VITE_SUPABASE_URL" npx vite --port "$app_port" --strictPort --mode e2e >"$workroot/app.log" 2>&1 ) &
APP_PID=$!
diff --git a/.claude/scripts/pending-deploys.mjs b/.claude/scripts/pending-deploys.mjs
index 4ccf2b23..26c60d91 100755
--- a/.claude/scripts/pending-deploys.mjs
+++ b/.claude/scripts/pending-deploys.mjs
@@ -1,112 +1,160 @@
#!/usr/bin/env node
-// pending-deploys — decide whether the session has schema-relevant changes
-// not yet covered by supabase/migrations/.
+// pending-deploys: decide whether the session has deploy-relevant changes not
+// yet covered by the migrations dir.
//
// 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.
+// Prints a non-empty marker (the changed deploy-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: --session missing, or the passed <SESSION_SHORT>
+// 0 - decision made (stdout empty = nothing to deploy, non-empty = paths).
+// 3 - could NOT decide: --session missing, or the passed <SESSION_SHORT>
// has session-base siblings but no refs of its own (likely a mismatch).
import { execFileSync } from "node:child_process";
+import {
+ loadConfig,
+ isDeployEnabled,
+ deployGlobs,
+} from "../hooks/lib/config.mjs";
-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) {
- // Couldn't decide — exit 3, never 0 (0 + empty stdout reads as "nothing to
- // deploy", which would silently skip a real pending deploy).
- process.stderr.write("--session <SESSION_SHORT> required\n");
- process.exit(3);
+// Convert a deploy-relevant glob (config.deploy.relevantGlobs) into an anchored
+// regex source. `**/` -> optional dir prefix, `**` -> any, `*` -> non-slash. The
+// git diff paths are repo-relative, so anchor at the start.
+export function globToRegexSource(glob) {
+ const escaped = glob.replace(/[.+^${}()|[\]\\]/g, "\\$&");
+ // Placeholder the glob operators FIRST, expand `*` last, then swap the
+ // placeholders in. Otherwise the `.*` inserted for `**` would be re-mangled by
+ // the single-`*` -> `[^/]*` pass.
+ const body = escaped
+ .replace(/\*\*\//g, "\0DS\0")
+ .replace(/\*\*/g, "\0D\0")
+ .replace(/\*/g, "[^/]*")
+ .replace(/\0DS\0/g, "(?:.*/)?")
+ .replace(/\0D\0/g, ".*");
+ return `^${body}`;
}
-const refExists = (ref) => {
+// The single deploy-relevance matcher, built from config.deploy.relevantGlobs
+// (TB.2: one definition, shared with the orchestrator's SIMPLE-review gate and
+// the planner's schema wording). Empty globs -> matches nothing.
+export function relevanceRegex(globs) {
+ if (!globs.length) return /a^/; // never matches
+ return new RegExp(globs.map(globToRegexSource).join("|"));
+}
+
+function main() {
+ 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", "");
+
+ // Pluggable deploy phase (TB.1): the migration round exists ONLY if this
+ // project configures a deploy adapter. With no config.deploy, there is nothing
+ // to deploy, so exit 0 (empty) and the orchestrator terminates at promotion
+ // with no PD state.
+ let cfg;
try {
- execFileSync("git", ["-C", APP, "show-ref", "--verify", "--quiet", ref], {
- stdio: "ignore",
- });
- return true;
- } catch {
- return false;
+ cfg = loadConfig(APP);
+ } catch (e) {
+ process.stderr.write(`pending-deploys: ${e.message}\n`);
+ process.exit(3);
+ }
+ if (!isDeployEnabled(cfg)) process.exit(0);
+
+ if (!SESSION) {
+ // Couldn't decide - exit 3, never 0 (0 + empty stdout reads as "nothing to
+ // deploy", which would silently skip a real pending deploy).
+ process.stderr.write("--session <SESSION_SHORT> required\n");
+ process.exit(3);
}
-};
-// 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 = "";
+ 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
+ }
+
+ // Deploy-relevance from config.deploy.relevantGlobs (TB.2): one definition of
+ // "deploy-relevant paths", not a hardcoded regex. A real migration requires a
+ // change under these globs (the DDL source of truth), so this is both
+ // necessary and sufficient to decide whether to offer the migration round.
+ const SCHEMA_RE = relevanceRegex(deployGlobs(cfg));
+
+ let changed = "";
try {
- bases = execFileSync(
+ changed = execFileSync(
"git",
[
"-C",
APP,
- "for-each-ref",
- "--format=%(refname:short)",
- "refs/heads/session-base/",
+ "diff",
+ "--name-only",
+ `session-base/${SESSION}..session/${SESSION}`,
],
{ stdio: ["pipe", "pipe", "pipe"] },
- )
- .toString()
- .trim();
- } catch {
- /* not a git repo / no refs — treated as no topology below */
- }
- if (bases) {
+ ).toString();
+ } catch (e) {
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`,
+ `pending-deploys: git diff failed for '${SESSION}': ${e.message}\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 the migrations dir and may no-op.)
+ if (relevant.length) process.stdout.write(`${relevant.join("\n")}\n`);
}
-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`);
+if (import.meta.url === `file://${process.argv[1]}`) main();
diff --git a/.claude/scripts/test/pending-deploys.test.mjs b/.claude/scripts/test/pending-deploys.test.mjs
index 887b069c..9ec49ab0 100644
--- a/.claude/scripts/test/pending-deploys.test.mjs
+++ b/.claude/scripts/test/pending-deploys.test.mjs
@@ -1,10 +1,14 @@
-// Tests for .claude/scripts/pending-deploys.mjs — decides whether a session has
-// schema-relevant changes worth a migration round.
+// Tests for .claude/scripts/pending-deploys.mjs: decides whether a session has
+// deploy-relevant changes worth a migration round. Config-driven (TB.1/TB.2):
+// the round exists iff config.deploy is present, and relevance comes from
+// config.deploy.relevantGlobs (one definition, unified with the orchestrator's
+// SIMPLE-review gate).
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";
+import { globToRegexSource, relevanceRegex } from "../pending-deploys.mjs";
const SCRIPT = new URL("../pending-deploys.mjs", import.meta.url).pathname;
@@ -12,17 +16,28 @@ function git(cwd, ...args) {
return execFileSync("git", args, { cwd }).toString();
}
-function setupRepo() {
+// A repo with a Supabase deploy adapter configured (so the deploy gate is open),
+// a declarative schema file, and the session topology branches.
+function setupRepo({ deploy = true } = {}) {
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/schemas"), { recursive: true });
mkdirSync(join(dir, "supabase/migrations"), { recursive: true });
writeFileSync(
join(dir, "src/types.ts"),
"export type Contact = { id: string };\n",
);
+ writeFileSync(
+ join(dir, "supabase/schemas/01_tables.sql"),
+ "create table contacts (id uuid primary key);\n",
+ );
+ const config = { validation: { steps: [] }, roles: {} };
+ if (deploy)
+ config.deploy = { adapter: "supabase", relevantGlobs: ["supabase/**"] };
+ writeFileSync(join(dir, "harness.config.json"), JSON.stringify(config));
git(dir, "add", ".");
git(dir, "commit", "-qm", "seed");
git(dir, "branch", "session-base/ab12cd34", "main");
@@ -30,23 +45,47 @@ function setupRepo() {
return dir;
}
+const run = (dir, ...args) =>
+ execFileSync("node", [SCRIPT, "--app", dir, ...args])
+ .toString()
+ .trim();
+
+describe("pending-deploys relevance (TB.2)", () => {
+ test("globToRegexSource anchors and expands ** / *", () => {
+ expect(globToRegexSource("supabase/**")).toBe("^supabase/.*");
+ expect(globToRegexSource("**/types.ts")).toBe("^(?:.*/)?types\\.ts");
+ });
+
+ test("relevanceRegex matches configured paths, not others", () => {
+ const re = relevanceRegex(["supabase/**"]);
+ expect(re.test("supabase/schemas/01_tables.sql")).toBe(true);
+ expect(re.test("src/types.ts")).toBe(false);
+ expect(relevanceRegex([]).test("supabase/schemas/x.sql")).toBe(false);
+ });
+});
+
describe("pending-deploys", () => {
- test("empty when session branch made no schema-relevant change", () => {
+ test("empty when session branch made no deploy-relevant change", () => {
const dir = setupRepo();
- const out = execFileSync("node", [
- SCRIPT,
- "--app",
- dir,
- "--session",
- "ab12cd34",
- ])
- .toString()
- .trim();
- expect(out).toBe("");
+ expect(run(dir, "--session", "ab12cd34")).toBe("");
+ rmSync(dir, { recursive: true, force: true });
+ });
+
+ test("non-empty when the session branch changes the declarative schema", () => {
+ const dir = setupRepo();
+ git(dir, "checkout", "-q", "session/ab12cd34");
+ writeFileSync(
+ join(dir, "supabase/schemas/01_tables.sql"),
+ "create table contacts (id uuid primary key, priority int);\n",
+ );
+ git(dir, "add", ".");
+ git(dir, "commit", "-qm", "add priority column");
+ git(dir, "checkout", "-q", "main");
+ expect(run(dir, "--session", "ab12cd34")).not.toBe("");
rmSync(dir, { recursive: true, force: true });
});
- test("non-empty when the session branch adds an entity field", () => {
+ test("a TS-only change (no schema file) is NOT deploy-relevant (unified definition)", () => {
const dir = setupRepo();
git(dir, "checkout", "-q", "session/ab12cd34");
writeFileSync(
@@ -54,18 +93,23 @@ describe("pending-deploys", () => {
"export type Contact = { id: string; priority: number };\n",
);
git(dir, "add", ".");
- git(dir, "commit", "-qm", "add priority");
+ git(dir, "commit", "-qm", "add priority to type only");
+ git(dir, "checkout", "-q", "main");
+ expect(run(dir, "--session", "ab12cd34")).toBe("");
+ rmSync(dir, { recursive: true, force: true });
+ });
+
+ test("no config.deploy -> exit 0 empty (deploy phase not configured, TB.1)", () => {
+ const dir = setupRepo({ deploy: false });
+ git(dir, "checkout", "-q", "session/ab12cd34");
+ writeFileSync(
+ join(dir, "supabase/schemas/01_tables.sql"),
+ "create table contacts (id uuid primary key, x int);\n",
+ );
+ git(dir, "add", ".");
+ git(dir, "commit", "-qm", "schema change but no deploy adapter");
git(dir, "checkout", "-q", "main");
- const out = execFileSync("node", [
- SCRIPT,
- "--app",
- dir,
- "--session",
- "ab12cd34",
- ])
- .toString()
- .trim();
- expect(out).not.toBe("");
+ expect(run(dir, "--session", "ab12cd34")).toBe("");
rmSync(dir, { recursive: true, force: true });
});
@@ -75,19 +119,17 @@ describe("pending-deploys", () => {
git(dir, "config", "user.email", "[email protected]");
git(dir, "config", "user.name", "t");
writeFileSync(join(dir, "x.ts"), "export const x = 1;\n");
+ writeFileSync(
+ join(dir, "harness.config.json"),
+ JSON.stringify({
+ validation: { steps: [] },
+ roles: {},
+ deploy: { adapter: "supabase", relevantGlobs: ["supabase/**"] },
+ }),
+ );
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("");
+ expect(run(dir, "--session", "xx99yy00")).toBe("");
rmSync(dir, { recursive: true, force: true });
});
@@ -110,7 +152,7 @@ describe("pending-deploys", () => {
});
test("fails loudly (exit 3 + stderr) on SESSION_SHORT_ID mismatch", () => {
- const dir = setupRepo(); // creates session-base/ab12cd34 + session/ab12cd34
+ const dir = setupRepo();
let code = 0,
stderr = "";
try {
diff --git a/docs/learnings/patterns.md b/docs/learnings/patterns.md
new file mode 100644
index 00000000..d6c048fc
--- /dev/null
+++ b/docs/learnings/patterns.md
@@ -0,0 +1,50 @@
+# Pattern Ledger
+
+Index of captured patterns (rules, skills, hooks, agents, escalations). See
+`/home/developer/.claude/local/{rules,skills,hooks,agents}/` for artifacts.
+
+## P-001 — Feature-smoke e2e runs before the deploy-time migration exists
+
+- **Status** : resolved (2026-07-17, TB.3 of adr/harness-action-plan.md)
+- **Resolution** : `e2e-smoke.sh` now materializes the session schema before running
+ the suite. When the session changed `supabase/schemas/`, it generates a THROWAWAY
+ migration from the schema delta into the isolated workdir (`npx supabase db diff`)
+ and applies it, so the isolated Postgres has the session's columns. The throwaway
+ never leaves the workdir (no file under `supabase/migrations/`). If diff or apply
+ fails, the Supabase e2e leg is SKIPPED ("schema pending migration round"), never a
+ false FAIL. Detection of "deploy-relevant paths" is unified in
+ `config.deploy.relevantGlobs` (TB.2).
+- **Type** : escalation
+- **Created** : 2026-07-17 (session 2e030b92, TASK-001)
+- **Last updated** : 2026-07-17 (session 2e030b92, TASK-001)
+- **Symptom** : `.claude/scripts/e2e-smoke.sh` fails specs that persist newly-added
+ schema columns through the real Supabase/PostgREST API. In session 2e030b92,
+ `e2e/TASK-001-company-twitter-fax-fields.spec.ts` failed 2/8 tests (new fields not
+ persisting/rendering, plus a secondary Mobile Chrome nav timeout), even though the
+ ticket's own scope was correct (schema files only, no SQL migration, per the harness
+ rule that ticket developers never write migrations).
+- **Trigger** : any COMPLEX ticket that adds/renames columns in `supabase/schemas/*.sql`
+ and ships an e2e spec exercising those columns, run through STATE B's Feature-smoke
+ step (before promotion, before the deploy-time migration round exists).
+- **Why no additive lever** : `e2e-smoke.sh` provisions its isolated stack by copying
+ `supabase/migrations/` (line 80-82) into a throwaway workdir and running
+ `npx supabase start` (line 102); the Supabase CLI builds the actual Postgres schema
+ from `migrations/*.sql` only, it never applies `supabase/schemas/*.sql` directly
+ (`schemas/` is source-of-truth used by `supabase db diff` to GENERATE a migration,
+ not something the CLI reads to build a DB). The harness deliberately defers migration
+ generation to PD-MIG-DEV, after promotion, so that many parallel tickets don't produce
+ conflicting migrations. Any schema-touching ticket therefore hits a real gap: its e2e
+ spec exercises columns the isolated stack's Postgres does not have yet, and the
+ insert/read 400s against PostgREST (unknown column) - a correct failure, not a feature
+ bug. Fixing the sequencing requires either (a) teaching `e2e-smoke.sh` to run
+ `supabase db diff` and apply a throwaway migration before starting the stack, or (b)
+ teaching the orchestrator to skip/defer the Supabase e2e leg for schema-touching diffs
+ until after PD-MIG-MERGE. Both are changes to a base harness script
+ (`.claude/scripts/e2e-smoke.sh`) or an orchestrator state rule
+ (`.claude/agents/orchestrator.md`), out of scope for a documentator/developer/orchestrator
+ to self-apply; a maintainer must decide and implement. Will reproduce on every future
+ schema-touching COMPLEX ticket until fixed, silently wasting an e2e round each time.
+- **Evidence** : session 2e030b92, TASK-001 - `e2e-smoke.sh` exit=1 log shows
+ `getByText('@acmecorp')` not found and a Mobile Chrome `goToCompanies` timeout;
+ confirmed `supabase/migrations/` contains no file touching `twitter_handle`/
+ `fax_number` while `supabase/schemas/01_tables.sql` and `03_views.sql` do.