Skip to content

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

feat(harness): Phase 0 structural wins

Jerome5d546d834579
diff --git a/.claude/agents/test-writer.md b/.claude/agents/test-writer.md
new file mode 100644
index 00000000..833adedd
--- /dev/null
+++ b/.claude/agents/test-writer.md
@@ -0,0 +1,64 @@
+---
+name: test-writer
+description: Optional test-only agent, off by default. Dispatched by the orchestrator (foreground, on the developer's worktree, before review) ONLY when a ticket carries "separate_test_writer": true. Writes or strengthens tests; never touches application code. Validation runs on its stop, same as the developer.
+model: sonnet
+tools:
+ - Read
+ - Write
+ - Edit
+ - Bash
+ - Glob
+ - Grep
+ - Skill
+---
+
+# test-writer
+
+You write or strengthen tests for a ticket a developer has already implemented.
+You NEVER touch application code. If a test fails because of a real bug in the
+code, flag it in your final message and stop; do not fix the code yourself.
+
+Your spawn prompt provides: `TASK_ID`, `WORKTREE_PATH`, `BRANCH_NAME`,
+`TICKET_FILE`. You run on the SAME worktree the developer just used, on top of
+its commits.
+
+## Scope (hard)
+
+- Read/write ONLY inside `<WORKTREE_PATH>` (`.claude/rules/worktree-scope.md`).
+ Every Bash call is prefixed `cd <WORKTREE_PATH> &&`.
+- Write ONLY test files (`*.test.ts`, `*.test.tsx`, `e2e/*.spec.ts`) and their
+ fixtures. Editing any non-test source file is out of scope, emit `FAILED`.
+
+## What to do
+
+1. Read `TICKET_FILE` (its `acceptance_criteria`) and the developer's diff
+ (`git diff session/<SESSION_SHORT_ID>...HEAD`).
+2. Derive tests from the acceptance criteria and real edge cases. Follow
+ `.claude/rules/testing.md`: assert user-observable behavior, not internals;
+ weight toward integration; complete assertions (`toEqual`, not partial
+ `toHaveProperty`). For e2e, load `Skill({skill: "playwright-testing"})` and
+ `Skill({skill: "e2e-conventions"})`.
+3. Commit your test files on `BRANCH_NAME` with `test(TASK-XXX): <what>`.
+
+## Strict prohibitions (from testing.md)
+
+- Never weaken or delete an assertion to make a red test pass. If the tested
+ behavior changed intentionally, say so and adjust; otherwise flag the failure.
+- Never use `.skip` / `.only` to route around a problem instead of flagging it.
+- Never add a `waitForTimeout` to stabilize a flaky test; find the real wait
+ condition (`waitForResponse` / `expect(locator).toBeVisible()`).
+- Never assert on cosmetic detail (CSS classes, non-meaningful DOM), a snapshot
+ as the primary assertion, or that a mock returned its configured value.
+
+## Validation & output
+
+The SubagentStop validation chain (typecheck + prettier + unit + e2e) runs on
+your stop, scoped to your worktree, exactly as it does for the developer. Do NOT
+run it manually (`.claude/rules/validation-commands.md`). If it fails, fix the
+tests and commit again on the next turn.
+
+Your very last line MUST be exactly one of (parsed by the orchestrator):
+
+- `DONE: branch=<BRANCH_NAME> commit=<short_sha> files=[<comma-separated test paths>]`
+- `FAILED: <one-line reason>` (e.g. a real code bug the tests exposed, or the
+ ticket needing an app-code change you are not allowed to make)
diff --git a/.claude/hooks/check-typescript-shortcuts.mjs b/.claude/hooks/check-typescript-shortcuts.mjs
new file mode 100755
index 00000000..2b768e7c
--- /dev/null
+++ b/.claude/hooks/check-typescript-shortcuts.mjs
@@ -0,0 +1,55 @@
+#!/usr/bin/env node
+// PostToolUse(Write|Edit): flag TypeScript typing escape hatches in .ts/.tsx files.
+//
+// Deliberately non-blocking (exit 1, not exit 2): it flags a workaround rather
+// than blocking a write, so a legitimate, justified suppression is never broken.
+// A justified `@ts-expect-error <reason>` on the same line is NOT flagged.
+
+import { readFileSync } from "node:fs";
+import { createHookContext } from "./lib/context.mjs";
+
+let input = {};
+try {
+ input = JSON.parse(readFileSync(0, "utf8"));
+} catch {
+ process.exit(0); // unparseable payload: nothing to flag, fail open
+}
+
+const filePath = input.tool_input?.file_path || "";
+if (!/\.(ts|tsx)$/.test(filePath)) process.exit(0);
+
+let content;
+try {
+ content = readFileSync(filePath, "utf8");
+} catch {
+ process.exit(0); // file gone / unreadable: nothing to flag
+}
+
+const hits = [];
+
+// Blanket escape hatches: any occurrence is a hit.
+if (/\$TSFixMe\b/.test(content)) hits.push("$TSFixMe");
+if (/:\s*any\b/.test(content)) hits.push(": any");
+if (/\bas\s+any\b/.test(content)) hits.push("as any");
+
+// Suppression directives are only a hit when unjustified (no explanation text
+// following the directive on the same line). `@ts-expect-error legacy API` is
+// fine; a bare `@ts-ignore` is not.
+const SUPPRESS = /@ts-(ignore|expect-error)\b[ \t]*(.*)$/gm;
+for (const m of content.matchAll(SUPPRESS)) {
+ const rest = (m[2] || "").replace(/^[\s:.-]+/, "").trim();
+ if (rest.length < 3) {
+ hits.push(`@ts-${m[1]} without justification`);
+ break;
+ }
+}
+
+if (hits.length === 0) process.exit(0);
+
+const ctx = createHookContext(input, "check-typescript-shortcuts");
+ctx.log(`FLAG ${filePath} ${hits.join(", ")}`);
+ctx.error(
+ `${filePath} contains a typing workaround (${[...new Set(hits)].join(", ")}).\n` +
+ `Replace it with the correct type instead of bypassing the typecheck.`,
+);
+process.exit(1);
diff --git a/.claude/hooks/reinject-invariants.mjs b/.claude/hooks/reinject-invariants.mjs
new file mode 100755
index 00000000..23e00753
--- /dev/null
+++ b/.claude/hooks/reinject-invariants.mjs
@@ -0,0 +1,42 @@
+#!/usr/bin/env node
+// PostCompact: re-inject the load-bearing harness invariants after the
+// conversation is compacted, so the coordinating thread does not lose them and
+// resume the duplicate-work / wrong-routing failures they prevent.
+//
+// Injection uses hookSpecificOutput.additionalContext, the same sanctioned path
+// session-bootstrap uses for SessionStart. Fail-open: any error exits 0 (a
+// PostCompact hook must never break the resumed session).
+
+import { readFileSync } from "node:fs";
+
+// A short, dense block: only the invariants a fresh context must not lose.
+// Keep it under ~25 lines.
+const INVARIANTS = [
+ "<harness-invariants> (re-injected after compaction)",
+ "- Worktree scope: each agent reads/writes ONLY its own <WORKTREE_PATH>; never edit $REPO/src directly. Every Bash needs a `cd <WORKTREE_PATH> &&` prefix.",
+ "- Git rights: the developer commits its OWN task branch; only the merger mutates session/base branches; no agent pushes or pulls (the user owns the remote).",
+ "- Launched is NOT done: an `Async agent launched ... agentId` acknowledgement means dispatched, not finished. Wait for the task-notification; do NOT start implementing the same change yourself.",
+ "- While an orchestrator runs: surface progress only; never route or re-implement the change in the main thread (that is the duplicate-work bug).",
+ "- Approvals (migration / plan gate): dispatch a FRESH orchestrator (new Agent call) with the right <intent>; never SendMessage the old one (relayed approvals carry no user authority).",
+ "</harness-invariants>",
+].join("\n");
+
+try {
+ readFileSync(0, "utf8"); // drain stdin; payload content is not needed
+} catch {
+ // no payload is fine; still emit the invariants below
+}
+
+try {
+ process.stdout.write(
+ JSON.stringify({
+ hookSpecificOutput: {
+ hookEventName: "PostCompact",
+ additionalContext: INVARIANTS,
+ },
+ }) + "\n",
+ );
+} catch {
+ // fail-open: never break the resumed session
+}
+process.exit(0);
diff --git a/.claude/hooks/test/check-typescript-shortcuts.test.mjs b/.claude/hooks/test/check-typescript-shortcuts.test.mjs
new file mode 100644
index 00000000..09e17987
--- /dev/null
+++ b/.claude/hooks/test/check-typescript-shortcuts.test.mjs
@@ -0,0 +1,80 @@
+// Tests for check-typescript-shortcuts.mjs, a non-blocking PostToolUse(Write|Edit)
+// flag. It scans the written .ts/.tsx file for typing escape hatches and exits 1
+// (flag, not block) with a stderr warning when it finds one; exit 0 otherwise.
+
+import { mkdtempSync, rmSync, writeFileSync } from "node:fs";
+import { tmpdir } from "node:os";
+import { dirname, join } from "node:path";
+import { fileURLToPath } from "node:url";
+import { spawnSync } from "node:child_process";
+import { afterAll, describe, test, expect } from "vitest";
+
+const HERE = dirname(fileURLToPath(import.meta.url));
+const HOOK = join(HERE, "..", "check-typescript-shortcuts.mjs");
+
+const tmpRoot = mkdtempSync(join(tmpdir(), "ts-shortcuts-"));
+
+afterAll(() => {
+ rmSync(tmpRoot, { recursive: true, force: true });
+});
+
+// Write `source` to a file named `name`, then run the hook against it.
+const runHook = (name, source) => {
+ const filePath = join(tmpRoot, name);
+ writeFileSync(filePath, source);
+ const input = JSON.stringify({
+ tool_name: "Write",
+ session_id: "test-1234",
+ tool_input: { file_path: filePath },
+ });
+ return spawnSync("node", [HOOK], { input, encoding: "utf8" });
+};
+
+const isFlagged = (r) => r.status === 1;
+
+describe("check-typescript-shortcuts hook", () => {
+ describe("typing escape hatches → flagged (exit 1)", () => {
+ const flagged = [
+ ["as-any.ts", "const x = value as any;"],
+ ["colon-any.ts", "let count: any = 0;"],
+ ["tsfixme.ts", "type T = $TSFixMe;"],
+ ["bare-ts-ignore.ts", "// @ts-ignore\nconst y = z.foo;"],
+ ["bare-ts-expect-error.tsx", "// @ts-expect-error\nreturn <div/>;"],
+ ];
+
+ test.each(flagged)("%s → flagged", (name, source) => {
+ const r = runHook(name, source);
+ expect(isFlagged(r)).toBe(true);
+ expect(r.stderr).toMatch(/typing workaround/);
+ });
+ });
+
+ describe("clean or justified code → not flagged (exit 0)", () => {
+ const clean = [
+ ["typed.ts", "const x: number = 1;\nconst s: string = 'ok';"],
+ [
+ "justified.ts",
+ "// @ts-expect-error legacy API returns an untyped payload\nconst y = z.foo;",
+ ],
+ ["anyword.ts", "const anything: string = 'not a match';"],
+ ];
+
+ test.each(clean)("%s → not flagged", (name, source) => {
+ const r = runHook(name, source);
+ expect(r.status).toBe(0);
+ });
+ });
+
+ test("non-TS file → ignored", () => {
+ const r = runHook("notes.md", "this has as any inside prose");
+ expect(r.status).toBe(0);
+ });
+
+ test("unparseable payload → fails open (exit 0)", () => {
+ const r = spawnSync("node", [HOOK], {
+ input: "not json",
+ encoding: "utf8",
+ });
+ expect(r.status).toBe(0);
+ });
+});
diff --git a/.claude/hooks/test/reinject-invariants.test.mjs b/.claude/hooks/test/reinject-invariants.test.mjs
new file mode 100644
index 00000000..14ff3dc1
--- /dev/null
+++ b/.claude/hooks/test/reinject-invariants.test.mjs
@@ -0,0 +1,67 @@
+// Tests for reinject-invariants.mjs, a PostCompact hook that re-injects the
+// load-bearing harness invariants via hookSpecificOutput.additionalContext.
+// It must always exit 0 (fail-open), emit parseable JSON, and stay compact.
+
+import { dirname, join } from "node:path";
+import { fileURLToPath } from "node:url";
+import { spawnSync } from "node:child_process";
+import { describe, test, expect } from "vitest";
+
+const HERE = dirname(fileURLToPath(import.meta.url));
+const HOOK = join(HERE, "..", "reinject-invariants.mjs");
+
+const runHook = (payload) =>
+ spawnSync("node", [HOOK], {
+ input: typeof payload === "string" ? payload : JSON.stringify(payload),
+ encoding: "utf8",
+ });
+
+const parse = (r) => JSON.parse(r.stdout);
+
+describe("reinject-invariants hook", () => {
+ test("emits additionalContext on a PostCompact payload", () => {
+ const r = runHook({
+ hook_event_name: "PostCompact",
+ trigger: "auto",
+ compact_summary: "previous work summary",
+ });
+ expect(r.status).toBe(0);
+ const out = parse(r);
+ expect(out.hookSpecificOutput.hookEventName).toBe("PostCompact");
+ expect(out.hookSpecificOutput.additionalContext).toMatch(
+ /harness-invariants/,
+ );
+ });
+
+ test("injected block covers the load-bearing invariants", () => {
+ const out = parse(
+ runHook({ hook_event_name: "PostCompact", trigger: "manual" }),
+ );
+ const ctx = out.hookSpecificOutput.additionalContext;
+ expect(ctx).toMatch(/Worktree scope/);
+ expect(ctx).toMatch(/Launched is NOT done/);
+ expect(ctx).toMatch(/orchestrator runs/i);
+ expect(ctx).toMatch(/Git rights/);
+ });
+
+ test("injected block stays under 25 lines", () => {
+ const out = parse(
+ runHook({ hook_event_name: "PostCompact", trigger: "auto" }),
+ );
+ const lines = out.hookSpecificOutput.additionalContext.split("\n").length;
+ expect(lines).toBeLessThanOrEqual(25);
+ });
+
+ test("fails open on an unparseable payload (still exit 0, still emits)", () => {
+ const r = runHook("not json at all");
+ expect(r.status).toBe(0);
+ expect(parse(r).hookSpecificOutput.additionalContext).toMatch(
+ /harness-invariants/,
+ );
+ });
+
+ test("fails open on empty stdin", () => {
+ const r = spawnSync("node", [HOOK], { input: "", encoding: "utf8" });
+ expect(r.status).toBe(0);
+ });
+});
diff --git a/.claude/rules/coding-style.md b/.claude/rules/coding-style.md
index f440d66c..4470be62 100644
--- a/.claude/rules/coding-style.md
+++ b/.claude/rules/coding-style.md
@@ -25,6 +25,11 @@ abstractions when repetition is real, not speculative.
YAGNI — do not build features before they are needed. Start simple,
refactor when the pressure is real.
+Scope discipline: implement exactly what the task asks, no more. An
+adjacent problem you notice (a nearby bug, a tempting refactor, missing
+tests elsewhere) is REPORTED, never fixed in the same change. Never expand
+scope silently.
+
## File organization
Many small files over few large files:
diff --git a/.claude/rules/dependency-safety.md b/.claude/rules/dependency-safety.md
new file mode 100644
index 00000000..51483eef
--- /dev/null
+++ b/.claude/rules/dependency-safety.md
@@ -0,0 +1,25 @@
+# Dependency safety
+
+Adding a new package is a supply-chain decision, so agents never do it silently.
+
+## Rule
+
+- New-package installs are denied by permissions (`settings.json` -> `permissions.deny`:
+ `Bash(npm install *)`, `Bash(npm i *)`, `Bash(pnpm add *)`, `Bash(yarn add *)`). A
+ deny is ~100% respected; a CLAUDE.md rule or a post-action warning is not.
+- Bare `npm install` / `pnpm install` / `yarn install` (no package argument, restoring
+ the lockfile) stays allowed: the literal space in the deny glob requires an argument,
+ so an argument-less install is not matched.
+- To add a package, the human validates THAT specific package first: minimum 21 days
+ since publication, healthy download/maintainer count, no open advisory
+ (`npm audit`, Snyk).
+
+## Third-party skills and MCP servers
+
+- Treat a downloaded skill/plugin (marketplace or external repo) like an npm dependency:
+ the same audits apply (they have shipped hardcoded secrets and malicious payloads).
+- Pin an MCP server's version once validated; do not let it auto-update without a fresh
+ human check.
+
+Automatic blocking reduces risk, it does not remove it: a periodic security review is
+still required for anything touching auth, payments, or sensitive data.
diff --git a/.claude/skills/grill-me/SKILL.md b/.claude/skills/grill-me/SKILL.md
new file mode 100644
index 00000000..0c3ccf81
--- /dev/null
+++ b/.claude/skills/grill-me/SKILL.md
@@ -0,0 +1,38 @@
+---
+name: grill-me
+description: Interrogate a vague or broad feature request BEFORE dispatching the harness orchestrator, to surface what the user has not anticipated. Use in the main thread when a #harness request is underspecified, when scope seems broad, or when a plan would come out too generic. Not for the orchestrator (headless, cannot ask).
+---
+
+# grill-me
+
+Ask probing questions about the request before any plan or code, to surface
+what the user has NOT anticipated, not just confirm what they already said.
+
+## How
+
+- **One question at a time**, in prose. Never a multiple-choice menu, never a
+ batch of five at once.
+- Read the answer, then ask the next most valuable question given it.
+- **Stop as soon as the scope is answerable** (roughly: you could write the
+ orchestrator dispatch prompt without guessing). Do not interrogate for its
+ own sake.
+
+## Cover, at minimum
+
+1. **Scope-out**: what is explicitly NOT in scope? What might look included but isn't?
+2. **Edge cases**: empty / invalid input, network or backend error, two users at once.
+3. **Existing interactions**: does this touch behavior already in place (permissions,
+ RLS, cached data, shared views, another resource)?
+4. **Definition of done**: what manual check confirms it works? Who validates before merge?
+5. **Reversibility**: if it turns out wrong, how hard is it to undo?
+
+If the user answers "I don't know" to a structural question, propose an explicit
+hypothesis and ask them to confirm rather than silently choosing.
+
+## After grilling
+
+Fold the answers into the orchestrator dispatch prompt (scope-out and
+acceptance become ticket constraints). Then dispatch the harness as usual.
+
+The orchestrator never invokes this skill: it runs headless and cannot hold an
+interactive back-and-forth. Grilling is a main-thread, pre-dispatch step.
diff --git a/.claude/styles/concise-dev.md b/.claude/styles/concise-dev.md
new file mode 100644
index 00000000..0a3f22db
--- /dev/null
+++ b/.claude/styles/concise-dev.md
@@ -0,0 +1,32 @@
+---
+name: concise-dev
+description: Direct, action-oriented responses for experienced developers who already know the project. Result first, prose only where the code does not speak for itself.
+---
+
+# Style: concise-dev
+
+Respond directly and action-oriented. This style is for daily use by
+experienced developers who already know the project.
+
+## Formatting rules
+
+- Go straight to the result: show the code or diff before explaining, not after.
+- Only explain what is not obvious from reading the code: an architecture
+ decision, a trade-off, a pitfall. Never explain what the code already says.
+- No recap of what was just done when the diff or command output already shows
+ it. Do not repeat in prose what is visible elsewhere in the response.
+- No generic opening or closing filler ("Here's what I did", "Let me know if
+ you have questions"). Go straight to the content.
+- On a review or bug-fix task: mention only points that require action or a
+ decision. Do not list points that are already fine.
+- If the task has an uncertain dimension or a hesitation, say so in one precise
+ sentence. Do not turn it into a list of generic warnings.
+
+## What this style does NOT change
+
+- Templates imposed by a skill (e.g. pr-description) still take priority over
+ this style for their specific scope; this style applies to the rest of the
+ conversation.
+- Security guardrails, clarification questions before an ambiguous task, and
+ explanations the user explicitly requested are never shortened in the name of
+ conciseness.
diff --git a/AGENTS.md b/AGENTS.md
index 8cea9ad8..9b8fb88d 100644
--- a/AGENTS.md
+++ b/AGENTS.md
@@ -190,3 +190,4 @@ Import `test-data/contacts.csv` via the Contacts page → Import button.
- Unit tests can be added in the `src/` directory (test files are named `*.test.ts` or `*.test.tsx`)
- User deletion is not supported to avoid data loss; use account disabling instead
- Filter operators must be supported by the `supabaseAdapter` when using FakeRest
+- Optional terse output for solo work: the `concise-dev` style ships at `.claude/styles/concise-dev.md`. To enable it just for yourself, copy it into `.claude/output-styles/` (or `~/.claude/output-styles/`) and run `/output-style concise-dev`, or set `"outputStyle": "concise-dev"` in your own `.claude/settings.local.json`. It is not enabled in the committed `settings.json`.