Skip to content

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

feat(harness): Phase A config foundation

Jerome6653d516088c
diff --git a/.claude/agents/documentator.md b/.claude/agents/documentator.md
index eb76d6ca..87e40cdf 100644
--- a/.claude/agents/documentator.md
+++ b/.claude/agents/documentator.md
@@ -34,8 +34,8 @@ You do not touch `$CLAUDE_PROJECT_DIR/src/`, `<WORKTREE_BASE>/**`, or anything e
| Source | Path |
|---|---|
| ADRs (developer's structural decisions) | `$CLAUDE_PROJECT_DIR/adr/ADR-*.md` |
-| Hook logs (objective failures) | `/chat-service/logs/<session-id>/hooks.log` |
-| Session logs (retries, friction) | `/chat-service/logs/<session-id>/log.jsonl` |
+| Hook logs (objective failures) | `<launcher logsDir>/<session-id>/hooks.log` (config.launcher.logsDir, e.g. `/chat-service/logs`) |
+| Session logs (retries, friction) | `<launcher logsDir>/<session-id>/log.jsonl` |
| Existing ledger | `$CLAUDE_PROJECT_DIR/docs/learnings/patterns.md` |
| Existing local artifacts | `/home/developer/.claude/local/{rules,skills,hooks,agents}/` |
@@ -56,24 +56,35 @@ Session logs can be large — read targeted ranges with `Read(offset, limit)`, d
6. If you produced a hook, **propose** the `settings.local.json` patch in your stdout report. Do not apply it unless the orchestrator's prompt explicitly tells you to.
7. Print a one-line summary: `Created P-NNN — <type> at <path>` (or `Updated P-NNN`).
-## Mode 2 — Business-knowledge synthesis
+## Mode 2: End-of-session capitalize (write-on-value)
-You operate directly on `$CLAUDE_PROJECT_DIR/` (the base branch), writing **only** `$CLAUDE_PROJECT_DIR/MEMORY.md`. Silence is the default — most sessions add nothing, and that's the expected outcome.
+Silence is the default: most sessions add nothing, and that is the expected, correct outcome. A ledger or a MEMORY.md that grows without discipline is worse than an incomplete one, so never force an artificial addition to look productive.
-1. Enumerate the session diff using the `SESSION_DIFF_BASE` two-dot range from your spawn prompt (`session-base/<short>..session/<short>` — the session's net change, independent of the base branch's name, using local refs so no fetch is needed):
+You may WRITE only `$CLAUDE_PROJECT_DIR/MEMORY.md` (and, for a Mode-1-style capture, the runtime local tree). Everything else in the routing table is a RECOMMENDATION you put in your report for a human to commit, because committed `.claude/` and `adr/` are outside your write scope.
+
+1. Enumerate the session diff using the `SESSION_DIFF_BASE` two-dot range from your spawn prompt (`session-base/<short>..session/<short>`, the session's net change, using local refs so no fetch is needed):
```
Bash("git -C $CLAUDE_PROJECT_DIR diff --stat <SESSION_DIFF_BASE>")
```
2. `Read("$CLAUDE_PROJECT_DIR/MEMORY.md")` to avoid duplicates. Treat as empty if missing.
3. Read the diff's domain-relevant files (types, migrations, dataProvider, resource definitions, entity-naming copy). Skip styling, formatting, infra.
-4. For each candidate fact, skip if: already in MEMORY.md, ephemeral, inferable from code alone, pure refactor/copy. Otherwise insert one bullet under `## Business Knowledge` (freshest first). **One sentence per bullet, hard cap.**
-5. Nothing concrete → exit silently, no Write, no commit. Reply `synthesized: nothing new`.
-6. Otherwise commit (two Bash calls, no chaining):
+4. **Route each candidate learning to its correct home.** Do not funnel everything into MEMORY.md:
+
+ | Learning | Destination | Action |
+ |---|---|---|
+ | Business detail / pitfall specific to THIS project, not inferable from code | `MEMORY.md` (`## Business Knowledge`) | WRITE (one sentence per bullet, freshest first) |
+ | General code convention, transposable to other projects | `.claude/rules/<slug>.md` | RECOMMEND in report (or Mode-1 capture in the local tree) |
+ | Reusable workflow / command sequence | `.claude/skills/<name>/SKILL.md` | RECOMMEND in report (or Mode-1 capture in the local tree) |
+ | Structural decision with weighed alternatives | an ADR under `adr/` | RECOMMEND (the developer writes ADRs in-worktree; flag if one is missing) |
+
+5. Skip any candidate that is: already recorded, ephemeral, inferable from code alone, or a pure refactor/copy.
+6. **Nothing worth capitalizing → write nothing, commit nothing.** Reply `synthesized: nothing to capitalize`. This is a complete, valid outcome.
+7. If (and only if) step 4 produced a MEMORY.md write, commit it (two Bash calls, no chaining):
```
Bash("git -C $CLAUDE_PROJECT_DIR add MEMORY.md")
- Bash("git -C $CLAUDE_PROJECT_DIR -c user.name='Documentator' -c user.email='[email protected]' commit -m 'docs(memory): business knowledge' --quiet")
+ Bash("git -C $CLAUDE_PROJECT_DIR -c user.name='Documentator' -c user.email='[email protected]' commit -m 'docs(memory): business knowledge' --quiet")
```
-7. Reply `synthesized: business_facts=N`.
+8. Reply `synthesized: business_facts=N` (and list any routed recommendations below it).
## Pattern entry format
@@ -110,7 +121,7 @@ For an `escalation`, replace **Resolution** with **Why no additive lever** and o
## Bash usage
-Restricted by hook to: `git log`/`git show`/`git diff`/`ls`/`wc -l`, plus the Mode 2 commands listed above (`git -C $CLAUDE_PROJECT_DIR diff/log`, `git -C $CLAUDE_PROJECT_DIR add MEMORY.md`, `git -C $CLAUDE_PROJECT_DIR -c user.name=Documentator -c [email protected] commit -m …` — author identity is pinned). Everything else: use Read/Glob/Grep.
+Restricted by hook to: `git log`/`git show`/`git diff`/`ls`/`wc -l`, plus the Mode 2 commands listed above (`git -C $CLAUDE_PROJECT_DIR diff/log`, `git -C $CLAUDE_PROJECT_DIR add MEMORY.md`, `git -C $CLAUDE_PROJECT_DIR -c user.name=Documentator -c [email protected] commit -m …`, author identity is pinned). Everything else: use Read/Glob/Grep.
## Output
diff --git a/.claude/agents/merger.md b/.claude/agents/merger.md
index fa6bc68b..f11a750e 100644
--- a/.claude/agents/merger.md
+++ b/.claude/agents/merger.md
@@ -132,7 +132,7 @@ cd $CLAUDE_PROJECT_DIR && flock $CLAUDE_PROJECT_DIR/.promote.lock bash -c '
[ -z "$DEFAULT" ] && { git show-ref --verify --quiet refs/heads/master && DEFAULT=master || DEFAULT=main; }
case "$DEFAULT" in main|master) [ "$ALLOW_MAIN" = "1" ] || { echo "main opt-in required for $DEFAULT"; exit 3; } ;; esac # audit A3: never silently commit to main/master without an explicit ALLOW_MAIN=1
git checkout -f "$DEFAULT" || exit 1 # switch to the promotion target (session fork-base branch, NOT $CLAUDE_PROJECT_DIR HEAD), discarding demo working-tree debris in the same step. `-f` replaces the old `git reset --hard HEAD; git checkout`: same clean-then-switch effect, but without `git reset --hard`, which the auto-mode command classifier blocks (audit #08).
- # Docker-only helper: re-applies the App.tsx variant that checkout reverts. Absent in a local checkout — skip it there.
+ # Launcher post-checkout script (config.launcher.postCheckoutScript, see rules/launcher-interface.md): re-applies the App.tsx variant that checkout reverts. The `-x` test makes it inert wherever the script is absent (a local checkout, or a project with no launcher).
[ -x /entrypoint-helpers/apply-app-variant.sh ] && /entrypoint-helpers/apply-app-variant.sh
git merge --no-ff session/<SESSION_SHORT_ID> -m "merge(session): <SESSION_SHORT_ID>" \
|| { git merge --abort; exit 1; }
@@ -176,7 +176,7 @@ cd $CLAUDE_PROJECT_DIR && flock $CLAUDE_PROJECT_DIR/.promote.lock bash -c '
[ -z "$DEFAULT" ] && DEFAULT=$(git symbolic-ref --short refs/remotes/origin/HEAD 2>/dev/null | sed "s@^origin/@@")
[ -z "$DEFAULT" ] && { git show-ref --verify --quiet refs/heads/master && DEFAULT=master || DEFAULT=main; }
git checkout -f "$DEFAULT" || exit 1 # clean-then-switch in one step; no `git reset --hard` (auto-mode classifier blocks it, audit #08)
- # Docker-only helper: re-applies the App.tsx variant that checkout reverts. Absent in a local checkout — skip it there.
+ # Launcher post-checkout script (config.launcher.postCheckoutScript, see rules/launcher-interface.md): re-applies the App.tsx variant that checkout reverts. The `-x` test makes it inert wherever the script is absent (a local checkout, or a project with no launcher).
[ -x /entrypoint-helpers/apply-app-variant.sh ] && /entrypoint-helpers/apply-app-variant.sh
git merge --no-ff <BRANCH_NAME> -m "rollback(<SESSION_SHORT_ID>): undo via agent" \
|| { git merge --abort; exit 1; }
diff --git a/.claude/hooks/bash-guard.mjs b/.claude/hooks/bash-guard.mjs
index 3273de48..f11b9f5b 100755
--- a/.claude/hooks/bash-guard.mjs
+++ b/.claude/hooks/bash-guard.mjs
@@ -8,6 +8,12 @@ import {
isOrchestrator,
isQualityReviewer,
} from "./lib/teams.mjs";
+import {
+ loadConfig,
+ validationSteps,
+ extraForbidden,
+ launcher,
+} from "./lib/config.mjs";
const input = JSON.parse(readFileSync(0, "utf8"));
const ctx = createHookContext(input, "bash-guard");
@@ -106,32 +112,61 @@ const runsLint = (c) => /(make\s+lint\b|npm\s+run\s+lint\b)/.test(c);
const runsBuild = (c) =>
/(npx\s+vite\s+build|npm\s+run\s+build\b|make\s+build\b)/.test(c);
-const VALIDATION_RULES = [
- [
+const CATEGORY_RULES = {
+ typecheck: [
runsTypecheck,
- "typecheck — validate-on-stop.mjs runs this automatically after you stop; read its stderr output instead.",
+ "typecheck: validate-on-stop.mjs runs this automatically after you stop; read its stderr output instead.",
],
- [
+ prettier: [
runsPrettier,
- "prettier — the validation hooks auto-apply prettier and commit the result; don't run it manually.",
+ "prettier: the validation hooks auto-apply prettier and commit the result; don't run it manually.",
],
- [
+ unit: [
runsUnitTests,
- "unit tests — the validation hooks run vitest automatically. In this sandbox vitest browser mode HANGS without CI=true (chromium headed waits for display). Trust the hooks.",
+ "unit tests: the validation hooks run vitest automatically. In this sandbox vitest browser mode HANGS without CI=true (chromium headed waits for display). Trust the hooks.",
],
- [
+ e2e: [
runsE2eTests,
- "e2e tests — the validation hooks run playwright in full mode only; in demo mode they're skipped. Don't run them manually.",
+ "e2e tests: the validation hooks run playwright in full mode only; in demo mode they're skipped. Don't run them manually.",
],
- [
+ lint: [
runsLint,
- "lint — prettier is auto-applied by the validation hooks; eslint runs via the project's editor config. Skip it.",
+ "lint: prettier is auto-applied by the validation hooks; eslint runs via the project's editor config. Skip it.",
],
- [
+ build: [
runsBuild,
- "build — don't run production builds during tickets; typecheck (run by the validation hooks) catches type errors.",
+ "build: don't run production builds during tickets; typecheck (run by the validation hooks) catches type errors.",
],
-];
+};
+
+// Which categories to guard comes from the SAME config the validation chain runs
+// (kills the triple-encoding: runner, guard, and doc no longer drift). Each
+// validation step's kind maps to a category, plus validation.extraForbidden
+// (lint/build — never run during tickets, not part of the chain). Fail-open to
+// ALL categories if the config can't be read, so a malformed config never
+// weakens the guard.
+const KIND_TO_CATEGORY = {
+ format: "prettier",
+ typecheck: "typecheck",
+ unit: "unit",
+ e2e: "e2e",
+};
+let activeCategories;
+try {
+ const cfg = loadConfig();
+ activeCategories = new Set([
+ ...validationSteps(cfg)
+ .map((s) => KIND_TO_CATEGORY[s.kind])
+ .filter(Boolean),
+ ...extraForbidden(cfg),
+ ]);
+} catch {
+ activeCategories = new Set(Object.keys(CATEGORY_RULES));
+}
+
+const VALIDATION_RULES = [...activeCategories]
+ .map((c) => CATEGORY_RULES[c])
+ .filter(Boolean);
const violation = VALIDATION_RULES.find(([matches]) => matches(cmd));
if (violation) {
@@ -145,16 +180,30 @@ if (violation) {
// Write/Edit tools, never Bash redirection/in-place edits. Bash writes bypass the
// Write|Edit-only block-migration-writes guard (a developer could otherwise write a migration in
// bash).
-const REDIRECT_TARGET_RE =
- /(^|[^0-9&])>>?\s*(\/dev\/null\b|\/chat-service\/logs\/\S*|\/|\.\.?\/|~\/|[a-zA-Z0-9._-]+\/|[a-zA-Z0-9._-]+\.[a-zA-Z0-9]+)/g;
+// The managed-launcher log dir (e.g. CRM Builder's /chat-service/logs) is a
+// launcher extension point: config.launcher.logsDir. A redirect into it is
+// exempt (agents legitimately append their logs there). When unset, only
+// /dev/null is exempt and no chat-service path is hardcoded.
+let logsDir = "";
+try {
+ logsDir = launcher(loadConfig()).logsDir || "";
+} catch {
+ logsDir = "";
+}
+const escapeRe = (s) => s.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
+const logsAlt = logsDir ? `${escapeRe(logsDir)}\\/\\S*|` : "";
+const REDIRECT_TARGET_RE = new RegExp(
+ `(^|[^0-9&])>>?\\s*(\\/dev\\/null\\b|${logsAlt}\\/|\\.\\.?\\/|~\\/|[a-zA-Z0-9._-]+\\/|[a-zA-Z0-9._-]+\\.[a-zA-Z0-9]+)`,
+ "g",
+);
const writesRedirect = (c) => {
// Evaluate the /dev/null and logs exemptions PER redirect, so an unrelated
// `cmd 2>/dev/null` can't disarm detection of a real `> file` write in the
// same command.
for (const m of c.matchAll(REDIRECT_TARGET_RE)) {
const target = m[2];
- if (target === "/dev/null" || target.startsWith("/chat-service/logs/"))
- continue;
+ if (target === "/dev/null") continue;
+ if (logsDir && target.startsWith(logsDir + "/")) continue;
return true;
}
return false;
diff --git a/.claude/hooks/block-duplicate-dispatch.mjs b/.claude/hooks/block-duplicate-dispatch.mjs
index f0830c83..0260a4b0 100755
--- a/.claude/hooks/block-duplicate-dispatch.mjs
+++ b/.claude/hooks/block-duplicate-dispatch.mjs
@@ -25,8 +25,11 @@ import { join } from "node:path";
import { createHash } from "node:crypto";
import { createHookContext } from "./lib/context.mjs";
import { parseDispatch } from "./lib/dispatch-parse.mjs";
+import { pipelineRoleSet, debounceRoleSet } from "./lib/teams.mjs";
-const DEBOUNCE_ROLES = new Set(["developer", "quality-reviewer", "merger"]);
+// Sourced from harness.config.json (config.roles debounce/pipeline flags) via
+// teams.mjs, so these sets and force-foreground's share one source of truth.
+const DEBOUNCE_ROLES = debounceRoleSet();
const DEBOUNCE_WINDOW_MS = 90 * 1000;
const PLANNER_STALE_MS = 60 * 60 * 1000;
@@ -55,13 +58,7 @@ const sha = (s) => createHash("sha1").update(s).digest("hex").slice(0, 16);
// corrective retry as a "duplicate" (a regression from force-foreground's deny-and-retry,
// caught by fresh-session run 8468cc06 - the planner never ran yet its marker blocked the
// retry for 60 min). Only debounce dispatches that will actually proceed (rib === false).
-const PIPELINE_ROLES = new Set([
- "developer",
- "quality-reviewer",
- "merger",
- "planner",
- "simple-developer",
-]);
+const PIPELINE_ROLES = pipelineRoleSet();
const childRole = PIPELINE_ROLES.has(d.subagentType)
? d.subagentType
: PIPELINE_ROLES.has(d.role)
diff --git a/.claude/hooks/block-orchestrator-merge.mjs b/.claude/hooks/block-orchestrator-merge.mjs
index 5a7d3937..47953877 100755
--- a/.claude/hooks/block-orchestrator-merge.mjs
+++ b/.claude/hooks/block-orchestrator-merge.mjs
@@ -6,16 +6,22 @@
// dead). The behavioral rule lives in orchestrator.md ("NEVER act as merger
// yourself"); this is the runtime guard.
//
-// OPT-IN: inert unless ATOMIC_CRM_ENFORCE_MERGE_GUARD=1. In a plain Claude Code
+// OPT-IN: inert unless HARNESS_ENFORCE_MERGE_GUARD=1 (deprecated fallback:
+// ATOMIC_CRM_ENFORCE_MERGE_GUARD, kept for one release). In a plain Claude Code
// checkout the main session is a general assistant, and blocking its git
-// merge/pull/checkout would break normal use — so it stays off until the
+// merge/pull/checkout would break normal use, so it stays off until the
// orchestrator explicitly enables it before a team wave.
import { readFileSync } from "node:fs";
+import { basename } from "node:path";
import { createHookContext } from "./lib/context.mjs";
import { isMerger } from "./lib/teams.mjs";
+import { loadConfig, launcher } from "./lib/config.mjs";
-if (process.env.ATOMIC_CRM_ENFORCE_MERGE_GUARD !== "1") process.exit(0);
+const mergeGuardEnabled =
+ process.env.HARNESS_ENFORCE_MERGE_GUARD === "1" ||
+ process.env.ATOMIC_CRM_ENFORCE_MERGE_GUARD === "1";
+if (!mergeGuardEnabled) process.exit(0);
const input = JSON.parse(readFileSync(0, "utf8"));
const ctx = createHookContext(input, "block-orchestrator-merge");
@@ -27,6 +33,17 @@ if ([ctx.agentName, ctx.agentType].some(isMerger)) process.exit(0);
const cmd = input.tool_input?.command || "";
if (!cmd) process.exit(0);
+// The post-checkout script (e.g. CRM Builder's apply-app-variant.sh) is a
+// launcher extension point: its path comes from config.launcher.postCheckoutScript
+// so no chat-service path is hardcoded here. When unset, that guard clause is
+// inert (a project with no post-checkout script has nothing to gate).
+let postCheckoutScript = "";
+try {
+ postCheckoutScript = launcher(loadConfig()).postCheckoutScript || "";
+} catch {
+ postCheckoutScript = "";
+}
+
let blocked = "";
if (/(^|[;&|\s])git\s+merge(\s|$)/.test(cmd)) blocked = "git merge";
else if (/(^|[;&|\s])git\s+checkout\s+(master|main)(\s|$)/.test(cmd))
@@ -34,8 +51,8 @@ else if (/(^|[;&|\s])git\s+checkout\s+(master|main)(\s|$)/.test(cmd))
else if (/(^|[;&|\s])git\s+pull(\s|$)/.test(cmd)) blocked = "git pull";
else if (/(^|[;&|\s])git\s+worktree\s+remove(\s|$)/.test(cmd))
blocked = "git worktree remove";
-else if (/apply-app-variant\.sh/.test(cmd))
- blocked = "apply-app-variant.sh (merger-only command)";
+else if (postCheckoutScript && cmd.includes(basename(postCheckoutScript)))
+ blocked = `${basename(postCheckoutScript)} (merger-only command)`;
if (blocked) {
ctx.fail(
diff --git a/.claude/hooks/force-foreground-orchestrator-dispatch.mjs b/.claude/hooks/force-foreground-orchestrator-dispatch.mjs
index 5100ab2b..f50914e0 100755
--- a/.claude/hooks/force-foreground-orchestrator-dispatch.mjs
+++ b/.claude/hooks/force-foreground-orchestrator-dispatch.mjs
@@ -18,17 +18,14 @@
import { readFileSync } from "node:fs";
import { createHookContext } from "./lib/context.mjs";
import { parseDispatch } from "./lib/dispatch-parse.mjs";
+import { pipelineRoleSet } from "./lib/teams.mjs";
-// Pipeline roles whose result the orchestrator MUST consume in the same turn. The
-// orchestrator (main->orchestrator hop) and documentator (fire-and-forget) are deliberately
-// excluded: their background dispatch is correct.
-const PIPELINE_ROLES = new Set([
- "developer",
- "quality-reviewer",
- "merger",
- "planner",
- "simple-developer",
-]);
+// Pipeline roles whose result the orchestrator MUST consume in the same turn come
+// from harness.config.json (config.roles `pipeline` flag), so this set and the
+// one in block-duplicate-dispatch share one source. The orchestrator
+// (main->orchestrator hop) and documentator (fire-and-forget) are excluded
+// (pipeline:false): their background dispatch is correct.
+const PIPELINE_ROLES = pipelineRoleSet();
let input;
try {
diff --git a/.claude/hooks/format-on-write.mjs b/.claude/hooks/format-on-write.mjs
new file mode 100755
index 00000000..8cf0a14b
--- /dev/null
+++ b/.claude/hooks/format-on-write.mjs
@@ -0,0 +1,52 @@
+#!/usr/bin/env node
+// PostToolUse(Write|Edit): format the file just written, using the formatter and
+// extension list from harness.config.json's format-kind validation step. This is
+// the human/main-thread convenience: harness subagents are SKIPPED because their
+// SubagentStop validation chain already applies the format step (and would
+// re-run it), so formatting their in-flight writes is redundant churn.
+//
+// Non-blocking (exit 1 on a formatter error): the Write already succeeded, so a
+// formatting failure only warns.
+
+import { execFileSync } from "node:child_process";
+import { readFileSync } from "node:fs";
+import { loadConfig, formatStep } from "./lib/config.mjs";
+
+let input = {};
+try {
+ input = JSON.parse(readFileSync(0, "utf8"));
+} catch {
+ process.exit(0);
+}
+
+// Skip harness subagents (they carry an agent_type / runtime agent name);
+// validate-on-stop covers them.
+if (input.agent_type || process.env.CLAUDE_AGENT_NAME) process.exit(0);
+
+const filePath = input.tool_input?.file_path;
+if (!filePath) process.exit(0);
+
+let step;
+try {
+ step = formatStep(loadConfig());
+} catch {
+ process.exit(0); // no readable config -> nothing to do
+}
+if (!step || !step.formatter) process.exit(0);
+
+const exts = step.extensions ?? [];
+if (exts.length && !exts.some((e) => filePath.endsWith(e))) process.exit(0);
+
+const [bin, ...baseArgs] = step.formatter.split(/\s+/).filter(Boolean);
+try {
+ execFileSync(bin, [...baseArgs, filePath], {
+ stdio: "ignore",
+ timeout: 15_000,
+ });
+} catch (err) {
+ console.error(
+ `format-on-write: failed to format ${filePath}: ${err.message}`,
+ );
+ process.exit(1);
+}
+process.exit(0);
diff --git a/.claude/hooks/lib/config.mjs b/.claude/hooks/lib/config.mjs
new file mode 100644
index 00000000..959cff82
--- /dev/null
+++ b/.claude/hooks/lib/config.mjs
@@ -0,0 +1,146 @@
+// harness.config.json loader: the single project-facts manifest consumed by
+// hooks/scripts at runtime (and by the renderer at sync time in a later phase).
+// Stdlib only. Fail-closed on a malformed config (throws a clear Error); a
+// MISSING file degrades to the built-in defaults so a config-less repo still
+// runs a minimal harness.
+
+import { existsSync, readFileSync } from "node:fs";
+import { join } from "node:path";
+import { REPO } from "./paths.mjs";
+
+export const CONFIG_FILENAME = "harness.config.json";
+
+// Minimal safe baseline. The committed harness.config.json overrides these.
+// Optional capabilities (deploy, app) are ABSENT here on purpose: a capability
+// exists iff its block is present in the config (see the optionality design
+// note in adr/harness-action-plan.md).
+const DEFAULTS = {
+ name: "harness",
+ layout: { src: "src", e2e: "e2e", adr: "adr" },
+ validation: { steps: [], extraForbidden: [] },
+ worktree: { provision: "npm-link" },
+ skills: { developerMenu: [] },
+ roles: {},
+ launcher: {
+ sessionDirEnv: "CHAT_SESSION_DIR",
+ turnSentinelDir: null,
+ postCheckoutScript: null,
+ logsDir: null,
+ },
+};
+
+const isObject = (v) => v !== null && typeof v === "object" && !Array.isArray(v);
+
+// Deep-merge `override` onto `base`. Objects merge recursively; arrays and
+// scalars from `override` REPLACE (never concatenate): a config that lists
+// validation.steps fully replaces the default empty list.
+function deepMerge(base, override) {
+ if (!isObject(base) || !isObject(override)) return override;
+ const out = { ...base };
+ for (const [k, v] of Object.entries(override)) {
+ out[k] = isObject(v) && isObject(base[k]) ? deepMerge(base[k], v) : v;
+ }
+ return out;
+}
+
+class ConfigError extends Error {}
+
+// Throw a clear, prefixed error so a fail-closed consumer surfaces exactly what
+// is wrong with the config.
+function fail(msg) {
+ throw new ConfigError(`${CONFIG_FILENAME}: ${msg}`);
+}
+
+function validate(cfg) {
+ if (!isObject(cfg)) fail("top level must be a JSON object");
+
+ if (!isObject(cfg.validation) || !Array.isArray(cfg.validation.steps)) {
+ fail("`validation.steps` must be an array");
+ }
+ for (const [i, step] of cfg.validation.steps.entries()) {
+ if (!isObject(step)) fail(`validation.steps[${i}] must be an object`);
+ if (typeof step.id !== "string" || !step.id) {
+ fail(`validation.steps[${i}] needs a non-empty string \`id\``);
+ }
+ if (typeof step.kind !== "string" || !step.kind) {
+ fail(`validation.steps[${step.id}] needs a non-empty string \`kind\``);
+ }
+ const isVitest = step.runner === "vitest";
+ if (!isVitest && (typeof step.command !== "string" || !step.command)) {
+ fail(`validation.steps[${step.id}] needs a \`command\` (or runner:"vitest")`);
+ }
+ if (isVitest && (typeof step.config !== "string" || !Array.isArray(step.projects))) {
+ fail(`validation.steps[${step.id}] (vitest) needs \`config\` and \`projects[]\``);
+ }
+ }
+
+ if (!isObject(cfg.roles)) fail("`roles` must be an object");
+ for (const [name, role] of Object.entries(cfg.roles)) {
+ if (!isObject(role) || typeof role.model !== "string" || !role.model) {
+ fail(`roles.${name} needs a non-empty string \`model\``);
+ }
+ }
+
+ if ("deploy" in cfg && cfg.deploy !== undefined) {
+ if (!isObject(cfg.deploy) || !Array.isArray(cfg.deploy.relevantGlobs)) {
+ fail("`deploy.relevantGlobs` must be an array when `deploy` is present");
+ }
+ }
+ return cfg;
+}
+
+const cache = new Map();
+
+/**
+ * Load and validate the harness config, merged over the defaults.
+ * @param {string} [repo] repo root holding harness.config.json (defaults to REPO)
+ * @returns {object} the validated, merged config
+ * @throws {Error} on malformed JSON or an invalid shape (fail-closed)
+ */
+export function loadConfig(repo = REPO) {
+ if (cache.has(repo)) return cache.get(repo);
+ const path = join(repo, CONFIG_FILENAME);
+ let merged;
+ if (!existsSync(path)) {
+ merged = validate(structuredClone(DEFAULTS));
+ } else {
+ let parsed;
+ try {
+ parsed = JSON.parse(readFileSync(path, "utf8"));
+ } catch (e) {
+ fail(`invalid JSON (${e.message})`);
+ }
+ merged = validate(deepMerge(DEFAULTS, parsed));
+ }
+ cache.set(repo, merged);
+ return merged;
+}
+
+// Test-only: drop the memoized config so a test can reload after writing a new
+// file to the same repo path.
+export function clearConfigCache() {
+ cache.clear();
+}
+
+// ---- Typed readers used by the config consumers (TA.2..TB.4) ----------------
+
+export const validationSteps = (cfg) => cfg.validation?.steps ?? [];
+export const extraForbidden = (cfg) => cfg.validation?.extraForbidden ?? [];
+export const isDeployEnabled = (cfg) => isObject(cfg.deploy);
+export const deployGlobs = (cfg) => cfg.deploy?.relevantGlobs ?? [];
+export const isAppSmokeEnabled = (cfg) => isObject(cfg.app);
+export const worktreeProvision = (cfg) => cfg.worktree?.provision ?? "npm-link";
+export const roleNames = (cfg) => Object.keys(cfg.roles ?? {});
+export const roleModel = (cfg, role) => cfg.roles?.[role]?.model ?? "";
+export const pipelineRoles = (cfg) =>
+ roleNames(cfg).filter((r) => cfg.roles[r]?.pipeline);
+export const debounceRoles = (cfg) =>
+ roleNames(cfg).filter((r) => cfg.roles[r]?.debounce);
+// Managed-launcher extension points (empty object when no launcher overlay).
+export const launcher = (cfg) => cfg.launcher ?? {};
+// The format-kind validation step (null when none), used by format-on-write.
+export const formatStep = (cfg) =>
+ validationSteps(cfg).find((s) => s.kind === "format") ?? null;
+// Steps a pre-PR / pre-push gate runs on the human path (fast checks only).
+export const prePrSteps = (cfg) =>
+ validationSteps(cfg).filter((s) => s.kind === "typecheck" || s.kind === "lint");
diff --git a/.claude/hooks/lib/context.mjs b/.claude/hooks/lib/context.mjs
index d167b5b4..990bb61d 100644
--- a/.claude/hooks/lib/context.mjs
+++ b/.claude/hooks/lib/context.mjs
@@ -5,10 +5,11 @@
// only the detail and never repeat the name.
import { appendFileSync, existsSync, mkdirSync, rmSync } from "node:fs";
-import { basename, dirname, join } from "node:path";
+import { basename, dirname, isAbsolute, join } from "node:path";
import { decisionBlock } from "./io.mjs";
import { REPO, TMP_ROOT, sanitizePath } from "./paths.mjs";
import { exec } from "./process.mjs";
+import { loadConfig, worktreeProvision } from "./config.mjs";
/**
* @param {string | Record<string, unknown>} input
@@ -65,6 +66,56 @@ export function createHookContext(input, name = "hook") {
const verdict = (verb, detail) => log(detail ? `${verb} ${detail}` : verb);
+ // The `npm-link` provisioning builtin: mirror $REPO/node_modules into the
+ // worktree. See provisionWorktree below for the config-driven dispatcher.
+ const linkNodeModules = (wt) => {
+ const target = join(wt, "node_modules");
+ if (existsSync(target)) return;
+ const source = join(REPO, "node_modules");
+ if (!existsSync(source)) return;
+ // Fast path: hardlink tree (cp -al) when the worktree base shares a
+ // filesystem with the repo. In dev containers /tmp and /workspaces are
+ // different mounts (cross-device), so cp -al fails; fall back to a full
+ // real copy. A symlinked node_modules is NOT an option: vitest browser
+ // mode (Chromium) hangs on it. See memory worktree-node-modules-provisioning.
+ if (exec("cp", ["-al", source, target]).status === 0) return;
+ rmSync(target, { recursive: true, force: true });
+ if (exec("cp", ["-a", source, target]).status !== 0) {
+ rmSync(target, { recursive: true, force: true });
+ throw new Error(`node_modules provisioning failed for ${wt} - cp -al and cp -a both failed`);
+ }
+ };
+
+ // Config-driven worktree provisioning (config.worktree.provision): the
+ // `npm-link` builtin (default, mirrors node_modules), `none` (no provisioning,
+ // for a stack that needs none), or a script path (run with the worktree as its
+ // one argument). Removes the npm assumption from worktree setup. Fail-closed on
+ // a provision-script error, like the npm-link builtin.
+ const provisionWorktree = (wt) => {
+ let mode = "npm-link";
+ try {
+ mode = worktreeProvision(loadConfig());
+ } catch {
+ mode = "npm-link";
+ }
+ if (mode === "none") {
+ log(`provision skipped (none) wt=${wt}`);
+ return;
+ }
+ if (mode === "npm-link") {
+ linkNodeModules(wt);
+ return;
+ }
+ const script = isAbsolute(mode) ? mode : join(REPO, mode);
+ const r = exec("bash", [script, wt], { cwd: REPO });
+ if (r.status !== 0) {
+ throw new Error(
+ `worktree provision script failed (${script}): ${(r.stderr || r.stdout || "").slice(0, 300)}`,
+ );
+ }
+ log(`provisioned via script ${script} wt=${wt}`);
+ };
+
return {
name,
repo: REPO,
@@ -111,26 +162,9 @@ export function createHookContext(input, name = "hook") {
process.exit(2);
},
- /**
- * @param {string} wt
- * @returns {void}
- */
- linkNodeModules(wt) {
- const target = join(wt, "node_modules");
- if (existsSync(target)) return;
- const source = join(REPO, "node_modules");
- if (!existsSync(source)) return;
- // Fast path: hardlink tree (cp -al) when the worktree base shares a
- // filesystem with the repo. In dev containers /tmp and /workspaces are
- // different mounts (cross-device), so cp -al fails — fall back to a full
- // real copy. A symlinked node_modules is NOT an option: vitest browser
- // mode (Chromium) hangs on it. See memory worktree-node-modules-provisioning.
- if (exec("cp", ["-al", source, target]).status === 0) return;
- rmSync(target, { recursive: true, force: true });
- if (exec("cp", ["-a", source, target]).status !== 0) {
- rmSync(target, { recursive: true, force: true });
- throw new Error(`node_modules provisioning failed for ${wt} — cp -al and cp -a both failed`);
- }
- },
+ // Worktree provisioning: the config-driven dispatcher plus the npm-link
+ // builtin it wraps (both defined as closures above).
+ provisionWorktree,
+ linkNodeModules,
};
}
diff --git a/.claude/hooks/lib/paths.mjs b/.claude/hooks/lib/paths.mjs
index 7503ea88..e1c3bf42 100644
--- a/.claude/hooks/lib/paths.mjs
+++ b/.claude/hooks/lib/paths.mjs
@@ -14,7 +14,10 @@ export const REPO = getRepo();
export const CONFIG_DIR =
process.env.CLAUDE_CONFIG_DIR || join(process.env.HOME || "/root", ".claude");
-export const TMP_ROOT = process.env.CRM_TMP_ROOT || "/tmp";
+// HARNESS_TMP_ROOT is the neutral name; CRM_TMP_ROOT is the deprecated fallback
+// kept for one release so existing launchers / tests keep working.
+export const TMP_ROOT =
+ process.env.HARNESS_TMP_ROOT || process.env.CRM_TMP_ROOT || "/tmp";
export function sanitizePath(p) {
return String(p ?? "").replace(/\//g, "_");
diff --git a/.claude/hooks/lib/teams.mjs b/.claude/hooks/lib/teams.mjs
index 94056d3f..0bb89b4b 100644
--- a/.claude/hooks/lib/teams.mjs
+++ b/.claude/hooks/lib/teams.mjs
@@ -1,8 +1,47 @@
// Agent identity helpers — the single source for every hook that gates on who
// an agent is.
+import { loadConfig, pipelineRoles, debounceRoles, roleNames } from "./config.mjs";
+
export const getFirstTaskId = (text) => (String(text ?? "").match(/TASK-[0-9]+/) || [])[0] || "";
+// Role SETS come from harness.config.json (config.roles: `pipeline` / `debounce`
+// flags), so force-foreground and block-duplicate-dispatch no longer hardcode
+// their own copies. Fail-open to the built-in defaults when the config is
+// missing or lists no roles (e.g. a config-less test repo), so a guard never
+// silently empties out.
+const DEFAULT_PIPELINE = [
+ "developer",
+ "quality-reviewer",
+ "merger",
+ "planner",
+ "simple-developer",
+ "test-writer",
+];
+const DEFAULT_DEBOUNCE = ["developer", "quality-reviewer", "merger"];
+
+const setFromConfig = (reader, fallback) => {
+ try {
+ const roles = reader(loadConfig());
+ return new Set(roles.length ? roles : fallback);
+ } catch {
+ return new Set(fallback);
+ }
+};
+
+/** Roles the orchestrator must dispatch foreground and whose result it consumes inline. */
+export const pipelineRoleSet = () => setFromConfig(pipelineRoles, DEFAULT_PIPELINE);
+/** Roles whose identical re-dispatch is debounced (async-ack double dispatch). */
+export const debounceRoleSet = () => setFromConfig(debounceRoles, DEFAULT_DEBOUNCE);
+/** Every declared role name (config.roles keys); [] on a config error. */
+export const configRoleNames = () => {
+ try {
+ return roleNames(loadConfig());
+ } catch {
+ return [];
+ }
+};
+
// Agent-name role predicates. Match the bare role, a suffixed name
// (merger-TASK-003), or an @-qualified address.
export const isQualityReviewer = (name) => /^quality-reviewer([-@]|$)/.test(name || "");
diff --git a/.claude/hooks/lib/validation.mjs b/.claude/hooks/lib/validation.mjs
index cfeb16a8..f7761c42 100644
--- a/.claude/hooks/lib/validation.mjs
+++ b/.claude/hooks/lib/validation.mjs
@@ -3,6 +3,7 @@ import { tmpdir } from "node:os";
import { basename, join } from "node:path";
import { getBaseBranch, getWorktreeChangeSummary, getWorktreePaths } from "./git.mjs";
import { bash, exec } from "./process.mjs";
+import { loadConfig, validationSteps } from "./config.mjs";
// `only` narrows to a single worktree when the caller already knows it
// (validate-on-stop scoping to the stopping agent's own task worktree);
@@ -86,11 +87,64 @@ function runVitest(wt, configFile, projects = [], changedSince = "") {
return { status: r.status, output, timedOut: r.status === 124 };
}
+// Per-kind tail length for failure output (mechanical, not a project fact).
+const TAIL_LINES = { format: 15, typecheck: 20, unit: 40, e2e: 50 };
+
+// A step is skipped when its `condition` is not met. `pathExists` gates on a
+// path under the repo (e.g. the supabase/functions unit-fn gate); `modeNot`
+// skips when MODE equals the given value (e.g. e2e in demo mode).
+function stepSkipped(ctx, step) {
+ const c = step.condition;
+ if (!c) return false;
+ if (c.pathExists && !existsSync(join(ctx.repo, c.pathExists))) {
+ ctx.log(`SKIP ${step.id} (no ${c.pathExists})`);
+ return true;
+ }
+ if (c.modeNot && (process.env.MODE || "demo") === c.modeNot) {
+ ctx.log(`${step.id} skipped (${c.modeNot} mode)`);
+ return true;
+ }
+ return false;
+}
+
+// Run ONE config-declared step in `cwd`. Returns { ok } or { ok:false, output }.
+// The step id is the caller's fail-report label, so config ids (prettier,
+// typecheck, unit-app, unit-fn, e2e) ARE the reported step names.
+function runStep(ctx, step, { cwd, base }) {
+ const tail = TAIL_LINES[step.kind] ?? 40;
+
+ if (step.runner === "vitest") {
+ const r = runVitest(cwd, step.config, step.projects, step.changedScoped ? base : "");
+ if (r.timedOut) return { ok: false, output: "TIMEOUT (>180s) -- vitest did not exit. Tests may be hanging." };
+ return r.status === 0 ? { ok: true } : { ok: false, output: r.output };
+ }
+
+ const r = bash(`${step.command} 2>&1`, { cwd });
+ if (r.status === 0) {
+ if (step.kind === "format" && step.autoCommit) {
+ if (exec("git", ["-C", cwd, "diff", "--quiet"]).status !== 0) {
+ exec("git", ["-C", cwd, "add", "-A"]);
+ exec("git", ["-C", cwd, "commit", "-m", `style(${basename(cwd)}): auto-apply prettier`]);
+ ctx.log(`auto-prettier committed wt=${cwd}`);
+ }
+ }
+ return { ok: true };
+ }
+ const detail =
+ step.kind === "format"
+ ? "Prettier could not format one or more files (likely a syntax error). Fix the issue and commit.\n" +
+ tailLines(r.stdout, tail)
+ : tailLines(r.stdout, tail);
+ return { ok: false, output: detail };
+}
+
// The full validation chain, run by validate-on-stop.mjs on SubagentStop (after
-// every developer stop, ticket or lightweight MODE). Per dirty worktree, fail-fast: prettier auto-fix (+ commit),
-// typecheck, unit app, unit functions; then e2e once in the repo (full mode
-// only). VALIDATE_DRY_RUN=1 skips everything, =fail simulates a failure.
-// Returns { ok: true, skipReason? } or { ok: false, step, output }.
+// every developer stop). Steps are declared in harness.config.json's
+// `validation.steps` (single source of truth, shared with bash-guard) and run in
+// config order: steps without `cwd:"repo"` run per dirty worktree (fail-fast);
+// `cwd:"repo"` steps (e2e) run once in the repo after the per-worktree pass.
+// VALIDATE_DRY_RUN=1 skips everything, =fail simulates a failure. A malformed
+// config fails closed. Returns { ok:true, skipReason? } or { ok:false, step, output }.
export function runValidationSteps(ctx, { worktree = "", base = "" } = {}) {
if (process.env.VALIDATE_DRY_RUN === "1") {
ctx.log("DRY_RUN=1, skipping validation");
@@ -101,6 +155,14 @@ export function runValidationSteps(ctx, { worktree = "", base = "" } = {}) {
return { ok: false, step: "dry-run", output: "Validation failed (simulated)." };
}
+ let steps;
+ try {
+ steps = validationSteps(loadConfig(ctx.repo));
+ } catch (e) {
+ // Fail closed: a malformed config must block the stop, not silently pass.
+ return { ok: false, step: "config", output: `${e.message}\n` };
+ }
+
const { worktrees, skipReason } = getWorktreesToValidate(ctx, {
skipAdrOnly: true,
only: worktree,
@@ -108,57 +170,30 @@ export function runValidationSteps(ctx, { worktree = "", base = "" } = {}) {
});
if (skipReason) return { ok: true, skipReason };
- const hasFunctions = existsSync(join(ctx.repo, "supabase", "functions"));
+ const perWorktree = steps.filter((s) => s.cwd !== "repo");
+ const repoLevel = steps.filter((s) => s.cwd === "repo");
for (const wt of worktrees) {
- const failed = (step, output) => {
- ctx.log(`FAIL step=${step} wt=${wt}\n${output}`);
- return { ok: false, step, output: `=== ${step} failed in ${wt} ===\n${output}\n` };
- };
-
- const pretty = bash(
- "npx prettier --write 'src/**/*.{ts,tsx,js,jsx,css,json,html}' 2>&1",
- { cwd: wt },
- );
- if (pretty.status !== 0) {
- return failed(
- "prettier",
- "Prettier could not format one or more files (likely a syntax error). Fix the issue and commit.\n" +
- tailLines(pretty.stdout, 15),
- );
- }
- if (exec("git", ["-C", wt, "diff", "--quiet"]).status !== 0) {
- exec("git", ["-C", wt, "add", "-A"]);
- exec("git", ["-C", wt, "commit", "-m", `style(${basename(wt)}): auto-apply prettier`]);
- ctx.log(`auto-prettier committed wt=${wt}`);
+ for (const step of perWorktree) {
+ if (stepSkipped(ctx, step)) continue;
+ const r = runStep(ctx, step, { cwd: wt, base });
+ if (!r.ok) {
+ ctx.log(`FAIL step=${step.id} wt=${wt}\n${r.output}`);
+ return { ok: false, step: step.id, output: `=== ${step.id} failed in ${wt} ===\n${r.output}\n` };
+ }
}
-
- const typecheck = bash("npm run typecheck 2>&1", { cwd: wt });
- if (typecheck.status !== 0) return failed("typecheck", tailLines(typecheck.stdout, 20));
-
- const app = runVitest(wt, "vitest.config.ts", ["app", "claude"], base);
- if (app.timedOut) return failed("unit-app", "TIMEOUT (>180s) -- vitest did not exit. Tests may be hanging.");
- if (app.status !== 0) return failed("unit-app", app.output);
-
- if (hasFunctions) {
- const fn = runVitest(wt, "vitest.config.ts", ["functions"], base);
- if (fn.timedOut) return failed("unit-fn", "TIMEOUT (>180s) -- vitest did not exit. Tests may be hanging.");
- if (fn.status !== 0) return failed("unit-fn", fn.output);
- }
-
ctx.log(`OK wt=${wt}`);
}
- const mode = process.env.MODE || "demo";
- if (mode === "demo") {
- ctx.log("e2e skipped (demo mode)");
- return { ok: true };
- }
- const e2e = bash("npx playwright test 2>&1", { cwd: ctx.repo });
- if (e2e.status !== 0) {
- ctx.log(`FAIL step=e2e exit=${e2e.status}`);
- return { ok: false, step: "e2e", output: tailLines(e2e.stdout, 50) + "\n" };
+ for (const step of repoLevel) {
+ if (stepSkipped(ctx, step)) continue;
+ const r = runStep(ctx, step, { cwd: ctx.repo, base });
+ if (!r.ok) {
+ ctx.log(`FAIL step=${step.id} exit`);
+ return { ok: false, step: step.id, output: r.output + "\n" };
+ }
+ ctx.log(`${step.id} OK`);
}
- ctx.log("e2e OK");
+
return { ok: true };
}
diff --git a/.claude/hooks/pre-pr-checks.mjs b/.claude/hooks/pre-pr-checks.mjs
new file mode 100755
index 00000000..90cd7c1d
--- /dev/null
+++ b/.claude/hooks/pre-pr-checks.mjs
@@ -0,0 +1,54 @@
+#!/usr/bin/env node
+// PreToolUse(Bash): before `gh pr create` or `git push`, run the fast config
+// checks (typecheck / lint validation steps) so a broken push is caught on the
+// HUMAN path. Harness subagents are SKIPPED: they never push, and their
+// SubagentStop chain already validates. exit 2 blocks the push/PR.
+
+import { execSync } from "node:child_process";
+import { readFileSync } from "node:fs";
+import { loadConfig, prePrSteps } from "./lib/config.mjs";
+import { REPO } from "./lib/paths.mjs";
+
+const PR_TRIGGER_RE = /\bgh\s+pr\s+create\b|\bgit\s+push\b/;
+
+let input = {};
+try {
+ input = JSON.parse(readFileSync(0, "utf8"));
+} catch {
+ process.exit(0);
+}
+
+// Human/main-thread only. A subagent carries an agent_type / runtime agent name.
+if (input.agent_type || process.env.CLAUDE_AGENT_NAME) process.exit(0);
+
+const command = input.tool_input?.command ?? "";
+if (!PR_TRIGGER_RE.test(command)) process.exit(0);
+
+let steps;
+try {
+ steps = prePrSteps(loadConfig());
+} catch {
+ process.exit(0); // no readable config -> do not block the human
+}
+if (!steps.length) process.exit(0);
+
+const failures = [];
+for (const step of steps) {
+ if (!step.command) continue;
+ try {
+ execSync(step.command, { cwd: REPO, stdio: "pipe", timeout: 120_000 });
+ } catch (err) {
+ const out = (err.stdout?.toString() || err.message || "").slice(0, 800);
+ failures.push(`- ${step.id} (\`${step.command}\`) failed:\n${out}`);
+ }
+}
+
+if (failures.length) {
+ console.error(
+ `pre-pr-checks: push/PR blocked, ${failures.length} check(s) failed:\n\n` +
+ failures.join("\n\n") +
+ `\n\nFix the issues above, then retry.`,
+ );
+ process.exit(2);
+}
+process.exit(0);
diff --git a/.claude/hooks/restrict-documentator-bash.mjs b/.claude/hooks/restrict-documentator-bash.mjs
index 230d83db..24303e69 100755
--- a/.claude/hooks/restrict-documentator-bash.mjs
+++ b/.claude/hooks/restrict-documentator-bash.mjs
@@ -53,8 +53,10 @@ const WHITELIST = [
/^ls( |$)/,
/^wc -l( |$)/,
/^git -C [^ ]+ add MEMORY\.md *$/,
- /^git -C [^ ]+ -c user\.name=['"]?Documentator['"]? -c user\.email=['"]?documentator@atomic-crm\.local['"]? commit -m /,
- /^git -C [^ ]+ -c user\.email=['"]?documentator@atomic-crm\.local['"]? -c user\.name=['"]?Documentator['"]? commit -m /,
+ // Author identity is pinned. Accept the neutral harness.local and the
+ // deprecated atomic-crm.local (kept for one release).
+ /^git -C [^ ]+ -c user\.name=['"]?Documentator['"]? -c user\.email=['"]?documentator@(harness|atomic-crm)\.local['"]? commit -m /,
+ /^git -C [^ ]+ -c user\.email=['"]?documentator@(harness|atomic-crm)\.local['"]? -c user\.name=['"]?Documentator['"]? commit -m /,
];
const isWhitelisted = (cmd) => WHITELIST.some((pattern) => pattern.test(cmd));
@@ -63,6 +65,6 @@ if (isWhitelisted(command)) {
}
ctx.error(
- "Bash command blocked for documentator. Allowed: git log, git show, git diff, ls, wc -l; Mode 2 only: 'git -C <repo> diff …', 'git -C <repo> log …', 'git -C <repo> add MEMORY.md', 'git -C <repo> -c user.name=Documentator -c [email protected] commit -m …'. Use Read/Glob/Grep otherwise.",
+ "Bash command blocked for documentator. Allowed: git log, git show, git diff, ls, wc -l; Mode 2 only: 'git -C <repo> diff …', 'git -C <repo> log …', 'git -C <repo> add MEMORY.md', 'git -C <repo> -c user.name=Documentator -c [email protected] commit -m …'. Use Read/Glob/Grep otherwise.",
);
process.exit(2);
diff --git a/.claude/hooks/setup-worktree.mjs b/.claude/hooks/setup-worktree.mjs
index e3f7f78f..c70d22d0 100755
--- a/.claude/hooks/setup-worktree.mjs
+++ b/.claude/hooks/setup-worktree.mjs
@@ -246,15 +246,14 @@ toProvision.push(worktreePath);
releaseLock();
try {
- for (const wt of toProvision) ctx.linkNodeModules(wt);
+ for (const wt of toProvision) ctx.provisionWorktree(wt);
} catch (e) {
- // Fail closed (exit 2 → block the dispatch): a developer must not start in a
+ // Fail closed (exit 2 -> block the dispatch): a developer must not start in a
// worktree with no dependencies. An uncaught throw would exit 1, which a
- // PreToolUse hook treats as non-blocking — letting the broken dispatch run.
- ctx.fail(
- `node_modules provisioning failed for ${worktreePath}: ${e.message}`,
- { log: `provision-failed wt=${worktreePath}` },
- );
+ // PreToolUse hook treats as non-blocking, letting the broken dispatch run.
+ ctx.fail(`worktree provisioning failed for ${worktreePath}: ${e.message}`, {
+ log: `provision-failed wt=${worktreePath}`,
+ });
}
ctx.accept(`OK wt=${worktreePath}`);
diff --git a/.claude/hooks/test/bash-guard.test.mjs b/.claude/hooks/test/bash-guard.test.mjs
index bd5ddfa2..7379592c 100644
--- a/.claude/hooks/test/bash-guard.test.mjs
+++ b/.claude/hooks/test/bash-guard.test.mjs
@@ -1,6 +1,6 @@
// Tests for bash-guard.mjs — browser rules (any caller) and validation-command rules (gated agents only). Blocks are decision JSON on stdout with exit 0; allowed commands produce no decision.
-import { mkdtempSync, rmSync } from "node:fs";
+import { mkdtempSync, rmSync, writeFileSync } from "node:fs";
import { tmpdir } from "node:os";
import { dirname, join } from "node:path";
import { fileURLToPath } from "node:url";
@@ -28,6 +28,25 @@ const runHook = (agent, command) => {
return spawnSync("node", [HOOK], { input, env, encoding: "utf8" });
};
+// Run the hook against a temp repo whose harness.config.json we control, so we
+// can prove the forbidden-command set is DERIVED from config.validation.
+const runHookWithConfig = (agent, command, config) => {
+ const repo = mkdtempSync(join(tmpdir(), "bash-guard-repo-"));
+ writeFileSync(join(repo, "harness.config.json"), JSON.stringify(config));
+ const env = { ...process.env, CRM_TMP_ROOT: tmpRoot, APP_DIR: repo };
+ delete env.CLAUDE_AGENT_NAME;
+ delete env.CLAUDE_PROJECT_DIR;
+ const input = JSON.stringify({
+ tool_name: "Bash",
+ agent_type: agent,
+ session_id: "test-1234",
+ tool_input: { command },
+ });
+ const r = spawnSync("node", [HOOK], { input, env, encoding: "utf8" });
+ rmSync(repo, { recursive: true, force: true });
+ return r;
+};
+
const isBlocked = (r) => r.stdout.includes('"decision":"block"');
describe("bash-guard hook", () => {
@@ -105,6 +124,49 @@ describe("bash-guard hook", () => {
});
});
+ describe("forbidden set is config-driven (TA.2: no triple-encoding)", () => {
+ // A config with only a typecheck step and no extraForbidden: typecheck stays
+ // guarded, but unit/e2e/build are no longer part of the chain, so the guard
+ // must NOT block them.
+ const typecheckOnly = {
+ validation: {
+ steps: [
+ { id: "typecheck", kind: "typecheck", command: "npm run typecheck" },
+ ],
+ extraForbidden: [],
+ },
+ roles: { developer: { model: "sonnet" } },
+ };
+
+ test("a kind present in config is still blocked", () => {
+ const r = runHookWithConfig(
+ "developer",
+ "npm run typecheck",
+ typecheckOnly,
+ );
+ expect(isBlocked(r)).toBe(true);
+ });
+
+ test("a kind absent from config is NOT blocked", () => {
+ const r = runHookWithConfig("developer", "npx vitest run", typecheckOnly);
+ expect(isBlocked(r)).toBe(false);
+ });
+
+ test("removing lint from extraForbidden stops blocking lint", () => {
+ const r = runHookWithConfig("developer", "npm run lint", typecheckOnly);
+ expect(isBlocked(r)).toBe(false);
+ });
+
+ test("extraForbidden build is blocked when listed", () => {
+ const withBuild = {
+ validation: { steps: [], extraForbidden: ["build"] },
+ roles: { developer: { model: "sonnet" } },
+ };
+ const r = runHookWithConfig("developer", "npm run build", withBuild);
+ expect(isBlocked(r)).toBe(true);
+ });
+ });
+
describe("guard-state rule — orchestrator only", () => {
const SD = "/tmp/_repo/sess-1234";
diff --git a/.claude/hooks/test/check-config-sync.test.mjs b/.claude/hooks/test/check-config-sync.test.mjs
new file mode 100644
index 00000000..465e3dad
--- /dev/null
+++ b/.claude/hooks/test/check-config-sync.test.mjs
@@ -0,0 +1,74 @@
+// Tests for scripts/check-config-sync.mjs: settings.json SubagentStop role
+// matchers must all be declared in harness.config.json (config.roles).
+
+import { mkdirSync, 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 { afterEach, describe, test, expect } from "vitest";
+
+const HERE = dirname(fileURLToPath(import.meta.url));
+const SCRIPT = join(HERE, "..", "..", "scripts", "check-config-sync.mjs");
+const REPO_ROOT = join(HERE, "..", "..", "..");
+
+const tmpRepos = [];
+afterEach(() => {
+ while (tmpRepos.length)
+ rmSync(tmpRepos.pop(), { recursive: true, force: true });
+});
+
+// Build a temp repo with a harness.config.json (roles) and a settings.json
+// (SubagentStop matchers), then run the script against it.
+const runAgainst = ({ roles, matchers }) => {
+ const repo = mkdtempSync(join(tmpdir(), "config-sync-"));
+ tmpRepos.push(repo);
+ mkdirSync(join(repo, ".claude"), { recursive: true });
+ const rolesObj = Object.fromEntries(
+ roles.map((r) => [r, { model: "sonnet" }]),
+ );
+ writeFileSync(
+ join(repo, "harness.config.json"),
+ JSON.stringify({ validation: { steps: [] }, roles: rolesObj }),
+ );
+ const SubagentStop = matchers.map((m) => ({ matcher: m, hooks: [] }));
+ writeFileSync(
+ join(repo, ".claude", "settings.json"),
+ JSON.stringify({ hooks: { SubagentStop } }),
+ );
+ return spawnSync("node", [SCRIPT, "--app", repo], { encoding: "utf8" });
+};
+
+describe("check-config-sync", () => {
+ test("all matcher tokens declared → exit 0", () => {
+ const r = runAgainst({
+ roles: ["developer", "test-writer", "merger"],
+ matchers: ["developer|test-writer", "merger"],
+ });
+ expect(r.status).toBe(0);
+ });
+
+ test("a matcher token missing from config.roles → exit 1", () => {
+ const r = runAgainst({
+ roles: ["developer", "merger"],
+ matchers: ["developer|test-writer", "merger"],
+ });
+ expect(r.status).toBe(1);
+ expect(r.stderr).toContain("test-writer");
+ });
+
+ test("renaming a role in BOTH files stays in sync → exit 0", () => {
+ const r = runAgainst({
+ roles: ["dev", "merger"],
+ matchers: ["dev", "merger"],
+ });
+ expect(r.status).toBe(0);
+ });
+
+ test("the committed repo is in sync → exit 0", () => {
+ const r = spawnSync("node", [SCRIPT, "--app", REPO_ROOT], {
+ encoding: "utf8",
+ });
+ expect(r.status).toBe(0);
+ });
+});
diff --git a/.claude/hooks/test/config.test.mjs b/.claude/hooks/test/config.test.mjs
new file mode 100644
index 00000000..87e2ef36
--- /dev/null
+++ b/.claude/hooks/test/config.test.mjs
@@ -0,0 +1,130 @@
+// Tests for lib/config.mjs: the harness.config.json loader. It merges the file
+// over the built-in defaults, validates the shape (fail-closed on malformed),
+// and degrades to defaults when the file is missing.
+
+import { mkdtempSync, rmSync, writeFileSync } from "node:fs";
+import { tmpdir } from "node:os";
+import { dirname, join } from "node:path";
+import { fileURLToPath } from "node:url";
+import { afterEach, describe, test, expect } from "vitest";
+import {
+ loadConfig,
+ clearConfigCache,
+ CONFIG_FILENAME,
+ isDeployEnabled,
+ deployGlobs,
+ pipelineRoles,
+ debounceRoles,
+ roleModel,
+ worktreeProvision,
+} from "../lib/config.mjs";
+
+const REPO_ROOT = join(
+ dirname(fileURLToPath(import.meta.url)),
+ "..",
+ "..",
+ "..",
+);
+
+const tmpRepos = [];
+const makeRepo = (config) => {
+ const dir = mkdtempSync(join(tmpdir(), "harness-config-"));
+ tmpRepos.push(dir);
+ if (config !== undefined) {
+ writeFileSync(
+ join(dir, CONFIG_FILENAME),
+ typeof config === "string" ? config : JSON.stringify(config),
+ );
+ }
+ clearConfigCache();
+ return dir;
+};
+
+const VALID = {
+ name: "sample",
+ validation: {
+ steps: [
+ { id: "typecheck", kind: "typecheck", command: "npm run typecheck" },
+ {
+ id: "unit",
+ kind: "unit",
+ runner: "vitest",
+ config: "vitest.config.ts",
+ projects: ["app"],
+ },
+ ],
+ },
+ roles: {
+ developer: { model: "sonnet", pipeline: true, debounce: true },
+ planner: { model: "opus", pipeline: true, debounce: false },
+ },
+ deploy: { adapter: "supabase", relevantGlobs: ["supabase/**"] },
+};
+
+afterEach(() => {
+ while (tmpRepos.length)
+ rmSync(tmpRepos.pop(), { recursive: true, force: true });
+ clearConfigCache();
+});
+
+describe("config loader", () => {
+ test("loads a valid config and applies defaults for absent keys", () => {
+ const cfg = loadConfig(makeRepo(VALID));
+ expect(cfg.name).toBe("sample");
+ // default filled in when absent
+ expect(worktreeProvision(cfg)).toBe("npm-link");
+ expect(cfg.launcher.sessionDirEnv).toBe("CHAT_SESSION_DIR");
+ });
+
+ test("missing file degrades to defaults (no deploy capability)", () => {
+ const cfg = loadConfig(makeRepo(undefined));
+ expect(isDeployEnabled(cfg)).toBe(false);
+ expect(cfg.validation.steps).toEqual([]);
+ });
+
+ test("typed readers reflect the config", () => {
+ const cfg = loadConfig(makeRepo(VALID));
+ expect(isDeployEnabled(cfg)).toBe(true);
+ expect(deployGlobs(cfg)).toEqual(["supabase/**"]);
+ expect(pipelineRoles(cfg).sort()).toEqual(["developer", "planner"]);
+ expect(debounceRoles(cfg)).toEqual(["developer"]);
+ expect(roleModel(cfg, "planner")).toBe("opus");
+ });
+
+ test("malformed JSON throws a clear, prefixed error", () => {
+ expect(() => loadConfig(makeRepo("{ not json"))).toThrow(
+ new RegExp(`${CONFIG_FILENAME}: invalid JSON`),
+ );
+ });
+
+ test("validation.steps not an array is rejected", () => {
+ expect(() =>
+ loadConfig(makeRepo({ validation: { steps: {} }, roles: {} })),
+ ).toThrow(/validation\.steps` must be an array/);
+ });
+
+ test("a role missing a model is rejected", () => {
+ expect(() =>
+ loadConfig(
+ makeRepo({ validation: { steps: [] }, roles: { developer: {} } }),
+ ),
+ ).toThrow(/roles\.developer needs/);
+ });
+
+ test("deploy present but without relevantGlobs is rejected", () => {
+ expect(() =>
+ loadConfig(
+ makeRepo({ validation: { steps: [] }, roles: {}, deploy: {} }),
+ ),
+ ).toThrow(/deploy\.relevantGlobs/);
+ });
+
+ test("the committed harness.config.json is valid", () => {
+ clearConfigCache();
+ const cfg = loadConfig(REPO_ROOT);
+ expect(cfg.name).toBe("atomic-crm");
+ expect(isDeployEnabled(cfg)).toBe(true);
+ expect(roleModel(cfg, "quality-reviewer")).toBe("opus");
+ expect(pipelineRoles(cfg)).toContain("test-writer");
+ });
+});
diff --git a/.claude/hooks/test/format-on-write.test.mjs b/.claude/hooks/test/format-on-write.test.mjs
new file mode 100644
index 00000000..9f8d769a
--- /dev/null
+++ b/.claude/hooks/test/format-on-write.test.mjs
@@ -0,0 +1,89 @@
+// Tests for format-on-write.mjs: a PostToolUse(Write|Edit) hook that formats the
+// written file using the config's format-step formatter + extension list, on the
+// human/main-thread path only (harness subagents are skipped). The formatter here
+// is a sentinel-writing script so the test verifies invocation/scoping without
+// depending on prettier.
+
+import { existsSync, 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 { afterEach, describe, test, expect } from "vitest";
+
+const HERE = dirname(fileURLToPath(import.meta.url));
+const HOOK = join(HERE, "..", "format-on-write.mjs");
+
+const tmpRepos = [];
+afterEach(() => {
+ while (tmpRepos.length)
+ rmSync(tmpRepos.pop(), { recursive: true, force: true });
+});
+
+// Build a temp repo whose format step's formatter is a script that touches a
+// sentinel, so we can assert whether it ran. Returns { run(agent, file), sentinel }.
+const setup = (extensions = [".ts", ".tsx"]) => {
+ const repo = mkdtempSync(join(tmpdir(), "format-on-write-"));
+ tmpRepos.push(repo);
+ const sentinel = join(repo, ".fmt-ran");
+ writeFileSync(join(repo, "fmt.sh"), `#!/bin/sh\ntouch "${sentinel}"\n`);
+ writeFileSync(
+ join(repo, "harness.config.json"),
+ JSON.stringify({
+ validation: {
+ steps: [
+ {
+ id: "prettier",
+ kind: "format",
+ command: "true",
+ formatter: `sh ${join(repo, "fmt.sh")}`,
+ extensions,
+ },
+ ],
+ },
+ roles: {},
+ }),
+ );
+ const run = (agent, file) => {
+ const env = { ...process.env, APP_DIR: repo };
+ delete env.CLAUDE_PROJECT_DIR;
+ delete env.CLAUDE_AGENT_NAME;
+ const filePath = join(repo, file);
+ writeFileSync(filePath, "const x=1");
+ const input = JSON.stringify({
+ tool_name: "Write",
+ ...(agent ? { agent_type: agent } : {}),
+ tool_input: { file_path: filePath },
+ });
+ return spawnSync("node", [HOOK], { input, env, encoding: "utf8" });
+ };
+ return { run, sentinel };
+};
+
+describe("format-on-write hook", () => {
+ test("main thread + matching extension → formatter runs", () => {
+ const { run, sentinel } = setup();
+ const r = run("", "a.ts");
+ expect(r.status).toBe(0);
+ expect(existsSync(sentinel)).toBe(true);
+ });
+
+ test("harness subagent → skipped (formatter does not run)", () => {
+ const { run, sentinel } = setup();
+ const r = run("developer", "a.ts");
+ expect(r.status).toBe(0);
+ expect(existsSync(sentinel)).toBe(false);
+ });
+
+ test("non-matching extension → skipped", () => {
+ const { run, sentinel } = setup([".ts"]);
+ const r = run("", "notes.md");
+ expect(r.status).toBe(0);
+ expect(existsSync(sentinel)).toBe(false);
+ });
+
+ test("unparseable payload → exits 0", () => {
+ const r = spawnSync("node", [HOOK], { input: "nope", encoding: "utf8" });
+ expect(r.status).toBe(0);
+ });
+});
diff --git a/.claude/hooks/test/pre-pr-checks.test.mjs b/.claude/hooks/test/pre-pr-checks.test.mjs
new file mode 100644
index 00000000..bcd55546
--- /dev/null
+++ b/.claude/hooks/test/pre-pr-checks.test.mjs
@@ -0,0 +1,79 @@
+// Tests for pre-pr-checks.mjs: a PreToolUse(Bash) hook that runs the config's
+// typecheck/lint steps before `gh pr create` / `git push`, on the human path
+// only. exit 2 blocks the push; harness subagents and non-trigger commands pass.
+
+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 { afterEach, describe, test, expect } from "vitest";
+
+const HERE = dirname(fileURLToPath(import.meta.url));
+const HOOK = join(HERE, "..", "pre-pr-checks.mjs");
+
+const tmpRepos = [];
+afterEach(() => {
+ while (tmpRepos.length)
+ rmSync(tmpRepos.pop(), { recursive: true, force: true });
+});
+
+// Temp repo with a single typecheck step whose command is `true` (passes) or
+// `false` (fails). Returns run(agent, command).
+const setup = (checkCommand) => {
+ const repo = mkdtempSync(join(tmpdir(), "pre-pr-"));
+ tmpRepos.push(repo);
+ writeFileSync(
+ join(repo, "harness.config.json"),
+ JSON.stringify({
+ validation: {
+ steps: [{ id: "typecheck", kind: "typecheck", command: checkCommand }],
+ },
+ roles: {},
+ }),
+ );
+ return (agent, command) => {
+ const env = { ...process.env, APP_DIR: repo };
+ delete env.CLAUDE_PROJECT_DIR;
+ delete env.CLAUDE_AGENT_NAME;
+ const input = JSON.stringify({
+ tool_name: "Bash",
+ ...(agent ? { agent_type: agent } : {}),
+ tool_input: { command },
+ });
+ return spawnSync("node", [HOOK], { input, env, encoding: "utf8" });
+ };
+};
+
+describe("pre-pr-checks hook", () => {
+ test("git push with a failing check → blocked (exit 2)", () => {
+ const run = setup("false");
+ const r = run("", "git push origin HEAD");
+ expect(r.status).toBe(2);
+ expect(r.stderr).toContain("typecheck");
+ });
+
+ test("git push with a passing check → allowed (exit 0)", () => {
+ const run = setup("true");
+ const r = run("", "git push origin HEAD");
+ expect(r.status).toBe(0);
+ });
+
+ test("gh pr create triggers the checks", () => {
+ const run = setup("false");
+ const r = run("", "gh pr create --fill");
+ expect(r.status).toBe(2);
+ });
+
+ test("non-trigger command → not checked (exit 0)", () => {
+ const run = setup("false");
+ const r = run("", "git status");
+ expect(r.status).toBe(0);
+ });
+
+ test("harness subagent pushing → skipped (exit 0, dev-agent stops unaffected)", () => {
+ const run = setup("false");
+ const r = run("developer", "git push origin HEAD");
+ expect(r.status).toBe(0);
+ });
+});
diff --git a/.claude/hooks/test/provision-worktree.test.mjs b/.claude/hooks/test/provision-worktree.test.mjs
new file mode 100644
index 00000000..c977d285
--- /dev/null
+++ b/.claude/hooks/test/provision-worktree.test.mjs
@@ -0,0 +1,90 @@
+// Tests for the config-driven worktree provisioning dispatcher
+// (context.mjs provisionWorktree, config.worktree.provision): `npm-link`
+// (builtin), `none` (no-op), or a script path. Run in a child node process with
+// APP_DIR pointing at a temp repo, so paths.mjs REPO resolves to that repo's
+// harness.config.json.
+
+import { existsSync, mkdtempSync, rmSync, writeFileSync } from "node:fs";
+import { tmpdir } from "node:os";
+import { dirname, join } from "node:path";
+import { fileURLToPath, pathToFileURL } from "node:url";
+import { spawnSync } from "node:child_process";
+import { afterEach, describe, test, expect } from "vitest";
+
+const HERE = dirname(fileURLToPath(import.meta.url));
+const CTX_URL = pathToFileURL(join(HERE, "..", "lib", "context.mjs")).href;
+
+const tmpDirs = [];
+afterEach(() => {
+ while (tmpDirs.length)
+ rmSync(tmpDirs.pop(), { recursive: true, force: true });
+});
+
+// Run provisionWorktree(wt) in a child process whose REPO is `repo`.
+const runProvision = (repo, wt) => {
+ const script = `
+ const { createHookContext } = await import(${JSON.stringify(CTX_URL)});
+ const ctx = createHookContext({ session_id: "prov-test" }, "prov");
+ ctx.provisionWorktree(process.env.WT);
+ console.log("PROVISION_OK");
+ `;
+ const env = { ...process.env, APP_DIR: repo, WT: wt };
+ delete env.CLAUDE_PROJECT_DIR;
+ return spawnSync("node", ["--input-type=module", "-e", script], {
+ env,
+ encoding: "utf8",
+ });
+};
+
+const makeRepo = (provision) => {
+ const repo = mkdtempSync(join(tmpdir(), "provision-repo-"));
+ tmpDirs.push(repo);
+ writeFileSync(
+ join(repo, "harness.config.json"),
+ JSON.stringify({
+ validation: { steps: [] },
+ roles: {},
+ worktree: { provision },
+ }),
+ );
+ return repo;
+};
+
+const makeWorktree = () => {
+ const wt = mkdtempSync(join(tmpdir(), "provision-wt-"));
+ tmpDirs.push(wt);
+ return wt;
+};
+
+describe("worktree provisioning dispatcher", () => {
+ test("`none` provisions nothing and does not error", () => {
+ const repo = makeRepo("none");
+ const wt = makeWorktree();
+ const r = runProvision(repo, wt);
+ expect(r.status).toBe(0);
+ expect(r.stdout).toContain("PROVISION_OK");
+ expect(existsSync(join(wt, "node_modules"))).toBe(false);
+ });
+
+ test("a script path is run with the worktree as its argument", () => {
+ const repo = makeRepo("provision.sh");
+ const sentinel = join(repo, ".provisioned");
+ // $1 is the worktree path; the script records that it ran.
+ writeFileSync(
+ join(repo, "provision.sh"),
+ `#!/bin/sh\necho "$1" > "${sentinel}"\n`,
+ );
+ const wt = makeWorktree();
+ const r = runProvision(repo, wt);
+ expect(r.status).toBe(0);
+ expect(existsSync(sentinel)).toBe(true);
+ });
+
+ test("default `npm-link` with no source node_modules is a safe no-op", () => {
+ const repo = makeRepo("npm-link"); // repo has no node_modules to mirror
+ const wt = makeWorktree();
+ const r = runProvision(repo, wt);
+ expect(r.status).toBe(0);
+ expect(existsSync(join(wt, "node_modules"))).toBe(false);
+ });
+});
diff --git a/.claude/hooks/test/turn-complete.test.mjs b/.claude/hooks/test/turn-complete.test.mjs
index 5147afde..f05088d4 100644
--- a/.claude/hooks/test/turn-complete.test.mjs
+++ b/.claude/hooks/test/turn-complete.test.mjs
@@ -3,7 +3,8 @@
// watcher polls. Must always exit 0 (a Stop hook never blocks) and never throw on
// a missing/malformed payload.
-import { existsSync, rmSync } from "node:fs";
+import { existsSync, 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";
@@ -33,4 +34,26 @@ describe("turn-complete", () => {
test("malformed payload → no throw, exits 0", () => {
expect(run("not json").status).toBe(0);
});
+
+ test("inert when config.launcher.turnSentinelDir is unset (no launcher)", () => {
+ // A repo whose config omits turnSentinelDir: the hook writes no sentinel.
+ const repo = mkdtempSync(join(tmpdir(), "turn-complete-repo-"));
+ writeFileSync(
+ join(repo, "harness.config.json"),
+ JSON.stringify({ validation: { steps: [] }, roles: {}, launcher: {} }),
+ );
+ const otherSid = "turn-complete-inert-9c1d";
+ const wouldBe = join("/tmp/pty-sentinels", `pty-turn-done-${otherSid}`);
+ rmSync(wouldBe, { force: true });
+ const env = { ...process.env, APP_DIR: repo };
+ delete env.CLAUDE_PROJECT_DIR;
+ const r = spawnSync("node", [HOOK], {
+ input: JSON.stringify({ session_id: otherSid }),
+ env,
+ encoding: "utf8",
+ });
+ expect(r.status).toBe(0);
+ expect(existsSync(wouldBe)).toBe(false);
+ rmSync(repo, { recursive: true, force: true });
+ });
});
diff --git a/.claude/hooks/turn-complete.mjs b/.claude/hooks/turn-complete.mjs
index aca81b5b..f99a89a9 100755
--- a/.claude/hooks/turn-complete.mjs
+++ b/.claude/hooks/turn-complete.mjs
@@ -1,22 +1,34 @@
#!/usr/bin/env node
-// Stop — create a sentinel file so the chat-service PtySession knows the turn is
-// complete. Stop fires after the JSONL transcript has been fully written, so the
-// watcher can emit its result event only once the transcript is flushed. The
-// watcher polls /tmp/pty-sentinels/pty-turn-done-<session_id>; a dedicated subdir
-// avoids waking every session's watcher on unrelated /tmp activity.
+// Stop: drop a per-session sentinel file so a managed launcher (e.g. CRM
+// Builder's chat-service PtySession) knows the turn is complete. Stop fires after
+// the JSONL transcript is fully written, so the watcher can emit its result event
+// only once the transcript is flushed.
+//
+// The sentinel directory is a launcher extension point: config.launcher
+// .turnSentinelDir (see .claude/rules/launcher-interface.md). When it is unset
+// (no managed launcher), this hook is INERT: no directory is created, no path is
+// hardcoded. Atomic CRM's config sets it to /tmp/pty-sentinels, preserving the
+// current CRM Builder behavior.
import { closeSync, mkdirSync, openSync, readFileSync } from "node:fs";
import { join } from "node:path";
+import { loadConfig, launcher } from "./lib/config.mjs";
let sid = "";
try {
sid = JSON.parse(readFileSync(0, "utf8")).session_id || "";
} catch {
- // no session id → nothing to signal
+ // no session id -> nothing to signal
}
-if (sid) {
- const dir = "/tmp/pty-sentinels";
+let dir = null;
+try {
+ dir = launcher(loadConfig()).turnSentinelDir || null;
+} catch {
+ dir = null; // fail-open: a config error must never break the Stop hook
+}
+
+if (sid && dir) {
mkdirSync(dir, { recursive: true });
closeSync(openSync(join(dir, `pty-turn-done-${sid}`), "w"));
}
diff --git a/.claude/rules/launcher-interface.md b/.claude/rules/launcher-interface.md
new file mode 100644
index 00000000..2535102e
--- /dev/null
+++ b/.claude/rules/launcher-interface.md
@@ -0,0 +1,30 @@
+# Launcher interface
+
+A "managed launcher" is an external surface that drives the harness (CRM
+Builder's chat-service is the reference launcher). The harness core stays neutral:
+every launcher-specific fact is an extension point under `config.launcher` in
+`harness.config.json`, and each consuming hook is INERT when its point is unset.
+CRM Builder / chat-service specifics live in Atomic CRM's project layer (its
+`harness.config.json`), never in a core hook.
+
+## Extension points (`config.launcher`)
+
+| Key | Meaning | Consumer | Unset behavior |
+|---|---|---|---|
+| `sessionDirEnv` | Env var carrying the managed session dir (default `CHAT_SESSION_DIR`) | `context.mjs`, `reviews.mjs`, `session-bootstrap.mjs` read this env directly | falls back to the recomputed `/tmp/<repo>/<id>` session dir |
+| `turnSentinelDir` | Dir where `turn-complete.mjs` drops `pty-turn-done-<sid>` so the launcher knows the turn ended | `turn-complete.mjs` | hook writes nothing (inert) |
+| `postCheckoutScript` | Script the merger runs after checkout to materialize the app variant | `merger.md` (runs it), `block-orchestrator-merge.mjs` (gates it merger-only) | not run; the guard clause is inert |
+| `logsDir` | Managed-launcher log dir agents may redirect into | `bash-guard.mjs` (redirect exemption) | only `/dev/null` is exempt |
+
+`CHAT_SESSION_DIR` is kept as the generic "managed session dir" variable name:
+it is set by the launcher, not by the core. Persona injection stays the
+launcher's job too, via `--append-system-prompt` (the web-chat orchestrator is
+this same `orchestrator` with a non-technical persona layered on at launch); the
+core never hardcodes a persona.
+
+## Adding a launcher
+
+Set the four keys under `config.launcher` in your project's `harness.config.json`.
+Leave a key unset (or the whole `launcher` block absent) and the matching hook
+stays inert, so a project with no managed launcher runs the harness with zero
+launcher coupling.
diff --git a/.claude/rules/validation-commands.md b/.claude/rules/validation-commands.md
index 10e325a1..8f122417 100644
--- a/.claude/rules/validation-commands.md
+++ b/.claude/rules/validation-commands.md
@@ -2,30 +2,38 @@
paths: []
---
-# Validation commands — DO NOT RUN
+# Validation commands: DO NOT RUN
-Validation is automated:
-- The `validate-on-stop.mjs` SubagentStop hook runs the full chain (prettier auto-fix, typecheck, unit, e2e) after every developer stop (ticket or lightweight MODE). A failed validation rejects the stop, the developer's internal loop fixes the issue, and only a green stop returns control to the orchestrator.
-- The `bash-guard.mjs` PreToolUse hook blocks `developer`, `quality-reviewer` from running them manually.
-- Prettier is auto-applied and committed by the validation chain — formatting never needs manual action unless a file has a syntax error.
+Validation is automated and config-driven. The steps live in ONE place,
+`harness.config.json` -> `validation.steps`, consumed by both the runner and the
+guard, so they can never drift:
-## Forbidden commands (developer / quality-reviewer)
+- `validate-on-stop.mjs` (SubagentStop) runs the whole chain after every
+ developer / test-writer stop: the format step (prettier auto-fix + commit),
+ typecheck, the unit steps, then e2e once in the repo (full mode only). A failed
+ step rejects the stop; the agent's internal loop fixes it and only a green stop
+ returns control to the orchestrator.
+- `bash-guard.mjs` (PreToolUse Bash) blocks `developer` / `quality-reviewer` from
+ running those same commands manually, plus `validation.extraForbidden` (lint,
+ build). The forbidden set is DERIVED from `validation.steps`, not hardcoded here.
-| Category | Commands |
-|---|---|
-| typecheck | `make typecheck`, `npm run typecheck`, `npx tsc`, `npx tsc --noEmit` |
-| prettier | `make lint`, `npm run prettier`, `npm run prettier:apply`, `npx prettier` |
-| unit tests | `npm run test:unit:app`, `npm run test:unit:functions`, `npm test`, `npx vitest`, `make test-unit*` |
-| e2e | `npx playwright test`, `make test-e2e*` |
-| lint | `npm run lint`, `npm run lint:typescript` |
-| build | `npx vite build`, `npm run build` |
+## Why blocked (developer / quality-reviewer)
-Why blocked:
-- Burns tool budget — each call returns a hook block error.
-- Can hang — `npx vitest` launches a headed Chromium browser; without a display it waits forever. Hooks set `CI=true` to force `chromium-headless-shell`; manual calls don't.
-- Duplicates hook work — the validation hooks already run them; failures appear in stderr.
+- Burns tool budget: each manual call the hook already runs is wasted.
+- Can hang: `npx vitest` launches a headed Chromium; without a display it waits
+ forever. The hooks set `CI=true` to force `chromium-headless-shell`; manual
+ calls do not.
+- Duplicates hook work: the validation hooks already run these; failures come back
+ on stderr.
+
+To change what runs (or what is forbidden), edit `harness.config.json`, never a
+command string in a hook or in this file.
## What to do instead
-- **Developer**: after implementation + commit, stop. Hooks run, inject failures via stderr if any. Fix and commit again on the next turn. Don't run the merge yourself — that's the merger's job.
-- **Reviewers**: focus on what hooks can't check (semantic review, integration wiring, e2e spec presence). To verify TypeScript, `Read` the source — don't run the compiler.
+- **Developer / test-writer**: after implementation + commit, stop. The hooks
+ run and inject any failures via stderr. Fix and commit again next turn. Do not
+ run the merge yourself: that is the merger's job.
+- **Reviewers**: focus on what hooks can't check (semantic review, integration
+ wiring, e2e spec presence). To verify TypeScript, `Read` the source, do not run
+ the compiler.
diff --git a/.claude/scripts/check-config-sync.mjs b/.claude/scripts/check-config-sync.mjs
new file mode 100755
index 00000000..f412f43c
--- /dev/null
+++ b/.claude/scripts/check-config-sync.mjs
@@ -0,0 +1,86 @@
+#!/usr/bin/env node
+// Verify that every agent-role referenced by a settings.json SubagentStop matcher
+// is a declared role in harness.config.json (config.roles). Claude Code requires
+// settings.json matchers to be literal strings (they cannot be computed from the
+// config), so this check is the bridge that keeps the two in sync: rename a role
+// in config AND settings -> the matcher token still resolves, pass; rename it in
+// config only -> the stale settings token is not a config role, fail.
+//
+// Usage: node .claude/scripts/check-config-sync.mjs [--app <repo>]
+// Exit 0 = in sync; exit 1 = drift (prints the offending tokens).
+
+import { existsSync, readFileSync } from "node:fs";
+import { join } from "node:path";
+import { loadConfig, roleNames } from "../hooks/lib/config.mjs";
+
+function resolveRepo(argv) {
+ const flag = argv.indexOf("--app");
+ if (flag !== -1 && argv[flag + 1]) return argv[flag + 1];
+ return process.env.APP_DIR || process.env.CLAUDE_PROJECT_DIR || process.cwd();
+}
+
+// SubagentStop matchers are role tokens (possibly `a|b`); PreToolUse/PostToolUse
+// matchers are tool names (Bash, Agent, Write|Edit) and are NOT roles, so only
+// SubagentStop is checked here.
+function settingsRoleTokens(settings) {
+ const entries = settings.hooks?.SubagentStop ?? [];
+ const tokens = new Set();
+ for (const entry of entries) {
+ const matcher = entry.matcher;
+ if (!matcher || typeof matcher !== "string") continue;
+ for (const t of matcher
+ .split("|")
+ .map((s) => s.trim())
+ .filter(Boolean)) {
+ tokens.add(t);
+ }
+ }
+ return [...tokens];
+}
+
+export function checkConfigSync(repo) {
+ const settingsPath = join(repo, ".claude", "settings.json");
+ if (!existsSync(settingsPath)) {
+ return { ok: false, error: `settings.json not found at ${settingsPath}` };
+ }
+ let settings;
+ try {
+ settings = JSON.parse(readFileSync(settingsPath, "utf8"));
+ } catch (e) {
+ return {
+ ok: false,
+ error: `settings.json is not valid JSON: ${e.message}`,
+ };
+ }
+ let roles;
+ try {
+ roles = new Set(roleNames(loadConfig(repo)));
+ } catch (e) {
+ return { ok: false, error: e.message };
+ }
+ const tokens = settingsRoleTokens(settings);
+ const missing = tokens.filter((t) => !roles.has(t));
+ return { ok: missing.length === 0, missing, tokens, roles: [...roles] };
+}
+
+// Run as CLI when invoked directly (not when imported by a test).
+if (import.meta.url === `file://${process.argv[1]}`) {
+ const repo = resolveRepo(process.argv.slice(2));
+ const r = checkConfigSync(repo);
+ if (r.error) {
+ console.error(`check-config-sync: ${r.error}`);
+ process.exit(1);
+ }
+ if (!r.ok) {
+ console.error(
+ `check-config-sync: settings.json SubagentStop matcher(s) reference roles not in harness.config.json: ${r.missing.join(", ")}.\n` +
+ `Declared roles: ${r.roles.join(", ")}.\n` +
+ `Rename the role in BOTH files, or add it to config.roles.`,
+ );
+ process.exit(1);
+ }
+ process.stdout.write(
+ `check-config-sync: OK (${r.tokens.length} role matcher(s) all declared)\n`,
+ );
+ process.exit(0);
+}
diff --git a/.claude/settings.json b/.claude/settings.json
index 2f62fd22..669ed0d0 100644
--- a/.claude/settings.json
+++ b/.claude/settings.json
@@ -18,7 +18,13 @@
"ENABLE_LSP_TOOL": "1"
},
"permissions": {
- "allow": []
+ "allow": [],
+ "deny": [
+ "Bash(npm install *)",
+ "Bash(npm i *)",
+ "Bash(pnpm add *)",
+ "Bash(yarn add *)"
+ ]
},
"attribution": {
"commit": "",
@@ -49,6 +55,11 @@
"type": "command",
"command": "$CLAUDE_PROJECT_DIR/.claude/hooks/bash-guard.mjs"
},
+ {
+ "type": "command",
+ "command": "$CLAUDE_PROJECT_DIR/.claude/hooks/pre-pr-checks.mjs",
+ "timeout": 150
+ },
{
"type": "command",
"command": "$CLAUDE_PROJECT_DIR/.claude/hooks/block-docker-containers.mjs"
@@ -116,6 +127,33 @@
]
}
],
+ "PostToolUse": [
+ {
+ "matcher": "Write|Edit",
+ "hooks": [
+ {
+ "type": "command",
+ "command": "$CLAUDE_PROJECT_DIR/.claude/hooks/format-on-write.mjs",
+ "timeout": 20
+ },
+ {
+ "type": "command",
+ "command": "$CLAUDE_PROJECT_DIR/.claude/hooks/check-typescript-shortcuts.mjs"
+ }
+ ]
+ }
+ ],
+ "PostCompact": [
+ {
+ "hooks": [
+ {
+ "type": "command",
+ "command": "$CLAUDE_PROJECT_DIR/.claude/hooks/reinject-invariants.mjs",
+ "timeout": 5
+ }
+ ]
+ }
+ ],
"Stop": [
{
"hooks": [
@@ -150,7 +188,7 @@
]
},
{
- "matcher": "developer",
+ "matcher": "developer|test-writer",
"hooks": [
{
"type": "command",
diff --git a/CLAUDE.md b/CLAUDE.md
index 6ba71459..8c0d45e9 100644
--- a/CLAUDE.md
+++ b/CLAUDE.md
@@ -2,39 +2,36 @@
# Agent Workflow
-Code-change requests can be handled by the **agent harness**: a team of subagents (planner, developer, quality-reviewer, merger, documentator) that implements the change through a deterministic, foreground pipeline in git worktrees. **It is opt-in and does NOT run by default;** by default the main thread implements the change itself, no agents.
+Code-change requests can run through the **agent harness**: subagents (planner, developer, quality-reviewer, merger, documentator) implementing the change via a deterministic foreground pipeline in git worktrees. **Opt-in, off by default;** otherwise the main thread implements the change itself.
-**Dispatch rule (top-level session only).** Only when the request opts into the harness (triggers under "Opting in") does the top-level session dispatch the `orchestrator` agent and relay its result; never route or implement it yourself in that case. Pass your context's `<session_dir>` in the dispatch prompt (the orchestrator needs it to namespace worktrees and branches). If you are a subagent (already inside the harness), ignore this: do your own job and never dispatch an orchestrator (the `block-nested-orchestrator` hook enforces it). The orchestrator owns all routing (classification SIMPLE vs COMPLEX, plus the SETUP / MEMORY / ROLLBACK-CONFLICT / RECOVERY intents, dispatch templates, wave + promotion mechanics, and the deploy-time migration round); it drives developer/reviewer/merger to a terminal point before returning. Each agent's last line is an output contract the others parse (`.claude/rules/agent-output-format.md`).
+**Dispatch rule (top-level session only).** Only on an opt-in (see "Opting in") does the top-level session dispatch the `orchestrator` and relay its result; never route or implement it yourself then. Pass your `<session_dir>` in the prompt (it namespaces worktrees/branches). A subagent NEVER dispatches an orchestrator (`block-nested-orchestrator` enforces it). The orchestrator owns all routing (SIMPLE/COMPLEX, plus SETUP/MEMORY/ROLLBACK-CONFLICT/RECOVERY, dispatch templates, waves, promotion, migration round) and drives the team to a terminal point. Each agent's last line is an output contract (`.claude/rules/agent-output-format.md`).
-**"Launched" is NOT "done" (read before you fill the silence).** The dispatch is *meant* to block until the orchestrator's final report, but in some runtimes (interactive Claude Code / the VS Code extension) the `Agent` tool returns immediately with `Async agent launched successfully … agentId: <id>` and the real result arrives later as a `task-notification`. That acknowledgement means dispatched, not finished. Do NOT read the quiet as "nothing is happening", and do NOT start implementing the feature yourself (no `Write`/`Edit`/`Bash` on the change, no re-dispatch): that is the exact bug that produces a duplicate, the main thread coding the same feature the orchestrator's developer is already building. While it runs your ONLY job is to surface progress and then relay the final `task-notification` report: for a `#technical-harness` run, stream its progress log into the chat (recipe under "Opting in"); for a plain `#harness` run there is no log, so just wait for the notification. This mirrors the guard the orchestrator applies to its own workers (`.claude/agents/orchestrator.md` → "launched is NOT done"). On the orchestrator's completion, before relaying, check `<session_dir>/needs-recovery`: the `completion-invariant` hook writes it when the orchestrator stopped with APPROVED-but-unmerged work (a nested orchestrator cannot resume itself). If present, dispatch a FRESH `orchestrator` whose prompt begins with `<intent>recovery</intent>` and passes the same `<session_dir>` (never `SendMessage` the old one); wait for it, then relay. It clears the marker on a clean finish.
+**"Launched" is NOT "done".** The dispatch is meant to block, but some runtimes (interactive Claude Code / the VS Code extension) return immediately with `Async agent launched … agentId: <id>` and deliver the result later as a `task-notification`. That ack means dispatched, not finished: do NOT fill the silence by implementing the feature yourself or re-dispatching (that duplicates the developer's work). While it runs, only surface progress, then relay the final report. On completion, before relaying, check `<session_dir>/needs-recovery` (written by `completion-invariant` when the orchestrator stopped with APPROVED-but-unmerged work): if present, dispatch a FRESH `orchestrator` with `<intent>recovery</intent>` and the same `<session_dir>` (never `SendMessage` the old one), wait, then relay.
-**PD-ASK round-trip (migration confirmation).** The orchestrator ends its turn with a pending question, typically *"apply the database migration now?"*, and the task completes. Relay it to the user (plain text or `AskUserQuestion`). Do NOT resume the old orchestrator with `SendMessage` to relay the answer: the runtime tags coordinator messages as carrying no user authority, so a relayed approval is ignored and the orchestrator loops re-asking forever. On the user's reply:
-- **Approved**: FIRST record the approval durably (otherwise its only audit trail is this conversation): write `<session_dir>/migration-approval.json` = `{"kind":"migration-approval","session_id":"<id>","question":"<what you asked>","answer":"<the user's verbatim reply>","approved_at":"<ISO-8601>","via":"AskUserQuestion"}`. THEN dispatch a **fresh** `orchestrator` (new `Agent` call) whose prompt begins with `<intent>apply-migration</intent>`, states the approval, references that record, and passes the same `<session_dir>`; it resumes the migration round from disk, applies it, and stamps the provenance onto the migration commit. The built-in security warning on a relayed approval still fires and is expected: the record is the durable trail, not a suppression of that warning.
-- **Wants changes**: dispatch a fresh `orchestrator` with the new request as usual.
+**PD-ASK round-trip (migration confirmation).** The orchestrator may end its turn asking *"apply the database migration now?"*. Relay it to the user; do NOT `SendMessage` the old orchestrator to relay the answer (relayed approvals carry no user authority, so it loops re-asking). On the reply:
+- **Approved**: FIRST write `<session_dir>/migration-approval.json` = `{"kind":"migration-approval","session_id":"<id>","question":"<asked>","answer":"<user's verbatim reply>","approved_at":"<ISO-8601>","via":"AskUserQuestion"}` (the durable audit trail). THEN dispatch a FRESH `orchestrator` whose prompt begins `<intent>apply-migration</intent>`, states the approval, references that record, and passes the same `<session_dir>`. The built-in security warning on a relayed approval is expected.
+- **Wants changes**: dispatch a fresh `orchestrator` with the new request.
-While that fresh dispatch runs, do not start a parallel plan B (don't generate the migration yourself, don't `TaskStop` it); wait for it to finish, then relay its result.
+While a fresh dispatch runs, don't start a parallel plan B; wait, then relay.
-**Gate level (plan review vs autonomy).** A harness request may carry `gate=none|plan|waves` (default **`plan`**); ALWAYS pass it as an explicit `GATE: <level>` line in the orchestrator dispatch prompt (use `GATE: plan` when the user did not specify). The orchestrator also fails closed (a missing or unrecognized `GATE` is treated as `plan`), so the gate is never silently skipped by an omitted line. `plan` (default) pauses after planning so the user reviews the tickets before any code is written; `none` runs autonomously to the terminal point (overnight); `waves` also pauses at each wave boundary. On a plan-gate pause, relay the plan + approval question to the user; on approval, dispatch a FRESH `orchestrator` with `<intent>execute-plan</intent>` and the same `<session_dir>` (never `SendMessage` the old one, same rule as the migration round-trip); on "wants changes", dispatch a fresh orchestrator with their new input. CRM Builder's launcher sets `gate=none`.
+**Gate level.** A request may carry `gate=none|plan|waves` (default **`plan`**); ALWAYS pass an explicit `GATE: <level>` line (the orchestrator also fails closed to `plan` on a missing/unknown value). `plan` pauses after planning for ticket review; `none` runs autonomously; `waves` also pauses at each wave. On a plan pause, relay the plan + question; on approval dispatch a FRESH `orchestrator` with `<intent>execute-plan</intent>` and the same `<session_dir>` (never `SendMessage`); on "wants changes" dispatch a fresh one. CRM Builder's launcher sets `gate=none`.
## Opting in
-Off by default. `#harness` (or "use the agent team" / "with the harness") routes a request through the orchestrator; "harness for this session" keeps it on for the whole session.
+Off by default. `#harness` (or "use the agent team" / "with the harness") routes through the orchestrator; "harness for this session" keeps it on all session.
-`#technical-harness` is the same opt-in for a real developer: it routes through the orchestrator **and** appends a `PERSONA: technical` line to the dispatch prompt (details in `.claude/agents/orchestrator.md` → "`PERSONA: technical`"), which changes four things:
+**Grill vague requests first.** For a vague or broad `#harness` request, run `Skill({skill: "grill-me"})` in the main thread BEFORE dispatching (the planner never questions; `gate=plan` only reacts after a plan). Fold the answers into the dispatch prompt. Skip when the request is already precise.
-1. **Full technical register:** removes the plain-language filter that hides file paths, `TASK-XXX`, git terms, and words like `database`/`migration`/`Supabase`.
-2. **Raw reporting:** the mechanical truth (per-ticket status, branch names, commit SHAs, reviewer verdicts, ADR paths), not a softened summary.
-3. **Stops at the session branch:** merges all work into `session/<id>` but does NOT promote to the base branch and does NOT run the deploy-time migration round; you review, promote, and generate/apply migrations yourself.
-4. **Live progress log:** appends each step (ticket dispatched, developer done, reviewer verdict, merge) to `<session_dir>/harness-progress.log`.
+`#technical-harness` is the same opt-in for a real developer: it appends a `PERSONA: technical` line (see `orchestrator.md` -> "`PERSONA: technical`"), which (1) uses the full technical register (file paths, `TASK-XXX`, git terms, `database`/`migration`/`Supabase`), (2) reports the mechanical truth (per-ticket status, branches, SHAs, verdicts, ADR paths), (3) stops at `session/<id>` (no promotion, no migration round; you promote and migrate yourself), and (4) appends every step to `<session_dir>/harness-progress.log`.
-**Live progress in the chat.** The orchestrator's report lands only when the run finishes (and may arrive as a `task-notification`, see "launched is NOT done" above), so give the developer a live feed of the progress log it appends to (effect 4). Dispatch the orchestrator with `run_in_background: true`, then immediately start a `Monitor` on that log so every step lands in the chat as it happens: `Monitor({command: "tail -n +1 -F <session_dir>/harness-progress.log", description: "harness progress", persistent: true})` (substitute the real `<session_dir>`; every log line is a real event, so no grep filter, and `-F` tolerates the file not existing yet). Do nothing else while it runs. The **authoritative** end signal is the orchestrator's `task-notification`, not the log (a crashed run goes quiet but still notifies): on it, `TaskStop` the monitor, relay the final report, and run `/harness-diff` to show the net diff of the session branch it stopped on. (A developer who prefers a terminal can also `tail -f` the same file directly.)
+**Live progress in the chat (technical runs).** The report lands only at the end (possibly as a `task-notification`), so feed the log live: dispatch the orchestrator with `run_in_background: true`, then `Monitor({command: "tail -n +1 -F <session_dir>/harness-progress.log", description: "harness progress", persistent: true})` (real `<session_dir>`; `-F` tolerates a missing file). Do nothing else while it runs. The authoritative end signal is the `task-notification`, not the log: on it, `TaskStop` the monitor, relay the report, and run `/harness-diff` on the session branch it stopped on.
## Agents
-orchestrator (routes the harness, dispatched by the main thread), planner, developer, quality-reviewer, merger, documentator. Models/roles: see each `.claude/agents/*.md`; **planner** and **quality-reviewer** run on opus, everything else on sonnet or haiku. (The web-chat variant is this same `orchestrator` with a non-technical persona layered on at launch via `--append-system-prompt`, used by CRM Builder.)
+orchestrator (routes the harness, dispatched by the main thread), planner, developer, quality-reviewer, merger, documentator. Models: **planner** and **quality-reviewer** on opus, the rest on sonnet/haiku (see each `.claude/agents/*.md`). The web-chat variant is this orchestrator with a non-technical persona injected via `--append-system-prompt` (CRM Builder).
-The **developer** is a single agent with no modes: it implements the ticket in `TICKET_FILE` (COMPLEX wave, peer-reviewed, writes ADRs for structural decisions, never writes SQL during tickets), or for a SIMPLE dispatch the change described inline via `CHANGE_REQUEST` (no ticket, no planner, on the shared `<base>/simple` worktree; it refuses with `FAILED: out of scope, needs COMPLEX flow` if the change needs a breakdown). Two session-level operations reach it as **skills** loaded on dispatch, run on the same `<base>/simple` worktree: `writing-migrations` (deploy-time SQL generation) and `resolving-rollback-conflicts` (replay merge-commit reverts). It applies the **Ponytail** minimization ladder (full mode) on every change: this is baked into its agent prompt (`developer.md` "Ponytail full mode is always on"), always in context on every dispatch, and the quality-reviewer enforces the same ladder on the resulting diff (flags over-engineering). It is a reasoning directive, not a hook-enforced step. Ponytail is also installed natively in-repo as on-demand skills (`.claude/skills/ponytail*`) and `/ponytail*` commands for interactive use in the main session; these do not affect the dev agents.
+The **developer** is one agent, no modes: it implements a `TICKET_FILE` (COMPLEX wave, peer-reviewed, ADRs for structural decisions, never SQL during tickets) or an inline `CHANGE_REQUEST` (SIMPLE, on the shared `<base>/simple` worktree; refuses `FAILED: out of scope, needs COMPLEX flow` if it needs a breakdown). Two session ops reach it as dispatch-loaded skills on `<base>/simple`: `writing-migrations` and `resolving-rollback-conflicts`. It applies the **Ponytail** ladder (full mode) on every change (baked into `developer.md`; the quality-reviewer enforces it on the diff). Ponytail is also in-repo as `.claude/skills/ponytail*` / `/ponytail*` for interactive use (these do not affect the dev agents). An optional `test-writer` runs only when a ticket sets `separate_test_writer: true`.
## Rules & hooks
-Mechanics live in `.claude/rules/` (worktree-scope, agent-output-format, validation-commands, lsp-usage, security-triggers). Hooks in `.claude/settings.json` / `.claude/hooks/` are `.mjs` ES modules.
+Mechanics live in `.claude/rules/` (worktree-scope, agent-output-format, validation-commands, lsp-usage, security-triggers, dependency-safety, launcher-interface). Project facts (validation steps, roles, deploy adapter, app smoke, launcher extension points) live in `harness.config.json`. Hooks in `.claude/settings.json` / `.claude/hooks/` are `.mjs` ES modules.
diff --git a/harness.config.json b/harness.config.json
new file mode 100644
index 00000000..a5626467
--- /dev/null
+++ b/harness.config.json
@@ -0,0 +1,100 @@
+{
+ "name": "atomic-crm",
+ "layout": {
+ "src": "src",
+ "e2e": "e2e",
+ "adr": "adr"
+ },
+ "validation": {
+ "steps": [
+ {
+ "id": "prettier",
+ "kind": "format",
+ "command": "npx prettier --write 'src/**/*.{ts,tsx,js,jsx,css,json,html}'",
+ "formatter": "npx prettier --write",
+ "autoCommit": true,
+ "extensions": [".ts", ".tsx", ".js", ".jsx", ".css", ".json", ".html"]
+ },
+ {
+ "id": "typecheck",
+ "kind": "typecheck",
+ "command": "npm run typecheck"
+ },
+ {
+ "id": "unit-app",
+ "kind": "unit",
+ "runner": "vitest",
+ "config": "vitest.config.ts",
+ "projects": ["app", "claude"],
+ "changedScoped": true
+ },
+ {
+ "id": "unit-fn",
+ "kind": "unit",
+ "runner": "vitest",
+ "config": "vitest.config.ts",
+ "projects": ["functions"],
+ "changedScoped": true,
+ "condition": { "pathExists": "supabase/functions" }
+ },
+ {
+ "id": "e2e",
+ "kind": "e2e",
+ "command": "npx playwright test",
+ "cwd": "repo",
+ "condition": { "modeNot": "demo" }
+ }
+ ],
+ "extraForbidden": ["lint", "build"]
+ },
+ "worktree": {
+ "provision": "npm-link"
+ },
+ "app": {
+ "smokeCommand": "npm run dev:demo",
+ "portBase": 5300,
+ "portArg": "--port",
+ "strictPortArg": "--strictPort",
+ "hashRouting": true,
+ "demoMode": true
+ },
+ "deploy": {
+ "adapter": "supabase",
+ "relevantGlobs": ["supabase/**"],
+ "schemaDir": "supabase/schemas",
+ "migrationsDir": "supabase/migrations"
+ },
+ "skills": {
+ "developerMenu": [
+ "frontend-dev",
+ "backend-dev",
+ "shadcn-customization",
+ "e2e-conventions",
+ "playwright-testing",
+ "adr-writing"
+ ]
+ },
+ "roles": {
+ "orchestrator": { "model": "sonnet", "pipeline": false, "debounce": false },
+ "planner": { "model": "opus", "pipeline": true, "debounce": false },
+ "developer": { "model": "sonnet", "pipeline": true, "debounce": true },
+ "simple-developer": {
+ "model": "sonnet",
+ "pipeline": true,
+ "debounce": false
+ },
+ "test-writer": { "model": "sonnet", "pipeline": true, "debounce": false },
+ "quality-reviewer": { "model": "opus", "pipeline": true, "debounce": true },
+ "merger": { "model": "haiku", "pipeline": true, "debounce": true },
+ "documentator": { "model": "sonnet", "pipeline": false, "debounce": false }
+ },
+ "documentator": {
+ "author": { "name": "Documentator", "email": "[email protected]" }
+ },
+ "launcher": {
+ "sessionDirEnv": "CHAT_SESSION_DIR",
+ "turnSentinelDir": "/tmp/pty-sentinels",
+ "postCheckoutScript": "/entrypoint-helpers/apply-app-variant.sh",
+ "logsDir": "/chat-service/logs"
+ }
+}