Open-source manufacturing ERP, MES and QMS. Quoting, MRP, inventory, shop floor, quality and lot/serial traceability on one Postgres schema, with a REST API and MCP server. Self-host or use Carbon Cloud.
TypeScript ai-agentsbill-of-materialserpinventory-managementleanmanufacturingmanufacturing-execution-systemmcp-servermesmrpopen-source-erppostgresqlproduction-planningqmsquality-management-systemreact-routerself-hostedsupabasetraceabilitytypescript
feat: loop-driven development foundation (@carbon/checks, @carbon/harness, conductor skill) (#948)
Brad Barbinf3591fe52023
diff --git a/.claude/skills/conductor/SKILL.md b/.claude/skills/conductor/SKILL.mdnew file mode 100644index 0000000000..2eec6af655--- /dev/null+++ b/.claude/skills/conductor/SKILL.md@@ -0,0 +1,72 @@+---+name: conductor+description: Supervised loop conductor — drive a single work item (a bug, a usability tweak, a small feature) through a doer→gate→keep-or-revert→ledger cycle to a gated PR, while the human watches. Use when asked to "conduct", "build", "fix", or "loop on" a specific item with the conductor. Supervised only — not autonomous/overnight (not yet supported). Backed by @carbon/harness + the @carbon/checks checks.+---++# conductor — supervised loop conductor++You are conducting a **supervised loop**: iterate doer→gate→keep/revert→ledger until the acceptance criteria are met, with the human watching and giving the final approval. Land a **gated PR** — never auto-merge.++This is the execution layer of the loop system. The deterministic helpers live in `@carbon/harness`; the checker is the four `@carbon/checks` checks.++## 0. Isolated worktree off `origin/main` (do this first)+- Every loop runs in its **own worktree, branched off the latest `origin/main`** — never stacked on another feature branch. Create it non-interactively:+ ```+ git fetch origin main+ crbn new loop/<id> --base origin/main --yes+ ```+ `crbn new --yes` skips all prompts (base defaults to `origin/main`) and prints the new worktree path; `cd` into it and do all the loop's work there.+- **Never run on `main`.** The loop's branch is `loop/<id>`.+- *(This assumes the loop system — `@carbon/harness` + `@carbon/checks` — is on `main`. Until that merges, the gate tooling only exists on the loop-system branch, so base off that branch instead.)*++## 1. Bind the work item+- If given a binding path (`llm/loops/<id>.loop.md`), read it. Otherwise write one from the request (see `llm/loops/README.md` for the format) and save it to `llm/loops/<id>.loop.md`.+- Parse it to validate the shape:+ `pnpm --filter @carbon/harness exec tsx -e "import {parseBinding} from '@carbon/harness'; import {readFileSync} from 'node:fs'; console.log(JSON.stringify(parseBinding(readFileSync('<path>','utf8'))))"`+- The binding has `id`, `kind` (bug|feature|usability|copy), `title`, `risk`, and an `acceptance` list. **Each acceptance criterion is the definition of done** — you are not finished until each is satisfied and provable.++## 2. The cycle (repeat until acceptance met OR the human stops)+For each iteration:++1. **Doer — make the smallest change toward the weakest-covered acceptance criterion.** Do not batch unrelated changes.+ - **UI work:** FIRST find the nearest existing screen/component that matches and *copy its layout/components/approach* — do not design from concepts. Cite the precedent path. (See the design's exemplar/precedent rule.)+ - **ERP-domain features** (accounting, RMAs, costing, tax, inventory valuation, …): FIRST use the `research` skill to ground the design in how real ERPs do it. Do not invent domain logic.+ - **Schema/migration changes:** after the change, regenerate types (`pnpm run generate:types`) BEFORE typechecking — a typecheck against stale types is a false green.+ - **Module code:** keep one `<module>.service.ts` and one `<module>.models.ts` per module; never scatter new service/models files.++2. **Gate.** Run these in order; every applicable one must be green:+ - **a. Floor gates** — `pnpm --filter @carbon/harness gates` (lint + `@carbon/checks` conformance + clobbers), plus `typecheck` for each package you touched (per-package, never whole-repo).+ - **b. Behavior gate — MANDATORY for ANY UI / user-facing change. A UI change is NOT solved until you have seen it work in the running app.** Boot the app (`crbn up` if it isn't already running), `/login`, and drive the affected screen with `agent-browser` (use the `/test` skill): **reproduce the exact failing condition the binding describes** (e.g. a record with 4+ labels) and **capture a BEFORE screenshot showing the bug**, then **confirm the fix works and capture an AFTER screenshot**. A UI change requires the **before/after pair** as proof — both go in the PR. The change cannot be kept or finished until this gate is green. This is not optional and not deferrable to PR time.+ - **If the stack cannot be brought up, the loop is BLOCKED** — stop and surface to the human. Do NOT proceed to keep/finish, and do NOT open a "done" PR with visual verification "pending." Reaching a "should I screenshot?" question is itself a failure of this gate.+ - **c. Correctness (logic bug/feature)** — the **reproduce→fix→same-path** test: write a test that fails on the bug, fix, watch the *same* test pass (a unit test, or the agent-browser playbook recorded in step b).+ - If any gate fails: fix it, or revert this iteration's change.++3. **Judge — dispatch a separate review subagent** (NOT yourself) to check the diff against the acceptance criteria and the design rules. It may send work back. Do not grade your own homework.++4. **Decide + ledger.** Keep the change iff **every gate is green — including the behavior gate (§2b) for UI work, with before/after screenshots proving the fix** — AND the judge approves; otherwise revert it. Append one entry to `llm/loops/<id>/ledger.jsonl`:+ `pnpm --filter @carbon/harness exec tsx -e "import {appendLedger} from '@carbon/harness'; appendLedger('llm/loops/<id>/ledger.jsonl', {iteration: <n>, change: '<summary>', gates: {<gate>: <bool>}, decision: '<keep|revert>', reason: '<why>', at: new Date().toISOString()})"`+ (The harness has no clock — you supply `at`.)++5. **Terminate?** If every acceptance criterion is met and provable → go to Finish. If you plateau (no progress across iterations) or the human stops → stop and report.++## 3. Finish — land a gated PR+- Embed the **before/after screenshots captured by the behavior gate (§2b)** in the PR body. A UI PR without them means the loop wasn't actually verified — do not open it.+- Open a **gated PR via the `gh` CLI** (`gh pr create`). Never merge. The PR body must:+ - state the **design rationale** (the precedent you copied; any `research`),+ - list, per acceptance criterion, **which gate proves it**,+ - embed the **before/after screenshots** for any UI change,+ - summarize the **ledger** (iterations, what was kept/reverted and why).+- **Surface every design decision for the human to approve / comment / improve** — design is never shipped silently.+- **Loop artifacts stay out of source.** `llm/loops/` (bindings, ledger, screenshots) is gitignored *runtime* — never commit it to the working branch. The **ledger summary goes in the PR body**, and **before/after screenshots are embedded in the PR body** from a shared, non-merging **`loop-artifacts`** branch (under `llm/loops/<id>/screenshots/`, referenced by raw URL) — never committed to the product tree. (`@carbon/harness`'s `openPr` does this hosting automatically.)++## Guardrails (non-negotiable)+- **A UI/user-facing change is never done without passing visual e2e verification in the running app (§2b).** If the stack can't boot, the loop is BLOCKED — stop and surface, not "done."+- Never auto-merge; the human approves the PR.+- Never run on `main`.+- Surface design changes to the human.+- Supervised only: do not background, schedule, or fan out across worktrees (later versions).++## Growing this+- Add a floor gate: append a `{ id, cmd }` to `FLOOR_GATES` in `@carbon/harness/src/gates.ts`.+- Add a binding field: extend the frontmatter + `parseBinding`.+- Visual e2e behavior verification is **in** v1 (§2b). Richer gates (TDD-mandatory, calibrated judge) and autonomy are deliberately out of v1.diff --git a/.gitignore b/.gitignoreindex ac80dbeae3..26baa9a7cb 100644--- a/.gitignore+++ b/.gitignore@@ -67,3 +67,8 @@ packages/database/supabase/seed.sqlapps/*/portless.jsonpackages/database/supabase/snippets/**.pr-review++# Loop run artifacts (conductor bindings, ledgers, screenshots) — runtime, not source.+# The ledger summary goes in the PR body; screenshots are hosted on the PR.+llm/loops/*+!llm/loops/README.mddiff --git a/llm/loops/README.md b/llm/loops/README.mdnew file mode 100644index 0000000000..86084c84c8--- /dev/null+++ b/llm/loops/README.md@@ -0,0 +1,24 @@+# llm/loops — loop bindings + ledgers++Home for the `build` conductor skill's work items.++- **Binding:** `llm/loops/<id>.loop.md` — one work item. YAML-ish frontmatter parsed by `@carbon/harness` `parseBinding` (no YAML lib; scalars + an `acceptance` list).+- **Ledger:** `llm/loops/<id>/ledger.jsonl` — append-only record of each loop iteration (change, gate results, keep/revert, reason). Written by `@carbon/harness` `appendLedger`.++## Binding format++```markdown+---+id: bug-reorder-align+kind: bug # bug | feature | usability | copy+title: Reorder button misaligns on short rows+risk: low # low | med | high+acceptance:+- Reorder button vertically centers in the row at <640px+- No new console errors on the line-items page+---++Freeform notes / context for the loop (optional).+```++Each `acceptance` bullet is a definition-of-done the loop must satisfy and prove via a gate.diff --git a/packages/checks/README.md b/packages/checks/README.mdnew file mode 100644index 0000000000..9373f02a98--- /dev/null+++ b/packages/checks/README.md@@ -0,0 +1,50 @@+# @carbon/checks++Executable checks for the loop system's "core".++## Conformance net++Forbids deprecated code patterns in migrations. Existing violations are+grandfathered in `src/conformance/baseline.json`; only **new** violations fail CI.++- Add a check: implement a `ConformanceCheck` under `src/conformance/`, add it to+ `CONFORMANCE_CHECKS` in `src/run.ts`, then re-baseline.+- Re-baseline (after intentionally accepting current state): `pnpm --filter @carbon/checks baseline`+- Run the gate: `pnpm --filter @carbon/checks test`++Each check records `provenance` (the transition event that retired the old pattern).++**Grandfathering granularity** is per `(checkId, file, snippet)`, not per occurrence:+adding a *second* occurrence of an already-baselined pattern to an already-baselined+file is not flagged. This is acceptable because shipped migrations are immutable /+append-only — new migration files, and new check types in old files, are always caught.++## Clobber check++Detects when the same DB object (view, function, or event-trigger) is redefined+on **both** the current branch and `main` since their merge-base — a "concurrent+redefinition" that will silently overwrite whichever side merges last.++- **What counts as a clobber:** `CREATE OR REPLACE VIEW`, `CREATE OR REPLACE FUNCTION`,+ or `attach_event_trigger(...)` targeting the same object name on both sides.+- **Run at PR time:** `pnpm --filter @carbon/checks clobbers`+ (needs `origin/main` fetched — run `git fetch origin main` first if needed).+- **Grow coverage:** add a `{ kind, re }` row to `OBJECT_PATTERNS` in+ `src/clobber.ts` — the `objectRefs` and `findClobbers` functions pick it up+ automatically.+- **Not in `test` gate:** the check requires git/branch context and is not+ appropriate for the static `vitest run` job. Run it as a separate CI step.+- **When a clobber is flagged:** rebase onto the latest `main`, then re-fork your+ redefinition from `main`'s version so you incorporate the concurrent change.++## Invariant net++Runnable database assertions. Each invariant is a `.sql` file in `src/invariants/`+that SELECTs the rows which **violate** the rule (empty result = healthy).++- Add an invariant: drop a `.sql` file in `src/invariants/` — no code or registration.+- Run against a database: `DATABASE_URL=<conn> pnpm --filter @carbon/checks invariants`+ (exits non-zero if any invariant returns rows).+- Invariants run against a **live DB** (a loop's worktree DB, or nightly against prod),+ NOT the static CI `test` job. The runner is DB-agnostic (injected query), so the+ logic is unit-tested without a database.diff --git a/packages/checks/package.json b/packages/checks/package.jsonnew file mode 100644index 0000000000..0c335a3b7d--- /dev/null+++ b/packages/checks/package.json@@ -0,0 +1,28 @@+{+ "name": "@carbon/checks",+ "version": "0.0.0",+ "private": true,+ "sideEffects": false,+ "exports": {+ ".": "./src/index.ts"+ },+ "scripts": {+ "clean": "rimraf .turbo node_modules dist",+ "lint": "biome lint --write ",+ "test": "vitest run",+ "typecheck": "tsgo --noEmit",+ "baseline": "tsx src/scripts/generate-baseline.ts",+ "invariants": "tsx src/scripts/run-invariants.ts",+ "clobbers": "tsx src/scripts/check-clobbers.ts"+ },+ "devDependencies": {+ "@carbon/config": "workspace:*",+ "@types/node": "^22",+ "@types/pg": "8.15.6",+ "pg": "8.20.0",+ "rimraf": "catalog:",+ "tsx": "catalog:",+ "typescript": "catalog:",+ "vitest": "catalog:"+ }+}diff --git a/packages/checks/src/baseline.test.ts b/packages/checks/src/baseline.test.tsnew file mode 100644index 0000000000..0fba1ec378--- /dev/null+++ b/packages/checks/src/baseline.test.ts@@ -0,0 +1,30 @@+import { describe, expect, it } from "vitest";+import { keyOf, parseBaseline } from "./baseline";+import type { Violation } from "./check";++const v: Violation = {+ file: "x.sql",+ line: 3,+ snippet: "NUMERIC(10,2)",+ message: "deprecated"+};++describe("baseline", () => {+ it("derives a stable key from checkId + file + snippet (line-independent)", () => {+ const a = keyOf("no-numeric-precision", v);+ const b = keyOf("no-numeric-precision", { ...v, line: 99 });+ expect(a).toBe(b);+ expect(a).toBe("no-numeric-precision::x.sql::NUMERIC(10,2)");+ });++ it("parses a baseline JSON array into a Set", () => {+ const set = parseBaseline('["k1","k2"]');+ expect(set.has("k1")).toBe(true);+ expect(set.size).toBe(2);+ });++ it("returns an empty Set for missing/invalid JSON", () => {+ expect(parseBaseline(undefined).size).toBe(0);+ expect(parseBaseline("not json").size).toBe(0);+ });+});diff --git a/packages/checks/src/baseline.ts b/packages/checks/src/baseline.tsnew file mode 100644index 0000000000..d4af34e2c0--- /dev/null+++ b/packages/checks/src/baseline.ts@@ -0,0 +1,40 @@+import { readFileSync, writeFileSync } from "node:fs";+import { dirname, join } from "node:path";+import { fileURLToPath } from "node:url";+import type { Violation } from "./check";++export type BaselineKey = string;++// Resolve from this source file (packages/checks/src/baseline.ts), not cwd, so+// the baseline is found regardless of where the process is invoked from.+const BASELINE_PATH = join(+ dirname(fileURLToPath(import.meta.url)),+ "conformance/baseline.json"+);++export function keyOf(checkId: string, v: Violation): BaselineKey {+ return `${checkId}::${v.file}::${v.snippet}`;+}++/** Pure parse so it is unit-testable without disk. */+export function parseBaseline(json: string | undefined): Set<BaselineKey> {+ if (!json) return new Set();+ try {+ const arr = JSON.parse(json);+ return Array.isArray(arr) ? new Set(arr as BaselineKey[]) : new Set();+ } catch {+ return new Set();+ }+}++export function loadBaseline(path = BASELINE_PATH): Set<BaselineKey> {+ try {+ return parseBaseline(readFileSync(path, "utf8"));+ } catch {+ return new Set();+ }+}++export function writeBaseline(keys: BaselineKey[], path = BASELINE_PATH): void {+ writeFileSync(path, `${JSON.stringify([...keys].sort(), null, 2)}\n`);+}diff --git a/packages/checks/src/check.ts b/packages/checks/src/check.tsnew file mode 100644index 0000000000..0739b1320c--- /dev/null+++ b/packages/checks/src/check.ts@@ -0,0 +1,42 @@+/** One occurrence of a forbidden pattern. */+export type Violation = {+ /** Migration file basename, e.g. "20260101120000_foo.sql", or "<inline>" in unit tests. */+ file: string;+ /** 1-based line number; 0 if unknown. */+ line: number;+ /** The exact matched text. */+ snippet: string;+ /** Human-readable reason. */+ message: string;+};++/**+ * A conformance check forbids a single deprecated pattern.+ * `scan` is PURE: same (file, contents) in → same violations out. No I/O.+ */+export type ConformanceCheck = {+ id: string;+ description: string;+ /** Provenance: the transition event that retired the old pattern (spec §5.7). */+ provenance: {+ deprecates: string;+ replacedBy: string;+ /** Migration/commit that flipped the standard, if known. */+ since?: string;+ };+ scan(file: string, contents: string): Violation[];+};++/** A module folder and its top-level entry names. */+export type ModuleDir = { name: string; dir: string; entries: string[] };++/**+ * A structure check inspects a directory's layout (not file text).+ * `inspect` is PURE: same module in → same violations out. No I/O.+ */+export type StructureCheck = {+ id: string;+ description: string;+ provenance: { deprecates: string; replacedBy: string; since?: string };+ inspect(module: ModuleDir): Violation[];+};diff --git a/packages/checks/src/clobber.test.ts b/packages/checks/src/clobber.test.tsnew file mode 100644index 0000000000..8a8438ea83--- /dev/null+++ b/packages/checks/src/clobber.test.ts@@ -0,0 +1,45 @@+import { describe, expect, it } from "vitest";+import { findClobbers, objectRefs } from "./clobber";++describe("objectRefs", () => {+ it("extracts views, functions, and event-trigger redefinitions", () => {+ const sql = `+ CREATE OR REPLACE VIEW "salesOrders" AS SELECT * FROM x;+ CREATE OR REPLACE FUNCTION get_total() RETURNS int AS $$ $$;+ SELECT attach_event_trigger('job', ARRAY[]::text[]);+ `;+ expect(objectRefs(sql)).toEqual(+ new Set(["view:salesOrders", "function:get_total", "event-trigger:job"])+ );+ });++ it("ignores non-redefining SQL", () => {+ expect(objectRefs("SELECT 1; INSERT INTO t VALUES (1);").size).toBe(0);+ });+});++describe("findClobbers", () => {+ it("flags an object redefined on both sides", () => {+ const branch = [+ { file: "b.sql", contents: 'CREATE OR REPLACE VIEW "v" AS SELECT 1;' }+ ];+ const main = [+ { file: "m.sql", contents: 'CREATE OR REPLACE VIEW "v" AS SELECT 2;' }+ ];+ const v = findClobbers(branch, main);+ expect(v).toHaveLength(1);+ expect(v[0]?.snippet).toBe("view:v");+ expect(v[0]?.file).toBe("b.sql");+ expect(v[0]?.message).toContain("m.sql");+ });++ it("does not flag disjoint redefinitions", () => {+ const branch = [+ { file: "b.sql", contents: 'CREATE OR REPLACE VIEW "a" AS SELECT 1;' }+ ];+ const main = [+ { file: "m.sql", contents: 'CREATE OR REPLACE VIEW "b" AS SELECT 2;' }+ ];+ expect(findClobbers(branch, main)).toHaveLength(0);+ });+});diff --git a/packages/checks/src/clobber.ts b/packages/checks/src/clobber.tsnew file mode 100644index 0000000000..6d14284b3b--- /dev/null+++ b/packages/checks/src/clobber.ts@@ -0,0 +1,61 @@+import type { Violation } from "./check";++export type SourceFile = { file: string; contents: string };++/** Patterns that identify a FULL redefinition of a DB object. Add a row to grow coverage. */+const OBJECT_PATTERNS: { kind: string; re: RegExp }[] = [+ {+ kind: "view",+ re: /create\s+(?:or\s+replace\s+)?(?:materialized\s+)?view\s+(?:if\s+not\s+exists\s+)?"?([a-zA-Z0-9_]+)"?/gi+ },+ {+ kind: "function",+ re: /create\s+or\s+replace\s+function\s+"?([a-zA-Z0-9_]+)"?/gi+ },+ {+ kind: "event-trigger",+ re: /attach_event_trigger\(\s*'([a-zA-Z0-9_]+)'/gi+ }+];++/** The set of `kind:name` objects redefined by a SQL string. */+export function objectRefs(sql: string): Set<string> {+ const refs = new Set<string>();+ for (const { kind, re } of OBJECT_PATTERNS) {+ for (const m of sql.matchAll(re)) {+ if (m[1]) refs.add(`${kind}:${m[1]}`);+ }+ }+ return refs;+}++function refMap(files: SourceFile[]): Map<string, string> {+ const map = new Map<string, string>();+ for (const f of files) {+ for (const ref of objectRefs(f.contents)) {+ if (!map.has(ref)) map.set(ref, f.file);+ }+ }+ return map;+}++/** Objects redefined on BOTH sides since the merge-base = clobber risk. */+export function findClobbers(+ branch: SourceFile[],+ main: SourceFile[]+): Violation[] {+ const mainRefs = refMap(main);+ const violations: Violation[] = [];+ for (const [ref, branchFile] of refMap(branch)) {+ const mainFile = mainRefs.get(ref);+ if (mainFile) {+ violations.push({+ file: branchFile,+ line: 0,+ snippet: ref,+ message: `Clobber risk: "${ref}" is redefined on this branch (${branchFile}) and on main (${mainFile}) since the merge-base. Rebase and re-fork your redefinition from main's latest version.`+ });+ }+ }+ return violations;+}diff --git a/packages/checks/src/conformance/baseline.json b/packages/checks/src/conformance/baseline.jsonnew file mode 100644index 0000000000..be45cf7a47--- /dev/null+++ b/packages/checks/src/conformance/baseline.json@@ -0,0 +1,201 @@+[+ "module-shape::settings::extra-service:backups.service.ts",+ "module-shape::shared::extra-models:imports.models.ts",+ "module-shape::shared::missing:ui",+ "module-shape::storage-rules::missing:types.ts",+ "no-legacy-rls::20230123004206_claims.sql::has_company_permission(",+ "no-legacy-rls::20230123004317_companies-rls.sql::has_company_permission(",+ "no-legacy-rls::20230123004339_employee-types.sql::has_company_permission(",+ "no-legacy-rls::20230123004409_permissions.sql::has_company_permission(",+ "no-legacy-rls::20230123004436_employee.sql::has_company_permission(",+ "no-legacy-rls::20230123004632_groups.sql::has_company_permission(",+ "no-legacy-rls::20230123212853_search.sql::has_company_permission(",+ "no-legacy-rls::20230126050441_abac.sql::has_company_permission(",+ "no-legacy-rls::20230215023746_abilities.sql::has_company_permission(",+ "no-legacy-rls::20230224035103_shifts.sql::has_company_permission(",+ "no-legacy-rls::20230302030217_equipment.sql::has_company_permission(",+ "no-legacy-rls::20230315222231_holidays.sql::has_company_permission(",+ "no-legacy-rls::20230319224154_partners.sql::has_company_permission(",+ "no-legacy-rls::20230329021751_contractors.sql::has_company_permission(",+ "no-legacy-rls::20230330024715_accounts.sql::has_company_permission(",+ "no-legacy-rls::20230330024716_parts.sql::has_company_permission(",+ "no-legacy-rls::20230412120726_services.sql::has_company_permission(",+ "no-legacy-rls::20230423023136_documents.sql::has_company_permission(",+ "no-legacy-rls::20230510035345_purchasing.sql::has_company_permission(",+ "no-legacy-rls::20230629113514_purchasing-files.sql::has_company_permission(",+ "no-legacy-rls::20230702114301_purchasing-rls.sql::has_company_permission(",+ "no-legacy-rls::20230705033432_ledgers.sql::has_company_permission(",+ "no-legacy-rls::20230728025201_receipts.sql::has_company_permission(",+ "no-legacy-rls::20230820020844_posting-groups.sql::has_company_permission(",+ "no-legacy-rls::20230924004608_accounts-payable.sql::has_company_permission(",+ "no-legacy-rls::20231109050239_supplier-details.sql::has_company_permission(",+ "no-legacy-rls::20231109050252_customer-details.sql::has_company_permission(",+ "no-legacy-rls::20240119095150_integrations.sql::has_company_permission(",+ "no-legacy-rls::20240311021818_custom-fields.sql::has_company_permission(",+ "no-legacy-rls::20240330054035_purchasing-documents.sql::has_company_permission(",+ "no-legacy-rls::20240330164855_quote-documents.sql::has_company_permission(",+ "no-legacy-rls::20240412224648_sales-orders.sql::has_company_permission(",+ "no-legacy-rls::20240608103855_tools.sql::has_company_permission(",+ "no-legacy-rls::20240608105638_consumables.sql::has_company_permission(",+ "no-legacy-rls::20240608111319_fixtures.sql::has_company_permission(",+ "no-legacy-rls::20240608114413_materials.sql::has_company_permission(",+ "no-legacy-rls::20240608124217_item-search.sql::has_company_permission(",+ "no-legacy-rls::20240621114604_method-rls.sql::has_company_permission(",+ "no-legacy-rls::20240623115054_parts-documents-rls.sql::has_company_permission(",+ "no-legacy-rls::20240630115404_model-uploads.sql::has_company_permission(",+ "no-legacy-rls::20240704105128_rfq.sql::has_company_permission(",+ "no-legacy-rls::20240713130609_rfq-rls.sql::has_company_permission(",+ "no-legacy-rls::20240715043906_quote-rls.sql::has_company_permission(",+ "no-legacy-rls::20240715055738_quote-files.sql::has_company_permission(",+ "no-legacy-rls::20240715134816_quote-pricing.sql::has_company_permission(",+ "no-legacy-rls::20240728004118_api-keys.sql::has_company_permission(",+ "no-legacy-rls::20240811231527_convert-rfq.sql::has_company_permission(",+ "no-legacy-rls::20240814000622_sales-rfq-line-bucket.sql::has_company_permission(",+ "no-legacy-rls::20240815020752_opportunity.sql::has_company_permission(",+ "no-legacy-rls::20240815185942_add-id-col-customerPartToItem.sql::has_company_permission(",+ "no-legacy-rls::20240817021131_people-vs-resources.sql::has_company_permission(",+ "no-legacy-rls::20240819115702_work-centers.sql::has_company_permission(",+ "no-legacy-rls::20240821150639_api-key-all-tables.sql::has_company_permission(",+ "no-legacy-rls::20240823024502_outside-operations.sql::has_company_permission(",+ "no-legacy-rls::20240831131003_sales-order-conversion.sql::has_company_permission(",+ "no-legacy-rls::20240902214024_opportunity-documents.sql::has_company_permission(",+ "no-legacy-rls::20240905110632_opportunity-update-fix.sql::has_company_permission(",+ "no-legacy-rls::20240908100622_terms.sql::has_company_permission(",+ "no-legacy-rls::20240909194622_jobs.sql::has_company_permission(",+ "no-legacy-rls::20240912181702_item-ledger-rls-update.sql::has_company_permission(",+ "no-legacy-rls::20240913145957_jobs-rls.sql::has_company_permission(",+ "no-legacy-rls::20240913162203_item-inventory.sql::has_company_permission(",+ "no-legacy-rls::20240915192542_job-methods.sql::has_company_permission(",+ "no-legacy-rls::20240927033740_job-operations-for-mes.sql::has_company_permission(",+ "no-legacy-rls::20241002012019_production-quantities.sql::has_company_permission(",+ "no-legacy-rls::20241010193506_quote-order-presentation-currency.sql::has_company_permission(",+ "no-legacy-rls::20241014130404_item-search-uuid.sql::has_company_permission(",+ "no-legacy-rls::20241021200602_thumbnails.sql::has_company_permission(",+ "no-legacy-rls::20241028205306_prepopulate-scrap-reasons.sql::has_company_permission(",+ "no-legacy-rls::20241030005037_external-links.sql::has_company_permission(",+ "no-legacy-rls::20241119015113_tags.sql::has_company_permission(",+ "no-legacy-rls::20241127142822_sales-settings.sql::has_company_permission(",+ "no-legacy-rls::20241127174710_process-tools.sql::has_company_permission(",+ "no-legacy-rls::20241130191054_employee-ability-fk.sql::has_company_permission(",+ "no-legacy-rls::20241206233602_supplier-quote-rls.sql::has_company_permission(",+ "no-legacy-rls::20241210140215_rls-performance.sql::has_company_permission(",+ "no-legacy-rls::20241217184843_configuration-options.sql::has_company_permission(",+ "no-legacy-rls::20241224174410_save-configuration.sql::has_company_permission(",+ "no-legacy-rls::20250110141302_document-group-performance.sql::has_company_permission (",+ "no-legacy-rls::20250110173720_no-quote-reasons.sql::has_company_permission(",+ "no-legacy-rls::20250113145319_operation-notes.sql::has_company_permission(",+ "no-legacy-rls::20250116182231_shipping-cost-on-purchase-order.sql::has_company_permission(",+ "no-legacy-rls::20250128094053_traceability.sql::has_company_permission(",+ "no-legacy-rls::20260115143000_purchasing-rfq.sql::has_company_permission(",+ "no-legacy-rls::20260430000001_tax-status.sql::has_company_permission(",+ "no-numeric-precision::20230330024715_accounts.sql::NUMERIC(20,8)",+ "no-numeric-precision::20230330024716_parts.sql::NUMERIC(15,5)",+ "no-numeric-precision::20230510035345_purchasing.sql::NUMERIC(10,5)",+ "no-numeric-precision::20230510035345_purchasing.sql::NUMERIC(9,2)",+ "no-numeric-precision::20230705033432_ledgers.sql::NUMERIC(12, 4)",+ "no-numeric-precision::20230705033432_ledgers.sql::NUMERIC(19, 4)",+ "no-numeric-precision::20230728025201_receipts.sql::NUMERIC(18, 4)",+ "no-numeric-precision::20230924004608_accounts-payable.sql::NUMERIC(10, 2)",+ "no-numeric-precision::20230924004608_accounts-payable.sql::NUMERIC(10, 4)",+ "no-numeric-precision::20240402052512_purchasing-conversion-factors.sql::NUMERIC(10, 2)",+ "no-numeric-precision::20240412224648_sales-orders.sql::NUMERIC(9,2)",+ "no-numeric-precision::20240619095417_methods.sql::NUMERIC(10,2)",+ "no-numeric-precision::20240619095417_methods.sql::NUMERIC(10,4)",+ "no-numeric-precision::20240704105128_rfq.sql::NUMERIC(20, 2)",+ "no-numeric-precision::20240715024405_quotes.sql::NUMERIC(10, 4)",+ "no-numeric-precision::20240715024405_quotes.sql::NUMERIC(10,2)",+ "no-numeric-precision::20240715024405_quotes.sql::NUMERIC(10,4)",+ "no-numeric-precision::20240715134816_quote-pricing.sql::NUMERIC(10,5)",+ "no-numeric-precision::20240802010740_add-unit-cost-to-quote-methods.sql::NUMERIC(10,4)",+ "no-numeric-precision::20240802114117_quote-line-quantities.sql::NUMERIC(10,5)",+ "no-numeric-precision::20240802114117_quote-line-quantities.sql::NUMERIC(20, 2)",+ "no-numeric-precision::20240809095324_save-quote-method.sql::NUMERIC(10,4)",+ "no-numeric-precision::20240819115702_work-centers.sql::NUMERIC(10,2)",+ "no-numeric-precision::20240823024502_outside-operations.sql::NUMERIC(10,4)",+ "no-numeric-precision::20240831131003_sales-order-conversion.sql::NUMERIC(10,4)",+ "no-numeric-precision::20240909194622_jobs.sql::NUMERIC(10, 4)",+ "no-numeric-precision::20240909194622_jobs.sql::NUMERIC(10,2)",+ "no-numeric-precision::20240909194622_jobs.sql::NUMERIC(10,4)",+ "no-numeric-precision::20240909194622_jobs.sql::NUMERIC(5, 2)",+ "no-numeric-precision::20240913162203_item-inventory.sql::NUMERIC(12, 4)",+ "no-numeric-precision::20240915192542_job-methods.sql::NUMERIC(10, 4)",+ "no-numeric-precision::20240915192542_job-methods.sql::NUMERIC(10,2)",+ "no-numeric-precision::20240915192542_job-methods.sql::NUMERIC(10,4)",+ "no-numeric-precision::20240920171731_job-requirements.sql::NUMERIC(10,4)",+ "no-numeric-precision::20240921113841_method-tree-short-circuit.sql::NUMERIC(10,4)",+ "no-numeric-precision::20240927033740_job-operations-for-mes.sql::NUMERIC(10,2)",+ "no-numeric-precision::20241010193506_quote-order-presentation-currency.sql::NUMERIC(10,4)",+ "no-numeric-precision::20241010193506_quote-order-presentation-currency.sql::NUMERIC(10,5)",+ "no-numeric-precision::20241024111311_active-job-operations.sql::NUMERIC(10,2)",+ "no-numeric-precision::20241029022721_add-link-to-item-card.sql::NUMERIC(10,2)",+ "no-numeric-precision::20241105002325_quote-taxes-and-shipping.sql::NUMERIC(10,5)",+ "no-numeric-precision::20241105100931_no-done-jobs-on-schedule.sql::NUMERIC(10,2)",+ "no-numeric-precision::20241114113119_add-sales-order-to-kanban.sql::NUMERIC(10,2)",+ "no-numeric-precision::20241114165314_sales-order-kanban-fix.sql::NUMERIC(10,2)",+ "no-numeric-precision::20241123162834_issued-materials.sql::NUMERIC(10, 4)",+ "no-numeric-precision::20241123162834_issued-materials.sql::NUMERIC(9, 2)",+ "no-numeric-precision::20241126124130_quote-shipping-cost.sql::NUMERIC(10,4)",+ "no-numeric-precision::20241202192419_supplier-quotes.sql::NUMERIC(10,4)",+ "no-numeric-precision::20241202192419_supplier-quotes.sql::NUMERIC(10,5)",+ "no-numeric-precision::20241202192419_supplier-quotes.sql::NUMERIC(20, 2)",+ "no-numeric-precision::20241210214820_purchasing-redux.sql::NUMERIC(10,4)",+ "no-numeric-precision::20241210214820_purchasing-redux.sql::NUMERIC(10,5)",+ "no-numeric-precision::20241211143656_add-image-to-kanban.sql::NUMERIC(10,2)",+ "no-numeric-precision::20250109000722_increase-numeric-values.sql::NUMERIC(10,5)",+ "no-numeric-precision::20250109000722_increase-numeric-values.sql::NUMERIC(16,5)",+ "no-numeric-precision::20250109034107_increase-numeric-values-2.sql::NUMERIC(10,5)",+ "no-numeric-precision::20250109034107_increase-numeric-values-2.sql::NUMERIC(16,5)",+ "no-numeric-precision::20250114224431_use-description-on-bom-tree.sql::NUMERIC(10,4)",+ "no-numeric-precision::20250120020943_fix-child-parent-thumbnail-on-kanban.sql::NUMERIC(10,2)",+ "no-numeric-precision::20250120143155_job-operation-assignments.sql::NUMERIC(10,2)",+ "no-numeric-precision::20250123183808_add-image-to-recent-in-mes.sql::NUMERIC(10,2)",+ "no-numeric-precision::20250123212102_mes-assignments.sql::NUMERIC(10,2)",+ "no-numeric-precision::20250124211733_thumbnail-fix-on-cards.sql::NUMERIC(10,2)",+ "no-numeric-precision::20250128094053_traceability.sql::NUMERIC(12, 4)",+ "no-numeric-precision::20250128195311_fix-purchasing-tax-percent.sql::NUMERIC(10,5)",+ "no-numeric-precision::20250130222216_include-complete-in-recent-jobs.sql::NUMERIC(10,2)",+ "no-numeric-precision::20250209000952_item_tracking.sql::NUMERIC(12, 4)",+ "no-numeric-precision::20250603011801_make-method-version.sql::NUMERIC(10, 2)",+ "no-numeric-precision::20250603011801_make-method-version.sql::NUMERIC(10,2)",+ "no-numeric-precision::20250610000433_demand-planning.sql::NUMERIC(3,2)",+ "no-numeric-precision::20250715083911_sales-order-lines.sql::NUMERIC(9,2)",+ "no-numeric-precision::20250828115039_portal-steps-use-process-name.sql::NUMERIC(9,2)",+ "no-numeric-precision::20251007014346_update-job-method-rpcs-with-shelf.sql::NUMERIC(10,2)",+ "no-numeric-precision::20251020183630_mrp-projections.sql::NUMERIC(3,2)",+ "no-numeric-precision::20251123000000_add-customer-name-to-operations.sql::NUMERIC(10,2)",+ "no-numeric-precision::20260115143000_purchasing-rfq.sql::NUMERIC(20, 10)",+ "no-numeric-precision::20260115143000_purchasing-rfq.sql::NUMERIC(20, 2)",+ "no-numeric-precision::20260116120000_item-scrap-percentage-on-job.sql::NUMERIC(5, 2)",+ "no-numeric-precision::20260129150000_quantity-price-breaks.sql::NUMERIC(15, 5)",+ "no-numeric-precision::20260129150000_quantity-price-breaks.sql::NUMERIC(20, 2)",+ "no-numeric-precision::20260130005853_external-id-migration.sql::NUMERIC(10,2)",+ "no-numeric-precision::20260203211225_external-id-view-fix.sql::NUMERIC(10,2)",+ "no-numeric-precision::20260226120000_supplier-part-price-lead-time.sql::NUMERIC(10, 5)",+ "no-numeric-precision::20260226120000_supplier-part-price-lead-time.sql::NUMERIC(10,5)",+ "no-numeric-precision::20260229000003_chart-of-accounts-tree.sql::NUMERIC(19, 4)",+ "no-numeric-precision::20260315000001_per-company-balance-rpc.sql::NUMERIC(19, 4)",+ "no-numeric-precision::20260315000002_exchange-rate-history.sql::NUMERIC(19, 4)",+ "no-numeric-precision::20260315000002_exchange-rate-history.sql::NUMERIC(20, 8)",+ "no-numeric-precision::20260319032303_explode-bom-item-master.sql::NUMERIC(10,2)",+ "no-numeric-precision::20260321143847_method-type-migration.sql::NUMERIC(10,2)",+ "no-numeric-precision::20260403120000_intercompany-tracking.sql::NUMERIC(19, 4)",+ "no-numeric-precision::20260408000000_method-tree-replenishment.sql::NUMERIC(10,2)",+ "no-numeric-precision::20260410031810_make-method-interceptors.sql::NUMERIC(10, 2)",+ "no-numeric-precision::20260413120001_pricing-rules.sql::NUMERIC(10, 5)",+ "no-numeric-precision::20260413120001_pricing-rules.sql::NUMERIC(15, 5)",+ "no-numeric-precision::20260413120001_pricing-rules.sql::NUMERIC(20, 2)",+ "no-numeric-precision::20260414120001_customer-item-price-override.sql::NUMERIC(15, 5)",+ "no-numeric-precision::20260414120001_customer-item-price-override.sql::NUMERIC(20, 2)",+ "no-numeric-precision::20260417000300_storage-unit-recreate-dependents.sql::NUMERIC(10,2)",+ "no-numeric-precision::20260419163058_inbound-inspection-sampling.sql::NUMERIC(5,2)",+ "no-numeric-precision::20260419163058_inbound-inspection-sampling.sql::NUMERIC(5,3)",+ "no-numeric-precision::20260421130000_nc-item-tracked-entity.sql::NUMERIC(12, 4)",+ "no-numeric-precision::20260426000000_tracked-entity-item-fk.sql::NUMERIC(10, 2)",+ "no-numeric-precision::20260504000000_cost-layers.sql::NUMERIC(12, 4)",+ "no-numeric-precision::20260524143827_fixed-assets.sql::NUMERIC(5,2)",+ "no-numeric-precision::20260527142837_rework.sql::NUMERIC(10,4)",+ "no-numeric-precision::20260601143527_picking-lists.sql::NUMERIC(12,4)",+ "no-numeric-precision::20260604120000_invoice-totals-computed-in-views.sql::NUMERIC(10,2)",+ "no-numeric-precision::20260604120000_invoice-totals-computed-in-views.sql::numeric(10,2)",+ "no-numeric-precision::20260618171234_material-supersession.sql::NUMERIC(10,2)"+]diff --git a/packages/checks/src/conformance/module-shape.test.ts b/packages/checks/src/conformance/module-shape.test.tsnew file mode 100644index 0000000000..f8e9f5c317--- /dev/null+++ b/packages/checks/src/conformance/module-shape.test.ts@@ -0,0 +1,68 @@+import { describe, expect, it } from "vitest";+import type { ModuleDir } from "../check";+import { moduleShape } from "./module-shape";++const mod = (name: string, entries: string[]): ModuleDir => ({+ name,+ dir: `/x/${name}`,+ entries+});++const COMPLIANT = [+ "sales.service.ts",+ "sales.models.ts",+ "types.ts",+ "ui",+ "index.ts",+ "sales.server.ts"+];++describe("moduleShape", () => {+ it("passes a compliant module", () => {+ expect(moduleShape.inspect(mod("sales", COMPLIANT))).toHaveLength(0);+ });++ it("flags a missing required entry (types.ts)", () => {+ const v = moduleShape.inspect(+ mod("sales", ["sales.service.ts", "sales.models.ts", "ui", "index.ts"])+ );+ expect(v).toHaveLength(1);+ expect(v[0]?.snippet).toBe("missing:types.ts");+ });++ it("flags an extra service file", () => {+ const v = moduleShape.inspect(+ mod("settings", [+ ...COMPLIANT.map((e) => e.replace("sales", "settings")),+ "backups.service.ts"+ ])+ );+ expect(v.map((x) => x.snippet)).toContain(+ "extra-service:backups.service.ts"+ );+ });++ it("flags a missing primary service file", () => {+ const v = moduleShape.inspect(+ mod("sales", ["sales.models.ts", "types.ts", "ui", "index.ts"])+ );+ expect(v.map((x) => x.snippet)).toContain("missing:sales.service.ts");+ });++ it("allows multiple .server.ts and utils/test files", () => {+ const v = moduleShape.inspect(+ mod("quality", [+ "quality.service.ts",+ "quality.models.ts",+ "types.ts",+ "ui",+ "index.ts",+ "quality.server.ts",+ "inspectionBalloon.server.ts",+ "quality.utils.ts",+ "quality.utils.test.ts"+ ])+ );+ expect(v).toHaveLength(0);+ });+});diff --git a/packages/checks/src/conformance/module-shape.ts b/packages/checks/src/conformance/module-shape.tsnew file mode 100644index 0000000000..2e23547379--- /dev/null+++ b/packages/checks/src/conformance/module-shape.ts@@ -0,0 +1,44 @@+import type { StructureCheck, Violation } from "../check";++/** Literal entries every module must contain. Edit this to grow the rule. */+const REQUIRED_ENTRIES = ["types.ts", "ui", "index.ts"];++export const moduleShape: StructureCheck = {+ id: "module-shape",+ description:+ "Each ERP module: one <name>.service.ts, one <name>.models.ts, types.ts, ui/, index.ts.",+ provenance: {+ deprecates: "scattered service/models files",+ replacedBy: "one <module>.service.ts + one <module>.models.ts"+ },+ inspect(module): Violation[] {+ const violations: Violation[] = [];+ const add = (snippet: string, message: string) =>+ violations.push({ file: module.name, line: 0, snippet, message });++ for (const name of REQUIRED_ENTRIES) {+ if (!module.entries.includes(name)) {+ add(`missing:${name}`, `Module "${module.name}" is missing ${name}.`);+ }+ }++ for (const kind of ["service", "models"] as const) {+ const expected = `${module.name}.${kind}.ts`;+ const found = module.entries.filter((e) => e.endsWith(`.${kind}.ts`));+ if (!found.includes(expected)) {+ add(+ `missing:${expected}`,+ `Module "${module.name}" must have ${expected}.`+ );+ }+ for (const extra of found.filter((e) => e !== expected)) {+ add(+ `extra-${kind}:${extra}`,+ `Extra ${kind} file "${extra}" — fold into ${expected}.`+ );+ }+ }++ return violations;+ }+};diff --git a/packages/checks/src/conformance/no-legacy-rls.test.ts b/packages/checks/src/conformance/no-legacy-rls.test.tsnew file mode 100644index 0000000000..d73d0f35b1--- /dev/null+++ b/packages/checks/src/conformance/no-legacy-rls.test.ts@@ -0,0 +1,24 @@+import { describe, expect, it } from "vitest";+import { noLegacyRls } from "./no-legacy-rls";++describe("noLegacyRls", () => {+ it("flags has_company_permission(...)", () => {+ const sql = "USING (has_company_permission('view', \"companyId\"))";+ const v = noLegacyRls.scan("p.sql", sql);+ expect(v).toHaveLength(1);+ expect(v[0]?.line).toBe(1);+ });++ it("allows the current get_companies_with_employee_permission helper", () => {+ const sql =+ "USING (\"companyId\" = ANY ((SELECT get_companies_with_employee_permission('view'))::text[]))";+ const v = noLegacyRls.scan("p.sql", sql);+ expect(v).toHaveLength(0);+ });++ it("records provenance pointing at the RLS refactor migration", () => {+ expect(noLegacyRls.provenance.since).toBe(+ "20250201181148_rls-refactor.sql"+ );+ });+});diff --git a/packages/checks/src/conformance/no-legacy-rls.ts b/packages/checks/src/conformance/no-legacy-rls.tsnew file mode 100644index 0000000000..6b825c53d0--- /dev/null+++ b/packages/checks/src/conformance/no-legacy-rls.ts@@ -0,0 +1,29 @@+import type { ConformanceCheck, Violation } from "../check";++const LEGACY_RLS = /has_company_permission\s*\(/gi;++export const noLegacyRls: ConformanceCheck = {+ id: "no-legacy-rls",+ description:+ "Use get_companies_with_employee_permission(...), not has_role()/has_company_permission().",+ provenance: {+ deprecates: "has_company_permission()",+ replacedBy: "get_companies_with_employee_permission()",+ since: "20250201181148_rls-refactor.sql"+ },+ scan(file, contents) {+ const violations: Violation[] = [];+ contents.split("\n").forEach((text, i) => {+ for (const m of text.matchAll(LEGACY_RLS)) {+ violations.push({+ file,+ line: i + 1,+ snippet: m[0],+ message:+ "Deprecated RLS helper; use get_companies_with_employee_permission()."+ });+ }+ });+ return violations;+ }+};diff --git a/packages/checks/src/conformance/no-numeric-precision.test.ts b/packages/checks/src/conformance/no-numeric-precision.test.tsnew file mode 100644index 0000000000..6c61ef540c--- /dev/null+++ b/packages/checks/src/conformance/no-numeric-precision.test.ts@@ -0,0 +1,33 @@+import { describe, expect, it } from "vitest";+import { noNumericPrecision } from "./no-numeric-precision";++describe("noNumericPrecision", () => {+ it("flags NUMERIC(x,y)", () => {+ const v = noNumericPrecision.scan(+ "a.sql",+ "amount NUMERIC(18, 4) NOT NULL"+ );+ expect(v).toHaveLength(1);+ expect(v[0]?.line).toBe(1);+ expect(v[0]?.snippet.toLowerCase().replace(/\s/g, "")).toBe(+ "numeric(18,4)"+ );+ });++ it("allows bare NUMERIC", () => {+ const v = noNumericPrecision.scan("a.sql", "amount NUMERIC NOT NULL");+ expect(v).toHaveLength(0);+ });++ it("reports the correct line across multiple lines", () => {+ const sql = ["id uuid,", "price NUMERIC(10,2),", "qty NUMERIC"].join("\n");+ const v = noNumericPrecision.scan("a.sql", sql);+ expect(v).toHaveLength(1);+ expect(v[0]?.line).toBe(2);+ });++ it("is case-insensitive", () => {+ const v = noNumericPrecision.scan("a.sql", "x numeric(5,2)");+ expect(v).toHaveLength(1);+ });+});diff --git a/packages/checks/src/conformance/no-numeric-precision.ts b/packages/checks/src/conformance/no-numeric-precision.tsnew file mode 100644index 0000000000..f62771b054--- /dev/null+++ b/packages/checks/src/conformance/no-numeric-precision.ts@@ -0,0 +1,28 @@+import type { ConformanceCheck, Violation } from "../check";++/** Matches NUMERIC(<int>, <int>) — the deprecated fixed-precision form. */+const NUMERIC_PRECISION = /numeric\s*\(\s*\d+\s*,\s*\d+\s*\)/gi;++export const noNumericPrecision: ConformanceCheck = {+ id: "no-numeric-precision",+ description: "Use bare NUMERIC, not NUMERIC(x,y).",+ provenance: {+ deprecates: "NUMERIC(x,y)",+ replacedBy: "NUMERIC"+ },+ scan(file, contents) {+ const violations: Violation[] = [];+ contents.split("\n").forEach((text, i) => {+ // matchAll on the per-line string avoids cross-line lastIndex state.+ for (const m of text.matchAll(NUMERIC_PRECISION)) {+ violations.push({+ file,+ line: i + 1,+ snippet: m[0],+ message: "NUMERIC(x,y) is deprecated; use bare NUMERIC."+ });+ }+ });+ return violations;+ }+};diff --git a/packages/checks/src/index.ts b/packages/checks/src/index.tsnew file mode 100644index 0000000000..c5a2e37f0b--- /dev/null+++ b/packages/checks/src/index.ts@@ -0,0 +1,27 @@+export type {+ ConformanceCheck,+ ModuleDir,+ StructureCheck,+ Violation+} from "./check";+export { findClobbers, objectRefs, type SourceFile } from "./clobber";+export { moduleShape } from "./conformance/module-shape";+export { noLegacyRls } from "./conformance/no-legacy-rls";+export { noNumericPrecision } from "./conformance/no-numeric-precision";+export {+ type Invariant,+ type InvariantResult,+ loadInvariants,+ type Query,+ runInvariants+} from "./invariant";+export {+ CONFORMANCE_CHECKS,+ collectFindings,+ type Finding,+ newViolations,+ STRUCTURE_CHECKS,+ scanAll,+ scanModules+} from "./run";+export { loadModules, modulesDir } from "./sources/modules";diff --git a/packages/checks/src/invariant.test.ts b/packages/checks/src/invariant.test.tsnew file mode 100644index 0000000000..3c06ab1181--- /dev/null+++ b/packages/checks/src/invariant.test.ts@@ -0,0 +1,52 @@+import { mkdtempSync, writeFileSync } from "node:fs";+import { tmpdir } from "node:os";+import { join } from "node:path";+import { describe, expect, it } from "vitest";+import { loadInvariants, runInvariants } from "./invariant";+import { repoRoot } from "./sources/migrations";++describe("loadInvariants", () => {+ it("loads each .sql file as an invariant keyed by basename (no extension)", () => {+ const dir = mkdtempSync(join(tmpdir(), "inv-"));+ writeFileSync(join(dir, "b-rule.sql"), "SELECT 2;");+ writeFileSync(join(dir, "a-rule.sql"), "SELECT 1;");+ writeFileSync(join(dir, "notes.txt"), "ignore");+ const inv = loadInvariants(dir);+ expect(inv.map((i) => i.id)).toEqual(["a-rule", "b-rule"]);+ expect(inv[0]?.sql).toBe("SELECT 1;");+ });+});++describe("runInvariants", () => {+ it("passes when the query returns no rows, fails when it returns violating rows", async () => {+ const invariants = [+ { id: "ok", sql: "SELECT 1 WHERE false" },+ { id: "bad", sql: "SELECT id FROM t" }+ ];+ const query = async (sql: string) =>+ sql.includes("FROM t") ? [{ id: "x" }, { id: "y" }] : [];+ const results = await runInvariants(invariants, query);+ expect(results).toEqual([+ { id: "ok", passed: true, violatingRows: [] },+ { id: "bad", passed: false, violatingRows: [{ id: "x" }, { id: "y" }] }+ ]);+ });++ it("captures a query error as a failed result without throwing", async () => {+ const query = async () => {+ throw new Error("boom");+ };+ const [r] = await runInvariants([{ id: "e", sql: "SELECT bad" }], query);+ expect(r?.passed).toBe(false);+ expect(r?.error).toContain("boom");+ });+});++describe("seed invariants", () => {+ it("loads the committed invariants directory", () => {+ const dir = `${repoRoot()}/packages/checks/src/invariants`;+ const inv = loadInvariants(dir);+ expect(inv.length).toBeGreaterThanOrEqual(1);+ expect(inv.some((i) => i.id === "tracked-entity-readable-id")).toBe(true);+ });+});diff --git a/packages/checks/src/invariant.ts b/packages/checks/src/invariant.tsnew file mode 100644index 0000000000..860d9bbef0--- /dev/null+++ b/packages/checks/src/invariant.ts@@ -0,0 +1,50 @@+import { readdirSync, readFileSync } from "node:fs";+import { join } from "node:path";++/** An invariant is a SQL query that returns rows which VIOLATE the rule (empty = healthy). */+export type Invariant = { id: string; sql: string };++/** Injected DB access so the runner is testable without a real database. */+export type Query = (sql: string) => Promise<unknown[]>;++export type InvariantResult = {+ id: string;+ passed: boolean;+ violatingRows: unknown[];+ error?: string;+};++export function loadInvariants(dir: string): Invariant[] {+ return readdirSync(dir)+ .filter((f) => f.endsWith(".sql"))+ .sort()+ .map((f) => ({+ id: f.replace(/\.sql$/, ""),+ sql: readFileSync(join(dir, f), "utf8")+ }));+}++export async function runInvariants(+ invariants: Invariant[],+ query: Query+): Promise<InvariantResult[]> {+ const results: InvariantResult[] = [];+ for (const inv of invariants) {+ try {+ const rows = await query(inv.sql);+ results.push({+ id: inv.id,+ passed: rows.length === 0,+ violatingRows: rows+ });+ } catch (e) {+ results.push({+ id: inv.id,+ passed: false,+ violatingRows: [],+ error: e instanceof Error ? e.message : String(e)+ });+ }+ }+ return results;+}diff --git a/packages/checks/src/invariants/tracked-entity-readable-id.sql b/packages/checks/src/invariants/tracked-entity-readable-id.sqlnew file mode 100644index 0000000000..c560025edb--- /dev/null+++ b/packages/checks/src/invariants/tracked-entity-readable-id.sql@@ -0,0 +1,5 @@+-- invariant: every tracked entity has a readableId+-- returns rows that VIOLATE the rule (none = healthy)+SELECT "id", "companyId"+FROM "trackedEntity"+WHERE "readableId" IS NULL;diff --git a/packages/checks/src/run.test.ts b/packages/checks/src/run.test.tsnew file mode 100644index 0000000000..ec16b3eb9f--- /dev/null+++ b/packages/checks/src/run.test.ts@@ -0,0 +1,29 @@+import { describe, expect, it } from "vitest";+import { newViolations, scanAll } from "./run";++describe("scanAll", () => {+ it("returns every (checkId, violation) across files and checks", () => {+ const files = [+ { file: "a.sql", contents: "x NUMERIC(10,2)" },+ { file: "b.sql", contents: "USING (has_company_permission('view'))" },+ { file: "c.sql", contents: "y NUMERIC" }+ ];+ const found = scanAll(files);+ const ids = found.map((f) => f.checkId).sort();+ expect(ids).toEqual(["no-legacy-rls", "no-numeric-precision"]);+ expect(found.every((f) => typeof f.violation.line === "number")).toBe(true);+ });+});++describe("conformance gate (real migrations vs baseline)", () => {+ it("introduces no NEW deprecated patterns beyond the committed baseline", () => {+ const fresh = newViolations();+ const detail = fresh+ .map(+ (f) =>+ ` ${f.checkId} ${f.violation.file}:${f.violation.line} ${f.violation.snippet}`+ )+ .join("\n");+ expect(fresh, `New conformance violations:\n${detail}`).toHaveLength(0);+ });+});diff --git a/packages/checks/src/run.ts b/packages/checks/src/run.tsnew file mode 100644index 0000000000..c5303fd61e--- /dev/null+++ b/packages/checks/src/run.ts@@ -0,0 +1,72 @@+import { keyOf, loadBaseline } from "./baseline";+import type {+ ConformanceCheck,+ ModuleDir,+ StructureCheck,+ Violation+} from "./check";+import { moduleShape } from "./conformance/module-shape";+import { noLegacyRls } from "./conformance/no-legacy-rls";+import { noNumericPrecision } from "./conformance/no-numeric-precision";+import {+ loadSqlFiles,+ migrationsDir,+ repoRoot,+ type SqlFile+} from "./sources/migrations";+import { loadModules, modulesDir } from "./sources/modules";++export const CONFORMANCE_CHECKS: ConformanceCheck[] = [+ noNumericPrecision,+ noLegacyRls+];++export const STRUCTURE_CHECKS: StructureCheck[] = [moduleShape];++export type Finding = { checkId: string; violation: Violation };++export function scanAll(+ files: SqlFile[],+ checks: ConformanceCheck[] = CONFORMANCE_CHECKS+): Finding[] {+ const out: Finding[] = [];+ for (const { file, contents } of files) {+ for (const check of checks) {+ for (const violation of check.scan(file, contents)) {+ out.push({ checkId: check.id, violation });+ }+ }+ }+ return out;+}++export function scanModules(+ modules: ModuleDir[],+ checks: StructureCheck[] = STRUCTURE_CHECKS+): Finding[] {+ const out: Finding[] = [];+ for (const m of modules) {+ for (const check of checks) {+ for (const violation of check.inspect(m)) {+ out.push({ checkId: check.id, violation });+ }+ }+ }+ return out;+}++/** Every finding across the real migrations (text) + modules (structure) under `root`. */+export function collectFindings(root: string = repoRoot()): Finding[] {+ return [+ ...scanAll(loadSqlFiles(migrationsDir(root))),+ ...scanModules(loadModules(modulesDir(root)))+ ];+}++/** Findings in the real migrations/modules that are NOT grandfathered by the baseline. */+export function newViolations(): Finding[] {+ const baseline = loadBaseline();+ return collectFindings().filter(+ (f) => !baseline.has(keyOf(f.checkId, f.violation))+ );+}diff --git a/packages/checks/src/scripts/check-clobbers.ts b/packages/checks/src/scripts/check-clobbers.tsnew file mode 100644index 0000000000..ded8216b12--- /dev/null+++ b/packages/checks/src/scripts/check-clobbers.ts@@ -0,0 +1,66 @@+import { execFileSync } from "node:child_process";+import { findClobbers, type SourceFile } from "../clobber";+import { repoRoot } from "../sources/migrations";++const MIGRATIONS = "packages/database/supabase/migrations";++function git(root: string, args: string[]): string {+ return execFileSync("git", args, { cwd: root, encoding: "utf8" }).trim();+}++function filesChanged(root: string, base: string, head: string): string[] {+ const out = git(root, [+ "diff",+ "--name-only",+ "--diff-filter=AM",+ `${base}...${head}`,+ "--",+ MIGRATIONS+ ]);+ return out ? out.split("\n").filter(Boolean) : [];+}++function readAt(root: string, ref: string, path: string): SourceFile | null {+ try {+ return {+ file: path.replace(`${MIGRATIONS}/`, ""),+ contents: git(root, ["show", `${ref}:${path}`])+ };+ } catch {+ return null;+ }+}++function main() {+ const root = repoRoot();+ const mainRef = process.env.CLOBBER_BASE_REF ?? "origin/main";+ let base: string;+ try {+ base = git(root, ["merge-base", "HEAD", mainRef]);+ } catch {+ console.error(+ `Could not compute merge-base with ${mainRef}. Fetch it first (git fetch origin main).`+ );+ process.exit(2);+ return;+ }+ const branchFiles = filesChanged(root, base, "HEAD")+ .map((p) => readAt(root, "HEAD", p))+ .filter((f): f is SourceFile => f !== null);+ const mainFiles = filesChanged(root, base, mainRef)+ .map((p) => readAt(root, mainRef, p))+ .filter((f): f is SourceFile => f !== null);++ const clobbers = findClobbers(branchFiles, mainFiles);+ if (clobbers.length === 0) {+ console.log(+ `No clobber risks vs ${mainRef} (merge-base ${base.slice(0, 9)}).`+ );+ process.exit(0);+ }+ for (const c of clobbers)+ console.log(`CLOBBER ${c.snippet}\n ${c.message}`);+ process.exit(1);+}++main();diff --git a/packages/checks/src/scripts/generate-baseline.ts b/packages/checks/src/scripts/generate-baseline.tsnew file mode 100644index 0000000000..596caa7949--- /dev/null+++ b/packages/checks/src/scripts/generate-baseline.ts@@ -0,0 +1,8 @@+import { keyOf, writeBaseline } from "../baseline";+import { collectFindings } from "../run";++const keys = [+ ...new Set(collectFindings().map((f) => keyOf(f.checkId, f.violation)))+];+writeBaseline(keys);+console.log(`Wrote ${keys.length} baselined conformance violations.`);diff --git a/packages/checks/src/scripts/run-invariants.ts b/packages/checks/src/scripts/run-invariants.tsnew file mode 100644index 0000000000..b5c684d035--- /dev/null+++ b/packages/checks/src/scripts/run-invariants.ts@@ -0,0 +1,41 @@+import { join } from "node:path";+import { Client } from "pg";+import { loadInvariants, type Query, runInvariants } from "../invariant";+import { repoRoot } from "../sources/migrations";++async function main() {+ const connectionString =+ process.env.DATABASE_URL ?? process.env.SUPABASE_DB_URL;+ if (!connectionString) {+ console.error(+ "Set DATABASE_URL (or SUPABASE_DB_URL) to the Postgres connection string."+ );+ process.exit(2);+ }+ const client = new Client({ connectionString });+ await client.connect();+ const query: Query = async (sql) => (await client.query(sql)).rows;+ try {+ const dir = join(repoRoot(), "packages/checks/src/invariants");+ const results = await runInvariants(loadInvariants(dir), query);+ let failed = 0;+ for (const r of results) {+ if (r.passed) {+ console.log(`PASS ${r.id}`);+ } else {+ failed++;+ console.log(+ `FAIL ${r.id} (${r.error ?? `${r.violatingRows.length} violating rows`})`+ );+ }+ }+ console.log(+ `\n${results.length - failed}/${results.length} invariants healthy.`+ );+ process.exit(failed > 0 ? 1 : 0);+ } finally {+ await client.end();+ }+}++void main();diff --git a/packages/checks/src/smoke.test.ts b/packages/checks/src/smoke.test.tsnew file mode 100644index 0000000000..180ca33fb8--- /dev/null+++ b/packages/checks/src/smoke.test.ts@@ -0,0 +1,7 @@+import { describe, expect, it } from "vitest";++describe("@carbon/checks", () => {+ it("runs", () => {+ expect(true).toBe(true);+ });+});diff --git a/packages/checks/src/sources/migrations.test.ts b/packages/checks/src/sources/migrations.test.tsnew file mode 100644index 0000000000..70a8f5d22c--- /dev/null+++ b/packages/checks/src/sources/migrations.test.ts@@ -0,0 +1,17 @@+import { mkdtempSync, writeFileSync } from "node:fs";+import { tmpdir } from "node:os";+import { join } from "node:path";+import { describe, expect, it } from "vitest";+import { loadSqlFiles } from "./migrations";++describe("loadSqlFiles", () => {+ it("loads .sql files sorted by name, ignoring non-sql", () => {+ const dir = mkdtempSync(join(tmpdir(), "core-"));+ writeFileSync(join(dir, "b.sql"), "SELECT 2;");+ writeFileSync(join(dir, "a.sql"), "SELECT 1;");+ writeFileSync(join(dir, "notes.txt"), "ignore me");+ const files = loadSqlFiles(dir);+ expect(files.map((f) => f.file)).toEqual(["a.sql", "b.sql"]);+ expect(files[0]?.contents).toBe("SELECT 1;");+ });+});diff --git a/packages/checks/src/sources/migrations.ts b/packages/checks/src/sources/migrations.tsnew file mode 100644index 0000000000..88e24eee5c--- /dev/null+++ b/packages/checks/src/sources/migrations.ts@@ -0,0 +1,32 @@+import { existsSync, readdirSync, readFileSync } from "node:fs";+import { dirname, join, resolve } from "node:path";+import { fileURLToPath } from "node:url";++export type SqlFile = { file: string; contents: string };++const MIGRATIONS_REL = "packages/database/supabase/migrations";++/**+ * Repo root, resolved from this source file (not cwd) so checks run correctly+ * from any working directory. This file is packages/checks/src/sources/ → 4 up.+ */+export function repoRoot(): string {+ const root = resolve(dirname(fileURLToPath(import.meta.url)), "../../../..");+ if (!existsSync(join(root, MIGRATIONS_REL))) {+ throw new Error(+ `Could not locate repo root from ${import.meta.url} (resolved ${root}); ${MIGRATIONS_REL} not found.`+ );+ }+ return root;+}++export function migrationsDir(root: string): string {+ return join(root, MIGRATIONS_REL);+}++export function loadSqlFiles(dir: string): SqlFile[] {+ return readdirSync(dir)+ .filter((f) => f.endsWith(".sql"))+ .sort()+ .map((f) => ({ file: f, contents: readFileSync(join(dir, f), "utf8") }));+}diff --git a/packages/checks/src/sources/modules.test.ts b/packages/checks/src/sources/modules.test.tsnew file mode 100644index 0000000000..a50ae83794--- /dev/null+++ b/packages/checks/src/sources/modules.test.ts@@ -0,0 +1,18 @@+import { mkdirSync, mkdtempSync, writeFileSync } from "node:fs";+import { tmpdir } from "node:os";+import { join } from "node:path";+import { describe, expect, it } from "vitest";+import { loadModules } from "./modules";++describe("loadModules", () => {+ it("returns one entry per subdirectory with its top-level names", () => {+ const root = mkdtempSync(join(tmpdir(), "mods-"));+ mkdirSync(join(root, "sales"));+ writeFileSync(join(root, "sales", "sales.service.ts"), "");+ mkdirSync(join(root, "sales", "ui"));+ writeFileSync(join(root, "README.md"), "");+ const mods = loadModules(root);+ expect(mods.map((m) => m.name)).toEqual(["sales"]);+ expect(mods[0]?.entries.sort()).toEqual(["sales.service.ts", "ui"]);+ });+});diff --git a/packages/checks/src/sources/modules.ts b/packages/checks/src/sources/modules.tsnew file mode 100644index 0000000000..f7a1479edb--- /dev/null+++ b/packages/checks/src/sources/modules.ts@@ -0,0 +1,17 @@+import { existsSync, readdirSync, statSync } from "node:fs";+import { join } from "node:path";+import type { ModuleDir } from "../check";++const MODULES_REL = "apps/erp/app/modules";++export function modulesDir(root: string): string {+ return join(root, MODULES_REL);+}++export function loadModules(dir: string): ModuleDir[] {+ if (!existsSync(dir)) return [];+ return readdirSync(dir)+ .map((name) => ({ name, dir: join(dir, name) }))+ .filter((m) => statSync(m.dir).isDirectory())+ .map((m) => ({ name: m.name, dir: m.dir, entries: readdirSync(m.dir) }));+}diff --git a/packages/checks/tsconfig.json b/packages/checks/tsconfig.jsonnew file mode 100644index 0000000000..8cee9135d1--- /dev/null+++ b/packages/checks/tsconfig.json@@ -0,0 +1,5 @@+{+ "extends": "@carbon/config/tsconfig/react-library.json",+ "include": ["src"],+ "exclude": ["dist", "build", "node_modules"]+}diff --git a/packages/checks/vitest.config.ts b/packages/checks/vitest.config.tsnew file mode 100644index 0000000000..9a3c27eaed--- /dev/null+++ b/packages/checks/vitest.config.ts@@ -0,0 +1 @@+export { default } from "@carbon/config/vitest";diff --git a/packages/dev/src/commands/new.ts b/packages/dev/src/commands/new.tsindex f8285c43a0..dd176027ca 100644--- a/packages/dev/src/commands/new.ts+++ b/packages/dev/src/commands/new.ts@@ -11,23 +11,44 @@ import {} from "../prompts.js";import { getWorktreeRoot, slugify } from "../worktree.js";-export async function newWorktree(opts?: { branch?: string }) {+export async function newWorktree(opts?: {+ branch?: string;+ base?: string;+ dir?: string;+ copyEnv?: boolean;+ yes?: boolean;+}) {intro("Carbon · new worktree");const here = await getWorktreeRoot();const parentDir = dirname(here);const repoBaseName = basename(here).replace(/-[a-z0-9-]+$/i, "");- const branch = await promptBranch(opts?.branch);+ // Non-interactive (`--yes`): skip every prompt, use flags/defaults.+ // Base defaults to origin/main so loops always branch off latest main.+ const nonInteractive = opts?.yes === true;++ const branch = nonInteractive+ ? opts?.branch+ : await promptBranch(opts?.branch);+ if (!branch) {+ throw new Error("crbn new --yes requires a branch name");+ }const defaultDir = `${repoBaseName}-${slugify(branch)}`;- const dirName = await promptDirName(parentDir, defaultDir);+ const dirName = nonInteractive+ ? (opts?.dir ?? defaultDir)+ : await promptDirName(parentDir, defaultDir);const targetPath = resolve(parentDir, dirName);const cur = await currentBranch(here);- const baseRef = await promptBaseRef(cur || null);+ const baseRef = nonInteractive+ ? (opts?.base ?? "origin/main")+ : await promptBaseRef(cur || null);- const copyEnv = await promptCopyEnv();+ const copyEnv = nonInteractive+ ? (opts?.copyEnv ?? true)+ : await promptCopyEnv();await tasks([{diff --git a/packages/dev/src/commands/up.ts b/packages/dev/src/commands/up.tsindex 5628866fd4..b6f96675cf 100644--- a/packages/dev/src/commands/up.ts+++ b/packages/dev/src/commands/up.ts@@ -72,6 +72,12 @@ type UpOpts = {borrow?: boolean;/** When false, skip portless proxy and use localhost URLs. */portless?: boolean;+ /**+ * Boot apps, wait until reachable, run this shell command, then tear the+ * stack down. Scopes the stack's lifetime to the command (headless/CI use):+ * `crbn up` exits with the command's exit code. No detached daemon to reap.+ */+ run?: string;};type Ctx = {@@ -193,6 +199,21 @@ export async function up(opts: UpOpts = {}) {// services-only, to a later manual `crbn down`).detachEarly();+ // --run: scope the stack's lifetime to a command (headless/CI). Boot apps,+ // wait until reachable, run it, then tear everything down. No daemon to reap.+ if (opts.run !== undefined) {+ outro("apps starting, then running command");+ await runAppsThenCommand(+ root,+ selectedApps,+ ctx.ports,+ portless,+ opts.run,+ stripeChild+ );+ return;+ }+if (selectedApps.length === 0) {// Services-only: the stack stays up after crbn exits, so let the stripe// listener outlive us too (apps mode kills it on teardown instead).@@ -538,6 +559,95 @@ async function runAppsThenTeardown(}}+// Port each app's dev server binds (mirrors apps.ts APP_PORT_KEYS).+const APP_PORT_KEY: Partial<Record<AppId, keyof PortMap>> = {+ erp: "PORT_ERP",+ mes: "PORT_MES"+};++/** A single readiness probe — any HTTP status means the dev server is up. */+async function appResponds(port: number): Promise<boolean> {+ try {+ const res = await fetch(`http://127.0.0.1:${port}/`, {+ signal: AbortSignal.timeout(4000)+ });+ return res.status > 0;+ } catch {+ return false;+ }+}++/** Poll each selected app's port until it serves (or the deadline passes). */+async function waitForApps(+ selectedApps: AppId[],+ ports: PortMap,+ timeoutMs = 180_000+): Promise<void> {+ const deadline = Date.now() + timeoutMs;+ for (const id of selectedApps) {+ const key = APP_PORT_KEY[id];+ const port = key ? ports[key] : undefined;+ if (port === undefined) continue;+ let up = false;+ while (Date.now() < deadline) {+ if (await appResponds(port)) {+ up = true;+ break;+ }+ await new Promise((r) => setTimeout(r, 1500));+ }+ if (up) log.info(`${id} reachable on :${port}`);+ else log.warn(`${id} not reachable on :${port} — running command anyway`);+ }+}++/**+ * Boot apps in the background, wait until reachable, run `command`, then tear+ * the whole stack down. The stack's lifetime is exactly the command's — the+ * headless/CI counterpart to the interactive Ctrl+C flow. Reuses the+ * AbortSignal teardown `spawnApps` already exposes, so there's no detached+ * daemon to track or reap. `crbn up` exits with the command's exit code.+ */+async function runAppsThenCommand(+ root: string,+ selectedApps: AppId[],+ ports: PortMap,+ portless: boolean,+ command: string,+ stripeChild?: ExecaChildProcess+) {+ const controller = new AbortController();+ const appsDone = spawnApps({+ root,+ apps: selectedApps,+ ports,+ portless,+ signal: controller.signal+ // biome-ignore lint/suspicious/noEmptyBlockStatements: supervisor errors surface via teardown+ }).catch(() => {});+ const detach = onShutdown(() => controller.abort());++ let exitCode = 0;+ try {+ await waitForApps(selectedApps, ports);+ log.step(`running: ${command}`);+ const res = await execa(command, {+ cwd: root,+ shell: true,+ stdio: "inherit",+ reject: false+ });+ exitCode = res.exitCode ?? 0;+ } finally {+ controller.abort(); // stop the app supervisors+ await appsDone;+ killStripe(stripeChild);+ await down({ silent: true });+ detach();+ }+ process.exitCode = exitCode;+}+// ---------------------------------------------------------------------------// Diagnostics// ---------------------------------------------------------------------------diff --git a/packages/dev/src/main.ts b/packages/dev/src/main.tsindex 2791bcf309..ddcbee1f00 100644--- a/packages/dev/src/main.ts+++ b/packages/dev/src/main.ts@@ -52,6 +52,11 @@ const main = defineCommand({default: true,description:"Use portless .dev URLs (use --no-portless for localhost mode)"+ },+ run: {+ type: "string",+ description:+ "Boot apps, wait until reachable, run this command, then tear the stack down (scopes the stack's lifetime to the command — for headless/CI use)"}},run: ({ args }) =>@@ -61,7 +66,8 @@ const main = defineCommand({apps: args.apps !== false,pull: args.pull === true,borrow: args.borrow === true,- portless: args.portless !== false+ portless: args.portless !== false,+ run: typeof args.run === "string" ? args.run : undefined})}),down: defineCommand({@@ -99,17 +105,45 @@ const main = defineCommand({args.force ? reset() : migrate({ regen: args.regen !== false })}),new: defineCommand({- meta: { description: "Interactive: create a worktree on a fresh branch" },+ meta: {+ description:+ "Create a worktree on a fresh branch (interactive, or non-interactive with --yes)"+ },args: {branch: {type: "positional",required: false,description: "Branch name (pre-fills the prompt)"+ },+ base: {+ type: "string",+ description:+ "Base ref to branch from (with --yes; defaults to origin/main)"+ },+ dir: {+ type: "string",+ description: "Worktree directory name (with --yes; default derived)"+ },+ "copy-env": {+ type: "boolean",+ default: true,+ description:+ "Copy .env from the current checkout (--no-copy-env to skip)"+ },+ yes: {+ type: "boolean",+ default: false,+ description:+ "Non-interactive: skip prompts, use flags/defaults (base defaults to origin/main)"}},run: ({ args }) =>newWorktree({- branch: typeof args.branch === "string" ? args.branch : undefined+ branch: typeof args.branch === "string" ? args.branch : undefined,+ base: typeof args.base === "string" ? args.base : undefined,+ dir: typeof args.dir === "string" ? args.dir : undefined,+ copyEnv: args["copy-env"] !== false,+ yes: args.yes === true})}),list: defineCommand({diff --git a/packages/harness/README.md b/packages/harness/README.mdnew file mode 100644index 0000000000..d3aee2cc34--- /dev/null+++ b/packages/harness/README.md@@ -0,0 +1,37 @@+# @carbon/harness++The deterministic substrate that powers the `build` conductor skill (loop conductor).++## Concepts++- **Bindings** — specs for a loop iteration, parsed from `llm/loops/<id>.loop.md` frontmatter.+- **Ledger** — append-only JSONL log of each iteration's outcome, stored at `llm/loops/<id>/ledger.jsonl`.+- **Floor gates** — cheap, deterministic checks that must pass before any iteration is recorded as `keep`.++## Usage++```ts+import { parseBinding, appendLedger, readLedger, runGates, FLOOR_GATES } from "@carbon/harness";+```++Run the floor gates manually:++```sh+pnpm --filter @carbon/harness gates+```++## Growing the gate list++Add a row to `FLOOR_GATES` in `src/gates.ts`. Each gate is `{ id: string, cmd: string }`. The CLI in `src/scripts/run-gates.ts` shells out via `execSync`; the `runGates` function itself stays pure (injected `Exec`) so it is unit-testable without spawning processes.++## File layout++```+src/+ binding.ts parse .loop.md frontmatter+ ledger.ts append-only JSONL ledger+ gates.ts gate runner (pure) + FLOOR_GATES+ scripts/+ run-gates.ts CLI entry point+ index.ts barrel+```diff --git a/packages/harness/package.json b/packages/harness/package.jsonnew file mode 100644index 0000000000..c4a72e2824--- /dev/null+++ b/packages/harness/package.json@@ -0,0 +1,25 @@+{+ "name": "@carbon/harness",+ "version": "0.0.0",+ "private": true,+ "sideEffects": false,+ "exports": {+ ".": "./src/index.ts"+ },+ "scripts": {+ "clean": "rimraf .turbo node_modules dist",+ "lint": "biome lint --write ",+ "test": "vitest run",+ "typecheck": "tsgo --noEmit",+ "gates": "tsx src/scripts/run-gates.ts",+ "loop": "tsx src/scripts/run-loop.ts"+ },+ "devDependencies": {+ "@carbon/config": "workspace:*",+ "@types/node": "^22",+ "rimraf": "catalog:",+ "tsx": "catalog:",+ "typescript": "catalog:",+ "vitest": "catalog:"+ }+}diff --git a/packages/harness/src/binding.test.ts b/packages/harness/src/binding.test.tsnew file mode 100644index 0000000000..871d14a46d--- /dev/null+++ b/packages/harness/src/binding.test.ts@@ -0,0 +1,41 @@+import { describe, expect, it } from "vitest";+import { parseBinding } from "./binding";++const MD = `---+id: bug-reorder+kind: bug+title: Reorder button misaligns+risk: low+acceptance:+- Button centers at <640px+- No console errors+---+Some freeform notes.`;++describe("parseBinding", () => {+ it("parses scalar fields and the acceptance list", () => {+ const b = parseBinding(MD);+ expect(b.id).toBe("bug-reorder");+ expect(b.kind).toBe("bug");+ expect(b.title).toBe("Reorder button misaligns");+ expect(b.risk).toBe("low");+ expect(b.acceptance).toEqual([+ "Button centers at <640px",+ "No console errors"+ ]);+ });++ it("throws on missing required fields", () => {+ expect(() => parseBinding("---\nkind: bug\n---")).toThrow(/id/);+ });++ it("strips surrounding quotes from scalars and acceptance items", () => {+ const b = parseBinding(+ `---\nid: "q-1"\nkind: 'bug'\ntitle: "Fix: the thing"\nacceptance:\n- "centers at <640px"\n---`+ );+ expect(b.id).toBe("q-1");+ expect(b.kind).toBe("bug");+ expect(b.title).toBe("Fix: the thing");+ expect(b.acceptance).toEqual(["centers at <640px"]);+ });+});diff --git a/packages/harness/src/binding.ts b/packages/harness/src/binding.tsnew file mode 100644index 0000000000..de2c534f3b--- /dev/null+++ b/packages/harness/src/binding.ts@@ -0,0 +1,56 @@+export type LoopKind = "bug" | "feature" | "usability" | "copy";++export type Binding = {+ id: string;+ kind: LoopKind;+ title: string;+ risk: "low" | "med" | "high";+ acceptance: string[];+};++const KINDS: LoopKind[] = ["bug", "feature", "usability", "copy"];++/** Trim surrounding whitespace and a single pair of wrapping quotes. */+function unquote(value: string): string {+ return value.trim().replace(/^(["'])(.*)\1$/, "$2");+}++/**+ * Parse the YAML-ish frontmatter of a `.loop.md` binding. No YAML dependency.+ * Scalars may be quoted or bare. The `acceptance` list must be contiguous+ * (one `- item` per line) — a blank line or another key ends it.+ */+export function parseBinding(md: string): Binding {+ const match = md.match(/^---\n([\s\S]*?)\n---/);+ if (!match || !match[1]) throw new Error("Binding has no frontmatter block.");+ const lines = match[1].split("\n");+ const scalars: Record<string, string> = {};+ const acceptance: string[] = [];+ let inAcceptance = false;+ for (const line of lines) {+ if (/^acceptance:\s*$/.test(line)) {+ inAcceptance = true;+ continue;+ }+ if (inAcceptance && /^\s*-\s+/.test(line)) {+ acceptance.push(unquote(line.replace(/^\s*-\s+/, "")));+ continue;+ }+ inAcceptance = false;+ const kv = line.match(/^([a-zA-Z]+):\s*(.*)$/);+ if (kv?.[1]) scalars[kv[1]] = unquote(kv[2] ?? "");+ }+ const id = scalars.id;+ if (!id) throw new Error("Binding missing required field: id");+ const kind = scalars.kind;+ if (!kind || !KINDS.includes(kind as LoopKind)) {+ throw new Error(`Binding kind must be one of ${KINDS.join("|")}`);+ }+ return {+ id,+ kind: kind as LoopKind,+ title: scalars.title ?? "",+ risk: (scalars.risk as Binding["risk"]) ?? "low",+ acceptance+ };+}diff --git a/packages/harness/src/gates.test.ts b/packages/harness/src/gates.test.tsnew file mode 100644index 0000000000..25324dc6e0--- /dev/null+++ b/packages/harness/src/gates.test.ts@@ -0,0 +1,25 @@+import { describe, expect, it } from "vitest";+import { type Exec, FLOOR_GATES, runGates } from "./gates";++describe("runGates", () => {+ it("runs each gate via the injected exec and reports pass/fail", () => {+ const exec: Exec = (cmd) => ({+ ok: !cmd.includes("clobbers"),+ output: cmd+ });+ const gates = [+ { id: "lint", cmd: "biome check" },+ { id: "clobbers", cmd: "pnpm clobbers" }+ ];+ const results = runGates(gates, exec);+ expect(results).toEqual([+ { id: "lint", passed: true, output: "biome check" },+ { id: "clobbers", passed: false, output: "pnpm clobbers" }+ ]);+ });++ it("ships a non-empty FLOOR_GATES list", () => {+ expect(FLOOR_GATES.length).toBeGreaterThan(0);+ expect(FLOOR_GATES.every((g) => g.id && g.cmd)).toBe(true);+ });+});diff --git a/packages/harness/src/gates.ts b/packages/harness/src/gates.tsnew file mode 100644index 0000000000..ace0c39a37--- /dev/null+++ b/packages/harness/src/gates.ts@@ -0,0 +1,17 @@+export type Gate = { id: string; cmd: string };+export type GateResult = { id: string; passed: boolean; output: string };+export type Exec = (cmd: string) => { ok: boolean; output: string };++/** The v1 floor: cheap, deterministic, reuses the @carbon/checks checks. Add a row to grow. */+export const FLOOR_GATES: Gate[] = [+ { id: "lint", cmd: "pnpm exec biome check" },+ { id: "conformance", cmd: "pnpm --filter @carbon/checks test" },+ { id: "clobbers", cmd: "pnpm --filter @carbon/checks clobbers" }+];++export function runGates(gates: Gate[], exec: Exec): GateResult[] {+ return gates.map((g) => {+ const r = exec(g.cmd);+ return { id: g.id, passed: r.ok, output: r.output };+ });+}diff --git a/packages/harness/src/index.ts b/packages/harness/src/index.tsnew file mode 100644index 0000000000..6e0d309e2b--- /dev/null+++ b/packages/harness/src/index.ts@@ -0,0 +1,36 @@+export { type Binding, type LoopKind, parseBinding } from "./binding";+export {+ type Exec,+ FLOOR_GATES,+ type Gate,+ type GateResult,+ runGates+} from "./gates";+export { appendLedger, type LedgerEntry, readLedger } from "./ledger";+export {+ behaviorGate,+ ensureStack,+ parseBehaviorResult,+ reachable+} from "./runner/behavior";+export { runLoop } from "./runner/loop";+export {+ buildDoerPrompt,+ buildJudgePrompt,+ extractJson,+ parseDoerResult,+ parseJudgeResult+} from "./runner/prompts";+export {+ type BehaviorResult,+ type ClaudeRequest,+ type ClaudeResult,+ DEFAULT_CONFIG,+ type DoerResult,+ type JudgeResult,+ type LoopOutcome,+ type RunnerConfig,+ type RunnerDeps,+ type Shell,+ type TerminalState+} from "./runner/types";diff --git a/packages/harness/src/ledger.test.ts b/packages/harness/src/ledger.test.tsnew file mode 100644index 0000000000..e90cebfa61--- /dev/null+++ b/packages/harness/src/ledger.test.ts@@ -0,0 +1,30 @@+import { mkdtempSync } from "node:fs";+import { tmpdir } from "node:os";+import { join } from "node:path";+import { describe, expect, it } from "vitest";+import { appendLedger, type LedgerEntry, readLedger } from "./ledger";++const entry = (over: Partial<LedgerEntry> = {}): LedgerEntry => ({+ iteration: 1,+ change: "centered the button",+ gates: { lint: true, conformance: true },+ decision: "keep",+ reason: "all floor gates green",+ at: "2026-06-25T00:00:00Z",+ ...over+});++describe("ledger", () => {+ it("appends entries and reads them back in order", () => {+ const path = join(mkdtempSync(join(tmpdir(), "led-")), "ledger.jsonl");+ appendLedger(path, entry({ iteration: 1 }));+ appendLedger(path, entry({ iteration: 2, decision: "revert" }));+ const all = readLedger(path);+ expect(all.map((e) => e.iteration)).toEqual([1, 2]);+ expect(all[1]?.decision).toBe("revert");+ });++ it("reads an empty/missing ledger as []", () => {+ expect(readLedger(join(tmpdir(), "nope-ledger.jsonl"))).toEqual([]);+ });+});diff --git a/packages/harness/src/ledger.ts b/packages/harness/src/ledger.tsnew file mode 100644index 0000000000..63bc65b3b6--- /dev/null+++ b/packages/harness/src/ledger.ts@@ -0,0 +1,28 @@+import { appendFileSync, mkdirSync, readFileSync } from "node:fs";+import { dirname } from "node:path";++export type LedgerEntry = {+ iteration: number;+ change: string;+ gates: Record<string, boolean>;+ decision: "keep" | "revert";+ reason: string;+ /** ISO timestamp, supplied by the caller (the harness has no clock). */+ at: string;+};++export function appendLedger(path: string, entry: LedgerEntry): void {+ mkdirSync(dirname(path), { recursive: true });+ appendFileSync(path, `${JSON.stringify(entry)}\n`);+}++export function readLedger(path: string): LedgerEntry[] {+ try {+ return readFileSync(path, "utf8")+ .split("\n")+ .filter(Boolean)+ .map((l) => JSON.parse(l) as LedgerEntry);+ } catch {+ return [];+ }+}diff --git a/packages/harness/src/runner/behavior.test.ts b/packages/harness/src/runner/behavior.test.tsnew file mode 100644index 0000000000..1f3563ef06--- /dev/null+++ b/packages/harness/src/runner/behavior.test.ts@@ -0,0 +1,102 @@+import { mkdtempSync, rmSync, writeFileSync } from "node:fs";+import { tmpdir } from "node:os";+import { join } from "node:path";+import { afterEach, beforeEach, describe, expect, it } from "vitest";+import { ensureStack, parseBehaviorResult, reachable } from "./behavior";+import type { Shell } from "./types";++let dir: string;+beforeEach(() => {+ dir = mkdtempSync(join(tmpdir(), "behavior-"));+});+afterEach(() => rmSync(dir, { recursive: true, force: true }));++/** A shell where curl to specific URLs returns a chosen HTTP code; others refuse. */+function curlShell(codes: Record<string, string>): Shell {+ return (cmd: string) => {+ const m = cmd.match(/curl .*'([^']+)'/);+ const url = m?.[1];+ if (url && codes[url]) return { ok: true, output: codes[url] };+ return { ok: false, output: "000" }; // connection refused+ };+}++describe("reachable", () => {+ it("treats 2xx/3xx/4xx as serving and a refused connection as down", () => {+ expect(+ reachable("https://erp.x.dev", curlShell({ "https://erp.x.dev": "200" }))+ ).toBe(true);+ expect(+ reachable("https://erp.x.dev", curlShell({ "https://erp.x.dev": "401" }))+ ).toBe(true);+ expect(+ reachable("https://erp.x.dev", curlShell({ "https://erp.x.dev": "302" }))+ ).toBe(true);+ expect(reachable("https://erp.x.dev", curlShell({}))).toBe(false);+ expect(+ reachable("https://erp.x.dev", curlShell({ "https://erp.x.dev": "503" }))+ ).toBe(false);+ });+});++describe("ensureStack", () => {+ const log = () => undefined;++ it("returns the live portless URL when it answers", () => {+ writeFileSync(+ join(dir, ".env.local"),+ "ERP_URL=https://erp.x.dev\nPORT_ERP=61934\n"+ );+ const out = ensureStack(+ dir,+ curlShell({ "https://erp.x.dev": "200" }),+ log+ );+ expect(out).toEqual({ baseUrl: "https://erp.x.dev" });+ });++ it("falls back to the localhost backend when portless is unreachable", () => {+ writeFileSync(+ join(dir, ".env.local"),+ "ERP_URL=https://erp.x.dev\nPORT_ERP=61934\n"+ );+ const out = ensureStack(+ dir,+ curlShell({ "http://localhost:61934": "200" }),+ log+ );+ expect(out).toEqual({ baseUrl: "http://localhost:61934" });+ });++ it("blocks when no URL answers even after a boot attempt", () => {+ writeFileSync(join(dir, ".env.local"), "ERP_URL=https://erp.x.dev\n");+ const out = ensureStack(dir, curlShell({}), log);+ expect("blocked" in out && out.blocked).toContain("not reachable");+ });++ it("blocks when .env.local has no ERP URL at all", () => {+ writeFileSync(join(dir, ".env.local"), "SOMETHING=else\n");+ const out = ensureStack(dir, curlShell({}), log);+ expect("blocked" in out && out.blocked).toContain("Carbon worktree");+ });+});++describe("parseBehaviorResult", () => {+ it("parses the fenced json verdict", () => {+ const text =+ 'verified.\n```json\n{"passed":true,"screenshots":["/a/01.png"],"notes":"saw it"}\n```';+ expect(parseBehaviorResult(text)).toEqual({+ passed: true,+ screenshots: ["/a/01.png"],+ notes: "saw it"+ });+ });++ it("defaults missing fields safely", () => {+ expect(parseBehaviorResult('```json\n{"passed":false}\n```')).toEqual({+ passed: false,+ screenshots: [],+ notes: ""+ });+ });+});diff --git a/packages/harness/src/runner/behavior.ts b/packages/harness/src/runner/behavior.tsnew file mode 100644index 0000000000..9ab61b8a9d--- /dev/null+++ b/packages/harness/src/runner/behavior.ts@@ -0,0 +1,218 @@+import { mkdirSync, readFileSync } from "node:fs";+import { join } from "node:path";+import type { Binding } from "../binding";+import { tryExtractJson } from "./prompts";+import { sq } from "./shell";+import type { BehaviorResult, RunnerConfig, RunnerDeps, Shell } from "./types";++/** Read one `KEY=value` line out of the worktree's `.env.local`. */+function readEnvVar(cwd: string, key: string): string | undefined {+ try {+ const env = readFileSync(join(cwd, ".env.local"), "utf8");+ const m = env.match(new RegExp(`^${key}=(.+)$`, "m"));+ return m?.[1]?.trim();+ } catch {+ return undefined;+ }+}++/**+ * The base URLs to try, in order: the portless `*.dev` host, then the localhost+ * backend (the app may be up on its port even when the portless proxy/cert is+ * flaky). Empty entries are dropped.+ */+function candidateUrls(cwd: string): string[] {+ const erpUrl = readEnvVar(cwd, "ERP_URL");+ const port = readEnvVar(cwd, "PORT_ERP");+ return [erpUrl, port ? `http://localhost:${port}` : undefined].filter(+ (u): u is string => Boolean(u)+ );+}++/** Is `url` serving? 2xx/3xx/4xx all count — the app responded; only a refused/timed-out connection fails. */+export function reachable(url: string, shell: Shell): boolean {+ const r = shell(`curl -k -s -o /dev/null -m 8 -w "%{http_code}" ${sq(url)}`);+ const code = Number.parseInt(r.output.trim(), 10);+ return Number.isFinite(code) && code >= 200 && code < 500;+}++/**+ * Make the app reachable, deterministically. Probe the candidates; if none+ * answer, make ONE bounded boot attempt (`crbn up --no-apps` brings up the+ * services and returns) and re-probe. Returns the live base URL, or a `blocked`+ * note — boot is environmental, so failure stops the loop rather than churning.+ */+export function ensureStack(+ cwd: string,+ shell: Shell,+ log: RunnerDeps["log"]+): { baseUrl: string } | { blocked: string } {+ const candidates = candidateUrls(cwd);+ if (candidates.length === 0) {+ return {+ blocked: "no ERP_URL/PORT_ERP in .env.local — is this a Carbon worktree?"+ };+ }+ for (const url of candidates) {+ if (reachable(url, shell)) return { baseUrl: url };+ }++ log({+ event: "behavior:boot",+ msg: "stack not reachable, attempting crbn up --no-apps"+ });+ shell("CARBON_DEV_YES=1 crbn up --no-apps", { cwd });+ for (const url of candidates) {+ if (reachable(url, shell)) return { baseUrl: url };+ }+ return {+ blocked: `ERP not reachable (tried ${candidates.join(", ")}); start the stack with app servers (\`crbn up\`) before UI loops`+ };+}++export function buildBehaviorPrompt(+ binding: Binding,+ baseUrl: string,+ email: string,+ shotDir: string+): string {+ return `You are the BEHAVIOR GATE in an unattended conductor loop. The code change is already applied in this worktree. Your job: prove — in the RUNNING app — that the fix works. There is NO human; never ask a question.++Work item (${binding.kind}): ${binding.title}++Acceptance criteria:+${binding.acceptance.map((c, i) => ` [${i}] ${c}`).join("\n")}++The app is reachable at ${baseUrl}. Use the \`agent-browser\` CLI (open / wait --load networkidle / snapshot -i / fill / click / screenshot).++Steps:+1. Log in via the dev bypass: open ${baseUrl}/login, fill the email field with "${email}", submit, and wait until you land on /x (the authenticated app). If login fails, that's a FAIL.+2. Navigate to the screen the work item affects and REPRODUCE the exact condition it describes (e.g. the specific record/state). Do not test a happy path that sidesteps the bug.+3. Verify the fix actually works on that screen.+4. Capture screenshots PROVING it to: ${shotDir} (use explicit file paths like ${shotDir}/after-<label>.png). At least one screenshot is required for a pass.++End your reply with EXACTLY one fenced json block, no prose after it:+\`\`\`json+{+ "passed": <true only if you SAW the fix work in the running app, with screenshots>,+ "screenshots": ["${shotDir}/after-...png", "..."],+ "notes": "<what you reproduced and observed>"+}+\`\`\``;+}++/** Prompt for the best-effort BEFORE capture (the fix is temporarily reverted). */+export function buildBeforePrompt(+ binding: Binding,+ baseUrl: string,+ email: string,+ shotDir: string+): string {+ return `You are capturing a BEFORE screenshot for an unattended conductor loop. The fix has been TEMPORARILY REVERTED, so the running app currently shows the BUG. There is NO human; never ask a question.++Work item (${binding.kind}): ${binding.title}+The failing condition: ${binding.acceptance[0] ?? binding.title}++The app is at ${baseUrl}. Log in via the dev bypass (email "${email}") if not already authenticated, navigate to the affected screen, and REPRODUCE the bug. The app was just hot-reloaded to the reverted code — reload the page and wait for it to settle before capturing. Capture ONE screenshot of the bug to ${shotDir}/before-01.png.++End your reply with EXACTLY one fenced json block, no prose after it:+\`\`\`json+{ "screenshots": ["${shotDir}/before-01.png"], "notes": "<what the bug looks like>" }+\`\`\``;+}++/**+ * Best-effort BEFORE capture: stash the doer's (uncommitted) fix so the app+ * shows the bug, screenshot it, then ALWAYS restore the fix. Failures here never+ * fail the gate — the AFTER capture is what verifies; before is a bonus for the+ * PR. Only stashes when there's actually a change to revert.+ */+function captureBefore(+ binding: Binding,+ cfg: RunnerConfig,+ deps: RunnerDeps,+ baseUrl: string,+ email: string,+ shotDir: string+): void {+ const { shell } = deps;+ const stash = shell("git stash push --include-untracked -m loop-before", {+ cwd: cfg.cwd+ });+ if (!stash.ok || /No local changes/.test(stash.output)) return;+ try {+ deps.claude({+ prompt: buildBeforePrompt(binding, baseUrl, email, shotDir),+ cwd: cfg.cwd,+ maxTurns: cfg.behaviorMaxTurns,+ maxBudgetUsd: cfg.behaviorMaxBudgetUsd+ });+ } catch {+ /* best-effort — the AFTER capture is what gates */+ } finally {+ shell("git stash pop", { cwd: cfg.cwd }); // ALWAYS restore the fix+ }+}++export function parseBehaviorResult(text: string): BehaviorResult {+ const raw = tryExtractJson<Partial<BehaviorResult>>(text);+ if (!raw) {+ return {+ passed: false,+ screenshots: [],+ notes: "behavior gate returned no JSON verdict"+ };+ }+ return {+ passed: raw.passed === true,+ screenshots: Array.isArray(raw.screenshots) ? raw.screenshots : [],+ notes: raw.notes ?? ""+ };+}++/**+ * The real UI behavior gate, matching `RunnerDeps.behaviorGate`. Deterministic+ * readiness check (blocks if the stack can't be brought up) + a model-driven+ * browser verification that must SEE the fix work and capture screenshots.+ */+export function behaviorGate(+ binding: Binding,+ cfg: RunnerConfig,+ deps: RunnerDeps+): BehaviorResult {+ const stack = ensureStack(cfg.cwd, deps.shell, deps.log);+ if ("blocked" in stack) {+ return {+ passed: false,+ screenshots: [],+ notes: stack.blocked,+ blocked: stack.blocked+ };+ }++ const email = readEnvVar(cfg.cwd, "DEV_BYPASS_EMAIL") ?? "[email protected]";+ const shotDir = join(cfg.cwd, `llm/loops/${binding.id}/screenshots`);+ mkdirSync(shotDir, { recursive: true });++ // BEFORE (best-effort): show the bug with the fix reverted, then restore it.+ captureBefore(binding, cfg, deps, stack.baseUrl, email, shotDir);++ // AFTER (essential): verify the fix works and screenshot it.+ const res = deps.claude({+ prompt: buildBehaviorPrompt(binding, stack.baseUrl, email, shotDir),+ cwd: cfg.cwd,+ maxTurns: cfg.behaviorMaxTurns,+ maxBudgetUsd: cfg.behaviorMaxBudgetUsd+ });+ const result = parseBehaviorResult(res.text);+ // A capped/errored run never counts as verified, even if it emitted a verdict.+ if (res.incomplete) {+ return {+ ...result,+ passed: false,+ notes:+ `${result.notes} [claude stopped: ${res.stopReason ?? "incomplete"}]`.trim()+ };+ }+ return result;+}diff --git a/packages/harness/src/runner/claude.ts b/packages/harness/src/runner/claude.tsnew file mode 100644index 0000000000..7fcd35c33f--- /dev/null+++ b/packages/harness/src/runner/claude.ts@@ -0,0 +1,68 @@+import { spawnSync } from "node:child_process";+import type { ClaudeRequest, ClaudeResult } from "./types";++const MAX_BUFFER = 64 * 1024 * 1024;++/**+ * Invoke `claude -p` headless and return the final text + cost. Runs with+ * `bypassPermissions` (the loop runs in an isolated worktree with a powerless+ * token; PreToolUse hooks are the real guardrail) and hard turn/budget caps so a+ * wedged session dies instead of spinning. `spawnSync` (no shell) passes the+ * prompt as a single argv element, so no escaping is needed.+ */+export function claude(req: ClaudeRequest): ClaudeResult {+ const args = [+ "-p",+ req.prompt,+ "--output-format",+ "json",+ "--permission-mode",+ "bypassPermissions",+ "--max-turns",+ String(req.maxTurns),+ "--max-budget-usd",+ String(req.maxBudgetUsd)+ ];+ const model = process.env.CONDUCTOR_MODEL;+ if (model) args.push("--model", model);++ const res = spawnSync("claude", args, {+ cwd: req.cwd,+ encoding: "utf8",+ maxBuffer: MAX_BUFFER+ });+ if (res.error)+ throw new Error(`claude failed to spawn: ${res.error.message}`);++ // `claude --output-format json` prints a result object even on a NON-ZERO+ // exit (a hit `--max-turns`/`--max-budget-usd` exits non-zero with+ // `is_error:true, subtype:"error_max_turns"|...`). Salvage it: a capped run+ // is a soft outcome the caller's parser handles, not a process crash. Only a+ // genuinely empty/unparseable stdout is fatal.+ let parsed:+ | {+ result?: string;+ total_cost_usd?: number;+ session_id?: string;+ is_error?: boolean;+ subtype?: string;+ }+ | undefined;+ try {+ parsed = JSON.parse(res.stdout);+ } catch {+ parsed = undefined;+ }+ if (!parsed) {+ throw new Error(+ `claude exited ${res.status} with no JSON result: ${(res.stdout || res.stderr || "").slice(0, 2000)}`+ );+ }+ return {+ text: parsed.result ?? "",+ costUsd: parsed.total_cost_usd ?? 0,+ sessionId: parsed.session_id ?? "",+ incomplete: parsed.is_error === true,+ stopReason: parsed.subtype+ };+}diff --git a/packages/harness/src/runner/loop.test.ts b/packages/harness/src/runner/loop.test.tsnew file mode 100644index 0000000000..cdf8031260--- /dev/null+++ b/packages/harness/src/runner/loop.test.ts@@ -0,0 +1,224 @@+import { mkdtempSync, rmSync } from "node:fs";+import { tmpdir } from "node:os";+import { join } from "node:path";+import { afterEach, beforeEach, describe, expect, it } from "vitest";+import type { Binding } from "../binding";+import { readLedger } from "../ledger";+import { runLoop } from "./loop";+import type {+ ClaudeRequest,+ ClaudeResult,+ DoerResult,+ JudgeResult,+ RunnerConfig,+ RunnerDeps+} from "./types";++const BINDING: Binding = {+ id: "bug-1",+ kind: "bug",+ title: "off-by-one in total",+ risk: "low",+ acceptance: ["total is correct", "a test covers it"]+};++function jsonText(obj: unknown): string {+ return `done.\n\`\`\`json\n${JSON.stringify(obj)}\n\`\`\``;+}+const doer = (d: Partial<DoerResult>) =>+ jsonText({+ change: "fix",+ packages: [],+ testCommand: "",+ touchedUI: false,+ ...d+ });+const judge = (j: Partial<JudgeResult>) =>+ jsonText({ approved: false, unmet: [], feedback: "", ...j });++let dir: string;+let ledgerPath: string;++beforeEach(() => {+ dir = mkdtempSync(join(tmpdir(), "loop-"));+ ledgerPath = join(dir, "ledger.jsonl");+});+afterEach(() => rmSync(dir, { recursive: true, force: true }));++function makeDeps(opts: {+ claude: (req: ClaudeRequest) => ClaudeResult;+ shell?: RunnerDeps["shell"];+ behaviorGate?: RunnerDeps["behaviorGate"];+}): RunnerDeps {+ return {+ claude: opts.claude,+ shell: opts.shell ?? (() => ({ ok: true, output: "" })),+ now: () => "2026-01-01T00:00:00.000Z",+ log: () => undefined,+ ...(opts.behaviorGate ? { behaviorGate: opts.behaviorGate } : {})+ };+}++function makeConfig(over: Partial<RunnerConfig> = {}): RunnerConfig {+ return {+ cwd: dir,+ ledgerPath,+ plateauAfter: 2,+ maxIterations: 8,+ doerMaxTurns: 10,+ doerMaxBudgetUsd: 1,+ judgeMaxTurns: 5,+ judgeMaxBudgetUsd: 1,+ behaviorMaxTurns: 10,+ behaviorMaxBudgetUsd: 1,+ ...over+ };+}++/** Queue doer/judge responses; route by which prompt the loop sent. */+function scriptedClaude(doers: string[], judges: string[]) {+ const d = [...doers];+ const j = [...judges];+ return (req: ClaudeRequest): ClaudeResult => {+ const isDoer = req.prompt.includes("You are the DOER");+ const text = (isDoer ? d.shift() : j.shift()) ?? jsonText({});+ return { text, costUsd: 0, sessionId: "s" };+ };+}++/** Dirty tree by default; named commands can be forced to fail. */+function dirtyShell(fail: string[] = []): RunnerDeps["shell"] {+ return (cmd: string) => {+ if (cmd === "git diff --quiet") return { ok: false, output: "" }; // dirty+ if (fail.some((f) => cmd.includes(f))) return { ok: false, output: "fail" };+ return { ok: true, output: "" };+ };+}++describe("runLoop", () => {+ it("ships when gates pass and the judge approves with nothing unmet", () => {+ const committed: string[] = [];+ const shell: RunnerDeps["shell"] = (cmd) => {+ if (cmd === "git diff --quiet") return { ok: false, output: "" };+ if (cmd.startsWith("git commit")) committed.push(cmd);+ return { ok: true, output: "" };+ };+ const deps = makeDeps({+ claude: scriptedClaude(+ [doer({ testCommand: "vitest run" })],+ [judge({ approved: true, unmet: [] })]+ ),+ shell+ });++ const out = runLoop(BINDING, makeConfig(), deps);++ expect(out.state).toBe("shipped");+ expect(out.iterations).toBe(1);+ expect(committed).toHaveLength(1);+ const ledger = readLedger(ledgerPath);+ expect(ledger.at(-1)?.decision).toBe("keep");+ });++ it("makes progress then ships once unmet is empty", () => {+ const deps = makeDeps({+ claude: scriptedClaude(+ [doer({}), doer({})],+ [+ judge({ approved: true, unmet: [1] }),+ judge({ approved: true, unmet: [] })+ ]+ ),+ shell: dirtyShell()+ });++ const out = runLoop(BINDING, makeConfig(), deps);++ expect(out.state).toBe("shipped");+ expect(out.iterations).toBe(2);+ expect(+ readLedger(ledgerPath).filter((e) => e.decision === "keep")+ ).toHaveLength(2);+ });++ it("reverts on a failed gate and plateaus after plateauAfter dry iterations", () => {+ const deps = makeDeps({+ claude: scriptedClaude([doer({}), doer({})], []), // judge never reached — gates fail+ shell: dirtyShell(["@carbon/checks test"]) // conformance gate fails+ });++ const out = runLoop(BINDING, makeConfig({ plateauAfter: 2 }), deps);++ expect(out.state).toBe("plateau");+ expect(out.iterations).toBe(2);+ const ledger = readLedger(ledgerPath);+ expect(ledger.every((e) => e.decision === "revert")).toBe(true);+ expect(ledger.at(-1)?.gates.conformance).toBe(false);+ });++ it("blocks when the doer reports it cannot proceed", () => {+ const deps = makeDeps({+ claude: scriptedClaude(+ [doer({ blocked: "need a product decision" })],+ []+ ),+ shell: dirtyShell()+ });++ const out = runLoop(BINDING, makeConfig(), deps);++ expect(out.state).toBe("blocked");+ expect(out.reason).toContain("need a product decision");+ });++ it("blocks a UI change when no behavior gate is wired (milestone 1)", () => {+ const deps = makeDeps({+ claude: scriptedClaude([doer({ touchedUI: true })], []),+ shell: dirtyShell()+ });++ const out = runLoop(BINDING, makeConfig(), deps);++ expect(out.state).toBe("blocked");+ expect(out.reason).toContain("behavior gate");+ });++ it("blocks (not reverts) when the behavior gate reports the stack is down", () => {+ const deps = makeDeps({+ claude: scriptedClaude([doer({ touchedUI: true })], []),+ shell: dirtyShell(),+ behaviorGate: () => ({+ passed: false,+ screenshots: [],+ notes: "down",+ blocked: "ERP not reachable"+ })+ });++ const out = runLoop(BINDING, makeConfig(), deps);++ expect(out.state).toBe("blocked");+ expect(out.reason).toContain("ERP not reachable");+ });++ it("runs the behavior gate for UI changes when wired", () => {+ let called = 0;+ const deps = makeDeps({+ claude: scriptedClaude(+ [doer({ touchedUI: true })],+ [judge({ approved: true, unmet: [] })]+ ),+ shell: dirtyShell(),+ behaviorGate: () => {+ called++;+ return { passed: true, screenshots: ["a.png"], notes: "ok" };+ }+ });++ const out = runLoop(BINDING, makeConfig(), deps);++ expect(called).toBe(1);+ expect(out.state).toBe("shipped");+ expect(readLedger(ledgerPath).at(-1)?.gates.behavior).toBe(true);+ });+});diff --git a/packages/harness/src/runner/loop.ts b/packages/harness/src/runner/loop.tsnew file mode 100644index 0000000000..7624553f91--- /dev/null+++ b/packages/harness/src/runner/loop.ts@@ -0,0 +1,221 @@+import type { Binding } from "../binding";+import { FLOOR_GATES, runGates } from "../gates";+import { appendLedger, readLedger } from "../ledger";+import {+ buildDoerPrompt,+ buildJudgePrompt,+ parseDoerResult,+ parseJudgeResult+} from "./prompts";+import { sq } from "./shell";+import type {+ JudgeResult,+ LoopOutcome,+ RunnerConfig,+ RunnerDeps,+ Shell+} from "./types";++/** Is the working tree dirty? `git diff --quiet` exits non-zero when it is. */+function isDirty(shell: Shell, cwd: string): boolean {+ return !shell("git diff --quiet", { cwd }).ok;+}++function commit(shell: Shell, cwd: string, message: string): void {+ shell("git add -A", { cwd });+ // sq() single-quotes the message — the doer's summary may contain backticks/$.+ shell(`git commit -m ${sq(message)}`, { cwd });+}++/** Discard the current iteration's uncommitted work. Ignored files (the ledger) survive. */+function revert(shell: Shell, cwd: string): void {+ shell("git checkout -- .", { cwd });+ shell("git clean -fd", { cwd });+}++function revertReason(+ gates: Record<string, boolean>,+ judge: JudgeResult+): string {+ const failed = Object.entries(gates)+ .filter(([, ok]) => !ok)+ .map(([id]) => id);+ if (failed.length > 0) return `gates failed: ${failed.join(", ")}`;+ if (!judge.approved) return `judge rejected: ${judge.feedback}`;+ return "reverted";+}++/**+ * Drive ONE work item through the conductor cycle to a green committed state,+ * fully unattended. This is the deterministic spine of the conductor skill,+ * promoted out of prose into code: the loop owns worktree state, gate execution,+ * keep/revert, the ledger, and the terminal-state machine; the model is invoked+ * only for the three judgment steps (doer, behavior, judge).+ *+ * Pure w.r.t. the outside world — every side effect goes through `deps`. The+ * caller (the script) creates the worktree and, on a `shipped` outcome, opens+ * the PR. This function never merges and never runs on `main`.+ */+export function runLoop(+ binding: Binding,+ config: RunnerConfig,+ deps: RunnerDeps+): LoopOutcome {+ const { claude, shell, now, log } = deps;+ const { cwd, ledgerPath } = config;+ let iteration = 0;+ let sinceKeep = 0;++ const end = (state: LoopOutcome["state"], reason: string): LoopOutcome => {+ log({ event: "loop:end", state, reason, iterations: iteration });+ return { state, iterations: iteration, reason };+ };++ while (iteration < config.maxIterations) {+ iteration++;+ try {+ const ledger = readLedger(ledgerPath);+ log({ event: "iteration:start", iteration });++ // 1. DOER — smallest change toward the weakest criterion.+ const doerRes = claude({+ prompt: buildDoerPrompt(binding, ledger),+ cwd,+ maxTurns: config.doerMaxTurns,+ maxBudgetUsd: config.doerMaxBudgetUsd+ });+ const doer = parseDoerResult(doerRes.text);+ log({+ event: "doer",+ iteration,+ change: doer.change,+ cost: doerRes.costUsd+ });++ if (doer.blocked) {+ revert(shell, cwd);+ return end("blocked", `doer blocked: ${doer.blocked}`);+ }++ // The doer may have decided nothing was needed. If the tree is clean, the+ // only question left is "are we done?" — let the judge confirm.+ const dirty = isDirty(shell, cwd);++ const gates: Record<string, boolean> = {};+ if (dirty) {+ // 2. FLOOR GATES (lint + conformance + clobbers) and per-package typecheck.+ const floor = config.gates ?? FLOOR_GATES;+ for (const r of runGates(floor, (cmd) => shell(cmd, { cwd }))) {+ gates[r.id] = r.passed;+ }+ for (const pkg of doer.packages) {+ gates[`typecheck:${pkg}`] = shell(`pnpm --filter ${pkg} typecheck`, {+ cwd+ }).ok;+ }++ // 3. BEHAVIOR GATE — UI changes are not done until seen working in the app.+ if (doer.touchedUI) {+ if (!deps.behaviorGate) {+ revert(shell, cwd);+ return end(+ "blocked",+ "change touches UI but the headless behavior gate is not available (milestone 2)"+ );+ }+ const b = deps.behaviorGate(binding, config, deps);+ if (b.blocked) {+ revert(shell, cwd);+ return end("blocked", `behavior gate blocked: ${b.blocked}`);+ }+ gates.behavior = b.passed;+ log({+ event: "behavior",+ iteration,+ passed: b.passed,+ shots: b.screenshots.length,+ notes: b.notes+ });+ }++ // 4. CORRECTNESS GATE — the reproduce→fix→same-path test.+ if (doer.testCommand) {+ gates.correctness = shell(doer.testCommand, { cwd }).ok;+ }+ }++ const gatesGreen = Object.values(gates).every(Boolean);++ // 5. JUDGE — only worth a session when the objective gates already pass.+ let judge: JudgeResult = {+ approved: false,+ unmet: [],+ feedback: "gates failed"+ };+ if (gatesGreen) {+ const judgeRes = claude({+ prompt: buildJudgePrompt(binding),+ cwd,+ maxTurns: config.judgeMaxTurns,+ maxBudgetUsd: config.judgeMaxBudgetUsd+ });+ judge = parseJudgeResult(judgeRes.text);+ log({+ event: "judge",+ iteration,+ approved: judge.approved,+ unmet: judge.unmet+ });+ }++ // 6. DECIDE + LEDGER. Keep iff every gate is green AND the judge approves.+ const keep = gatesGreen && judge.approved;+ if (dirty) {+ if (keep) commit(shell, cwd, `loop(${binding.id}): ${doer.change}`);+ else revert(shell, cwd);+ }+ appendLedger(ledgerPath, {+ iteration,+ change: doer.change,+ gates,+ decision: keep ? "keep" : "revert",+ reason: keep+ ? "all gates green; judge approved"+ : revertReason(gates, judge),+ at: now()+ });++ // 7. TERMINATE?+ if (keep && judge.unmet.length === 0) {+ return end("shipped", "all acceptance criteria met and provable");+ }+ // Progress = a real change was committed. A clean no-op never counts.+ if (keep && dirty) sinceKeep = 0;+ else sinceKeep++;+ if (sinceKeep >= config.plateauAfter) {+ return end("plateau", `no progress across ${sinceKeep} iterations`);+ }+ } catch (err) {+ // Any unexpected failure (e.g. claude returned no JSON at all, git/fs+ // error) is recorded and ends the run cleanly — never an uncaught crash+ // that loses the worktree state and writes no ledger.+ const message = err instanceof Error ? err.message : String(err);+ try {+ revert(shell, cwd);+ } catch {+ /* best-effort */+ }+ appendLedger(ledgerPath, {+ iteration,+ change: "(error)",+ gates: {},+ decision: "revert",+ reason: `loop error: ${message}`,+ at: now()+ });+ return end("error", message);+ }+ }++ return end("plateau", `hit max iterations (${config.maxIterations})`);+}diff --git a/packages/harness/src/runner/pr.ts b/packages/harness/src/runner/pr.tsnew file mode 100644index 0000000000..d4e5e225ba--- /dev/null+++ b/packages/harness/src/runner/pr.ts@@ -0,0 +1,190 @@+import { mkdtempSync, readdirSync, writeFileSync } from "node:fs";+import { tmpdir } from "node:os";+import { dirname, join } from "node:path";+import type { Binding } from "../binding";+import { readLedger } from "../ledger";+import { sq } from "./shell";+import type { Shell } from "./types";++/** Screenshot files the behavior gate captured for this loop, if any. */+function screenshots(ledgerPath: string): string[] {+ try {+ const dir = join(dirname(ledgerPath), "screenshots");+ return readdirSync(dir)+ .filter((f) => /\.(png|jpe?g|gif)$/i.test(f))+ .map((f) => join(dir, f))+ .sort();+ } catch {+ return [];+ }+}++const ARTIFACTS_BRANCH = "loop-artifacts";++/**+ * Host the loop's screenshots so they render inline in the PR. Loop artifacts+ * must not pollute the product tree (the conductor guardrail), so they live on+ * ONE shared, non-merging `loop-artifacts` branch (gh-pages style) under+ * `llm/loops/<id>/screenshots/` — appended via a temp index on the branch tip so+ * earlier loops' artifacts survive. All git plumbing, no checkout / working-tree+ * change. Returns raw URLs GitHub renders, or null on any failure so the caller+ * falls back to listing paths rather than failing the PR.+ */+function hostScreenshots(+ id: string,+ shots: string[],+ shell: Shell,+ cwd: string+): { name: string; url: string }[] | null {+ const repo = shell("gh repo view --json nameWithOwner -q .nameWithOwner", {+ cwd+ });+ if (!repo.ok || !repo.output.trim()) return null;+ const slug = repo.output.trim(); // owner/repo++ // Resolve the shared branch's current tip (absent on the first loop ever).+ const fetched = shell(`git fetch origin ${ARTIFACTS_BRANCH}`, { cwd });+ const tip = fetched.ok+ ? shell("git rev-parse FETCH_HEAD", { cwd }).output.trim()+ : "";++ // Build a temp index on top of the tip and add each screenshot.+ const idx = join(mkdtempSync(join(tmpdir(), "loop-idx-")), "index");+ const withIdx = (cmd: string) =>+ shell(`GIT_INDEX_FILE=${sq(idx)} ${cmd}`, { cwd });+ if (tip && !withIdx(`git read-tree ${tip}`).ok) return null;++ const hosted: { name: string; url: string }[] = [];+ for (const path of shots) {+ const h = shell(`git hash-object -w ${sq(path)}`, { cwd });+ if (!h.ok || !h.output.trim()) return null;+ const name = path.split("/").pop() ?? "shot.png";+ const repoPath = `llm/loops/${id}/screenshots/${name}`;+ const add = withIdx(+ `git update-index --add --cacheinfo 100644,${h.output.trim()},${repoPath}`+ );+ if (!add.ok) return null;+ hosted.push({+ name,+ url: `https://raw.githubusercontent.com/${slug}/${ARTIFACTS_BRANCH}/${repoPath}`+ });+ }++ const tree = withIdx("git write-tree");+ if (!tree.ok || !tree.output.trim()) return null;+ const commit = shell(+ `git commit-tree ${tree.output.trim()} ${tip ? `-p ${tip}` : ""} -m ${sq(`chore(loops): screenshots for ${id}`)}`,+ { cwd }+ );+ if (!commit.ok || !commit.output.trim()) return null;+ // Non-force append; a stale tip (a concurrent loop pushed) just fails → paths.+ const push = shell(+ `git push origin ${commit.output.trim()}:refs/heads/${ARTIFACTS_BRANCH}`,+ { cwd }+ );+ if (!push.ok) return null;++ return hosted;+}++/** Sort key + label so before/after captures read in the right order. */+function shotRank(name: string): number {+ if (/before/i.test(name)) return 0;+ if (/after/i.test(name)) return 1;+ return 2;+}+function shotLabel(name: string): string | null {+ if (/before/i.test(name)) return "**Before**";+ if (/after/i.test(name)) return "**After**";+ return null;+}++/** The "Behavior verification" section: embedded images if hosted, else paths. */+function behaviorSection(+ hosted: { name: string; url: string }[] | null,+ shots: string[]+): string[] {+ if (hosted && hosted.length > 0) {+ const ordered = [...hosted].sort(+ (a, b) => shotRank(a.name) - shotRank(b.name)+ );+ const out = ["### Behavior verification"];+ for (const h of ordered) {+ const label = shotLabel(h.name);+ if (label) out.push(label, "");+ out.push(``, "");+ }+ return out;+ }+ if (shots.length > 0) {+ return [+ "### Behavior verification",+ "_captured locally (hosting unavailable):_",+ ...shots.map((s) => `- \`${s}\``),+ ""+ ];+ }+ return [];+}++/**+ * Push the loop branch and open a **gated** PR (never merged). The body carries+ * the design rationale surface: acceptance checklist, embedded behavior-gate+ * screenshots, and the full ledger, so a human reviewer sees every kept/reverted+ * iteration and why. Returns the PR URL.+ */+export function openPr(+ binding: Binding,+ ledgerPath: string,+ shell: Shell,+ cwd: string,+ /** PR base branch. Defaults to the repo default (main); pass the loop's base+ * branch to show only the loop's commit when it wasn't branched off main. */+ base?: string+): string {+ const ledger = readLedger(ledgerPath);+ const kept = ledger.filter((e) => e.decision === "keep").length;+ const shots = screenshots(ledgerPath);+ const hosted =+ shots.length > 0 ? hostScreenshots(binding.id, shots, shell, cwd) : null;++ const body = [+ `## ${binding.title}`,+ "",+ `**Kind:** ${binding.kind} · **Risk:** ${binding.risk}`,+ "",+ "### Acceptance",+ ...binding.acceptance.map((c) => `- [x] ${c}`),+ "",+ ...behaviorSection(hosted, shots),+ "### Ledger",+ ...ledger.map(+ (e) => `- #${e.iteration} **${e.decision}** — ${e.change} _(${e.reason})_`+ ),+ "",+ `_Conducted headless: ${kept} kept / ${ledger.length} iterations. ` ++ `Gated PR — requires human review, do not auto-merge._`+ ].join("\n");++ const bodyFile = join(mkdtempSync(join(tmpdir(), "loop-pr-")), "body.md");+ writeFileSync(bodyFile, body);++ const push = shell("git push -u origin HEAD", { cwd });+ if (!push.ok) throw new Error(`git push failed: ${push.output}`);++ const title = `loop(${binding.id}): ${binding.title}`;+ const baseArg = base ? ` --base ${sq(base)}` : "";+ const r = shell(+ `gh pr create --title ${sq(title)} --body-file ${sq(bodyFile)}${baseArg}`,+ { cwd }+ );+ if (!r.ok) throw new Error(`gh pr create failed: ${r.output}`);++ return (+ r.output+ .split("\n")+ .map((l) => l.trim())+ .filter((l) => l.startsWith("http"))+ .at(-1) ?? r.output.trim()+ );+}diff --git a/packages/harness/src/runner/prompts.ts b/packages/harness/src/runner/prompts.tsnew file mode 100644index 0000000000..12ac0407e8--- /dev/null+++ b/packages/harness/src/runner/prompts.ts@@ -0,0 +1,142 @@+import type { Binding } from "../binding";+import type { LedgerEntry } from "../ledger";+import type { DoerResult, JudgeResult } from "./types";++/** Pull the last fenced ```json block out of model text. Throws if none parses. */+export function extractJson<T>(text: string): T {+ const blocks = [...text.matchAll(/```json\s*([\s\S]*?)```/g)];+ const last = blocks.at(-1)?.[1];+ if (!last) throw new Error("No ```json block in model output.");+ return JSON.parse(last.trim()) as T;+}++/** Like extractJson, but returns null instead of throwing — for total parsers. */+export function tryExtractJson<T>(text: string): T | null {+ try {+ return extractJson<T>(text);+ } catch {+ return null;+ }+}++function ledgerSummary(ledger: LedgerEntry[]): string {+ if (ledger.length === 0) return "(no prior iterations)";+ return ledger+ .map(+ (e) =>+ `#${e.iteration} ${e.decision.toUpperCase()} — ${e.change} (${e.reason})`+ )+ .join("\n");+}++function acceptanceList(binding: Binding): string {+ return binding.acceptance.map((c, i) => ` [${i}] ${c}`).join("\n");+}++/**+ * The doer makes the SMALLEST change toward the weakest-covered acceptance+ * criterion, then reports a structured handoff. Encodes the conductor's §2.1+ * rules for an unattended agent: there is no human, so it never asks — it+ * decides or BLOCKS.+ */+export function buildDoerPrompt(+ binding: Binding,+ ledger: LedgerEntry[]+): string {+ return `You are the DOER in an unattended conductor loop. There is NO human watching — you may never ask a question; either make a change, or report \`blocked\`.++Work item (${binding.kind}, risk ${binding.risk}): ${binding.title}++Acceptance criteria (each is a definition of done):+${acceptanceList(binding)}++Prior iterations:+${ledgerSummary(ledger)}++Your job THIS iteration:+- Make the SMALLEST change toward the weakest-covered acceptance criterion. Do not batch unrelated changes.+- UI work: FIRST copy the nearest existing screen/component (precedent), don't design from concepts.+- ERP-domain logic (accounting, costing, tax, inventory valuation, RMAs): ground it in how real ERPs work; don't invent domain logic.+- Schema/migration changes: run \`pnpm run generate:types\` BEFORE any typecheck (stale types = false green).+- Module code: keep ONE \`<module>.service.ts\` and ONE \`<module>.models.ts\`; never scatter new ones.+- Correctness: write a test that FAILS on the bug/missing-feature and PASSES after your change. Report its exact command.++You are running inside the loop's git worktree. Make your edits directly. Do NOT commit — the loop decides keep/revert. Do NOT open a PR.++End your reply with EXACTLY one fenced json block, no prose after it:+\`\`\`json+{+ "change": "<one line: what you changed>",+ "packages": ["@carbon/<pkg>", "..."],+ "testCommand": "<command that fails before / passes after, or \\"\\">",+ "touchedUI": <true if any user-facing UI changed, else false>,+ "blocked": "<omit unless you cannot proceed without a human; then explain why>"+}+\`\`\``;+}++/**+ * The judge reviews the uncommitted working tree against acceptance + design+ * rules. A SEPARATE session — never the doer grading itself.+ */+export function buildJudgePrompt(binding: Binding): string {+ return `You are the JUDGE in an unattended conductor loop. Review the current UNCOMMITTED change against the acceptance criteria and Carbon's design rules. Be skeptical — do not rubber-stamp.++Work item (${binding.kind}, risk ${binding.risk}): ${binding.title}++Acceptance criteria:+${acceptanceList(binding)}++Inspect the change yourself: run \`git diff\` (and \`git status\`) in the worktree. Check:+- Does the change actually advance the weakest criterion, with a real reproduce→fix→pass test?+- Does it follow Carbon conventions (module layout, RLS/migration rules, existing components over ad-hoc styles)?+- Is the scope minimal — no unrelated edits?+- For each acceptance criterion, is it now MET and provable?++End your reply with EXACTLY one fenced json block, no prose after it:+\`\`\`json+{+ "approved": <true only if THIS change is correct, in-scope, and convention-clean>,+ "unmet": [<indices of acceptance criteria still NOT satisfied; empty array means all done>],+ "feedback": "<concise: what's wrong, or what remains>"+}+\`\`\``;+}++export function parseDoerResult(text: string): DoerResult {+ const raw = tryExtractJson<Partial<DoerResult>>(text);+ // No verdict ⇒ the doer was cut off (limit) or misbehaved. Block rather than+ // silently revert — we can't trust what it left in the tree.+ if (!raw) {+ return {+ change: "(no verdict)",+ packages: [],+ testCommand: "",+ touchedUI: false,+ blocked:+ "doer returned no JSON verdict (possibly hit a turn/budget limit)"+ };+ }+ return {+ change: raw.change ?? "(no summary)",+ packages: Array.isArray(raw.packages) ? raw.packages : [],+ testCommand: raw.testCommand ?? "",+ touchedUI: raw.touchedUI === true,+ ...(raw.blocked ? { blocked: raw.blocked } : {})+ };+}++export function parseJudgeResult(text: string): JudgeResult {+ const raw = tryExtractJson<Partial<JudgeResult>>(text);+ if (!raw)+ return {+ approved: false,+ unmet: [],+ feedback: "judge returned no JSON verdict"+ };+ return {+ approved: raw.approved === true,+ unmet: Array.isArray(raw.unmet) ? raw.unmet : [],+ feedback: raw.feedback ?? ""+ };+}diff --git a/packages/harness/src/runner/shell.ts b/packages/harness/src/runner/shell.tsnew file mode 100644index 0000000000..ce816a70c9--- /dev/null+++ b/packages/harness/src/runner/shell.ts@@ -0,0 +1,25 @@+import { execSync } from "node:child_process";+import type { Shell } from "./types";++const MAX_BUFFER = 64 * 1024 * 1024;++/** Real cwd-aware command runner. Never throws — failures come back as `ok: false`. */+export const shell: Shell = (cmd, opts) => {+ try {+ const output = execSync(cmd, {+ cwd: opts?.cwd,+ encoding: "utf8",+ stdio: ["ignore", "pipe", "pipe"],+ maxBuffer: MAX_BUFFER+ });+ return { ok: true, output };+ } catch (e) {+ const err = e as { stdout?: string; stderr?: string };+ return { ok: false, output: `${err.stdout ?? ""}${err.stderr ?? ""}` };+ }+};++/** POSIX single-quote escape, safe for arbitrary content in a shell command. */+export function sq(s: string): string {+ return `'${s.replace(/'/g, `'\\''`)}'`;+}diff --git a/packages/harness/src/runner/types.ts b/packages/harness/src/runner/types.tsnew file mode 100644index 0000000000..bbb6ecb461--- /dev/null+++ b/packages/harness/src/runner/types.ts@@ -0,0 +1,126 @@+import type { Binding } from "../binding";+import type { Gate } from "../gates";++/** How a run ends. `shipped` = green committed state ready for a PR. */+export type TerminalState = "shipped" | "blocked" | "plateau" | "error";++export type LoopOutcome = {+ state: TerminalState;+ iterations: number;+ /** Set when `state === "shipped"` and the script opened a PR. */+ prUrl?: string;+ reason: string;+};++/**+ * What the doer subagent reports after one change attempt. The doer is agentic+ * (it edits files in the worktree); this is its structured handoff to the loop.+ */+export type DoerResult = {+ /** One-line summary of the change made (goes in the ledger). */+ change: string;+ /** Packages touched, for per-package typecheck — e.g. ["@carbon/checks"]. */+ packages: string[];+ /** A command that FAILS before the fix and PASSES after (the correctness gate). "" if N/A. */+ testCommand: string;+ /** True if the change touches UI / user-facing surface (needs the behavior gate). */+ touchedUI: boolean;+ /** Set when the doer cannot proceed without a human — surfaces as a BLOCKED outcome. */+ blocked?: string;+};++/** The judge subagent's verdict on the current (uncommitted) iteration. */+export type JudgeResult = {+ approved: boolean;+ /** Indices into `binding.acceptance` of criteria still unmet. Empty ⇒ done. */+ unmet: number[];+ feedback: string;+};++/** Outcome of the UI behavior gate (boot stack + agent-browser). */+export type BehaviorResult = {+ passed: boolean;+ screenshots: string[];+ notes: string;+ /**+ * Set when the gate cannot even attempt verification — the stack isn't up and+ * a bounded boot failed. This is environmental: ends the loop as BLOCKED (the+ * skill's "stack can't boot → stop and surface"), never a silent revert/retry.+ */+ blocked?: string;+};++export type ClaudeRequest = {+ prompt: string;+ cwd: string;+ maxTurns: number;+ maxBudgetUsd: number;+};++export type ClaudeResult = {+ /** The model's final text (we parse a trailing ```json block out of it). */+ text: string;+ costUsd: number;+ sessionId: string;+ /** True when claude stopped on an error/limit (`is_error`) — the text may be partial. */+ incomplete?: boolean;+ /** claude's stop subtype, e.g. "error_max_turns" / "error_max_budget". */+ stopReason?: string;+};++/** A command runner bound to a working directory. Mirrors `Exec` but cwd-aware. */+export type Shell = (+ cmd: string,+ opts?: { cwd?: string }+) => { ok: boolean; output: string };++/**+ * Everything the pure loop needs from the outside world. Inject fakes in tests;+ * the script wires real `claude -p` / `git` / `crbn` adapters.+ */+export type RunnerDeps = {+ claude: (req: ClaudeRequest) => ClaudeResult;+ shell: Shell;+ /** ISO timestamp — the harness has no clock, the caller supplies one. */+ now: () => string;+ log: (event: Record<string, unknown>) => void;+ /**+ * The UI behavior gate. Absent in milestone 1 — when a change `touchedUI` and+ * this is undefined, the loop BLOCKS (honest: a UI change unverified is not done).+ */+ behaviorGate?: (+ binding: Binding,+ cfg: RunnerConfig,+ deps: RunnerDeps+ ) => BehaviorResult;+};++export type RunnerConfig = {+ /** Absolute path to the worktree the loop runs in. */+ cwd: string;+ /** Where to append the ledger (e.g. llm/loops/<id>/ledger.jsonl). */+ ledgerPath: string;+ /** Stop after this many consecutive iterations with no kept change. */+ plateauAfter: number;+ /** Hard ceiling on total iterations. */+ maxIterations: number;+ /** The floor gates to run each dirty iteration. Defaults to Carbon's FLOOR_GATES. */+ gates?: Gate[];+ doerMaxTurns: number;+ doerMaxBudgetUsd: number;+ judgeMaxTurns: number;+ judgeMaxBudgetUsd: number;+ behaviorMaxTurns: number;+ behaviorMaxBudgetUsd: number;+};++export const DEFAULT_CONFIG: Omit<RunnerConfig, "cwd" | "ledgerPath"> = {+ plateauAfter: 2,+ maxIterations: 8,+ doerMaxTurns: 60,+ doerMaxBudgetUsd: 5,+ judgeMaxTurns: 20,+ judgeMaxBudgetUsd: 2,+ behaviorMaxTurns: 40,+ behaviorMaxBudgetUsd: 3+};diff --git a/packages/harness/src/runner/worktree.ts b/packages/harness/src/runner/worktree.tsnew file mode 100644index 0000000000..8d83a429b6--- /dev/null+++ b/packages/harness/src/runner/worktree.ts@@ -0,0 +1,38 @@+import { mkdtempSync, readFileSync } from "node:fs";+import { tmpdir } from "node:os";+import { join } from "node:path";+import { sq } from "./shell";+import type { Shell } from "./types";++/**+ * Create the loop's isolated worktree off `origin/main` and return its absolute+ * path. `crbn new` writes the path to the file named by `$CRBN_NEW_TARGET`+ * (its shell wrapper uses this to `cd`), so we point it at a temp file and read.+ *+ * Note: this depends on `crbn` being invocable as a plain command on the box's+ * PATH. If `crbn` is only a shell function in an interactive profile, run the+ * loop with an explicit `--cwd` worktree you created instead (milestone 1).+ */+export function createWorktree(id: string, shell: Shell): string {+ const fetch = shell("git fetch origin main");+ if (!fetch.ok) throw new Error(`git fetch failed: ${fetch.output}`);++ const target = join(mkdtempSync(join(tmpdir(), "crbn-")), "target");+ const r = shell(+ `CRBN_NEW_TARGET=${sq(target)} crbn new loop/${id} --base origin/main --yes`+ );+ if (!r.ok) throw new Error(`crbn new failed: ${r.output}`);+ try {+ return readFileSync(target, "utf8").trim();+ } catch {+ throw new Error(`crbn new did not write a worktree path: ${r.output}`);+ }+}++/**+ * Remove the local worktree after the PR is pushed. Uses raw git (not the+ * interactive `crbn remove`); the remote branch stays alive for the open PR.+ */+export function removeWorktree(path: string, shell: Shell): void {+ shell(`git worktree remove --force ${sq(path)}`);+}diff --git a/packages/harness/src/scripts/run-gates.ts b/packages/harness/src/scripts/run-gates.tsnew file mode 100644index 0000000000..9e4359fbd3--- /dev/null+++ b/packages/harness/src/scripts/run-gates.ts@@ -0,0 +1,20 @@+import { execSync } from "node:child_process";+import { FLOOR_GATES, runGates } from "../gates";++const results = runGates(FLOOR_GATES, (cmd) => {+ try {+ return { ok: true, output: execSync(cmd, { encoding: "utf8" }) };+ } catch (e) {+ const err = e as { stdout?: string; stderr?: string };+ return { ok: false, output: `${err.stdout ?? ""}${err.stderr ?? ""}` };+ }+});+let failed = 0;+for (const r of results) {+ console.log(`${r.passed ? "PASS" : "FAIL"} ${r.id}`);+ if (!r.passed) failed++;+}+console.log(+ `\n${results.length - failed}/${results.length} floor gates green.`+);+process.exit(failed > 0 ? 1 : 0);diff --git a/packages/harness/src/scripts/run-loop.ts b/packages/harness/src/scripts/run-loop.tsnew file mode 100644index 0000000000..1581d94fae--- /dev/null+++ b/packages/harness/src/scripts/run-loop.ts@@ -0,0 +1,63 @@+import { appendFileSync, mkdirSync, readFileSync } from "node:fs";+import { dirname, resolve } from "node:path";+import { parseBinding } from "../binding";+import { behaviorGate } from "../runner/behavior";+import { claude } from "../runner/claude";+import { runLoop } from "../runner/loop";+import { openPr } from "../runner/pr";+import { shell } from "../runner/shell";+import { DEFAULT_CONFIG, type RunnerConfig } from "../runner/types";++// Usage: tsx src/scripts/run-loop.ts <binding.loop.md> [--cwd <worktree>] [--no-pr]+//+// Milestone 1: run inside a worktree you already created (`crbn new` + `crbn up`)+// and pass it via --cwd. Drives one binding to a gated PR, fully unattended.+const argv = process.argv.slice(2);+const bindingPath = argv.find((a) => !a.startsWith("--"));+if (!bindingPath) {+ console.error(+ "usage: run-loop <binding.loop.md> [--cwd <worktree>] [--no-pr]"+ );+ process.exit(2);+}++const cwdIdx = argv.indexOf("--cwd");+const cwdArg = cwdIdx >= 0 ? argv[cwdIdx + 1] : undefined;+const cwd = resolve(+ cwdArg && !cwdArg.startsWith("--") ? cwdArg : process.cwd()+);+const noPr = argv.includes("--no-pr");++const binding = parseBinding(readFileSync(resolve(bindingPath), "utf8"));+const ledgerPath = resolve(cwd, `llm/loops/${binding.id}/ledger.jsonl`);+const logPath = resolve(cwd, `llm/loops/${binding.id}/run.log.jsonl`);+mkdirSync(dirname(logPath), { recursive: true });++const log = (event: Record<string, unknown>) => {+ const line = JSON.stringify({ at: new Date().toISOString(), ...event });+ console.log(line);+ try {+ appendFileSync(logPath, `${line}\n`);+ } catch {+ /* logging is best-effort */+ }+};++const config: RunnerConfig = { ...DEFAULT_CONFIG, cwd, ledgerPath };++const outcome = runLoop(binding, config, {+ claude,+ shell,+ now: () => new Date().toISOString(),+ log,+ behaviorGate+});+log({ event: "outcome", ...outcome });++if (outcome.state === "shipped" && !noPr) {+ const url = openPr(binding, ledgerPath, shell, cwd);+ log({ event: "pr", url });+ console.log(`\nPR: ${url}`);+}++process.exit(outcome.state === "shipped" ? 0 : 1);diff --git a/packages/harness/src/smoke.test.ts b/packages/harness/src/smoke.test.tsnew file mode 100644index 0000000000..431f718f76--- /dev/null+++ b/packages/harness/src/smoke.test.ts@@ -0,0 +1,7 @@+import { describe, expect, it } from "vitest";++describe("@carbon/harness", () => {+ it("runs", () => {+ expect(true).toBe(true);+ });+});diff --git a/packages/harness/tsconfig.json b/packages/harness/tsconfig.jsonnew file mode 100644index 0000000000..8cee9135d1--- /dev/null+++ b/packages/harness/tsconfig.json@@ -0,0 +1,5 @@+{+ "extends": "@carbon/config/tsconfig/react-library.json",+ "include": ["src"],+ "exclude": ["dist", "build", "node_modules"]+}diff --git a/packages/harness/vitest.config.ts b/packages/harness/vitest.config.tsnew file mode 100644index 0000000000..9a3c27eaed--- /dev/null+++ b/packages/harness/vitest.config.ts@@ -0,0 +1 @@+export { default } from "@carbon/config/vitest";diff --git a/pnpm-lock.yaml b/pnpm-lock.yamlindex 6e17a61f0b..97ce0f7acd 100644--- a/pnpm-lock.yaml+++ b/pnpm-lock.yaml@@ -1799,6 +1799,33 @@ importers:specifier: 'catalog:'version: 4.1.6(@opentelemetry/[email protected])(@types/[email protected])([email protected](@types/[email protected])([email protected])([email protected])([email protected])([email protected]))+ packages/checks:+ devDependencies:+ '@carbon/config':+ specifier: workspace:*+ version: link:../config+ '@types/node':+ specifier: ^22+ version: 22.19.7+ '@types/pg':+ specifier: 8.15.6+ version: 8.15.6+ pg:+ specifier: 8.20.0+ version: 8.20.0+ rimraf:+ specifier: 'catalog:'+ version: 5.0.10+ tsx:+ specifier: 'catalog:'+ version: 4.21.0+ typescript:+ specifier: 'catalog:'+ version: 5.8.3+ vitest:+ specifier: 'catalog:'+ version: 4.1.6(@opentelemetry/[email protected])(@types/[email protected])([email protected](@types/[email protected])([email protected])([email protected])([email protected])([email protected]))+packages/config:dependencies:'@tailwindcss/typography':@@ -2308,6 +2335,27 @@ importers:specifier: 'catalog:'version: 4.1.6(@opentelemetry/[email protected])(@types/[email protected])([email protected](@types/[email protected])([email protected])([email protected])([email protected])([email protected]))+ packages/harness:+ devDependencies:+ '@carbon/config':+ specifier: workspace:*+ version: link:../config+ '@types/node':+ specifier: ^22+ version: 22.19.7+ rimraf:+ specifier: 'catalog:'+ version: 5.0.10+ tsx:+ specifier: 'catalog:'+ version: 4.21.0+ typescript:+ specifier: 'catalog:'+ version: 5.8.3+ vitest:+ specifier: 'catalog:'+ version: 4.1.6(@opentelemetry/[email protected])(@types/[email protected])([email protected](@types/[email protected])([email protected])([email protected])([email protected])([email protected]))+packages/jobs:dependencies:'@ai-sdk/openai':