Skip to content

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.

docs: skills rewrite (#1014)

Brad Barbineda69a86cb34
diff --git a/.ai/runs/2026-07-02-skills-rewrite.md b/.ai/runs/2026-07-02-skills-rewrite.md
new file mode 100644
index 0000000000..f55ffb4541
--- /dev/null
+++ b/.ai/runs/2026-07-02-skills-rewrite.md
@@ -0,0 +1,101 @@
+# Skills rewrite — optimize for productivity and quality of execution
+
+Branch: `skills-rewrite` (off origin/main). Complete rewrite of `.ai/skills/`.
+
+Design principle: **write every skill for the weakest plausible executor.** Exact
+commands with expected output, one canonical path per task, decision tables with
+defaults, explicit STOP rules, verifiable done-criteria. No reliance on the reader
+inferring intent.
+
+## Defects being fixed
+
+- [x] 5 skills have HTML comments ABOVE the YAML frontmatter (spec-writing,
+ root-cause, fix, check-and-commit, create-agents-md) — breaks description
+ parsing; the comment leaks into the trigger description.
+- [x] `plan` + `execute` reference skills that don't exist (`/forms`,
+ `/database-transactions`, `/verify`); `packages/form/AGENTS.md` references
+ non-existent `.ai/skills/forms/SKILL.md`.
+- [x] Competing artifact conventions: brainstorm→`.ai/research/*-design.md` vs
+ spec-writing→`.ai/specs/{date}-{slug}.md`; plan→`.ai/plans/` vs
+ AGENTS.md→`.ai/runs/`; execute tracker→`.ai/scratch/tasks/todo.md`.
+- [x] `fix`/`check-and-commit`/`execute` prescribe whole-repo `pnpm run typecheck`
+ (OOMs the machine per improve skill + conductor + user experience).
+- [x] `check-and-commit` uses `git add -A` and unconditional push.
+- [x] `plan`'s own SQL example violates repo conventions (gen_random_uuid, no
+ companyId).
+- [x] Three overlapping debugging skills with contradictory instructions
+ (root-cause read-only vs systematic-debugging vs debugging-difficult-bugs).
+- [x] `error` saves screenshots to `docs/e2e/` (NOT gitignored; pollutes the docs
+ app) — move to `.ai/scratch/e2e/` (gitignored).
+- [x] `conductor` references legacy `llm/loops/README.md` (gitignored/absent) and
+ carries a stale "loop system not yet on main" caveat.
+- [x] `improve` references `.ai/recommendations/` (doesn't exist).
+- [x] `smoke-test` has a trailing-space typo in `/x/people/employee ` route.
+
+## Canonical conventions (baked into every skill)
+
+- Research → `.ai/research/{slug}.md`; specs → `.ai/specs/{YYYY-MM-DD}-{slug}.md`
+ (lifecycle per `.ai/specs/AGENTS.md`); implementation plans + progress →
+ `.ai/plans/{YYYY-MM-DD}-{slug}.md` (per Brad's 2026-07-02 correction; run logs
+ stay in `.ai/runs/`); playbooks → `.ai/playbooks/{slug}.md`;
+ improve handoff plans → `.ai/plans/improve/`; e2e failure captures →
+ `.ai/scratch/e2e/`.
+- Typecheck is ALWAYS scoped: `pnpm exec turbo run typecheck --filter=<pkg>`.
+ Never `pnpm typecheck` / `pnpm run typecheck` (whole-repo; OOMs).
+- Migrations: `pnpm run generate:types` BEFORE typechecking.
+- Format/lint fix: `pnpm exec biome check --write <paths>`.
+- Commit: stage specific paths (never `git add -A`); conventional message; push
+ only if the branch tracks a remote or the user asked.
+
+## Work items
+
+- [x] Survey all 27 skills + wiring + cross-references (2 Explore agents + direct reads)
+- [x] Rewrite core feature chain: research, spec-writing (absorbs brainstorm),
+ plan, execute, feature
+- [x] Rewrite bug chain: root-cause (absorbs systematic-debugging),
+ debugging-difficult-bugs, fix
+- [x] Rewrite gates: check-and-commit, self-review, conductor
+- [x] Rewrite browser chain: login, error, smoke-test, test
+- [x] Rewrite meta: create-agents-md, writing-skills, test-driven-development
+- [x] Light edits: improve (broken refs incl. references/*), carbon-docs (scratch ref)
+- [x] Leave unchanged: pr-explainer, pr-splitter (already correct + imperative),
+ ui (remote-managed shim), agent-browser + make-interfaces-feel-better
+ (external, pinned in skills-lock.json)
+- [x] Delete: brainstorm (merged into spec-writing), systematic-debugging (merged
+ into root-cause; useful references moved to root-cause/references/); also
+ removed writing-skills' imported meta-files (persuasion-principles,
+ graphviz/render-graphs, subagent-testing doc, 1150-line best-practices)
+- [x] New: .ai/skills/README.md index
+- [x] Update: AGENTS.md Workflows router rows + scoped-typecheck line;
+ packages/form/AGENTS.md stale ref; install-skills.sh frontmatter guard
+- [x] Verify: installer runs clean with guard (25 skills linked), every SKILL.md
+ has line-1 frontmatter + dir-matching name + description, no references to
+ deleted/phantom skills or missing files remain
+- [x] Commit on skills-rewrite branch
+
+## Wave 2 — treat ALL inherited content as suspect; harden for weak executors
+
+- [x] Fact-checked inherited claims: smoke-test module routes verified against
+ `path.ts` + `routes/x+` (all real); /login greeting verified
+ (`apps/erp/app/components/Greeting.tsx`); moved reference files carry no
+ stale `superpowers:` refs
+- [x] Fixed nested-fence rendering bug in plan + create-agents-md templates
+ (```` outer fences); added fence-balance check to the verification sweep
+- [x] Added "Announce at start" to every workflow skill (building blocks,
+ externals, and reference skills intentionally excluded)
+- [x] Added red-flag rationalization lists at the discipline pressure points:
+ spec-writing (self-resolving the gate), plan (under-specified tasks),
+ execute (improvising), fix (test-after / scope creep), check-and-commit
+ (gate weakening, "probably pre-existing" now requires proof), root-cause
+ (fix-before-cause)
+- [x] check-and-commit: mechanical changed-files→package-names snippet (weak
+ models fumble the --filter mapping)
+- [x] pr-splitter: full rewrite — non-interactive extraction recipes (the old
+ skill prescribed `git restore -p`, which hangs in agent harnesses),
+ merge-base detection, scratchpad moved to gitignored .ai/scratch/
+- [x] pr-explainer: full rewrite around a bundled assets/template.html
+ (styled, self-contained, `<!-- FILL -->` markers) — filling a template
+ beats inventing 200 lines of HTML
+- [x] writing-skills: new authoring rules 8–10 (announce, non-interactive only,
+ bundle assets for generative output), four-backtick fence trap, and
+ "re-verify inherited claims" added to rule 6
diff --git a/.ai/scripts/install-skills.sh b/.ai/scripts/install-skills.sh
index 2eea92062d..821a6e9258 100755
--- a/.ai/scripts/install-skills.sh
+++ b/.ai/scripts/install-skills.sh
@@ -84,6 +84,18 @@ link_skills() {
name=$(basename "$skill_dir")
[ -f "$skill_dir/SKILL.md" ] || continue
+ # Guard: frontmatter must start on line 1 and its name must match the dir.
+ # (A comment above the frontmatter breaks description parsing in harnesses.)
+ if [ "$(head -n 1 "$skill_dir/SKILL.md")" != "---" ]; then
+ echo " ⚠ $name: SKILL.md does not start with '---' frontmatter on line 1" >&2
+ else
+ local fm_name
+ fm_name=$(sed -n '2,10s/^name:[[:space:]]*//p' "$skill_dir/SKILL.md" | head -n 1)
+ if [ -n "$fm_name" ] && [ "$fm_name" != "$name" ]; then
+ echo " ⚠ $name: frontmatter name '$fm_name' does not match directory name" >&2
+ fi
+ fi
+
ln -sfn "$rel_prefix/$name" "$harness_dir/$name"
count=$((count + 1))
done
diff --git a/.ai/skills/README.md b/.ai/skills/README.md
new file mode 100644
index 0000000000..d786721514
--- /dev/null
+++ b/.ai/skills/README.md
@@ -0,0 +1,71 @@
+# Carbon skills — index
+
+Source of truth for agent skills. Installed as symlinks into `.claude/skills/`
+and `.codex/skills/` by `.ai/scripts/install-skills.sh` (runs on `pnpm prepare`;
+manually: `pnpm install-skills`). Authoring rules: `writing-skills/SKILL.md`.
+
+## Pipelines
+
+**Feature** (phased, human gates at spec + plan):
+
+```
+/research → /spec-writing → /plan → /execute → /test → /self-review
+ 🛑 open questions 🛑 plan approval
+```
+
+`/feature` runs this pipeline end-to-end. `/execute` commits per task via
+`/check-and-commit`.
+
+**Bug fix**:
+
+```
+/root-cause → (/debugging-difficult-bugs if runtime evidence needed) → /fix → /check-and-commit
+```
+
+**Supervised loop** (single scoped item, doer→gate→judge): `/conductor`.
+
+**Advisory audit** (read-only, produces handoff plans): `/improve`.
+
+## Skills
+
+| Skill | Purpose | Produces |
+|-------|---------|----------|
+| `research` | Competitor/industry survey for a feature | `.ai/research/{slug}.md` |
+| `spec-writing` | Design + spec with Open Questions hard stop | `.ai/specs/{date}-{slug}.md` |
+| `plan` | Implementation plan from a finalized spec | `.ai/plans/{date}-{slug}.md` |
+| `execute` | Run an approved plan task by task | commits on the branch |
+| `feature` | The full pipeline above, orchestrated | all of the above |
+| `root-cause` | Read-only bug analysis → brief | root-cause brief (chat) |
+| `debugging-difficult-bugs` | Temporary JSONL runtime instrumentation | log-backed root cause |
+| `fix` | Minimal fix from a brief + red→green regression test | ready-to-commit change |
+| `check-and-commit` | Gate suite, then commit specific files | conventional commit |
+| `self-review` | Review your own branch before/at PR time | Must fix / Risks / Suggestions |
+| `conductor` | Supervised doer→gate→judge loop to a gated PR | PR + ledger |
+| `improve` | Senior-advisor audit; plans for other agents to execute | `.ai/plans/improve/` |
+| `test` | Drive changed flows in the browser; cache playbooks | pass/fail + `.ai/playbooks/{slug}.md` |
+| `smoke-test` | Do all core modules load? | pass/fail table |
+| `login` | Authenticate agent-browser against local dev | authed session (building block) |
+| `error` | Capture screenshot + snapshot on browser failure | `.ai/scratch/e2e/…` (building block) |
+| `create-agents-md` | Generate/refresh a grounded AGENTS.md | `AGENTS.md` |
+| `carbon-docs` | Author reader-facing docs in the docs app | `docs/content/**` |
+| `test-driven-development` | Red→green→refactor discipline (vitest) | tests-first code |
+| `writing-skills` | House guide for authoring skills | skills |
+| `pr-explainer` | Self-contained HTML review aid for a PR | `.pr-review/*.html` |
+| `pr-splitter` | Split a large PR into reviewable stacked PRs | branches + split notes |
+| `ui` | Remote-managed UI exploration shim (uidotsh) | — |
+| `agent-browser` | External: browser CLI reference (pinned in `skills-lock.json`) | — |
+| `make-interfaces-feel-better` | External: UI polish principles (pinned in `skills-lock.json`) | — |
+
+## Conventions every skill follows
+
+- Workflow skills announce themselves at start ("Using the {name} skill — …")
+ so the human always knows which playbook is running.
+- Typecheck is always scoped: `pnpm exec turbo run typecheck --filter=<pkg>`.
+ Whole-repo typecheck OOMs — no skill may prescribe it.
+- `pnpm run generate:types` after any migration, before typechecking.
+- Commits only through `/check-and-commit` (explicit file staging, conventional
+ messages); push only when the branch tracks a remote or the user asked.
+- Ephemeral output (screenshots, debug logs) goes to gitignored `.ai/scratch/`,
+ never into tracked trees.
+- `agent-browser` + `make-interfaces-feel-better` are external skills pinned in
+ `skills-lock.json` — update them via their upstream, don't edit in place.
diff --git a/.ai/skills/brainstorm/SKILL.md b/.ai/skills/brainstorm/SKILL.md
deleted file mode 100644
index b83cb906e7..0000000000
--- a/.ai/skills/brainstorm/SKILL.md
+++ /dev/null
@@ -1,171 +0,0 @@
----
-name: brainstorm
-description: Research-driven brainstorming and design for a feature. Use when designing a new feature, exploring approaches, or making design decisions. Automatically researches competitors before asking design questions, then hands off to /plan for implementation. Triggers on "brainstorm", "design", "design a feature", "plan a feature", "how should we build X", or any request to explore approaches for a feature.
----
-
-# Brainstorm: Research-Driven Design
-
-Transform feature ideas into well-researched designs. Unlike traditional brainstorming that asks endless questions, this skill **researches competitors first** so design decisions are informed by industry patterns.
-
-**Announce at start:** "I'm using the brainstorm skill to design this with research."
-
-## The Problem This Solves
-
-Traditional brainstorming:
-```
-Claude: "How should we handle partial shipments?"
-User: "Good question, how does SAP do it?"
-Claude: [researches]
-Claude: "What about backorders?"
-User: "How does NetSuite handle that?"
-Claude: [researches again]
-... repeat 10 times ...
-```
-
-This skill front-loads that research.
-
-## Workflow
-
-```
-┌──────────────┐ ┌──────────────┐ ┌──────────────┐ ┌──────────────┐
-│ 1. Scope │───▶│ 2. Research │───▶│ 3. Design │───▶│ 4. Document │
-│ Feature │ │ Competitors │ │ With Data │ │ & Approve │
-└──────────────┘ └──────────────┘ └──────────────┘ └──────────────┘
-```
-
-## Step 1: Scope the Feature
-
-### 1.1 Understand the Request
-
-Ask focused questions (max 3-4) to understand:
-- **What** — The core capability
-- **Why** — The problem it solves
-- **Where** — Which part of Carbon (ERP, MES, Academy)
-- **Who** — Primary users
-
-### 1.2 Classify the Domain
-
-Map to research domains:
-
-| Domain | Keywords | Competitors |
-|--------|----------|-------------|
-| Accounting | GL, AP, AR, invoicing, payments | SAP, NetSuite |
-| Manufacturing | Jobs, work orders, BOMs, routing | SAP, Epicor |
-| MES | Real-time tracking, scheduling, dispatch | SAP, Manufacturo, First Resonance |
-| CNC/Sheet Metal | Quoting, estimating, nesting | SAP, Fulcrum, Paperless Parts |
-| Quality | Inspection, SPC, FAI, GD&T | SAP, 1factory, HighQA |
-| Inventory | Valuation, lots, warehousing | SAP, NetSuite, Fishbowl |
-| Sales | Quotes, orders, pricing | SAP, NetSuite |
-| Purchasing | POs, suppliers, receiving | SAP, NetSuite, Coupa |
-
-### 1.3 Identify Research Questions
-
-Before researching, list the key design questions:
-
-```markdown
-## Research Questions for [Feature]
-1. [Data model question]
-2. [Workflow question]
-3. [Edge case question]
-4. [Integration question]
-```
-
-## Step 2: Research Competitors
-
-### 2.1 Execute Research
-
-Invoke `/research [feature]` targeting the identified questions.
-
-Search patterns per competitor:
-- `[Competitor] [feature] documentation`
-- `[Competitor] [feature] workflow`
-- `[Competitor] [feature] best practices`
-
-### 2.2 Synthesize
-
-Structure findings as:
-1. **Key Consensus** — What all competitors agree on
-2. **Unique Approaches** — Interesting variations
-3. **Answers to Questions** — Direct answers from Step 1.3
-
-Save to `.ai/research/[feature-slug].md`.
-
-## Step 3: Design With Data
-
-Now brainstorm **with research in hand**.
-
-### 3.1 For Each Design Decision
-
-1. **State the question**
-2. **Reference the research** — "SAP and NetSuite both..."
-3. **Propose 2-3 approaches** with trade-offs
-4. **Recommend one** based on industry patterns
-
-### 3.2 Cover These Areas
-
-- **Data Model** — Tables, relationships, key fields
-- **Workflows** — User journeys, state transitions
-- **Edge Cases** — How competitors handle the tricky stuff
-- **Integration** — How this connects to existing Carbon features
-
-## Step 4: Document & Approve
-
-### 4.1 Write Design Spec
-
-Save to `.ai/research/[feature-name]-design.md`:
-
-```markdown
-# [Feature] Design Specification
-
-## Summary
-[One paragraph]
-
-## Research Summary
-[Key findings, link to full research]
-
-## Design Decisions
-
-### [Decision 1]
-**Question:** [The design question]
-**Industry Pattern:** [What competitors do]
-**Our Approach:** [What we'll do and why]
-
-## Data Model
-[Schema]
-
-## Workflows
-[User journeys]
-
-## Edge Cases
-[Tricky stuff, informed by competitors]
-```
-
-### 4.2 Self-Review
-
-Before presenting to user:
-- [ ] No placeholders or TBDs
-- [ ] All research questions answered
-- [ ] Data model complete
-- [ ] Edge cases addressed
-
-### 4.3 Get Approval
-
-Present the spec and wait for explicit approval before proceeding.
-
-## Output
-
-| Artifact | Location |
-|----------|----------|
-| Competitor research | `.ai/research/[feature-slug].md` |
-| Design specification | `.ai/research/[feature-name]-design.md` |
-
-## Next Step
-
-After approval, hand off to `/plan` to create the implementation plan.
-
-## When to Stop and Ask
-
-- Feature is more complex than expected
-- Decisions require business input (not just technical)
-- Research reveals conflicting patterns with no clear winner
-- Uncertain about something that affects other Carbon modules
diff --git a/.ai/skills/carbon-docs/SKILL.md b/.ai/skills/carbon-docs/SKILL.md
index c7daa23723..64b4b331e4 100644
--- a/.ai/skills/carbon-docs/SKILL.md
+++ b/.ai/skills/carbon-docs/SKILL.md
@@ -16,6 +16,8 @@ description: >-
warm-paper aesthetic. It is no longer scaffolded; it exists and ships content. This skill is how to add
or change docs **in that system, in its house style, grounded in real Carbon code.**
+**Announce at start:** "Using the carbon-docs skill — authoring docs for {topic}."
+
> The single biggest mistake is writing plausible ERP-generic prose. Carbon's behavior is specific and
> often counterintuitive (WIP is a GL balance not a table; payment is a field not an entity; overhead is
> not absorbed; fixed-asset disposal is scrapping-only). **Every claim is grounded in source.** See the
@@ -300,4 +302,4 @@ Never declare docs done without: the new content rendering (in the user's runnin
`pnpm --filter docs build`), every internal link resolving, any new `<Term>` glossary entries grounded in
source + their popovers rendering, names matching real code, **no generic repeated
headings**, and a re-read that confirms each page says what matters / names the mistake / points onward. Then
-record progress (`.ai/scratch/tasks/` + memory). **Don't kill or rebuild under the user's running dev server.**
+record progress (the `.ai/plans/` plan file if one exists, + memory). **Don't kill or rebuild under the user's running dev server.**
diff --git a/.ai/skills/check-and-commit/SKILL.md b/.ai/skills/check-and-commit/SKILL.md
index 95ed3d6b49..358ecae3ad 100644
--- a/.ai/skills/check-and-commit/SKILL.md
+++ b/.ai/skills/check-and-commit/SKILL.md
@@ -1,129 +1,121 @@
-<!-- Workflow pattern inspired by Open Mercato (MIT License)
- https://github.com/open-mercato/open-mercato
- Copyright (c) 2025-2026 Open Mercato contributors -->
-
---
name: check-and-commit
-description: Pre-commit verification gate. Runs Carbon's validation suite in order, fixes straightforward failures, and commits+pushes only when all gates pass. Use after /fix or manual changes.
+description: Pre-commit verification gate — runs Carbon's validation gates in order (generate:types if schema changed, biome, scoped typecheck, scoped tests, build if needed), fixes straightforward failures, then commits the specific files with a conventional message. Use after /fix, after an /execute task, or after manual changes when the work should be committed. Commits only when every gate is green; pushes only if the branch already tracks a remote or the user asked.
---
+<!-- Workflow pattern inspired by Open Mercato (MIT License)
+ https://github.com/open-mercato/open-mercato
+ Copyright (c) 2025-2026 Open Mercato contributors -->
-# check-and-commit — pre-commit verification gate
+# check-and-commit — verification gate, then commit
-Run all validation gates, fix what's auto-fixable, and commit only when everything is green.
+Run the gates in order, fix what's mechanically fixable, and commit only when
+everything is green. This skill is the only place in the workflow that commits.
-**Announce at start:** "I'm using the check-and-commit skill to verify and commit."
+**Announce at start:** "Using the check-and-commit skill — running the gates,
+then committing."
-## 1. Detect schema changes
+## Step 1: Identify what changed
```bash
-git diff --cached --name-only -- 'packages/database/supabase/migrations/' | head -1
+git status --porcelain
+git diff --name-only
```
-If any migration files are staged or modified, set `SCHEMA_CHANGED=true`.
-
-## 2. Run gates in order
+From the changed paths, derive:
-Run each gate sequentially. Stop on failure, fix if straightforward, re-run.
+- `SCHEMA_CHANGED` — any file under `packages/database/supabase/migrations/`
+- the set of **touched packages** — run this to map changed files to workspace
+ package names (these are the `--filter` values for the gates):
-### Gate 1: Generate types (if schema changed)
+ ```bash
+ git diff --name-only HEAD | while read -r f; do
+ d=$(dirname "$f")
+ while [ "$d" != "." ] && [ ! -f "$d/package.json" ]; do d=$(dirname "$d"); done
+ [ -f "$d/package.json" ] && sed -n 's/.*"name": *"\([^"]*\)".*/\1/p' "$d/package.json" | head -1
+ done | sort -u
+ ```
-```bash
-# Only if SCHEMA_CHANGED
-pnpm run generate:types
-```
-
-If types changed, stage them: `git add packages/database/src/`.
-
-### Gate 2: Lint
-
-```bash
-pnpm run lint
-```
+- whether any file is **outside** the intended change (leftover debug file,
+ unrelated edit). If yes → exclude it from staging and mention it in the report.
-**Auto-fixable?** Run `pnpm run lint --fix`, stage fixed files, re-run lint to confirm.
+## Step 2: Run the gates in order
-### Gate 3: Typecheck
+Stop on failure, apply the fix policy (Step 3), re-run the failed gate.
```bash
-pnpm run typecheck
-```
+# Gate 1 — types (only if SCHEMA_CHANGED)
+pnpm run generate:types
+# then include the regenerated files in the commit
-**Stale types?** If errors reference missing columns/types from a new migration and Gate 1 was skipped, run `pnpm run generate:types` now, then re-run typecheck.
+# Gate 2 — format + lint (auto-fixes in place)
+pnpm exec biome check --write --no-errors-on-unmatched <changed paths>
-**Other type errors from your changes?** Fix them directly, re-run.
+# Gate 3 — typecheck, one package at a time. NEVER whole-repo (`pnpm typecheck`
+# runs every package at once and OOMs the machine).
+pnpm exec turbo run typecheck --filter=<pkg> # repeat per touched package
-### Gate 4: Test
+# Gate 4 — tests per touched package
+pnpm --filter <pkg> test
-```bash
-pnpm run test
+# Gate 5 — build, ONLY if the change affects build outputs
+# (package exports, config files, SST infra)
+pnpm exec turbo run build --filter=<pkg>
```
-**Failures from your changes?** Fix the code or test, re-run.
+## Step 3: Fix policy
-**Pre-existing failures?** Note them in the report but don't block the commit.
+| Failure | Action |
+|---------|--------|
+| Biome formatting/import order | Already fixed by `--write`; re-run to confirm clean |
+| Type error from stale generated types | Run Gate 1, re-run typecheck |
+| Type/test error caused by this change | Fix the code, re-run |
+| Pre-existing failure, unrelated to this change | Note in report; don't block, don't fix |
+| Anything unclear or still failing after **2** fix attempts | STOP — report BLOCKED |
-### Gate 5: Build (if needed)
-
-Only run if the change affects build outputs (package exports, config, SST):
-
-```bash
-pnpm run build
-```
+"Pre-existing" must be proven, not assumed: the failing file/test is untouched
+by this diff, or the same failure reproduces on the merge-base. If you can't
+show one of those, treat it as caused by this change.
-## 3. Fix policy
+Red flags — thinking any of these means the gate is being weakened; STOP:
-| Failure type | Action |
-|-------------|--------|
-| Lint auto-fixable (formatting, import order) | Fix automatically, re-run |
-| Type error from stale generated types | Run `generate:types`, re-run |
-| Type error from your change | Fix the code, re-run |
-| Test failure from your change | Fix the code or test, re-run |
-| Pre-existing / unrelated failure | Note in report, don't block |
-| Build failure from your change | Fix, re-run |
-| Unclear or complex failure | **Stop. Report as blocked.** |
+- "I'll run the gates once at the end instead of in order"
+- "`git add -A` is faster"
+- "that failure is probably pre-existing" (prove it — see above)
+- "the gate is flaky, I'll just retry until it passes"
-**Limit: 2 fix-and-retry cycles per gate.** If a gate still fails after 2 attempts, stop and report as blocked.
+## Step 4: Commit
-## 4. Commit and push
-
-Only when **all gates pass**:
+Only when all applicable gates pass:
```bash
-git add -A
+git add <each changed file, listed explicitly> # NEVER `git add -A` or `git add .`
git commit -m "<type>(<scope>): <description>"
-git push
```
-Use conventional commits: `fix`, `feat`, `chore`, `refactor`, `test`, `docs`.
+- Types: `fix`, `feat`, `chore`, `refactor`, `test`, `docs`. Scope = module or
+ package (`fix(inventory): …`).
+- Staging is explicit because worktrees accumulate runtime files (env files,
+ screenshots, `.jsonl` debug logs) that must never be committed.
+- **Push only if** the branch already tracks a remote (`git rev-parse
+ --abbrev-ref @{upstream}` succeeds) **or** the user asked to push. Otherwise
+ leave the commit local and say so.
-## 5. Report
+## Step 5: Report
```markdown
## Check & Commit Report
-
**Result:** COMMITTED | BLOCKED
-**Gates:**
| Gate | Result | Notes |
|------|--------|-------|
-| generate:types | PASS / SKIP | <if run, note what changed> |
-| lint | PASS | <if auto-fixed, list files> |
-| typecheck | PASS | |
-| test | PASS | <note any pre-existing failures> |
+| generate:types | PASS / SKIP | |
+| biome | PASS | <files auto-fixed> |
+| typecheck (<pkgs>) | PASS | |
+| test (<pkgs>) | PASS | <pre-existing failures noted> |
| build | PASS / SKIP | |
-**Auto-fixed:** <list files fixed during gate runs, or "none">
-
-**Commit:** `<sha>` — `<commit message>`
-**Branch:** `<branch-name>`
+**Commit:** `<sha>` — `<message>` · **Pushed:** yes/no
+**Excluded from staging:** <files left uncommitted and why, or "none">
```
-If blocked:
-
-```markdown
-**Result:** BLOCKED
-
-**Blocking gate:** <gate name>
-**Error:** <concise error summary>
-**Attempts:** <what was tried>
-```
+If BLOCKED: name the gate, the concise error, and what was attempted.
diff --git a/.ai/skills/conductor/SKILL.md b/.ai/skills/conductor/SKILL.md
index 401231099b..5bb319d161 100644
--- a/.ai/skills/conductor/SKILL.md
+++ b/.ai/skills/conductor/SKILL.md
@@ -1,104 +1,167 @@
---
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.
+description: Supervised loop conductor — drive a single work item (a bug, a usability tweak, a small feature) through a doer→gate→judge→keep-or-revert→ledger cycle to a gated PR, while the human watches. Use when asked to "conduct", "loop on", or build/fix one tightly-scoped item with explicit acceptance criteria. Backed by @carbon/harness and the @carbon/checks gates. Supervised only — never autonomous/overnight, never auto-merged. For multi-phase features prefer /feature.
---
-# 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, read it. Otherwise write one from the request (see `llm/loops/README.md` for the format) and save it to `llm/loops/runs/<id>/binding.loop.md` (run-loop also persists the binding there automatically).
-- 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** — before running any gate, auto-format with `biome check --write --no-errors-on-unmatched` and stage the fixes (this is the `check-and-commit` skill's Gate 2 applied in-loop — every commit must be biome-clean). Then run `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 change that affects user-facing behavior.** Choose the **simplest sufficient proof** from this hierarchy:
- 1. **Unit / integration test (red→green)** — Write a test that fails on the old behavior and passes on the new. **Preferred when applicable:** logic changes, data transformations, component rendering, conditional visibility, service behavior, and anything testable without a running stack. Fast, deterministic, CI-portable, and it lives in the repo as a regression guard.
- 2. **Agent-browser visual verification** — Boot the app (`crbn up`), `/login`, drive the affected screen with `agent-browser`: reproduce the exact failing condition, capture a **BEFORE screenshot**, confirm the fix, capture an **AFTER screenshot**. **Required when the proof is inherently visual** — layout, spacing, overflow, responsive behavior, animation, or anything where seeing the pixels is the only meaningful assertion.
- 3. **CLI / script proof** — For non-UI changes (migrations, CLI tools, API endpoints), a command that demonstrates the correct output before and after.
- - **The principle: take the simplest possible path to provability.** If a unit test proves it, use a unit test. If it genuinely requires seeing pixels, use agent-browser. Never choose a heavier method when a lighter one gives the same confidence.
- - **At least one proof method must pass.** A user-facing change without proof is not done — the gate is flexible about *how*, not *whether*.
- - **If visual verification is needed and the stack cannot be brought up, the loop is BLOCKED** — stop and surface to the human. Do NOT open a "done" PR with verification "pending."
- - **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. Do not grade your own homework. The judge does **not** return a holistic "looks good" — a single overall verdict rewards fluent-looking diffs that are subtly wrong. Instead it uses **binary decomposition**:
- - **Decompose each acceptance criterion + applicable design rule into atomic yes/no questions** — one verifiable property per question (e.g. "Does the change handle the 4+-label case the binding names?", "Is the precedent component actually reused, not re-implemented?", "Are audit fields + `companyId` set on every new write?"). Concrete, checkable criteria are what decomposition is *for*.
- - **Answer each question yes/no with a one-line justification grounded in a specific diff hunk or gate artifact** (file:line, screenshot, test name). A "yes" with no citation is a fail.
- - **Enumerate failure modes explicitly** — regressions, missed edge cases, fabricated/placeholder values, broken multi-tenancy — rather than trusting that a coherent-looking diff is correct.
- - **Approve only if every binary question passes.** Any "no" → the judge sends work back, and **the specific failed question becomes the next iteration's weakest-covered target** (§2.1) — so a rejection is directly actionable, not a vague "improve this."
- - **Do not over-decompose inherently holistic criteria.** For genuinely subjective acceptance (does this *feel* polished, is the copy clear), keep the judgment holistic — forcing atomic checks on a tolerant criterion produces a harsher judge that diverges from human taste. Decompose the verifiable; judge the subjective as a whole.
- - Use a **capable model** for the judge — decomposition surfaces failure modes but does not rescue a weak evaluator. Keep the question set tight; do not let it accrete unactionable boilerplate over iterations.
-
-4. **Decide + ledger.** Keep the change iff **every gate is green — including the behavior gate (§2b) with sufficient proof** — AND the judge approves; otherwise revert it. Append one entry to `llm/loops/runs/<id>/ledger.jsonl`:
- `pnpm --filter @carbon/harness exec tsx -e "import {appendLedger} from '@carbon/harness'; appendLedger('llm/loops/runs/<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.
-
-## 2b. Post-build AGENTS.md freshness audit
-After the cycle converges (all acceptance criteria met, gates green), run a
-freshness audit before opening the PR:
-
-1. List every package and module directory the branch touched:
+# conductor — supervised doer→gate→judge loop
+
+Iterate on one work item until its acceptance criteria are met and provable,
+with the human watching and giving final approval. Ship a **gated PR** — never
+merge. Architecture context: `.ai/docs/loop-system.md`; the deterministic
+helpers live in `packages/harness` (see its `AGENTS.md`).
+
+**Announce at start:** "Using the conductor skill — supervised loop on
+{work item}."
+
+## Step 0: Isolated worktree off origin/main — always first
+
+```bash
+git fetch origin main
+crbn new loop/<id> --base origin/main --yes # prints the worktree path
+```
+
+Do all loop work in that worktree, on branch `loop/<id>`. **Never run on
+`main`, and never stack on another feature branch.**
+
+## Step 1: Bind the work item
+
+The binding is a `.loop.md` file with frontmatter `id`, `kind`
+(`bug|feature|usability|copy`), `title`, `risk`, optional `issue`, and an
+`acceptance` list (field reference: `packages/harness/AGENTS.md`). If given a
+binding path, read it; otherwise write one from the request to
+`llm/loops/runs/<id>/binding.loop.md` (gitignored runtime). Validate the shape:
+
+```bash
+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'))))"
+```
+
+**Each acceptance criterion is the definition of done** — you are not finished
+until every one is satisfied and provable.
+
+## Step 2: The cycle (repeat until acceptance met or the human stops)
+
+### 2.1 Doer
+
+Make the **smallest change toward the weakest-covered acceptance criterion**.
+Never batch unrelated changes. Domain rules:
+
+- **UI work**: FIRST find the nearest existing screen/component and copy its
+ layout/components/approach — cite the precedent path. Never design from concepts.
+- **ERP-domain logic** (accounting, RMA, costing, valuation, tax…): FIRST run
+ `/research` — never invent domain logic.
+- **Schema changes**: `pnpm run generate:types` after the migration, BEFORE
+ typechecking (stale types make typecheck a false green).
+- **Module code**: one `{module}.service.ts` + one `{module}.models.ts`.
+
+### 2.2 Gate
+
+Run in order; every applicable gate must be green:
+
+a. **Floor gates** — format first, then the harness gate suite (lint +
+ `@carbon/checks` conformance + clobber detection), then scoped typechecks:
+
+ ```bash
+ pnpm exec biome check --write --no-errors-on-unmatched <changed paths>
+ pnpm --filter @carbon/harness gates
+ pnpm exec turbo run typecheck --filter=<pkg> # per touched package, never whole-repo
+ ```
+
+b. **Behavior gate — mandatory for ANY user-facing change.** Choose the
+ **simplest sufficient proof**:
+
+ 1. **Unit/integration test (red→green)** — preferred whenever the behavior is
+ testable without a running stack: logic, transformations, rendering,
+ conditional visibility, service behavior. Fast, CI-portable, lives on as a
+ regression guard.
+ 2. **Agent-browser visual verification** — required when the proof is
+ inherently visual (layout, spacing, overflow, animation): boot with
+ `crbn up`, `/login`, drive the screen per `/test`, capture BEFORE and
+ AFTER screenshots.
+ 3. **CLI/script proof** — for non-UI changes (migrations, endpoints): a
+ command demonstrating correct output.
+
+ Never pick a heavier method when a lighter one gives the same confidence —
+ but at least one proof must pass. **If visual proof is needed and the stack
+ cannot boot, the loop is BLOCKED** — surface to the human; do not open a
+ "done" PR with verification pending.
+
+c. **Correctness (bug fixes)** — reproduce→fix→same-path: the test (or recorded
+ browser playbook) that failed on the bug must pass after the fix.
+
+Any gate fails → fix it or revert this iteration's change.
+
+### 2.3 Judge — a separate subagent, never yourself
+
+Dispatch a review subagent to check the diff against the acceptance criteria
+and design rules. Do not grade your own homework, and do not accept a holistic
+"looks good":
+
+- **Decompose** each acceptance criterion + applicable design rule into atomic
+ yes/no questions (one verifiable property each: "Is the precedent component
+ actually reused, not re-implemented?", "Are audit fields + `companyId` set on
+ every new write?").
+- Each answer needs a **one-line justification citing a specific diff hunk or
+ artifact** (file:line, test name, screenshot). A "yes" without a citation is a fail.
+- **Enumerate failure modes explicitly** — regressions, missed edge cases,
+ placeholder values, broken multi-tenancy.
+- Approve only if every question passes. Any "no" → that question becomes the
+ next iteration's weakest-covered target.
+- Keep genuinely subjective criteria (copy clarity, polish) holistic — don't
+ force atomic checks onto matters of taste.
+
+### 2.4 Decide + ledger
+
+Keep the change iff **every gate is green (including the behavior proof) AND
+the judge approves**; otherwise revert it. Append one entry per iteration:
+
+```bash
+pnpm --filter @carbon/harness exec tsx -e "import {appendLedger} from '@carbon/harness'; appendLedger('llm/loops/runs/<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`.)
+
+### 2.5 Terminate?
+
+All criteria met and provable → Step 3. No progress across iterations
+(plateau) or the human stops → stop and report honestly.
+
+## Step 3: Post-build freshness audit
+
+Before opening the PR:
+
+1. List touched package/module dirs:
`git diff --name-only origin/main...HEAD | grep -E '^(packages|apps/erp/app/modules)/' | cut -d/ -f1-2 | sort -u`
- (for modules: cut at depth 5 to get `apps/erp/app/modules/{name}`)
-2. For each touched directory that has an AGENTS.md, read the AGENTS.md and
- check whether any concrete references (function names, table names, exports,
- import paths) are stale relative to the code you just wrote.
-3. Fix any stale references in the same branch — small, scoped edits.
-4. If the build revealed a new pitfall or lesson, append it to `.ai/lessons.md`
- using the `Context → Problem → Rule → Applies to` format.
-
-This is the **self-healing loop** — every build is a freshness audit.
-
-## 3. Finish — land a gated PR
-- Run the `check-and-commit` skill on the final branch state before opening the PR: run `biome check --write --no-errors-on-unmatched`, stage any fixes, then the full gate suite (§2a). This is the final format + lint + type pass — ensures the PR goes up biome-clean.
-- Embed the **proof captured by the behavior gate (§2b)** in the PR body:
- - **Unit/integration tests:** name the test file(s) and the red→green assertion(s)
- - **Visual verification:** embed before/after screenshots
- - **CLI/script proof:** include the command and its output
- A PR without proof that the behavior gate passed means the loop wasn't 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 and how** (test name, screenshots, or CLI output),
- - embed **before/after screenshots** for visual changes,
- - 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/runs/` (bindings, ledger, outcome, 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/runs/<id>/screenshots/`, referenced by raw URL) — never committed to the product tree. (`@carbon/harness`'s `openPr` does this hosting automatically.)
-
-## Guardrails (non-negotiable)
-- **A user-facing change is never done without sufficient proof (§2b).** The proof must use the simplest method from the provability hierarchy — unit test when applicable, visual verification when inherently visual, CLI proof for non-UI. If visual verification is needed and 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).
+ (modules: cut to depth 5 for `apps/erp/app/modules/{name}`).
+2. For each with an `AGENTS.md`, fix any reference your changes made stale —
+ small scoped edits in the same branch.
+3. New pitfall discovered? Append it to `.ai/lessons.md`
+ (`Context → Problem → Rule → Applies to`).
+
+## Step 4: Finish — land a gated PR
+
+1. Final pass: run `/check-and-commit` on the branch state (biome + gates), so
+ the PR goes up clean.
+2. Open the PR with `gh pr create` — **never merge**. The body must include:
+ - the design rationale (precedent copied; research cited),
+ - per acceptance criterion: **which gate proves it and how** (test name,
+ before/after screenshots, or CLI output),
+ - a ledger summary (iterations, kept/reverted and why).
+3. Loop artifacts (`llm/loops/runs/<id>/` — binding, ledger, screenshots) are
+ gitignored runtime and never committed to the product tree; the harness's
+ `openPr` hosts screenshots for embedding.
+4. Surface every design decision for the human to approve or improve — design
+ is never shipped silently.
+
+## Guardrails — non-negotiable
+
+- A user-facing change without sufficient proof is never done.
+- Never auto-merge; never run on `main`; never background or fan out — this is
+ the supervised loop.
+- If blocked, say BLOCKED and why. Never report "done, verification pending".
## 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`.
-- Provability hierarchy (unit test → visual → CLI) is **in** v1 (§2b). Richer gates (calibrated judge) and autonomy are deliberately out of v1.
+
+- New floor gate: append `{ id, cmd }` to `FLOOR_GATES` in
+ `packages/harness/src/gates.ts` (ask first — it raises the bar for all builds).
+- New binding field: extend the frontmatter + `parseBinding` in
+ `packages/harness/src/binding.ts`.
diff --git a/.ai/skills/create-agents-md/SKILL.md b/.ai/skills/create-agents-md/SKILL.md
index 04e71fc631..e1d7bb63a8 100644
--- a/.ai/skills/create-agents-md/SKILL.md
+++ b/.ai/skills/create-agents-md/SKILL.md
@@ -1,286 +1,140 @@
-<!-- Workflow pattern inspired by Open Mercato (MIT License)
- https://github.com/open-mercato/open-mercato
- Copyright (c) 2025-2026 Open Mercato contributors -->
---
name: create-agents-md
-description: Create or refresh an AGENTS.md for a Carbon package or ERP module. Reads actual source code, existing AGENTS.md, and .ai/rules/ to produce a prescriptive, grounded document. Use when adding a new module/package or when a build touches code that an existing AGENTS.md references.
+description: Create or refresh an AGENTS.md for a Carbon package or ERP module by reading the actual source code — every claim traced to a real function, table, or export. Use when adding a new module/package, when the conductor's freshness audit or /self-review flags a stale AGENTS.md, or on explicit request. Do not write an AGENTS.md from memory or by copying a sibling's content.
---
+<!-- Workflow pattern inspired by Open Mercato (MIT License)
+ https://github.com/open-mercato/open-mercato
+ Copyright (c) 2025-2026 Open Mercato contributors -->
-# create-agents-md — Generate or Refresh AGENTS.md
-
-Produce a prescriptive AGENTS.md grounded in actual source code. Every claim
-MUST trace to a real function name, table name, import path, or file. Never
-describe what "might" exist — grep and verify.
-
-**Announce at start:** "I'm using the create-agents-md skill to generate/refresh the AGENTS.md."
-
-## When to Use
-
-| Trigger | Action |
-|---------|--------|
-| New package or module directory created | Create AGENTS.md |
-| Conductor post-build freshness audit flags staleness | Refresh AGENTS.md |
-| Explicit request (`/create-agents-md modules/purchasing`) | Create or refresh |
-| Self-review flags missing AGENTS.md | Create AGENTS.md |
-
-## Procedure
+# create-agents-md — generate or refresh an AGENTS.md
-### Step 1: Identify the target
+Produce a prescriptive AGENTS.md grounded in source. Every claim MUST trace to a
+real function name, table name, import path, or file — grep and verify; never
+describe what "might" exist.
-Determine whether the target is a **package** (`packages/{name}/`) or a
-**module** (`apps/erp/app/modules/{name}/`). This decides layout expectations,
-line-length budget, and which conventions apply.
+**Announce at start:** "Using the create-agents-md skill — generating/refreshing
+the AGENTS.md for {target}."
-- **Package:** `≤100 lines`
-- **Module:** `60–100 lines`
+## Step 1: Identify the target
-### Step 2: Read actual source code
+- **Package**: `packages/{name}/` → budget ≤100 lines
+- **Module**: `apps/erp/app/modules/{name}/` → budget 60–100 lines
-Do NOT write from memory or assumptions. Read the real files:
+## Step 2: Read the actual source
```bash
-# For a module:
+# Module:
ls apps/erp/app/modules/{name}/
-cat apps/erp/app/modules/{name}/{name}.service.ts
-cat apps/erp/app/modules/{name}/{name}.models.ts
-cat apps/erp/app/modules/{name}/index.ts
-ls apps/erp/app/modules/{name}/ui/ 2>/dev/null
+grep -n "^export" apps/erp/app/modules/{name}/{name}.service.ts
+grep -n "export const.*=.*z\." apps/erp/app/modules/{name}/{name}.models.ts
+grep -rn "\.from(" apps/erp/app/modules/{name}/{name}.service.ts | sed 's/.*\.from("\([^"]*\)").*/\1/' | sort -u
+grep -rn "\.rpc(" apps/erp/app/modules/{name}/ | sed 's/.*\.rpc("\([^"]*\)".*/\1/' | sort -u
+grep -rn "requirePermissions" apps/erp/app/routes/x+/{name}* | head -10
-# For a package:
+# Package:
ls packages/{name}/src/
cat packages/{name}/src/index.ts
cat packages/{name}/package.json | jq '.exports'
```
-Grep for concrete artifacts:
-
-```bash
-# Find exported functions
-grep -n "^export " apps/erp/app/modules/{name}/{name}.service.ts
-
-# Find tables this module touches
-grep -rn "\.from(" apps/erp/app/modules/{name}/{name}.service.ts | sed 's/.*\.from("\(.*\)").*/\1/' | sort -u
-
-# Find zod validators
-grep -n "export const.*=.*z\." apps/erp/app/modules/{name}/{name}.models.ts
-
-# Find route permission scopes
-grep -rn "requirePermissions" apps/erp/app/routes/x+/{name}* | head -10
-
-# Find RPCs
-grep -rn "\.rpc(" apps/erp/app/modules/{name}/ | sed 's/.*\.rpc("\(.*\)".*/\1/' | sort -u
-```
-
-### Step 3: Read existing AGENTS.md (if refreshing)
-
-```bash
-cat apps/erp/app/modules/{name}/AGENTS.md 2>/dev/null
-# or
-cat packages/{name}/AGENTS.md 2>/dev/null
-```
+## Step 3: If refreshing, read the existing file
-If refreshing:
-- **Preserve** any human-added notes, warnings, or domain explanations
-- **Update** stale function names, table names, imports, or cross-references
-- **Add** new exports, tables, or patterns introduced since last write
-- **Remove** references to deleted code (verify deletion with `grep`)
+- **Preserve** human-added notes, warnings, and domain explanations.
+- **Update** stale function/table/import names (verify each with grep).
+- **Add** new exports/tables/patterns; **remove** references to deleted code.
-### Step 4: Read relevant .ai/rules/ files
+## Step 4: Read the relevant rules
-```bash
-ls .ai/rules/
-# Load rules that apply to this module/package
-cat .ai/rules/conventions-index.md
-```
+Find the `.ai/rules/` files that govern this area (via the root `AGENTS.md`
+Task Router) and reference them in the Rules References section — only files
+that actually exist.
-Identify which rules files are relevant (e.g., `conventions-database.md` for
-database packages, module-specific rules like `purchasing-conversion-factors.md`).
+## Step 5: Write it
-### Step 5: Generate the AGENTS.md
+### Module template
-Follow the template below. Every section is mandatory unless marked optional.
-
----
-
-## Template: Module AGENTS.md
-
-```markdown
+````markdown
# {Module Name} Module
-{One-line description of what this module does in the ERP domain.}
+{One line: what this module does in the ERP domain.}
## Key Domain Concepts
-
-{For AI agents unfamiliar with manufacturing/ERP — explain 3–6 domain terms
- that appear in the code. Use bold term + dash + plain-English definition.
- Include status lifecycles where they exist.}
-
-- **{Term}** — {definition}
+{3–6 terms a non-manufacturing AI needs. **Term** — plain-English definition.
+ Include status lifecycles.}
## Safety
-
### Always
-{3–5 prescriptive rules. Use MUST language. Ground in real code.}
-- MUST {do X} — `{function/table}` depends on this.
-
+- MUST {do X} — `{function/table}` depends on it. {3–5 rules, grounded}
### Ask First
-{2–3 items where human judgment is needed.}
-- {action} — {why it's risky}.
-
+- {action} — {why risky}. {2–3 items}
### Never
-{2–3 hard prohibitions with rationale.}
-- {action} — {what breaks if you do}.
+- {action} — {what breaks}. {2–3 items}
## Validation Commands
-
-{Exact shell commands to verify changes in this module.}
-
```bash
-pnpm --filter {package} typecheck
-pnpm --filter {package} test
-# Module-specific checks
+pnpm exec turbo run typecheck --filter=erp
+pnpm --filter erp test
```
## Key Data Model
-
-{Main tables this module owns. Use a table. Include purpose column.}
-
| Table / View | Purpose |
|---|---|
-| `{table}` | {one-line purpose} |
## Key Service Functions
+- `{functionName}` — {what it does} {only what another module would call}
-{Real exported functions from {name}.service.ts. List the important ones
- — not every helper, just what another module would call.}
-
-- `{functionName}` — {what it does}
-
-## Key Exports
-
-{For packages: subpath exports from package.json. For modules: barrel
- exports from index.ts. Use real import paths.}
-
-```typescript
-import { {export} } from "~/modules/{name}";
-// or
-import { {export} } from "@carbon/{name}";
-```
-
-## Copy From
-
-{OPTIONAL — only if this module/package is a good template for new ones.
- Table showing what to copy and what to change.}
-
+## Copy From {OPTIONAL — only if this module is a good template}
| To build… | Copy from… | Then change… |
-|-----------|-----------|--------------|
-| {new feature} | `{file}` | {what to adapt} |
## Related Modules
-
-{Cross-references to modules this one interacts with. One bullet per
- module, explain the integration point.}
-
-- **{module}** — {how they interact}
+- **{module}** — {integration point}
## Rules References
-
-{Pointers to .ai/rules/ files that govern this module's patterns.}
-
- `.ai/rules/{file}.md` — {what it covers}
-```
+````
----
-
-## Template: Package AGENTS.md
+### Package template
-```markdown
+````markdown
# @carbon/{name}
-{One-line description.}
-
-## Always
-
-{3–5 prescriptive rules with MUST language.}
-
-## Ask First
-
-{2–3 items.}
+{One line.}
-## Never
-
-{2–3 prohibitions with rationale.}
+## Always / Ask First / Never
+{Same shape as the module template.}
## Validation Commands
-
```bash
pnpm --filter @carbon/{name} typecheck
pnpm --filter @carbon/{name} test
```
## Key Exports
-
-{Subpath export table. Use real subpaths from package.json exports field.}
-
| Subpath | Provides |
|---------|----------|
-| `.` | {what the default export gives} |
-| `./{sub}` | {what this subpath gives} |
+| `.` | {…} | {real subpaths from package.json exports}
## Cross-References
-
-{Pointers to rules, related packages, consuming apps.}
-```
-
----
-
-## Quality Checklist
-
-Before saving the AGENTS.md, verify:
-
-- [ ] **Every function name** listed actually exists (`grep -n "export.*{name}" {file}`)
-- [ ] **Every table name** listed actually exists (`grep -rn "from.*{table}" {file}`)
-- [ ] **Every import path** listed is real (`cat {index} | grep {export}`)
-- [ ] **Tone is prescriptive** — "MUST use X", not "X is used"
-- [ ] **Line count** is within budget (≤100 for packages, 60–100 for modules)
-- [ ] **No placeholders** — no `{TODO}`, `TBD`, or `fill in later`
-- [ ] **Domain concepts section** exists (modules only) and explains terms a non-manufacturing AI would need
-- [ ] **Cross-references** to `.ai/rules/` files are present and the files exist
-- [ ] **Human-added notes** are preserved (if refreshing)
-
-## Anti-Patterns
-
-- ❌ Listing functions you didn't grep for — they may have been renamed or deleted
-- ❌ Describing architecture abstractly — "uses a service layer" says nothing useful
-- ❌ Copying another module's AGENTS.md and changing the name — each module has different tables, functions, and domain concepts
-- ❌ Exceeding line budget — if it's too long, cut the least useful entries from Key Service Functions or Key Data Model
-- ❌ Omitting the Never section — every module has destructive actions worth prohibiting
-
-## Examples of Good vs Bad
-
-**Bad:**
-```
-- Services handle data access
-- The module uses Supabase for queries
-```
-
-**Good:**
-```
-- MUST use `insertManualInventoryAdjustment` for quantity changes — it creates
- proper ledger entries and handles tracked entity updates.
-- MUST scope by `companyId` and `locationId` — inventory is location-scoped.
-```
-
-**Bad:**
-```
-## Key Functions
-- Various CRUD operations for the module
-```
-
-**Good:**
-```
-## Key Service Functions
-- `getPurchaseOrder` / `getPurchaseOrders` / `getPurchaseOrderLines` — read POs
-- `closePurchaseOrder` — marks a PO closed
-- `convertSupplierQuoteToOrder` — calls `convert` edge function
-```
+{rules, related packages, consuming apps}
+````
+
+## Done when — verify each line
+
+- [ ] Every function name exists: `grep -n "export.*{name}" {file}` hits
+- [ ] Every table name exists: grep in the service file hits
+- [ ] Every import path is real (check the barrel / exports field)
+- [ ] Every referenced `.ai/rules/` file exists
+- [ ] Tone is prescriptive ("MUST use X"), not descriptive ("X is used")
+- [ ] Line count within budget; no `{placeholder}` / TBD left
+- [ ] Modules: Key Domain Concepts present; Never section present
+- [ ] Refresh: human-added notes preserved
+
+## Anti-patterns
+
+- Listing functions you didn't grep for (renamed/deleted ones will lie)
+- Abstract architecture prose ("uses a service layer" says nothing)
+- Copying a sibling AGENTS.md and renaming — every module has different tables,
+ functions, and concepts
+- Vague bullets: "Services handle data access" ❌ vs
+ "MUST use `insertManualInventoryAdjustment` for quantity changes — it creates
+ ledger entries and updates tracked entities" ✅
diff --git a/.ai/skills/debugging-difficult-bugs/SKILL.md b/.ai/skills/debugging-difficult-bugs/SKILL.md
index 25d903cffa..24da5aaddc 100644
--- a/.ai/skills/debugging-difficult-bugs/SKILL.md
+++ b/.ai/skills/debugging-difficult-bugs/SKILL.md
@@ -1,179 +1,94 @@
---
name: debugging-difficult-bugs
-description: Use early when debugging a medium or hard bug, especially when tests alone may not reveal the real runtime failure. Trigger this before extended TDD iteration when a bug involves runtime state, ordering, persistence, streaming, concurrency, UI/manual reproduction, external services, or when a red or newly passing test may not model the real issue. Skip only when the root cause is already directly proven by a stack trace or deterministic test that exercises the real runtime path.
+description: Runtime-instrumentation debugging for bugs that static reading can't pin down — add temporary unconditional JSONL logging to the real code path, reproduce, read the log, then fix. Use when /root-cause lands at MEDIUM/LOW confidence, when a bug involves runtime state, ordering, caching, streaming, concurrency, or manual/UI reproduction, or before a second speculative fix. Skip when a stack trace or a deterministic failing test already proves the cause.
---
-# Debugging Difficult Bugs
+# debugging-difficult-bugs — instrument, reproduce, read, then fix
-Use this skill early for medium or hard bugs where normal TDD may give false confidence because the test does not fully capture the real bug.
+Core idea: when you can't see the failure by reading code, **make the runtime
+tell you**. Add temporary append-only JSONL logging along the real code path,
+reproduce the real issue once, read the log chronologically, and only then fix.
+Never make a second speculative fix without new runtime evidence.
-Core idea: **instrument the actual runtime path, reproduce the real issue, then inspect append-only JSONL logs before deciding on a fix.**
+**Announce at start:** "Using the debugging-difficult-bugs skill — instrumenting
+the runtime path to observe the failure."
-## When to Use
+## Step 1: State the uncertainty
-Use this workflow near the start of debugging when any of these are true:
+Write down: what you believe, what you can't verify statically, and the exact
+runtime path that must be observed (route → service → query, edge function, job).
-- The bug is medium or hard complexity, especially if it spans multiple functions, packages, processes, or UI/runtime boundaries.
-- A test is red, but the failing test might be an incomplete model of the real bug.
-- You are tempted to make a second speculative fix without new runtime evidence.
-- The bug depends on runtime ordering, state, caching, streaming, concurrency, persistence, UI interaction, or external services.
-- The user says they can reproduce the issue manually.
-- The test passes after a change, but you are not confident it proves the actual reported bug is fixed.
+## Step 2: Add temporary unconditional instrumentation
-Do **not** keep iterating only on tests if you do not understand the runtime behavior.
+Rules:
-Skip this workflow only when the root cause is already directly proven by a stack trace or by a deterministic failing test that exercises the real runtime path. If you are tempted to make a second speculative fix, use this workflow.
-
-## Required Approach
-
-1. **State the uncertainty**
- - Acknowledge that the current test may not capture the actual bug.
- - Identify the real code path that must be observed.
-
-2. **Add temporary unconditional instrumentation**
- - Add minimal but sufficient logs through the suspected code flow.
- - Log boundaries, meaningful branch decisions, state transitions, async ordering points, return values, and caught errors; do not log every line.
- - Logs must be unconditional: do **not** gate them behind an env var, debug flag, or log level.
- - Each log point must append one JSON object per line to a `.jsonl` file in the current working directory.
- - Include enough context to reconstruct the path: event name, timestamp, relevant ids, input shape, state transitions, branch decisions, return values, and caught errors.
-
-3. **Reproduce the real issue**
- - Prefer to run the reproduction yourself if possible.
- - If the issue requires the user's environment or manual interaction, ask the user to reproduce it after instrumentation is added.
- - Tell the user exactly which `.jsonl` file to send or ask them to tell you when reproduction is complete so you can inspect it.
-
-4. **Analyze the log before fixing**
- - Read the JSONL log chronologically.
- - Compare expected flow vs actual flow.
- - Identify the first point where state or behavior diverges.
- - Only then implement the fix.
-
-5. **Clean up instrumentation**
- - Remove all temporary unconditional logs after root cause is understood and the fix is verified.
- - Remove debug imports, helper functions, generated `.jsonl` files, and any other temporary artifacts.
- - Check the final diff for instrumentation remnants.
- - Do not leave debug files, log helpers, or noisy runtime logging in the final diff unless the user explicitly asks.
-
-6. **Keep or improve tests**
- - Add or adjust a focused regression test once the real bug is understood.
- - Make the test assert the actual broken behavior discovered from logs, not the earlier incorrect assumption.
-
-## JSONL Logging Pattern
-
-Use append-only JSONL in `cwd` so it works across CLIs, dev servers, tests, and manual reproduction.
-
-### Node / TypeScript
+- **Unconditional** — never gated behind an env var, debug flag, or log level.
+ If reproduction requires remembering to set a flag, it will silently not fire.
+- **Append-only JSONL**, one JSON object per line, to a file in the process's
+ working directory.
+- Log **boundaries and decisions**, not every line: function entry/exit, branch
+ decisions with the data that caused them, state before/after mutation, async
+ ordering markers, caught errors, return-value shapes.
+- Log **shapes, not payloads**: ids, keys, counts, statuses. Never log tokens,
+ auth headers, cookies, or full user content.
```ts
-import { appendFileSync } from 'node:fs';
-import { join } from 'node:path';
+import { appendFileSync } from "node:fs";
+import { join } from "node:path";
function debugBug(event: string, data: Record<string, unknown> = {}) {
appendFileSync(
- join(process.cwd(), 'debug-difficult-bug.jsonl'),
- `${JSON.stringify({
- ts: new Date().toISOString(),
- event,
- ...data,
- })}\n`,
+ join(process.cwd(), "debug-difficult-bug.jsonl"),
+ `${JSON.stringify({ ts: new Date().toISOString(), event, ...data })}\n`
);
}
-```
-Call it at every meaningful branch or state transition:
-
-```ts
-debugBug('workflow.start', { runId, stepId, inputKeys: Object.keys(input ?? {}) });
-
-debugBug('workflow.beforeStep', {
- runId,
- stepId,
- status: step.status,
- hasResumeData: Boolean(resumeData),
-});
-
-try {
- const result = await executeStep();
- debugBug('workflow.afterStep', { runId, stepId, resultShape: Object.keys(result ?? {}) });
- return result;
-} catch (error) {
- debugBug('workflow.stepError', {
- runId,
- stepId,
- errorName: error instanceof Error ? error.name : typeof error,
- errorMessage: error instanceof Error ? error.message : String(error),
- });
- throw error;
-}
+debugBug("service.beforeUpdate", { id, companyId, status: row.status });
```
-## What to Log
+**Carbon multi-process note.** The ERP/MES dev servers, edge functions (Docker
+`edge-runtime` container), and Inngest handlers run as separate processes with
+different working directories. Log `process.cwd()` + a process role once at
+startup, or use distinct filenames (`debug-erp.jsonl`, `debug-edge.jsonl`). For
+edge functions, `console.error` JSON lines (visible in container logs) can stand
+in when the container filesystem is awkward to reach.
-Prefer compact, structured data over huge dumps.
+## Step 3: Reproduce the real issue once
-Log:
+- Prefer reproducing yourself: boot the stack (`crbn up` if not already
+ running), authenticate with `/login`, and drive the exact failing flow with
+ `agent-browser` (the `/test` skill documents Carbon's form gotchas —
+ `requestSubmit`, react-aria blur).
+- If only the user can reproduce (their data, their environment), tell them
+ exactly: "I added temporary logging. Reproduce the issue once, then point me
+ at `<cwd>/debug-difficult-bug.jsonl`."
-- Function or phase name.
-- Stable ids: request id, run id, thread id, resource id, step id, tool call id.
-- Input/output **shape**: keys, counts, lengths, statuses.
-- Branch decisions and the data that caused them.
-- State before and after mutation.
-- Error names/messages and relevant metadata.
-- Ordering markers for async, streaming, or concurrent flows.
-
-Avoid logging:
-
-- API keys, auth headers, tokens, cookies, credentials.
-- Full user content unless necessary and safe.
-- Large payloads that make the log unreadable.
-- Binary data or full model responses unless the bug requires it.
-
-Treat debug logs as potentially sensitive. Do not ask the user to paste them into public issues, PRs, or shared channels unless they have reviewed/redacted them first.
-
-If sensitive data might appear, log redacted summaries:
-
-```ts
-debugBug('request.received', {
- hasAuthHeader: Boolean(headers.authorization),
- bodyKeys: Object.keys(body ?? {}),
- messageCount: body?.messages?.length,
-});
-```
-
-## Reproduction Handoff to User
-
-When the user needs to reproduce manually, say exactly this shape:
-
-```text
-I added temporary unconditional JSONL instrumentation. Please reproduce the issue once, then send me or point me at:
-
-<cwd>/debug-difficult-bug.jsonl
-
-After I inspect that log, I’ll remove the instrumentation and make the actual fix.
-```
+## Step 4: Read the log BEFORE fixing
-If multiple processes have different working directories, either:
+Read chronologically and answer, in writing:
-- log the absolute `process.cwd()`, process role, and pid at startup, or
-- write distinct files like `debug-server-flow.jsonl`, `debug-worker-flow.jsonl`, and `debug-client-flow.jsonl`.
+1. Did the instrumented path actually run?
+2. What was the expected sequence of events?
+3. What was the actual sequence?
+4. What is the **first** point where state/order/branch diverges from expectation?
-## Analysis Checklist
+That first divergence is the root cause candidate. Feed it back into the
+root-cause brief (or write one now) — then implement via `/fix`, whose failing
+regression test must assert the *actual* divergence you observed, not your
+earlier assumption.
-Before writing the fix, answer:
+## Step 5: Clean up — mandatory
-- Did the instrumented code path actually run?
-- What was the expected sequence of events?
-- What was the actual sequence?
-- What is the first incorrect state, missing value, duplicate event, or wrong branch?
-- Does the original red test capture that exact divergence?
-- If not, how should the regression test change?
+- Remove every temporary log call, helper, and import.
+- Delete generated `.jsonl` files.
+- Check the final diff explicitly for leftovers:
+ `git diff | grep -n "debugBug\|debug-difficult\|\.jsonl"` → expect no hits.
-## Final Verification
+The final diff contains only the fix and its tests.
-A difficult bug is not done until:
+## Done when
-- The real reproduction path passes.
-- The regression test fails before the fix and passes after the fix, when feasible.
-- Temporary unconditional instrumentation is removed.
-- The final diff contains only the fix and intentional tests.
-- You can explain the root cause using evidence from the JSONL log.
\ No newline at end of file
+- [ ] The first divergence point is identified from log evidence (quote the lines)
+- [ ] The fix landed via `/fix` with a red→green regression test asserting that behavior
+- [ ] Reproduction of the original flow now passes
+- [ ] Zero instrumentation remnants in the diff
diff --git a/.ai/skills/error/SKILL.md b/.ai/skills/error/SKILL.md
index 928aa85e2a..c9841f74e5 100644
--- a/.ai/skills/error/SKILL.md
+++ b/.ai/skills/error/SKILL.md
@@ -1,58 +1,56 @@
---
name: error
-description: Capture a screenshot and snapshot of the current browser page when an error is encountered during e2e testing. Saves to docs/e2e/<slug>/screenshots/.
+description: Capture a screenshot plus element snapshot of the current browser page when an error appears during e2e testing, saved to gitignored .ai/scratch/e2e/. Use whenever an agent-browser snapshot shows "Something went wrong", an auth error, a blank page, or an unexpected redirect. Building block — it captures and returns; the caller decides whether to continue.
---
-# Error Capture
+# error — capture browser failure diagnostics
-Capture diagnostic artifacts when the browser shows an error during e2e testing. This skill is a building block — other skills (e.g. `/smoke-test`) invoke it when they detect a failure.
+Capture artifacts when the browser shows a failure, then hand control back to
+the calling skill. Never stops the calling run by itself.
-## When to Use
+## When to invoke
-Call this whenever an `agent-browser snapshot` reveals:
-- "Something went wrong" heading
-- "Authentication Error" or similar error message
-- A blank page or unexpected redirect
-- Any content that indicates the page failed to render
+Any `agent-browser snapshot` that reveals:
-## Procedure
+- a "Something went wrong" heading
+- "Authentication Error" or similar
+- a blank page or unexpected redirect
+- any content indicating the page failed to render
-### 1. Determine the worktree slug
+## Steps
-Read `.env.local` in the project root and extract the `CARBON_WORKTREE` value.
+### 1. Resolve the slug
-### 2. Ensure the output directory exists
+Use `CARBON_WORKTREE` from `.env.local` if present; otherwise the current
+branch name:
```bash
-mkdir -p docs/e2e/${CARBON_WORKTREE}/screenshots
+SLUG=$(grep '^CARBON_WORKTREE' .env.local | cut -d= -f2)
+[ -z "$SLUG" ] && SLUG=$(git branch --show-current | tr '/' '-')
```
-### 3. Capture the screenshot
+### 2. Capture both artifacts
-Use a descriptive filename with the module/route name and a timestamp:
+Save to `.ai/scratch/e2e/` — it is gitignored (`.ai/scratch/` in `.gitignore`).
+Never save captures under `docs/` (that's the documentation app, and it is
+tracked).
```bash
-agent-browser screenshot docs/e2e/${CARBON_WORKTREE}/screenshots/${module}-$(date +%Y%m%d-%H%M%S).png
+mkdir -p .ai/scratch/e2e/${SLUG}
+STAMP=$(date +%Y%m%d-%H%M%S)
+agent-browser screenshot .ai/scratch/e2e/${SLUG}/${module}-${STAMP}.png
+agent-browser snapshot -i > .ai/scratch/e2e/${SLUG}/${module}-${STAMP}.txt
```
-For example: `docs/e2e/my-worktree/screenshots/accounting-20260606-143022.png`
+`${module}` = a short name for the route/feature under test (e.g. `accounting`).
+The `.txt` snapshot lets you debug element structure without reopening a browser.
-### 4. Capture the snapshot text
+### 3. Report and return
-Save the element snapshot alongside the screenshot for debugging without a browser:
-
-```bash
-agent-browser snapshot -i > docs/e2e/${CARBON_WORKTREE}/screenshots/${module}-$(date +%Y%m%d-%H%M%S).txt
-```
-
-### 5. Report
-
-After capturing, log the file paths and continue — do **not** stop the calling skill. The caller decides whether to abort or continue.
+Log both file paths and **continue** — the caller decides whether to abort.
+Include the paths in the caller's final report so a human can open them.
## Output
-Two files saved to `docs/e2e/<slug>/screenshots/`:
-- `{module}-{timestamp}.png` — visual screenshot
-- `{module}-{timestamp}.txt` — element snapshot text
-
-These paths are gitignored (`docs/e2e` in `.gitignore`).
+- `.ai/scratch/e2e/{slug}/{module}-{timestamp}.png` — screenshot
+- `.ai/scratch/e2e/{slug}/{module}-{timestamp}.txt` — element snapshot
diff --git a/.ai/skills/execute/SKILL.md b/.ai/skills/execute/SKILL.md
index 07c5209c35..23a19c94d9 100644
--- a/.ai/skills/execute/SKILL.md
+++ b/.ai/skills/execute/SKILL.md
@@ -1,201 +1,96 @@
---
name: execute
-description: Execute implementation plans task by task with verification. Use after /plan to implement the feature. Follows each task exactly, runs verifications, commits frequently. Triggers on "execute the plan", "implement the plan", "run the plan", or after /plan approval.
+description: Execute an approved implementation plan from .ai/plans/ task by task, running each task's verification and committing per task via the check-and-commit gate. Use when asked to "execute the plan", "implement the plan", or after /plan approval. Do not use without an approved plan file — run /plan first — and do not use it to redesign; a plan gap means stop and re-plan.
---
-# Execute: Plan Implementation
+# execute — run an implementation plan
-Execute implementation plans task by task. Follow each step exactly, run all verifications, commit after each task.
+Input: an approved plan at `.ai/plans/{date}-{slug}.md`. Output: working,
+verified, committed code on the feature branch, with the plan's Progress
+checklist fully checked off.
-**Announce at start:** "I'm using the execute skill to implement this plan."
+Your job is to follow the plan exactly — not to improve it. Deviations are
+blockers, not judgment calls.
-## Prerequisites
+**Announce at start:** "Using the execute skill — implementing the plan at
+{path}."
-Before executing:
-1. An implementation plan exists (from `/plan`)
-2. The plan has been approved
-3. You're on the correct branch
+## Step 1: Load and sanity-check
-If no plan exists, suggest running `/plan` first.
+1. Read the whole plan file. Confirm: you are on the branch it names, the spec
+ it references exists, and its task dependencies are consistent.
+2. If anything is missing or contradictory → **STOP** and report before touching
+ code.
-## Workflow
+## Step 2: Per-task loop
-```
-┌──────────────┐ ┌──────────────┐ ┌──────────────┐ ┌──────────────┐
-│ 1. Load Plan │───▶│ 2. Execute │───▶│ 3. Verify │───▶│ 4. Complete │
-│ & Review │ │ Each Task │ │ & Commit │ │ & Review │
-└──────────────┘ └──────────────┘ └──────────────┘ └──────────────┘
-```
-
-## Step 1: Load Plan & Review
-
-### 1.1 Load the Plan
-
-Read `.ai/plans/[feature-name]-plan.md`.
-
-### 1.2 Critical Review
-
-Before starting, check:
-- [ ] Plan makes sense
-- [ ] No obvious gaps
-- [ ] Dependencies are clear
-- [ ] On correct branch
-
-If concerns exist, raise them before proceeding.
-
-### 1.3 Create Progress Tracker
-
-Track progress in `.ai/scratch/tasks/todo.md`:
-
-```markdown
-## [Feature] Implementation
-
-- [ ] Task 1: [Title]
-- [ ] Task 2: [Title]
-...
-```
-
-## Carbon-Specific Skills to Load
-
-When executing tasks, load the appropriate Carbon skill for guidance:
-
-| Task Type | Skill/Workflow | Load When |
-|-----------|----------------|-----------|
-| Database migrations | `.ai/rules/workflow-database-migration.md` | Creating tables, columns, RLS |
-| Forms & validators | `/forms` skill | Building UI forms |
-| Multi-row writes | `/database-transactions` skill | Bulk updates, atomic operations |
-| UI polish | `/make-interfaces-feel-better` skill | Animations, shadows, typography |
-
-**For migrations:** Read `.ai/rules/workflow-database-migration.md` before writing SQL to ensure:
-- `id()` function for primary keys
-- `companyId` with composite primary key
-- Standardized RLS policies (SELECT, INSERT, UPDATE, DELETE)
-- Audit columns (createdBy, createdAt, updatedBy, updatedAt)
-
-**For forms:** Invoke `/forms` to get ValidatedForm patterns, zod conventions, and action handlers.
-
-## Step 2: Execute Each Task
-
-For each task:
-
-### 2.1 Mark In Progress
-
-Update `.ai/scratch/tasks/todo.md`:
-```markdown
-- [x] Task 1: Create migration ✓
-- [ ] Task 2: Add types (in progress)
-- [ ] Task 3: Service layer
-```
-
-### 2.2 Follow Steps Exactly
-
-The plan has bite-sized steps. Follow them exactly:
-- Use the exact file paths
-- Use the exact code
-- Run the exact commands
-
-### 2.3 Run Verifications
-
-Every task has verification steps. Run them all:
-- Tests must pass
-- Commands must produce expected output
-- TypeScript must compile
-
-### 2.4 Commit
-
-After task passes verification:
-```bash
-git add [specific files] && git commit -m "[type](module): [description]"
-```
-
-### 2.5 Mark Complete
-
-Update tracker and move to next task.
-
-## Step 3: Handle Blockers
-
-### When to Stop
+For each unchecked task, in dependency order:
-**Stop immediately when:**
-- Test fails and you can't quickly fix it
-- Plan has a gap (missing step or unclear instruction)
-- Verification produces unexpected output
-- You need to make a decision not covered by the plan
+1. **Read the task** and every file it lists (including the precedent file for
+ UI tasks).
+2. **Do exactly the steps.** Exact paths, exact code, exact commands. If the
+ task says "copy from precedent X", open X and match its structure and idiom.
+3. **Run the task's Verify block** and compare against the expected output. A
+ verification you didn't run counts as failed.
+4. **Commit via `/check-and-commit`** (it runs the gates, stages the task's
+ files specifically, and writes a conventional commit). One commit per task.
+5. **Check the task off** in the plan file's Progress list.
-### What to Do
+Reminders that override anything the plan forgot:
-1. **Don't guess** — Stop and ask
-2. **Document the blocker** — What happened, what you tried
-3. **Propose options** — If you have ideas, share them
+- After any migration is applied: `pnpm run generate:types` BEFORE typechecking.
+- Typecheck only per package: `pnpm exec turbo run typecheck --filter=<pkg>`.
+ Never run a whole-repo typecheck.
+- Never rebuild or reset the database to make a task pass — stop and report.
-### After Blocker Resolution
+## Step 3: Blockers — when to STOP
-Return to the task and continue.
+Stop immediately and report (do not guess, do not improvise) when:
-## Step 4: Complete & Review
+- A verification fails and one focused fix attempt doesn't make it pass.
+- The plan has a gap: missing step, wrong path, unstated decision.
+- An escape hatch condition in the plan triggers.
+- You are about to touch a file the task lists as out of scope.
-### 4.1 Final Verification
+Report format: what happened, exact command + output, what you tried, 1–2
+options if you have them. After the human resolves it, resume the loop. If the
+plan itself is wrong, go back to `/plan` and update the plan file first — never
+push through with an unplanned design change.
-After all tasks:
-- [ ] All tests pass: `pnpm test`
-- [ ] TypeScript compiles: `pnpm typecheck`
-- [ ] Lint passes: `pnpm lint`
+Red flags — thinking any of these means you are improvising; STOP instead:
-### 4.2 Feature Verification
+- "the plan is close enough, I'll adapt this step"
+- "I'll run all the verifications together at the end"
+- "this extra fix is obviously needed" (out-of-scope is a blocker, not a favor)
+- "the verification failed but the code looks right"
-Use `/verify` to test the feature in the browser:
-- Happy path works
-- Edge cases handled
-- No regressions
+## Step 4: Parallel tasks (optional)
-### 4.3 Self-Review
+Tasks marked independent may be dispatched to subagents — one task per subagent,
+each given the full task text verbatim plus the branch name. Never let two
+subagents touch the same file. Verify and commit each result through the same
+per-task loop; you (the main agent) run the gates, not the subagent.
-Use `/self-review` to check your work before declaring done.
+## Step 5: Finish
-### 4.4 Report Completion
+After the last task:
-```markdown
-## Implementation Complete
-
-**Branch:** feature/[name]
-**Commits:** N commits
-**Tests:** X new tests, all passing
-
-**Summary:**
-- [What was built]
-- [Key decisions made during implementation]
-- [Any deviations from plan and why]
-
-**Ready for:** PR creation / further review
-```
-
-## Subagent Strategy
-
-For plans with independent tasks, consider dispatching subagents:
+1. Full test pass: `pnpm test` (turbo scopes caching; this one is safe repo-wide).
+2. For anything user-facing: browser-verify with `/test` (boots on the running
+ `crbn up` stack, logs in, drives the changed flows). A UI change without a
+ passing browser check is **not done** — if the stack can't boot, the work is
+ BLOCKED, not complete.
+3. Review your own diff with `/self-review`.
+4. Report:
```markdown
-## Parallelizable Tasks
-
-Tasks 3, 4, 5 are independent (all depend only on Task 2).
-Dispatch 3 subagents in parallel:
-- Subagent A: Task 3
-- Subagent B: Task 4
-- Subagent C: Task 5
+## Implementation complete
+**Plan:** .ai/plans/{date}-{slug}.md (all tasks checked)
+**Branch / commits:** {branch}, {N} commits
+**Tests:** {X added, all passing — command + result}
+**Browser verification:** {flows verified via /test, or explicit N/A for non-UI}
+**Deviations from plan:** {none, or list with reasons}
+**Ready for:** PR
```
-Use the Agent tool with clear context for each subagent.
-
-## Output
-
-| Artifact | Location |
-|----------|----------|
-| Working code | Feature branch |
-| Progress tracker | `.ai/scratch/tasks/todo.md` |
-| Commits | Git history |
-
-## Next Steps
-
-After execution:
-- Create PR (if ready)
-- Run `/self-review`
-- Use `/verify` for browser testing
+Open a PR only if the user asked for one.
diff --git a/.ai/skills/feature/SKILL.md b/.ai/skills/feature/SKILL.md
index a9651f2afa..1f1535781e 100644
--- a/.ai/skills/feature/SKILL.md
+++ b/.ai/skills/feature/SKILL.md
@@ -1,120 +1,53 @@
---
name: feature
-description: End-to-end feature development orchestrator. Composes /research, /brainstorm, /plan, and /execute into a single workflow. Use when building a new feature from scratch. Triggers on "build a feature", "implement X from scratch", "full feature development for Y".
+description: End-to-end feature pipeline that runs /research, /spec-writing, /plan, /execute, /test, and /self-review in order with human gates between phases. Use when building a new feature from scratch ("build a feature", "implement X from scratch"). Do not use for bug fixes (use /root-cause then /fix) or when an artifact already exists — enter the pipeline at the first missing phase instead.
---
-# Feature: End-to-End Development Orchestrator
+# feature — end-to-end pipeline
-Orchestrates the full feature development lifecycle by composing smaller skills:
+Runs the full feature lifecycle by invoking the phase skills in order. This
+skill adds no logic of its own — each phase's rules live in its own skill.
-```
-/research → /brainstorm → /plan → /execute → /verify
-```
+**Announce at start:** "Using the feature skill — running the full pipeline for
+{feature}."
-**Announce at start:** "I'm using the feature skill to orchestrate end-to-end development."
+## The pipeline
-## When to Use This vs Individual Skills
+| # | Phase | Skill | Artifact | Gate before next phase |
+|---|-------|-------|----------|-------------------------|
+| 1 | Research | `/research` | `.ai/research/{slug}.md` | none |
+| 2 | Design + spec | `/spec-writing` | `.ai/specs/{date}-{slug}.md` | 🛑 every Open Question resolved by the user |
+| 3 | Plan | `/plan` | `.ai/plans/{date}-{slug}.md` | 🛑 user approves the plan |
+| 4 | Build | `/execute` | commits on the feature branch | all tasks verified + committed |
+| 5 | Browser verify | `/test` | pass/fail table + playbooks | every user-facing flow passes |
+| 6 | Review | `/self-review` | Must fix / Risks / Suggestions | Must-fix items resolved |
-| Use `/feature` when... | Use individual skills when... |
-|------------------------|-------------------------------|
-| Building something new from scratch | You only need one phase |
-| Want the full research-to-implementation flow | Design already exists |
-| Don't want to invoke each skill manually | Plan already exists |
+Run the phases strictly in order. Announce each phase transition in one line
+("Phase 3: planning — spec approved, writing the plan").
-## The Pipeline
+## Entering mid-pipeline
-### Phase 1: Research (`/research`)
+Start at the first phase whose artifact is missing or stale:
-Identify the domain and research competitors:
-- SAP (always)
-- Domain-specific best-in-class competitors
-- Save to `.ai/research/[feature].md`
+| You already have | Start at |
+|------------------|----------|
+| Nothing | Phase 1 |
+| Research file | Phase 2 |
+| Finalized spec (open questions resolved) | Phase 3 |
+| Approved plan | Phase 4 |
+| Built code, unverified | Phase 5 |
-### Phase 2: Brainstorm (`/brainstorm`)
+## Hard rules
-Design with research in hand:
-- Use competitor patterns to inform decisions
-- Document design choices with rationale
-- Save to `.ai/research/[feature]-design.md`
-- **Gate:** User approval required
+- Never skip a 🛑 gate. The gates exist to force human judgment at the two
+ points where rework is most expensive (design and plan).
+- Never let a phase write its artifact somewhere non-canonical — the paths in
+ the table are the only correct ones.
+- If a later phase reveals the spec was wrong, stop, update the spec (and its
+ changelog), re-gate, then resume.
-### Phase 3: Plan (`/plan`)
+## Alternative: the conductor
-Create implementation plan:
-- Break into 2-5 minute tasks
-- Complete code, no pseudocode
-- Save to `.ai/plans/[feature]-plan.md`
-- **Gate:** User approval required
-
-### Phase 4: Execute (`/execute`)
-
-Implement the plan:
-- Follow each task exactly
-- Run verifications
-- Commit after each task
-
-### Phase 5: Verify (`/verify`)
-
-Test in browser:
-- Happy path
-- Edge cases
-- No regressions
-
-## Usage
-
-```
-User: /feature lot tracking for inventory
-
-Claude: I'm using the feature skill to orchestrate end-to-end development.
-
-Phase 1: Research
-[Invokes /research inventory lot tracking]
-[Saves to .ai/research/lot-tracking.md]
-
-Phase 2: Brainstorm
-[Invokes /brainstorm with research context]
-[Presents design spec]
-[Waits for approval]
-
-Phase 3: Plan
-[Invokes /plan]
-[Presents implementation plan]
-[Waits for approval]
-
-Phase 4: Execute
-[Invokes /execute]
-[Implements each task]
-
-Phase 5: Verify
-[Invokes /verify]
-[Tests feature]
-```
-
-## Artifacts Produced
-
-| Phase | Artifact | Location |
-|-------|----------|----------|
-| Research | Competitor analysis | `.ai/research/[feature].md` |
-| Brainstorm | Design spec | `.ai/research/[feature]-design.md` |
-| Plan | Implementation plan | `.ai/plans/[feature]-plan.md` |
-| Execute | Working code | Feature branch |
-| Verify | Test evidence | Screenshots/logs |
-
-## Composable Skills
-
-Each phase uses a standalone skill you can invoke directly:
-
-- `/research [topic]` — Survey competitor best practices
-- `/brainstorm [feature]` — Research-driven design
-- `/plan [feature]` — Create implementation plan
-- `/execute [feature]` — Implement from plan
-- `/verify` — Test feature in browser
-- `/self-review` — Review before PR
-
-## Skipping Phases
-
-If you already have artifacts, skip to the appropriate phase:
-
-- Have research? Start with `/brainstorm`
-- Have design spec? Start with `/plan`
-- Have plan? Start with `/execute`
+For a single tightly-scoped item (a bug, a usability tweak, a small feature)
+with explicit acceptance criteria, prefer `/conductor` — it runs a
+doer→gate→judge loop with the human watching instead of this phased pipeline.
diff --git a/.ai/skills/fix/SKILL.md b/.ai/skills/fix/SKILL.md
index 7ecb34f6ca..ecea1f47bd 100644
--- a/.ai/skills/fix/SKILL.md
+++ b/.ai/skills/fix/SKILL.md
@@ -1,140 +1,123 @@
-<!-- Workflow pattern inspired by Open Mercato (MIT License)
- https://github.com/open-mercato/open-mercato
- Copyright (c) 2025-2026 Open Mercato contributors -->
-
---
name: fix
-description: Implement the minimal code change from a root-cause brief. Writes code, adds regression tests, validates gates. No commit, no push, no PR — the conductor or open-pr handles that.
+description: Implement the minimal code change from a root-cause brief, with a mandatory red→green regression test and scoped validation gates. Use after /root-cause (or when the cause is already proven) to write the fix. No commit, no push, no PR from this skill — /check-and-commit handles committing. Do not use without a root-cause brief, and do not use for features (use /plan + /execute).
---
+<!-- Workflow pattern inspired by Open Mercato (MIT License)
+ https://github.com/open-mercato/open-mercato
+ Copyright (c) 2025-2026 Open Mercato contributors -->
-# fix — minimal code change from a root-cause brief
-
-You are implementing the **smallest correct fix** for a bug that has already been analyzed. You have a root-cause brief (from `/root-cause` or equivalent) that tells you exactly what to change and why. Your job is to execute that change, prove it works, and stop.
-
-**Announce at start:** "I'm using the fix skill to implement the change from the root-cause brief."
-
-## 0. Prerequisites
+# fix — minimal change from a root-cause brief
-Before writing any code:
+Input: a root-cause brief (from `/root-cause` or equivalent proof). Output: the
+smallest correct fix plus a regression test, all gates green, ready for
+`/check-and-commit`. Your job is to execute the brief, prove it, and stop.
-1. **Read the root-cause brief.** If none exists, stop and run `/root-cause` first.
-2. **Read `.ai/lessons.md`** — check for pitfalls in the affected area.
-3. **Read the module AGENTS.md** for the affected package/module.
-4. **Read `BACKWARD_COMPATIBILITY.md`** — know which surfaces are FROZEN, STABLE, or ADDITIVE-ONLY.
-5. **Check issue assignment.** If working from a GitHub issue, ensure it's assigned to `carbon-agent` with the `agent:working` label:
- ```bash
- gh issue edit <number> --add-assignee carbon-agent --add-label "agent:working"
- ```
+**Announce at start:** "Using the fix skill — implementing the change from the
+root-cause brief."
-## 1. Plan the change
+## Step 0: Prerequisites
-Before touching code, list:
-- **Files to modify** (from the brief's "Files to change")
-- **Files to create** (new test files, migrations)
-- **Callers to update** (if changing a service function signature)
+1. **Read the brief.** No brief → STOP and run `/root-cause` first.
+2. Read `.ai/lessons.md` for the affected area.
+3. Read the affected module/package `AGENTS.md`.
+4. Read `BACKWARD_COMPATIBILITY.md` if the brief lists any BC impact.
+5. If working a GitHub issue: `gh issue edit <number> --add-assignee carbon-agent --add-label "agent:working"`.
-Verify the plan against the brief. If the brief says change 2 files and you're planning to change 8, stop and re-scope.
+## Step 1: Plan the change
-## 2. Implement
+List before touching code: files to modify (from the brief), files to create
+(tests, migrations), callers to update (if a signature changes — grep for every
+call site). If the brief says 2 files and your list says 8 → STOP and re-scope
+with the human.
-### Rules
+## Step 2: Write the failing test FIRST
-- **One concern per change.** Fix the bug. Don't refactor, don't clean up, don't "improve while here."
-- **Follow existing patterns.** Read the surrounding code and match its style. Use `grep` to find similar patterns in the codebase.
-- **companyId scoping.** Every new or modified query that touches tenant data MUST include `companyId` filtering. This is Carbon's equivalent of a security gate — never skip it.
-- **Service file discipline.** One `{module}.service.ts` and one `{module}.models.ts` per module. Never scatter new service/models files.
-- **Import conventions.** `~/*` for app code, `@carbon/*` for workspace packages.
-- **Schema changes.** If the fix requires a migration:
- - Read `.ai/rules/workflow-database-migration.md` first
- - Use `id('prefix')` for primary keys
- - Include `companyId` with composite PK `("id", "companyId")`
- - Add standard audit columns
- - Run `pnpm run generate:types` after applying the migration, BEFORE typechecking
+Mandatory for every fix. Write a regression test that reproduces the bug, then
+run it and **watch it fail** before changing any production code:
-## 3. Write regression tests
+```bash
+pnpm --filter <pkg> exec vitest run <path/to/test>
+# Expected: FAIL, for the reason the brief describes (not a typo/import error)
+```
-**Mandatory.** Every fix MUST include at least one test that:
+A test that passes immediately proves nothing — it isn't testing the bug. Test
+locations: `apps/erp/app/modules/{module}/__tests__/` or
+`packages/{pkg}/src/__tests__/` (or next to the source, matching siblings). Copy
+setup patterns from a sibling test file.
-1. **Would have failed** before the fix (red → green pattern)
-2. **Passes** after the fix
-3. **Guards against regression** — if someone reverts the fix, this test catches it
+If the bug is only provable in the browser (layout, visual state), the failing
+proof is a `/test` run + BEFORE screenshot instead — say so explicitly.
-Place tests adjacent to the code following Carbon conventions:
-- Module tests: `apps/erp/app/modules/{module}/__tests__/`
-- Package tests: `packages/{package}/src/__tests__/`
-- Use existing test utilities and patterns from sibling test files
+## Step 3: Implement
-## 4. Validate
+- **One concern.** Fix the bug. No refactoring, no cleanup, no "while I'm here".
+- **Match surrounding patterns** — grep for similar code and copy its idiom.
+- **companyId scoping** on every new or modified tenant-data query. Never skip.
+- **Module discipline**: one `{module}.service.ts`, one `{module}.models.ts`.
+- **Imports**: `~/*` app code, `@carbon/*` workspace packages.
+- **Schema changes**: follow `.ai/rules/workflow-database-migration.md`; then
+ `pnpm run generate:types` BEFORE typechecking.
+- **Minimal blast radius**: fewest files, fewest lines, still complete.
-Run the validation gates **in this order**. Every applicable gate must pass:
+## Step 4: Validate (scoped gates, in order)
```bash
-# 1. Regenerate types (only if schema changed)
+# 1. Types (only if schema changed)
pnpm run generate:types
-# 2. Lint
-pnpm run lint
+# 2. Format + lint the files you touched
+pnpm exec biome check --write <changed paths>
-# 3. Typecheck
-pnpm run typecheck
+# 3. Typecheck each touched package — NEVER whole-repo (it OOMs)
+pnpm exec turbo run typecheck --filter=<pkg>
-# 4. Tests
-pnpm run test
+# 4. Tests for each touched package — your new test must now PASS
+pnpm --filter <pkg> test
```
-**If a gate fails:**
-- Read the error carefully
-- Fix it if the failure is caused by your change
-- Re-run the failed gate
-- If the failure is pre-existing (unrelated to your change), note it in the output but don't fix it
-
-## 5. Self-review
+Gate failed? Read the error. Caused by your change → fix and re-run. Clearly
+pre-existing and unrelated → note it in the output, don't chase it. Two failed
+fix attempts on the same gate → STOP, report BLOCKED.
-Before declaring ready, check:
+## Step 5: Self-review
| Check | Question |
|-------|----------|
-| **Scope** | Did I change only what the brief called for? |
-| **companyId** | Does every new/modified query scope by `companyId` where needed? |
-| **BC contract** | Does the change touch any FROZEN surface? Any STABLE surface without deprecation? |
-| **Callers** | Did I update all callers of any changed signature? |
-| **Tests** | Does my test actually fail without the fix? |
-| **Imports** | Am I using `~/*` and `@carbon/*` correctly? |
-| **Patterns** | Does my code match the style of surrounding code? |
-
-## 6. Output
+| Scope | Did I change only what the brief called for? |
+| Red→green | Did I watch the test fail before the fix and pass after? |
+| companyId | Every new/modified query scoped? |
+| Callers | Every caller of a changed signature updated? |
+| BC | Any FROZEN surface touched? STABLE without deprecation? |
+| Patterns | Does the code read like its neighbors? |
+| Leftovers | No debug logging, commented-out code, or stray files in the diff? |
-Produce exactly this structure:
+## Step 6: Output
```markdown
## Fix Summary
+**Status:** READY | BLOCKED <if BLOCKED: what and why>
+**Root-cause brief:** <path/link>
+**Files changed:** <path — what>
+**Regression test:** <path — failed before fix (output), passes after (output)>
+**Gates:** generate:types PASS|SKIP · biome PASS · typecheck(<pkgs>) PASS · test(<pkgs>) PASS
+**BC assessment:** NONE | <surfaces and how they comply>
+**Summary:** <2–3 sentences>
+```
-**Status:** READY | BLOCKED
-<if BLOCKED: explain what's blocking and what's needed>
-
-**Root-cause brief:** <link or path to the brief>
-
-**Files changed:**
-- `path/to/file.ts` — <what changed>
-- `path/to/other.ts` — <what changed>
-
-**Tests added:**
-- `path/to/test.ts` — <what it verifies>
+Then hand off to `/check-and-commit`.
-**Validation gates:**
-- generate:types — PASS | SKIP (no schema change)
-- lint — PASS
-- typecheck — PASS
-- test — PASS
+## Guardrails
-**BC assessment:** NONE | <list touched surfaces and how they comply>
+- **No commit, no push, no PR** from this skill.
+- **No scope creep** — related bugs get one line in the output, not a fix.
+- **No guessing** — if the brief is unclear or you disagree with it, STOP and
+ say so. Don't implement a fix you don't believe in.
-**Summary:** <2-3 sentences on what was fixed and how>
-```
-
-## Guardrails
+Red flags — thinking any of these means the process is off the rails; STOP:
-- **No commit, no push, no PR.** The conductor or `/open-pr` handles that. Your job ends at "code is ready, gates pass."
-- **No scope creep.** If you discover a related bug, note it in the output — don't fix it.
-- **No guessing.** If the root-cause brief is unclear or you disagree with it, stop and say so. Don't implement a fix you don't believe in.
-- **Minimal blast radius.** Prefer the fix that touches the fewest files and changes the fewest lines while being correct and complete.
+- "the fix is obvious, I'll write the test after" (a test written after passes
+ immediately and proves nothing — Step 2 comes first)
+- "while I'm here, I'll clean this up too"
+- "the test is hard to write, I'll just verify manually" (report BLOCKED instead)
+- "the brief is probably right" (if the code you read doesn't confirm the cause,
+ go back to /root-cause)
diff --git a/.ai/skills/improve/SKILL.md b/.ai/skills/improve/SKILL.md
index d15bb8ced3..f73a05ce73 100644
--- a/.ai/skills/improve/SKILL.md
+++ b/.ai/skills/improve/SKILL.md
@@ -40,7 +40,7 @@ Map the territory before judging it. **In Carbon, recon means reading the `.ai/r
- `.ai/rules/conventions-*.md` — forms, services, ui, database conventions. Plans must tell the executor to **match** these.
- `.ai/lessons.md` — hard-won corrections (RLS pattern, upsert audit-field clobbering, `.merge()` after `.refine()`, `accountId` not `accountNumber`, enum conventions, etc.). **A finding that contradicts a lesson is by-design — do not report it.**
- `.ai/rules/workflow-*.md` — `workflow-database-migration.md`, `workflow-edge-function.md`, `workflow-event-system.md`. Any plan touching these areas must cite and follow the workflow.
- - `.ai/recommendations/*.md` — existing forward-looking proposals (don't duplicate them in Direction).
+ - `.ai/specs/` + `.ai/plans/improve/` (if present) — existing specs, plans, and previously rejected findings (don't duplicate them in Direction).
- Identify the exact **build / test / lint / typecheck** commands (these become verification gates in every plan). From recon of `package.json` + `turbo.json`:
- Install: `pnpm install`
- Typecheck (SCOPED ONLY): `turbo run typecheck --filter=<pkg>`
@@ -92,7 +92,7 @@ Present the vetted findings table to the user, ordered by leverage (impact ÷ ef
| # | Finding | Category | Impact | Effort | Risk | Evidence |
-Present **direction findings separately**, after the table — 2–4 grounded suggestions max, each with evidence and trade-offs in two or three sentences. Cross-check `.ai/recommendations/` first so you don't re-propose what's already on file.
+Present **direction findings separately**, after the table — 2–4 grounded suggestions max, each with evidence and trade-offs in two or three sentences. Cross-check `.ai/specs/` and `.ai/plans/improve/` first so you don't re-propose what's already on file.
Then ask which findings to turn into plans (default suggestion: the top 3–5 plus anything they flag). Surface **dependency ordering** (e.g. "characterization tests for `@carbon/<pkg>` must land before the refactor"). Wait for the selection. Do not write 30 plans nobody asked for. If running non-interactively, write plans for the top 3–5 by leverage and record that default in `.ai/plans/improve/README.md`.
@@ -129,7 +129,7 @@ Finish by writing `.ai/plans/improve/README.md` with the recommended execution o
- `quick` / `deep` (anywhere) → effort level for the audit; see the table in Phase 2. Composes with everything (`quick security`, `deep --issues`). Default `standard`.
- With a focus argument (e.g. `security`, `perf`, `tests`, `migrations`) → run Recon, then audit only that category, then plan.
- `branch` → audit only the current branch's changes: scope = files changed since the merge-base with `main` (`git diff --name-only $(git merge-base origin/main HEAD)..HEAD`) plus their direct importers/callers. Light recon, all categories, usually no subagents. **Tag every finding `introduced` (by this branch) or `pre-existing`** — separate them in the table. If on `main` or zero commits ahead, say so and offer a full audit.
-- `next` (or `features`, `roadmap`) → run Recon, then audit only the direction category in more depth: 4–6 grounded suggestions, each with evidence, trade-offs, coarse effort. Selected ones become design/spike plans. Check `.ai/recommendations/` first.
+- `next` (or `features`, `roadmap`) → run Recon, then audit only the direction category in more depth: 4–6 grounded suggestions, each with evidence, trade-offs, coarse effort. Selected ones become design/spike plans. Check `.ai/specs/` and `.ai/plans/improve/` first.
- `plan <description>` → skip the audit; the user already knows what they want. Run Recon (read the relevant `.ai/rules/` + `.ai/rules/conventions-*`), investigate just enough to specify it properly, write a single plan. Resolve ambiguity from the codebase first; only what's left becomes questions, asked one at a time with a recommended answer.
- `review-plan <file>` → critique an existing plan in `.ai/plans/improve/` against the template's standards and tighten it. If you authored it this session, also have a fresh-context subagent read it cold and report ambiguities.
- `execute <plan>` → dispatch a cheaper executor subagent on one plan (isolated worktree), then review its diff like a tech lead — re-run done criteria, check scope, read the code — and render a verdict. Treat the diff as untrusted until reviewed. Requires a host that can spawn worktree subagents. **Read [references/closing-the-loop.md](references/closing-the-loop.md) before the first dispatch.**
diff --git a/.ai/skills/improve/references/audit-playbook.md b/.ai/skills/improve/references/audit-playbook.md
index ae04c7fc31..6fce2eda9e 100644
--- a/.ai/skills/improve/references/audit-playbook.md
+++ b/.ai/skills/improve/references/audit-playbook.md
@@ -97,10 +97,10 @@ Lowest default priority — only flag where absence has a concrete cost:
## 9. Direction — features & where to take this next
-Forward-looking: what this codebase wants to become. **Grounding rule:** every suggestion must cite evidence from the repo — a suggestion that could apply to any ERP ("add AI", "add dark mode") is noise. **Check `.ai/recommendations/` first** and never re-propose what's on file. Sources of grounded signal:
+Forward-looking: what this codebase wants to become. **Grounding rule:** every suggestion must cite evidence from the repo — a suggestion that could apply to any ERP ("add AI", "add dark mode") is noise. **Check `.ai/specs/` and `.ai/plans/improve/` first** and never re-propose what's on file. Sources of grounded signal:
- **Unfinished intent**: TODO/FIXME clusters around one theme, feature flags never rolled out, stubbed modules, abandoned mid-feature work in git history.
-- **Stated-but-undelivered**: items in `.ai/recommendations/`, `.ai/scratch/tasks/*.md`, or rule docs describing intended direction the code hasn't caught up to.
+- **Stated-but-undelivered**: unimplemented specs in `.ai/specs/`, open items in `.ai/plans/improve/`, or rule docs describing intended direction the code hasn't caught up to.
- **Surface asymmetries**: one-directional pairs (export without import, create without bulk-create, a module with CRUD-minus-one), a capability one app has that the parallel app lacks (erp ↔ mes).
- **The adjacent possible**: capabilities the existing architecture makes disproportionately cheap — an MCP tool one service-function away (Carbon already exposes ~1187 MCP tools), a report one query from the existing service layer, an integration the data model already supports.
- **Friction worth productizing**: things users evidently do by hand around Carbon.
diff --git a/.ai/skills/improve/references/plan-template.md b/.ai/skills/improve/references/plan-template.md
index 1cde0c55bb..8f0a669e4d 100644
--- a/.ai/skills/improve/references/plan-template.md
+++ b/.ai/skills/improve/references/plan-template.md
@@ -85,10 +85,11 @@ NEVER run DB migrate/seed/rebuild commands.)
executor's environment. Skip the section otherwise.)
- Carbon skills the executor should invoke if available, and for what:
- "use the `forms` skill when adding the validator in step 2";
- "use the `database-transactions` skill for the atomic write in step 3".
+ "use the `test-driven-development` skill for the regression test in step 2";
+ "use the `check-and-commit` skill to gate the final commit".
- Workflow docs worth reading first by path:
- "`.ai/rules/workflow-database-migration.md` before writing the migration in step 4".
+ "`.ai/rules/workflow-database-migration.md` before writing the migration in step 4";
+ "`.ai/rules/conventions-forms.md` before adding the validator in step 2".
## Scope
diff --git a/.ai/skills/login/SKILL.md b/.ai/skills/login/SKILL.md
index e506f856d2..36bf0fd411 100644
--- a/.ai/skills/login/SKILL.md
+++ b/.ai/skills/login/SKILL.md
@@ -1,23 +1,28 @@
---
name: login
-description: Log into the local Carbon ERP dev server using agent-browser and DEV_BYPASS_EMAIL. Use before any browser automation that requires an authenticated session.
+description: Log into the local Carbon ERP dev server with agent-browser using the DEV_BYPASS_EMAIL bypass. Use before any browser automation that needs an authenticated session (/test, /smoke-test, manual verification). Requires a running dev stack (crbn up). Building block — it leaves the session open for the caller.
---
-# Login
+# login — authenticate the local browser session
-Authenticate against the local Carbon ERP dev environment using the `DEV_BYPASS_EMAIL` bypass. This skill is a building block — other skills (e.g. `/smoke-test`) invoke it before doing authenticated work.
+Authenticate against the local Carbon dev environment via `DEV_BYPASS_EMAIL`.
+Other skills (`/test`, `/smoke-test`) invoke this before authenticated work.
## Prerequisites
-- Dev server running (`pnpm dev` or `crbn up`)
-- `[email protected]` set in `.env.local` (added automatically by `crbn up`)
-- The `[email protected]` user seeded in the database (done automatically by `crbn up`)
+- Dev server running (`crbn up`; plain `pnpm dev` also works)
+- `[email protected]` in `.env.local` and the `[email protected]`
+ user seeded — both are done automatically by `crbn up`
-## Procedure
+## Steps
### 1. Resolve the ERP URL
-Read `.env.local` in the project root and extract the `ERP_URL` value. This varies per worktree.
+```bash
+grep '^ERP_URL' .env.local
+```
+
+The value varies per worktree — always read it; never assume a URL or port.
### 2. Open the login page
@@ -25,32 +30,38 @@ Read `.env.local` in the project root and extract the `ERP_URL` value. This vari
agent-browser open ${ERP_URL}/login && agent-browser wait --load networkidle && agent-browser snapshot -i
```
+(If `wait --load networkidle` times out — dev HMR keeps sockets open — use
+`sleep 3` then `agent-browser snapshot -i` instead.)
+
### 3. Fill the email and submit
-Find the email input and the sign-in button from the snapshot refs:
+From the snapshot, find the email input ref and the sign-in button ref:
```bash
agent-browser fill @eN "[email protected]"
-agent-browser click @eN && agent-browser wait --load networkidle
+agent-browser click @eM && agent-browser wait --load networkidle
```
-### 4. Verify login succeeded
+### 4. Verify — do not assume
```bash
agent-browser snapshot -i
```
-Confirm the page:
-- Redirected to `/x` (the authenticated dashboard)
-- Shows a greeting like "Good afternoon, Test" or "Good morning, Test"
-- Displays module cards (Accounting, Sales, Inventory, etc.)
+Login **succeeded** only if the page:
+- redirected to `/x` (the authenticated dashboard), and
+- shows a greeting ("Good morning, Test" / "Good afternoon, Test") and module cards.
-If the snapshot instead shows "Authentication Error" or remains on `/login`, login **failed** — stop and report the error.
+If the snapshot shows "Authentication Error" or is still on `/login` → login
+**failed**. STOP and report the snapshot content; do not retry blindly.
## Output
-After successful login the browser session is authenticated. Subsequent `agent-browser` commands in the same session will carry the auth cookies. Do **not** call `agent-browser close` — leave the session open for the caller.
+The browser session is authenticated; subsequent `agent-browser` commands carry
+the auth cookies. **Do not run `agent-browser close`** — leave the session open
+for the caller.
-## Navigating to the MES
+## MES
-The MES app is at a separate URL. Read `MES_URL` from `.env.local` to navigate there. The same auth cookies apply — no separate login is needed.
+The MES app is a separate URL: read `MES_URL` from `.env.local` and navigate
+there. The same cookies apply — no separate login.
diff --git a/.ai/skills/plan/SKILL.md b/.ai/skills/plan/SKILL.md
index 64c8521226..4550a6df9c 100644
--- a/.ai/skills/plan/SKILL.md
+++ b/.ai/skills/plan/SKILL.md
@@ -1,252 +1,134 @@
---
name: plan
-description: Create detailed implementation plans from design specs. Use after brainstorming to create step-by-step implementation plans. Each task is 2-5 minutes of work with exact code and commands. Triggers on "plan the implementation", "create a plan for", "write the implementation plan", or after /brainstorm approval.
+description: Turn a finalized spec into a step-by-step implementation plan at .ai/plans/{YYYY-MM-DD}-{slug}.md, where every task has exact file paths, exact commands, and a verification with expected output. Use when asked to "plan the implementation", "create a plan", or after a spec's open questions are resolved. Do not use while the spec still has unresolved open questions, and do not use it to design — design happens in /spec-writing.
---
-# Plan: Implementation Planning
+# plan — implementation plan from a spec
-Transform design specifications into detailed, executable implementation plans. Each task is bite-sized (2-5 minutes) with complete code — no pseudocode, no "fill in details."
+Input: a finalized spec (`.ai/specs/{date}-{slug}.md` with zero unresolved open
+questions) or, for small changes, an explicit user description. Output: a plan at
+`.ai/plans/{YYYY-MM-DD}-{slug}.md` that `/execute` can follow mechanically.
-**Announce at start:** "I'm using the plan skill to create the implementation plan."
+Write the plan for the **weakest plausible executor**: an agent with no memory of
+this session. Every task must be executable from the plan text alone.
-## Prerequisites
+**Announce at start:** "Using the plan skill — turning the spec into an
+implementation plan."
-Before planning:
-1. A design spec exists (from `/brainstorm` or provided by user)
-2. The design has been approved
-3. Key decisions are documented
+## Step 1: Check prerequisites
-If no spec exists, suggest running `/brainstorm` first.
+1. Read the spec. If any Open Question is unchecked → **STOP** and return to
+ `/spec-writing` Step 7. Do not plan around an open question.
+2. Read `.ai/lessons.md` and the module `AGENTS.md` for every module the spec
+ touches.
+3. Read the matching guides for the work in the plan (from the root `AGENTS.md`
+ Task Router). At minimum:
+ - migrations → `.ai/rules/workflow-database-migration.md`
+ - services → `.ai/rules/conventions-services.md`
+ - forms/UI → `.ai/rules/conventions-forms.md` + `packages/form/AGENTS.md`
+ - database access → `.ai/rules/database-patterns.md`
-## Workflow
+## Step 2: Decompose into tasks
-```
-┌──────────────┐ ┌──────────────┐ ┌──────────────┐ ┌──────────────┐
-│ 1. Load Spec │───▶│ 2. Decompose │───▶│ 3. Write │───▶│ 4. Review │
-│ │ │ Into Tasks │ │ Each Task │ │ & Approve │
-└──────────────┘ └──────────────┘ └──────────────┘ └──────────────┘
-```
-
-## Step 1: Load the Design Spec
-
-Read the design spec from `.ai/research/[feature-name]-design.md`.
-
-Extract:
-- Data model changes
-- Workflows to implement
-- Edge cases to handle
-- Integration points
-
-## Carbon-Specific References
-
-**IMPORTANT:** Before writing tasks, load these Carbon-specific resources:
-
-| Task Type | Reference | What It Covers |
-|-----------|-----------|----------------|
-| Database migrations | `.ai/rules/workflow-database-migration.md` | Multi-tenancy, RLS, id(), audit columns, indexes |
-| Forms & UI | `/forms` skill | ValidatedForm, zod validators, form components |
-| Database writes | `/database-transactions` skill | Kysely transactions, atomic operations |
+- One task = one verifiable unit of work (a migration, a service function + its
+ test, a route + form, a UI component). If a task can't be verified by a single
+ command or a single browser check, split it.
+- Default order: migration → `pnpm run generate:types` → models (zod) → service
+ functions (+ unit tests) → routes/actions → UI → browser verification.
+- For every UI task, name the **precedent**: the existing Carbon screen or
+ component to copy from (file path). Do not design UI from concepts — grep
+ `packages/react/src/` and `apps/erp/app/components/` first.
+- Mark tasks that are independent of each other — `/execute` may run them as
+ parallel subagents.
-### Migration Tasks Must Follow
+## Step 3: Write each task
-From `.ai/rules/workflow-database-migration.md`:
-- Use `id()` for primary keys, not UUID
-- Include `companyId` with composite primary key `("id", "companyId")`
-- Add standard audit columns (createdBy, createdAt, updatedBy, updatedAt)
-- Use standardized RLS policy names (SELECT, INSERT, UPDATE, DELETE)
-- Never use `000000` as HHMMSS in migration filename (use random digits)
-- Update corresponding `.models.ts` with zod validators
+Every task uses exactly this shape:
-### Form Tasks Must Follow
-
-Invoke `/forms` skill to get:
-- ValidatedForm patterns
-- Zod validator conventions
-- Form component usage
-- Action handler patterns
-
-## Step 2: Decompose Into Tasks
-
-### 2.1 Task Granularity
-
-Each task should be **2-5 minutes of work** representing **one discrete action**:
-
-Good task:
-```
-Task 1: Create lot table migration
-- Write migration file
-- Run migration
-- Verify table exists
-```
+````markdown
+## Task N: {imperative title}
-Bad task:
-```
-Task 1: Implement lot tracking
-- Create tables, services, routes, UI...
-```
-
-### 2.2 Task Ordering
-
-Order tasks for TDD:
-1. Database migrations
-2. Types and interfaces
-3. Service layer (with tests)
-4. Route handlers (with tests)
-5. UI components
-6. Integration tests
-
-### 2.3 Dependencies
-
-Identify which tasks depend on others. Independent tasks can be parallelized with subagents.
-
-## Step 3: Write Each Task
-
-For each task, provide:
-
-### 3.1 Files Section
-
-```markdown
+**Depends on:** {task numbers, or "none"}
**Files:**
-- Create: `packages/database/supabase/migrations/NNNN_add_lots.sql`
-- Modify: `packages/database/src/types.ts`
-- Test: `apps/erp/app/modules/inventory/__tests__/lots.test.ts`
-```
-
-### 3.2 Numbered Steps
+- Create: `{exact path}`
+- Modify: `{exact path}` — {what changes}
+- Copy from (precedent): `{exact path of the exemplar}`
-```markdown
**Steps:**
-
-1. Create migration file at `packages/database/supabase/migrations/20240115120000_add_lot_table.sql`:
- ```sql
- CREATE TABLE lot (
- id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
- ...
- );
- ```
-
-2. Run migration:
- ```bash
- pnpm db:migrate
- ```
-
-3. Verify:
- ```bash
- psql -c "SELECT * FROM lot LIMIT 1;"
- # Expected: empty result, no error
- ```
-
-4. Commit:
- ```bash
- git add -A && git commit -m "feat(inventory): add lot table migration"
- ```
-```
-
-### 3.3 Requirements
-
-- **Exact file paths** — No "in the appropriate directory"
-- **Complete code** — No pseudocode or "add appropriate logic"
-- **Exact commands** — With expected output
-- **No placeholders** — No TBD, "similar to Task N", or "fill in"
-
-## Step 4: Review & Approve
-
-### 4.1 Save the Plan
-
-Save to `.ai/plans/[feature-name]-plan.md`:
-
-```markdown
-# [Feature] Implementation Plan
-
-## Overview
-- **Design Spec:** `.ai/research/[feature-name]-design.md`
-- **Tasks:** N tasks, estimated M minutes
-- **Dependencies:** [diagram or list]
-
-## Task 1: [Title]
-**Files:**
-- ...
-
-**Steps:**
-1. ...
-
-## Task 2: [Title]
-...
+1. {exact instruction; include full SQL for migrations, function signatures for
+ services, and the exemplar to copy for UI}
+2. ...
+
+**Verify:**
+```bash
+{exact command}
+# Expected: {what the output must contain}
```
-### 4.2 Self-Review Checklist
-
-Before presenting:
-- [ ] Every task is 2-5 minutes
-- [ ] No pseudocode or placeholders
-- [ ] All file paths are exact
-- [ ] All commands include expected output
-- [ ] Tasks follow TDD order
-- [ ] Dependencies are clear
-- [ ] Migration tasks follow `.ai/rules/workflow-database-migration.md`
-- [ ] Form tasks reference `/forms` skill patterns
+**Out of scope:** {things that look related but must NOT be touched}
+````
-### 4.3 Get Approval
+Hard rules for task content:
-Present the plan and wait for explicit approval.
+- **Migrations**: create with `pnpm db:migrate:new <name>` (never hand-pick a
+ timestamp; never `000000` as HHMMSS). SQL must use `id('prefix')` defaults,
+ `companyId` + composite PK `("id", "companyId")`, audit columns
+ (`createdBy/createdAt/updatedBy/updatedAt`), RLS policies per
+ `.ai/rules/conventions-database.md`, and be idempotent (`IF NOT EXISTS` /
+ `DROP ... IF EXISTS` guards). Never backdate a timestamp older than the newest
+ migration on `main`. The task after any migration is always
+ `pnpm run generate:types`.
+- **Verification is scoped.** Typecheck a package with
+ `pnpm exec turbo run typecheck --filter=<pkg>` (e.g. `--filter=erp`,
+ `--filter=@carbon/react`). Never plan a whole-repo `pnpm typecheck` — it OOMs.
+ Tests: `pnpm --filter <pkg> test`.
+- **No placeholders.** No "TBD", no "similar to Task 3", no "add appropriate
+ logic". If you can't specify it, the spec is incomplete — go back.
+- **Escape hatches.** Where a task rests on an assumption, add: "If {assumption}
+ turns out false, STOP and report — do not improvise."
-## Output
+Red flags — if you catch yourself writing any of these, the task is
+under-specified; fix it before moving on:
-| Artifact | Location |
-|----------|----------|
-| Implementation plan | `.ai/plans/[feature-name]-plan.md` |
+- "similar to the previous task" / "as appropriate" / "etc."
+- a Verify block with no expected output
+- a UI task with no precedent file path
+- a migration task without a `generate:types` follow-up
-## Next Step
+## Step 4: Write the plan file
-After approval, hand off to `/execute` to run the plan.
-
-## Plan Format Reference
+Save to `.ai/plans/{YYYY-MM-DD}-{slug}.md` (today's date, same slug as the spec):
```markdown
-# [Feature] Implementation Plan
+# {Feature} — implementation plan
+
+**Spec:** .ai/specs/{date}-{slug}.md
+**Research:** .ai/research/{slug}.md
+**Branch:** {branch name}
-## Overview
-- **Design Spec:** [path]
-- **Research:** [path]
-- **Estimated Time:** N tasks × 3 min avg = ~M minutes
-- **Branch:** feature/[feature-name]
+## Progress
+- [ ] Task 1: {title}
+- [ ] Task 2: {title}
## Dependencies
-Task 2 depends on Task 1 (migration must exist)
-Tasks 3-5 are independent (can parallelize)
+{`Task 2 needs Task 1 (types)`, `Tasks 4–5 independent`}
---
+{tasks}
+```
-## Task 1: Create database migration
-
-**Files:**
-- Create: `packages/database/supabase/migrations/20240115120000_add_X.sql`
-
-**Steps:**
-
-1. Create migration:
- ```sql
- -- Full SQL here
- ```
-
-2. Run:
- ```bash
- pnpm db:migrate
- ```
-
-3. Verify:
- ```bash
- command
- # Expected output
- ```
+The Progress checklist is the live tracker — `/execute` checks items off in this
+file. Do not create a separate todo file.
-4. Commit:
- ```bash
- git add -A && git commit -m "feat(module): add X table"
- ```
+## Step 5: Self-check, then present
----
+- [ ] Every task has exact paths, exact commands, expected output
+- [ ] Every migration task follows the hard rules above and is followed by a
+ `generate:types` step
+- [ ] Every UI task names its precedent file
+- [ ] No whole-repo typecheck anywhere in the plan
+- [ ] Every acceptance criterion in the spec is covered by at least one task,
+ and the final task is browser verification via `/test` for user-facing work
-## Task 2: Add TypeScript types
-...
-```
+Present the plan path and a one-paragraph summary. Wait for approval, then hand
+off to `/execute`.
diff --git a/.ai/skills/pr-explainer/SKILL.md b/.ai/skills/pr-explainer/SKILL.md
index 41eb120003..3e561b401e 100644
--- a/.ai/skills/pr-explainer/SKILL.md
+++ b/.ai/skills/pr-explainer/SKILL.md
@@ -1,151 +1,78 @@
---
name: pr-explainer
-description: Use when creating an approachable, self-contained HTML review aid for a pull request; explaining what changed, why it matters, how it works, and how it fits into the broader system; turning PR diffs, commits, tests, and architecture context into a local `.pr-review/` HTML page for reviewers; or helping reviewers understand complex code changes without dumping the full diff.
+description: Build a self-contained HTML review aid at .pr-review/{branch}.html that teaches a reviewer what a PR changes and why — problem, system context, before/after flow, focused diffs, verification evidence, takeaway. Use when asked to explain a PR, help reviewers understand a complex change, or produce a review page for a branch. Do not use it as a substitute for review itself (/self-review) or instead of a PR description.
---
-# PR Explainer
+# pr-explainer — teach the PR in one HTML page
-Create a local, self-contained HTML page that teaches a reviewer the PR story: what changed, why it matters, how it works, how it fits into the system, and how it was verified.
+Output: one self-contained HTML file in `.pr-review/` (gitignored) that a
+reviewer can open locally and understand the PR without GitHub. It supplements
+the real diff review; it never replaces it.
-## Required workflow
+**Announce at start:** "Using the pr-explainer skill — building the review page
+for {branch}."
-1. **Understand the PR before writing HTML**
- - Collect PR title/number, branch, link if available, base branch, commit range, changed files, and verification already performed.
- - Inspect the current state with `git status --short`.
- - Inspect recent commits with `git log --oneline -n 10`.
- - Inspect scope with `git diff <base>...HEAD --stat` and `git diff <base>...HEAD`.
- - If one commit carries the main change, inspect it with `git show --stat <commit>` and `git show <commit>`.
+## Step 1: Gather the facts (before writing any HTML)
-2. **Find the explanation path**
- - Do not explain files in raw diff order.
- - Teach the change in this order when possible:
- 1. problem,
- 2. system context,
- 3. before/after data or control flow,
- 4. key code changes,
- 5. proof from tests/builds/manual checks,
- 6. reviewer takeaway.
- - Classify changed files as core behavior, plumbing/integration, tests, release metadata, or incidental noise.
- - Highlight only files that help explain the PR.
-
-3. **Write for approachability**
- - Use plain language, short sections, concrete before/after examples, small focused snippets, diagrams, tables, and callouts.
- - Explain the problem before implementation details.
- - Define acronyms or package-specific terms before using them.
- - Avoid dumping the full diff or assuming the reviewer already knows internal context.
-
-4. **Create a local self-contained HTML file**
- - Put generated files in `.pr-review/`.
- - Use one HTML file containing all CSS and content.
- - Do not commit `.pr-review/` by default.
- - Prefer repo ignore rules or `.git/info/exclude` so generated review pages stay out of commits.
-
-## Recommended HTML structure
-
-Use this structure unless the PR clearly needs a different teaching order:
-
-1. **Hero**
- - PR number/title, one-sentence summary, branch/link/status.
- - Small metrics: files changed, tests added, packages affected.
-
-2. **Problem**
- - Previous behavior.
- - Why it was wrong, confusing, missing, or risky.
-
-3. **System Context**
- - Where the change sits in the product or architecture.
- - Upstream callers, downstream behavior, and why this is the right layer.
- - Behavior intentionally not changed.
-
-4. **Before/After Flow**
- - Visual old path vs. new path when the PR changes flow, state, ownership, permissions, request handling, data transformation, or component relationships.
-
-5. **Code Walkthrough**
- - Step-by-step explanation path.
- - Focused diffs for important files only.
- - Explain what each snippet accomplishes and why it is necessary.
-
-6. **Tests / Verification**
- - Tests added or updated.
- - Commands run for tests, build, typecheck, lint, or manual verification.
- - Known unrelated warnings or failures, if any.
-
-7. **Reviewer Takeaway**
- - The shortest useful mental model of the PR.
- - What the reviewer should focus on while reviewing the actual diff.
-
-## Diagrams
-
-Add diagrams when they reduce cognitive load. Prefer simple HTML/CSS diagrams over external dependencies.
-
-Good diagram types:
-
-- Request flow: Client → Server → Handler → Service → Result
-- Before/after path: broken path vs. fixed path
-- Ownership map: package/module responsibility boundaries
-- Data transformation: input → normalized form → output
-- State machine: pending → running → complete/error
-
-Each diagram must answer: “What does this help the reviewer understand faster?”
-
-## Focused diff snippets
-
-Show snippets along the explanation path, not giant patches. Each important snippet should include:
-
-- file path,
-- relevant added/removed lines only,
-- visual styling for additions/removals,
-- a short explanation,
-- connection back to the PR story.
-
-Use this pattern:
-
-```html
-<div class="diff">
- <div class="diff-title">packages/example/src/file.ts</div>
- <pre>
-<span class="del">- old behavior</span>
-<span class="add">+ new behavior</span>
- </pre>
-</div>
+```bash
+BASE=$(git merge-base origin/main HEAD)
+git status --short # current state
+git log --oneline $BASE..HEAD # the commits
+git diff $BASE...HEAD --stat # scope + the metrics numbers
+git diff $BASE...HEAD # read the whole diff
+gh pr view --json number,title,url 2>/dev/null # if a PR exists
```
-A reviewer should understand the PR without opening GitHub, but the page should not replace the final full diff review.
+Also collect: verification already performed this session (test runs, browser
+checks, screenshots) — the page must report real evidence, not aspirations.
-## Verification requirements
+## Step 2: Classify files and find the teaching order
-End with proof. Include exact commands when available, for example:
+Classify every changed file: **core behavior** · plumbing/integration · tests ·
+metadata/release · incidental noise. Only core behavior and load-bearing
+plumbing get walkthrough sections; the rest gets at most one line.
-```text
-pnpm --filter @scope/package test path/to/test.ts -- --run
-pnpm turbo build --filter ./packages/package
-```
-
-If verification was not run, say so clearly and list the recommended commands.
-
-## Final checklist
+Teach in this order (never raw diff order): problem → system context →
+before/after flow → key code changes → verification → reviewer takeaway.
-Before calling the page done, confirm it has:
+## Step 3: Fill the template
-- clear one-sentence summary,
-- problem statement,
-- before/after explanation,
-- broader system context,
-- visual diagram where useful,
-- step-by-step code walkthrough,
-- focused diffs with file paths,
-- tests and verification commands,
-- reviewer takeaway,
-- self-contained HTML/CSS,
-- stored in `.pr-review/`,
-- not staged or committed unless explicitly requested.
-
-## Default output
-
-When asked to create a PR explainer, produce or update a `.pr-review/*.html` file and summarize:
+```bash
+mkdir -p .pr-review
+cp .ai/skills/pr-explainer/assets/template.html .pr-review/{branch}.html
+```
-1. output path,
-2. PR story covered,
-3. key sections included,
-4. verification evidence included,
-5. whether `.pr-review/` remains untracked or excluded.
\ No newline at end of file
+The template has one section per teaching step, styled and ready — every spot
+to fill is marked with a `<!-- FILL: ... -->` comment. Work top to bottom:
+
+1. **Header**: PR number/title/branch/link; metrics from `--stat` (real numbers).
+2. **Problem**: previous behavior and why it was wrong/missing/risky, with a
+ concrete example.
+3. **System context**: upstream callers, downstream effects, why this layer;
+ name what is intentionally unchanged.
+4. **Before → after flow**: duplicate the `.flow` rows, mark changed nodes with
+ `class="node hot"`. Delete the section if the PR changes no flow. Put the
+ one counterintuitive fact in the callout.
+5. **Code walkthrough**: one `.diff` block per important file — only the lines
+ that matter (`.add` / `.del` / `.ctx` spans), each followed by a short
+ paragraph: what it accomplishes and how it connects to the story.
+6. **Tests & verification**: exact commands run and their results. If a check
+ was not run, say so and list the recommended command — never imply
+ verification that didn't happen.
+7. **Reviewer takeaway**: the shortest useful mental model + what to focus on
+ in the real diff.
+
+Writing rules: plain language; define repo-specific terms at first use; small
+focused snippets over full patches; delete any template section that doesn't
+apply (empty sections are noise).
+
+## Step 4: Check and hand off
+
+- [ ] Every `<!-- FILL -->` comment is either filled or its section deleted
+- [ ] Metrics match `git diff $BASE...HEAD --stat`
+- [ ] Every claim in Verification corresponds to a command actually run
+- [ ] File opens standalone (no external assets) — it's one HTML file
+- [ ] `.pr-review/` stays untracked (`git status` shows nothing staged from it)
+
+Report: the output path, the PR story covered, and any verification gaps the
+page discloses.
diff --git a/.ai/skills/pr-explainer/assets/template.html b/.ai/skills/pr-explainer/assets/template.html
new file mode 100644
index 0000000000..e17ce786c1
--- /dev/null
+++ b/.ai/skills/pr-explainer/assets/template.html
@@ -0,0 +1,153 @@
+<!doctype html>
+<html lang="en">
+<head>
+<meta charset="utf-8" />
+<meta name="viewport" content="width=device-width, initial-scale=1" />
+<!-- FILL: page title -->
+<title>PR #000 — Title</title>
+<style>
+ :root {
+ --bg: #fbfbf9; --panel: #ffffff; --ink: #262323; --faint: rgba(38,35,35,.62);
+ --hairline: #e7e7e3; --accent: #1e84b0; --code-bg: #21201d; --code-ink: #f2f0ec;
+ --add-bg: #e4f8da; --add-ink: #2c5e14; --del-bg: #fde5e2; --del-ink: #8c2318;
+ --callout-bg: #dff5ff; --callout-border: #a9daf3;
+ }
+ * { box-sizing: border-box; }
+ body { margin: 0; background: var(--bg); color: var(--ink);
+ font: 16px/1.65 ui-sans-serif, system-ui, -apple-system, "Segoe UI", sans-serif; }
+ main { max-width: 860px; margin: 0 auto; padding: 48px 24px 96px; }
+ h1 { font-size: 28px; line-height: 1.25; margin: 8px 0 4px; }
+ h2 { font-size: 20px; margin: 48px 0 12px; padding-top: 24px; border-top: 1px solid var(--hairline); }
+ h3 { font-size: 16px; margin: 24px 0 8px; }
+ p, li { max-width: 72ch; }
+ a { color: var(--accent); }
+ .kicker { color: var(--faint); font-size: 13px; letter-spacing: .06em; text-transform: uppercase; }
+ .summary { font-size: 18px; color: var(--faint); margin-top: 0; }
+ .metrics { display: flex; flex-wrap: wrap; gap: 8px; margin: 16px 0 0; padding: 0; list-style: none; }
+ .metrics li { border: 1px solid var(--hairline); background: var(--panel);
+ border-radius: 999px; padding: 4px 12px; font-size: 13px; color: var(--faint); }
+ .metrics b { color: var(--ink); font-weight: 600; }
+ .callout { background: var(--callout-bg); border: 1px solid var(--callout-border);
+ border-radius: 10px; padding: 12px 16px; margin: 16px 0; }
+ .callout .label { font-size: 11px; font-weight: 700; letter-spacing: .08em;
+ text-transform: uppercase; color: var(--accent); }
+ code, pre { font: 13px/1.6 ui-monospace, SFMono-Regular, Menlo, monospace; }
+ code { background: #efefeb; border-radius: 4px; padding: 1px 5px; }
+ pre { background: var(--code-bg); color: var(--code-ink); border-radius: 10px;
+ padding: 14px 16px; overflow-x: auto; }
+ pre code { background: none; padding: 0; }
+ /* Focused diff snippet */
+ .diff { border: 1px solid var(--hairline); border-radius: 10px; overflow: hidden; margin: 16px 0; }
+ .diff-title { font: 12px/1 ui-monospace, monospace; background: var(--panel);
+ border-bottom: 1px solid var(--hairline); padding: 8px 12px; color: var(--faint); }
+ .diff pre { margin: 0; border-radius: 0; background: var(--panel); color: var(--ink); }
+ .diff .add { display: block; background: var(--add-bg); color: var(--add-ink); }
+ .diff .del { display: block; background: var(--del-bg); color: var(--del-ink); }
+ .diff .ctx { display: block; color: var(--faint); }
+ /* Before/after flow diagram */
+ .flow { display: flex; flex-wrap: wrap; align-items: center; gap: 8px; margin: 12px 0; }
+ .flow .node { border: 1px solid var(--hairline); background: var(--panel);
+ border-radius: 8px; padding: 6px 12px; font-size: 14px; }
+ .flow .node.hot { border-color: var(--accent); box-shadow: 0 0 0 1px var(--accent) inset; }
+ .flow .arrow { color: var(--faint); }
+ .flow-label { font-size: 12px; font-weight: 700; letter-spacing: .06em;
+ text-transform: uppercase; color: var(--faint); margin: 16px 0 4px; }
+ table { border-collapse: collapse; width: 100%; margin: 12px 0; font-size: 14px; }
+ th, td { text-align: left; border-bottom: 1px solid var(--hairline); padding: 8px 10px; vertical-align: top; }
+ th { color: var(--faint); font-weight: 600; }
+ .takeaway { background: var(--panel); border: 1px solid var(--hairline);
+ border-radius: 12px; padding: 16px 20px; margin-top: 16px; }
+</style>
+</head>
+<body>
+<main>
+
+ <header>
+ <!-- FILL: PR number, branch, link -->
+ <p class="kicker">PR #000 · branch-name · <a href="#">github link</a></p>
+ <!-- FILL: PR title -->
+ <h1>Title of the change</h1>
+ <!-- FILL: one-sentence summary a reviewer can repeat from memory -->
+ <p class="summary">One sentence: what this PR does and why it matters.</p>
+ <ul class="metrics">
+ <!-- FILL: real numbers from git diff --stat -->
+ <li><b>0</b> files changed</li>
+ <li><b>+0 / −0</b> lines</li>
+ <li><b>0</b> tests added</li>
+ <li><b>0</b> packages touched</li>
+ </ul>
+ </header>
+
+ <section>
+ <h2>The problem</h2>
+ <!-- FILL: previous behavior; why it was wrong, confusing, missing, or risky.
+ Concrete example > abstract description. -->
+ <p></p>
+ </section>
+
+ <section>
+ <h2>Where this sits in the system</h2>
+ <!-- FILL: upstream callers, downstream effects, why this layer is the right
+ place. Name what is intentionally NOT changed. -->
+ <p></p>
+ </section>
+
+ <section>
+ <h2>Before → after</h2>
+ <!-- FILL: keep the two flows parallel so the difference jumps out.
+ Mark the changed node(s) with class="node hot". Delete if the PR
+ doesn't change a flow. -->
+ <p class="flow-label">Before</p>
+ <div class="flow">
+ <span class="node">Client</span><span class="arrow">→</span>
+ <span class="node">Handler</span><span class="arrow">→</span>
+ <span class="node hot">old behavior</span>
+ </div>
+ <p class="flow-label">After</p>
+ <div class="flow">
+ <span class="node">Client</span><span class="arrow">→</span>
+ <span class="node">Handler</span><span class="arrow">→</span>
+ <span class="node hot">new behavior</span>
+ </div>
+ <div class="callout">
+ <span class="label">Why</span>
+ <!-- FILL: the counterintuitive fact a reviewer would otherwise miss -->
+ <p></p>
+ </div>
+ </section>
+
+ <section>
+ <h2>Code walkthrough</h2>
+ <!-- FILL: one .diff block per important file, in teaching order (not diff
+ order). Each snippet: only the lines that matter, then one short
+ paragraph on what it accomplishes. Repeat the block as needed. -->
+ <h3>1. What changed first</h3>
+ <div class="diff">
+ <div class="diff-title">path/to/file.ts</div>
+ <pre><span class="del">- old line</span><span class="add">+ new line</span><span class="ctx"> unchanged context</span></pre>
+ </div>
+ <p></p>
+ </section>
+
+ <section>
+ <h2>Tests &amp; verification</h2>
+ <!-- FILL: tests added/updated and the exact commands run with results.
+ If something was NOT verified, say so and list the recommended command. -->
+ <table>
+ <tr><th>Check</th><th>Command</th><th>Result</th></tr>
+ <tr><td></td><td><code></code></td><td></td></tr>
+ </table>
+ </section>
+
+ <section>
+ <h2>Reviewer takeaway</h2>
+ <div class="takeaway">
+ <!-- FILL: the shortest useful mental model of the PR, plus what to focus
+ on while reading the real diff. -->
+ <p></p>
+ </div>
+ </section>
+
+</main>
+</body>
+</html>
diff --git a/.ai/skills/pr-splitter/SKILL.md b/.ai/skills/pr-splitter/SKILL.md
index 34eb9ed87d..16b7f87f82 100644
--- a/.ai/skills/pr-splitter/SKILL.md
+++ b/.ai/skills/pr-splitter/SKILL.md
@@ -1,113 +1,163 @@
---
name: pr-splitter
-description: Use when breaking a large, complex, messy, or hard-to-review pull request into multiple smaller PRs; planning stacked PRs; extracting independent changes from a branch; splitting mixed refactor and behavior changes; managing drift after review feedback; rebasing follow-up PRs as earlier PRs change; or preserving original branch intent while shipping incrementally.
+description: Split a large, messy, or hard-to-review pull request into smaller reviewable PRs (stacked or parallel) without losing any of the original work — snapshot the branch, extract changes non-interactively, verify each PR independently, and track drift as review feedback lands. Use when a PR is too big to review, mixes refactors with behavior changes, or needs incremental delivery. Requires committed work on a branch — commit or stash first.
---
-# PR Splitter
+# pr-splitter — break a big PR into reviewable pieces
-Preserve the original PR as source material, build smaller reviewable PRs intentionally, and track drift locally as review feedback changes the stack.
+The original branch is source material, never a casualty: snapshot it, build
+smaller PRs from it deliberately, and keep a local ledger of what went where.
-## Required workflow
+**Announce at start:** "Using the pr-splitter skill — splitting {branch} into
+smaller PRs."
-1. **Snapshot before touching history**
- - Check `git status`.
- - Create an immutable local reference to the original branch: `git branch backup/original-large-pr`.
- - Do not delete or rewrite the original branch until the split is complete.
+Never use interactive git commands (`git restore -p`, `git add -i`,
+`git rebase -i`) — they hang in this environment. Every extraction below is
+non-interactive.
-2. **Inventory the original PR**
- - Inspect `git diff --stat <base>...HEAD`, `git diff --name-only <base>...HEAD`, and `git log --oneline <base>..HEAD`.
- - Classify changes by review unit: prep/refactor, API/type changes, behavior, tests, docs, cleanup, generated/lock files.
+## Step 1: Snapshot before touching anything
-3. **Create a local scratchpad**
- - Write split notes to an uncommitted local file, preferably `.notes/pr-split.md`.
- - Ensure `.notes/` is ignored or leave it untracked. Do not commit scratchpad notes unless the user explicitly asks.
- - Track: original branch, base branch, planned PRs, files/hunks extracted, verification per PR, remaining original diff, and intentional drift from review feedback.
+```bash
+git status --porcelain # must be empty; if not, STOP — commit or stash first
+BASE=$(git merge-base origin/main HEAD)
+git branch backup/original-$(git branch --show-current)
+```
-4. **Choose the split shape**
- - Use stacked PRs when later work depends on earlier work.
- - Use parallel PRs only when changes are truly independent.
- - Use foundation + parallel follow-ups when one shared prep change unlocks independent work.
+Do not delete or rewrite the original branch until the split has fully shipped.
-5. **Extract changes safely**
- - Prefer fresh branches from the correct base plus selective restore over rewriting messy history.
- - Use path-level extraction for clean file ownership: `git checkout backup/original-large-pr -- path/to/file`.
- - Use hunk-level extraction for mixed files: `git restore -p --source backup/original-large-pr -- path/to/file`.
- - Keep each PR independently buildable and reviewable.
+## Step 2: Inventory the original PR
-6. **Verify each PR independently**
- - Run the narrowest relevant build, typecheck, lint, and tests for that PR's scope.
- - Do not leave tests, docs, or generated files separated from the code they validate unless the split plan explicitly calls for it.
+```bash
+git diff --stat $BASE...HEAD
+git diff --name-only $BASE...HEAD
+git log --oneline $BASE..HEAD
+```
-7. **Manage drift deliberately**
- - Treat reviewer-approved changes as the new source of truth for the stack.
- - After changing an earlier PR, rebase dependent PRs onto it and resolve conflicts in favor of the reviewed direction, not blindly in favor of the original branch.
- - Compare the evolving stack against `backup/original-large-pr` to find remaining intent, not to force byte-for-byte equality.
- - Record intentional differences in `.notes/pr-split.md`.
+Classify every changed file into exactly one review unit:
-8. **Use range-diff for rewritten stacks**
- - Use `git range-diff` after rebases, conflict resolution, or force-pushes to understand what changed.
- - Summarize meaningful range-diff results for reviewers when updating a stacked PR.
+| Unit | Examples |
+|------|----------|
+| prep / refactor | renames, extractions, no behavior change |
+| API / type changes | signatures, models, generated types |
+| behavior | the actual feature/fix logic |
+| tests | new or changed tests |
+| docs / metadata | AGENTS.md, docs, changelogs |
+| generated / lockfiles | `pnpm-lock.yaml`, generated types |
-## PR description pattern
+## Step 3: Create the scratchpad
-Keep PR descriptions concise and reviewer-facing:
+Write `.ai/scratch/pr-split.md` (gitignored — never commit it):
```markdown
-## Summary
+# PR split — {original branch}
+Backup: backup/original-{branch} · Base: {BASE sha}
-This is PR N of M split from a larger change.
+## Planned PRs
+1. {branch-name} — scope: … — files/hunks: … — verify: … — status: …
-## Scope
+## Remaining original intent
+- …
+
+## Drift notes (date / branch / what changed and why)
+- …
+```
-- ...
+## Step 4: Choose the split shape
-## Intentionally excluded
+| Situation | Shape |
+|-----------|-------|
+| Later work depends on earlier work | **Stacked** PRs (each branched off the previous) |
+| Changes are truly independent | Parallel PRs off main |
+| One shared prep change unlocks independent work | Foundation PR + parallel follow-ups |
+| Unsure | Stacked — dependency mistakes surface as conflicts, not broken builds |
-- Follow-up PR will handle ...
+Rules: never separate tests from the code they verify; never split one behavior
+across two PRs by file boundary; each PR must build and pass its tests alone.
-## Verification
+## Step 5: Extract non-interactively
-- ...
+Start each PR from the correct base (`main`, or the previous PR in the stack):
+
+```bash
+git checkout -b {pr-branch} {base}
```
-Do not put the full split ledger in PR descriptions. Keep detailed extraction notes and drift tracking in `.notes/pr-split.md`.
+**Whole files** (the file belongs entirely to this PR):
-## Scratchpad template
+```bash
+git checkout backup/original-{branch} -- path/to/file.ts
+```
-```markdown
-# PR split scratchpad
+**Part of a file** (the file mixes changes for different PRs):
-Original branch: backup/original-large-pr
-Base branch: main
+```bash
+git diff {base} backup/original-{branch} -- path/to/file.ts > .ai/scratch/extract.patch
+# Edit .ai/scratch/extract.patch: keep the file header lines (---/+++),
+# DELETE every @@-hunk that belongs to a different PR, keep the hunks you want.
+git apply .ai/scratch/extract.patch
+```
-## Planned PRs
+If `git apply` fails (context mismatch), do not fight it: open the file and
+make the wanted changes by hand, using the patch as the reference. Then delete
+the patch file.
-1. branch-name
- - Scope:
- - Files/hunks extracted:
- - Verification:
- - Status:
+Commit each extraction with a conventional message and check it off in the
+scratchpad, noting exactly which files/hunks moved.
-## Remaining original intent
+## Step 6: Verify each PR independently
+
+For every PR branch, before opening it:
+
+```bash
+pnpm exec biome check --write --no-errors-on-unmatched <changed paths>
+pnpm exec turbo run typecheck --filter=<pkg> # per touched package, never whole-repo
+pnpm --filter <pkg> test
+```
-- ...
+A PR that only compiles on top of an unmerged sibling is stacked — say so in
+its description and set its GitHub base branch accordingly.
-## Drift notes
+## Step 7: PR descriptions
+
+```markdown
+## Summary
+PR {N} of {M} split from {original branch}.
-- Date / branch / reason:
+## Scope
+- …
+
+## Intentionally excluded (follow-up PRs)
+- …
+
+## Verification
+- {commands run + results}
```
-## Common failure modes
+Keep the detailed extraction ledger in `.ai/scratch/pr-split.md`, not in PR
+bodies.
+
+## Step 8: Manage drift as reviews land
+
+- Reviewer-approved changes are the **new source of truth** — when an earlier
+ PR changes, rebase its dependents onto it and resolve conflicts in favor of
+ the reviewed direction, never blindly back toward the original branch.
+- After any rebase/force-push: `git range-diff {old-tip}...{new-tip}` and
+ summarize meaningful differences for reviewers.
+- Periodically diff the stack against the backup to find **remaining intent**
+ (work not yet shipped in any PR) — not to force byte-for-byte equality.
+- Record every intentional divergence in the scratchpad's drift notes.
-Avoid splitting by file when behavior spans files, extracting tests without code, leaving follow-up PRs uncompilable, force-pushing without a reviewer summary, deleting the original branch early, and reverting review feedback while resolving stack conflicts.
+## Done when
-## Default output
+- [ ] Every hunk of `git diff $BASE...backup/original-{branch}` is either shipped
+ in a PR or explicitly listed in the scratchpad as dropped (with a reason)
+- [ ] Each PR builds and passes its scoped gates independently
+- [ ] Tests shipped in the same PR as the code they verify
+- [ ] Backup branch still intact
-When asked to split a PR, produce:
+## Failure modes to avoid
-1. proposed PR sequence,
-2. branch strategy,
-3. scratchpad path and initial contents,
-4. extraction commands,
-5. verification plan for each PR,
-6. drift-management plan.
\ No newline at end of file
+Splitting by file when behavior spans files · extracting tests without their
+code · a follow-up PR that doesn't compile · force-pushing without a range-diff
+summary · deleting the backup early · resolving stack conflicts by reverting
+reviewer feedback.
diff --git a/.ai/skills/research/SKILL.md b/.ai/skills/research/SKILL.md
index c7bdb2ca55..58da12bec8 100644
--- a/.ai/skills/research/SKILL.md
+++ b/.ai/skills/research/SKILL.md
@@ -1,116 +1,105 @@
---
name: research
-description: Survey best practices from competitor ERPs and point solutions for a given feature. Use when designing new features, evaluating approaches, or understanding industry patterns. Triggers on "research best practices", "how do competitors do X", "survey the market for Y", "what's the industry standard for", or any request to understand how other systems handle a feature.
+description: Survey how best-in-class ERPs and point solutions implement a feature, and produce a findings file at .ai/research/{slug}.md. Use when designing a new feature, evaluating approaches, or answering "how do competitors / SAP / the industry do X". Required before designing any ERP-domain feature (accounting, costing, tax, inventory valuation, RMA, MRP, etc.). Do not use for UI styling questions (copy an existing Carbon screen instead) or for bugs (use root-cause).
---
-# Research: Competitor Best Practices
+# research — competitor best-practice survey
-Survey how best-in-class ERPs and point solutions implement a feature. Carbon spans accounting, manufacturing, MES, quality, and more — this skill ensures we research the **right** competitors for each domain, not just any ERP.
+Input: a feature or domain question. Output: `.ai/research/{feature-slug}.md` with
+consensus patterns and a recommendation for Carbon. This skill only researches and
+writes the findings file — it does not design, plan, or write code.
-## Domain-to-Competitor Mapping
+**Announce at start:** "Using the research skill — surveying how competitors
+handle {feature}."
-| Domain | Always | Primary Competitors | Keywords |
-|--------|--------|---------------------|----------|
-| **Accounting** | SAP | NetSuite | GL, AP, AR, invoicing, payments, accruals, journal entries, financial reports |
-| **Discrete Manufacturing** | SAP | Epicor | Job shops, work orders, BOMs, routing, shop floor, job costing |
-| **MES / Production Tracking** | SAP | Manufacturo, First Resonance | Real-time tracking, IoT, machine monitoring, production scheduling, dispatch |
-| **CNC Parts / Sheet Metal** | SAP | Fulcrum, Paperless Parts | Quoting, estimating, nesting, machine-specific routing, RFQ |
-| **Quality** | SAP | 1factory, HighQA | Inspection, SPC, compliance, FAI, PPAP, measurement, GD&T |
-| **Inventory** | SAP | NetSuite, Fishbowl | Valuation, lot tracking, cycle counting, warehouse, locations |
-| **Sales / CRM** | SAP | NetSuite, Salesforce | Quotes, orders, customers, pricing, commissions |
-| **Purchasing** | SAP | NetSuite, Coupa | POs, suppliers, receiving, vendor management, procurement |
-| **Unknown** | SAP | *(discover first)* | First search for "best [domain] software" to identify leaders |
+## Step 1: Classify the domain
-**SAP is always included** — it's the gold standard for enterprise patterns, even when point solutions are more innovative.
+Match the request against this table. A feature may match multiple rows (e.g.
+"shop floor inspections" → MES + Quality). Research every matching row.
-## Workflow
+| Domain | Always | Also research | Keywords |
+|--------|--------|---------------|----------|
+| Accounting | SAP | NetSuite | GL, AP, AR, invoicing, payments, accruals, journal entries, period close, financial reports |
+| Discrete manufacturing | SAP | Epicor | job shops, work orders, BOMs, routing, job costing |
+| MES / production tracking | SAP | Manufacturo, First Resonance | real-time tracking, dispatch, machine monitoring, scheduling |
+| CNC parts / sheet metal | SAP | Fulcrum, Paperless Parts | quoting, estimating, nesting, RFQ |
+| Quality | SAP | 1factory, HighQA | inspection, SPC, FAI, PPAP, GD&T, NCR |
+| Inventory | SAP | NetSuite, Fishbowl | valuation, lots, cycle counting, warehouses |
+| Sales / CRM | SAP | NetSuite, Salesforce | quotes, orders, pricing, commissions |
+| Purchasing | SAP | NetSuite, Coupa | POs, suppliers, receiving, procurement |
+| Anything else | SAP | discover first | search `best <domain> software` and pick the top 2 leaders before deep research |
-### Step 1: Classify the Domain
+SAP is always included — it is the reference for enterprise patterns even when
+point solutions are more innovative.
-Read the feature request and match it to domains above using keywords. A feature may span multiple domains (e.g., "shop floor quality inspections" → MES + Quality).
+## Step 2: Write the research questions
-### Step 2: Identify Competitors to Research
+Before searching, list 3–6 concrete questions the design will need answered.
+Prefer data-model and workflow questions over UI questions:
-1. **Always include SAP** for any feature
-2. **Add domain-specific competitors** from the mapping table
-3. **For unknown domains**: First search `best [domain] software 2025` to identify 2-3 leaders before deep research
+- What entities and status lifecycles does the competitor use?
+- What edge cases do they handle that we might miss?
+- Is there an industry-standard term we should adopt instead of inventing one?
-### Step 3: Execute Targeted Searches
+## Step 3: Search
-For each competitor, search for:
-- `[Competitor] [feature] documentation`
-- `[Competitor] [feature] how it works`
-- `[Competitor] [feature] best practices`
+For each competitor, run searches shaped like:
-Example for "inventory valuation":
-- `SAP S/4HANA inventory valuation methods`
-- `NetSuite inventory costing FIFO LIFO average`
-- `SAP inventory valuation configuration`
+- `<Competitor> <feature> documentation`
+- `<Competitor> <feature> how it works`
+- `<Competitor> <feature> best practices`
-### Step 4: Synthesize Findings
+Rules:
-Structure research as actionable patterns:
+- Be specific: `SAP S/4HANA inventory valuation methods`, not `SAP inventory`.
+- Fan searches out to subagents (one competitor or one question per subagent) to
+ keep the main context clean. Each subagent returns findings + source URLs only.
+- Focus on data models, workflows, and terminology — not screenshots or UI copy.
-1. **Key Consensus** — What all/most competitors agree on (these are likely industry requirements)
-2. **Competitor-Specific Details** — Unique approaches worth noting
-3. **Recommended Approach** — What Carbon should do, citing which competitor patterns to follow
+## Step 4: Write the findings file
-### Step 5: Save Output
-
-Save the research to `.ai/research/[feature-slug].md` using the output format below.
-
-## Output Format
+Save to `.ai/research/{feature-slug}.md` (kebab-case slug). Use exactly this
+structure:
```markdown
-# [Feature] Research: Best Practices Survey
+# {Feature} Research: Best Practices Survey
## Summary
-One paragraph describing what was researched and key findings.
+One paragraph: what was researched, key findings.
## Competitors Surveyed
-- **SAP S/4HANA** — [why relevant]
-- **[Competitor]** — [why relevant]
+- **SAP S/4HANA** — {why relevant}
+- **{Competitor}** — {why relevant}
## Key Consensus Patterns
+### 1. {Pattern name}
+- **SAP**: {how SAP does it}
+- **{Competitor}**: {how they do it}
+- **Rationale**: {why this is the standard}
-### 1. [Pattern Name]
-- **SAP**: [how SAP does it]
-- **[Competitor]**: [how they do it]
-- **Rationale**: [why this is the standard]
-
-### 2. [Pattern Name]
-...
+## Answers to Research Questions
+1. {Question} — {answer, citing which competitor}
## Competitor-Specific Details
-
-### SAP
-[Notable implementation details, configuration options, terminology]
-
-### [Competitor]
-[Notable implementation details, unique approaches]
+### {Competitor}
+{notable configuration options, terminology, unique approaches}
## Recommended Approach for Carbon
-
-Based on the research:
-1. [Recommendation with rationale]
-2. [Recommendation with rationale]
+1. {Recommendation with rationale, naming the competitor pattern it follows}
## Sources
-- [Link 1]
-- [Link 2]
+- {URL}
```
+## Done when
-## When to Use
-
-- Designing a new feature and want to understand industry patterns
-- Evaluating multiple approaches and want to see what competitors chose
-- Building domain knowledge before implementation
-- Validating that a proposed design matches industry standards
+- [ ] Every matching domain row was researched, SAP included
+- [ ] Every research question from Step 2 has an answer (or is explicitly marked
+ unanswered — carry it into the spec's Open Questions)
+- [ ] The findings file exists at `.ai/research/{slug}.md` with all sections filled
+- [ ] Every claim has a source URL in the Sources section
-## Tips
+## Next step
-- **Be specific**: "inventory valuation for job costing" yields better results than just "inventory"
-- **Cross-domain features**: Research all relevant domains (e.g., "shop floor inspections" → MES + Quality)
-- **Unknown domains**: Don't guess competitors — search for "best [domain] software" first
-- **Focus on patterns, not UI**: We want to understand the underlying data model and workflows, not copy screens
+Hand the findings file to `/spec-writing` (design + spec) or cite it from an
+existing spec. Do not start implementation from research alone.
diff --git a/.ai/skills/root-cause/SKILL.md b/.ai/skills/root-cause/SKILL.md
index adfebfc141..f9260a50f6 100644
--- a/.ai/skills/root-cause/SKILL.md
+++ b/.ai/skills/root-cause/SKILL.md
@@ -1,104 +1,133 @@
-<!-- Workflow pattern inspired by Open Mercato (MIT License)
- https://github.com/open-mercato/open-mercato
- Copyright (c) 2025-2026 Open Mercato contributors -->
-
---
name: root-cause
-description: Read-only root-cause analysis for bugs. Produces a brief with root cause, files to change, approach, and risks. No edits, no commits. Use before /fix or conductor.
+description: Read-only root-cause analysis for any bug, test failure, or unexpected behavior — before proposing or writing any fix. Produces a brief with the root cause, files to change, approach, and risks. No edits, no commits, no state-changing commands. Use before /fix or /conductor whenever the cause isn't already proven. If static reading can't reach a confident cause, it hands off to /debugging-difficult-bugs for runtime instrumentation.
---
+<!-- Workflow pattern inspired by Open Mercato (MIT License)
+ https://github.com/open-mercato/open-mercato
+ Copyright (c) 2025-2026 Open Mercato contributors -->
# root-cause — read-only bug analysis
-You are performing a **read-only** root-cause analysis. You will not edit any files, create branches, or run commands that mutate state. Your output is a brief that a human or the `/fix` skill will act on.
-
-**Announce at start:** "I'm using the root-cause skill to analyze this bug."
+You are performing **read-only** analysis: no file edits, no branches, no
+commands that mutate state. Output is a brief that a human or `/fix` acts on.
-## 0. Load context
+The iron rule: **no fix without a root cause.** A fix proposed before the cause
+is understood is a guess, and guesses create new bugs. Symptom patches are
+failure even when they make the error disappear.
-Before investigating, load these in order:
+**Announce at start:** "Using the root-cause skill — read-only analysis of this
+bug."
-1. **Issue / bug report** — read the full description, repro steps, and any linked threads.
-2. **`.ai/lessons.md`** — check for known pitfalls related to the affected area.
-3. **AGENTS.md Task Router** — match the bug's domain to the relevant guides in `.ai/rules/` and module `AGENTS.md` files.
-4. **Module AGENTS.md** — read the `AGENTS.md` in the affected module/package directory for local architecture, imports, and conventions.
+## Step 0: Load context
-## 1. Reproduce mentally
+1. The bug report — full description, repro steps, linked threads/issues.
+2. `.ai/lessons.md` — known pitfalls in the affected area.
+3. Root `AGENTS.md` Task Router → the matching `.ai/rules/` guides.
+4. The affected module/package `AGENTS.md`.
-Trace the bug from symptom to origin without running code:
+## Step 1: Establish the facts
-1. **Read the error** — full stack trace, error message, HTTP status. Note file paths and line numbers.
-2. **Identify the entry point** — which route, loader, action, or event handler is involved?
-3. **Trace the data flow** — follow the call chain: route → service function → database query → response. Note every transformation.
-4. **Check the schema** — read the relevant migration(s) and types. Verify column names, types, and constraints match what the code expects.
+1. **Read the error completely** — full stack trace, message, HTTP status, file
+ and line numbers. The error text often contains the answer.
+2. **Reproduce or trace.** State the exact repro steps. If you cannot reproduce
+ even mentally, gather more data — do not guess.
+3. **Check recent changes**: `git log --oneline -20 -- <affected paths>` and the
+ branch diff. Most bugs live in what changed last.
+4. **Trace the data flow** from entry point to origin: route → loader/action →
+ service function → query → response. Note every transformation. Follow the
+ bad value **backward** to where it is first wrong — fix at the source, not
+ where the symptom surfaces (see `references/root-cause-tracing.md`).
+5. **Check the schema**: read the *newest* relevant migrations (order by
+ timestamp) and generated types. Column names and constraints must match what
+ the code assumes.
-## 2. Carbon-specific checks
+## Step 2: Carbon-specific failure modes
-Run through these common Carbon failure modes:
+Check each of these before inventing exotic theories:
| Check | What to look for |
-|-------|-----------------|
-| **companyId scoping** | Every query that reads or writes tenant data MUST filter by `companyId`. Missing scoping = cross-tenant data leak or empty results. |
-| **RLS policy gaps** | New tables or columns without corresponding RLS policies. Check `packages/database/supabase/migrations/` for the table's policies. |
-| **Stale generated types** | Code referencing columns/tables added in a recent migration but `pnpm run generate:types` was not run afterward. |
-| **Permission scope mismatch** | `requirePermissions()` or `permissions.can()` using a string that doesn't match the DB scope. See `BACKWARD_COMPATIBILITY.md` — scopes are FROZEN. |
-| **Service function signature drift** | Caller passing args that don't match the service function's current signature (params added/removed/reordered). |
-| **Multi-tenancy in new code** | New tables missing `companyId` column, composite PK `("id", "companyId")`, or `id('prefix')` default. |
-| **Import path staleness** | Code importing from a path that was moved without a re-export bridge. |
-
-## 3. Narrow the root cause
-
-- **Single hypothesis.** Form one specific theory: "The bug is caused by X in file Y because Z."
-- **Verify against the code.** Read the suspected file(s) and confirm the theory holds. If it doesn't, form a new hypothesis — don't force-fit.
-- **Distinguish root cause from symptom.** A `TypeError` in the UI might be caused by a missing RLS policy three layers down. Keep tracing until you reach the origin.
-
-## 4. Assess confidence
-
-Rate your confidence:
+|-------|------------------|
+| companyId scoping | A query missing `companyId` filtering → cross-tenant leak or empty results |
+| Stale generated types | Code references columns from a new migration but `pnpm run generate:types` wasn't run — typecheck greens lie |
+| RLS policy gaps | New table/column without policies; check the table's migrations |
+| Permission strings | `requirePermissions()` / `permissions.can()` scopes are string literals — invisible to typecheck; grep the whole repo after any scope rename |
+| Service signature drift | Caller args don't match the service function's current signature |
+| Migration ordering | A migration backdated older than deployed ones applies out of order on remotes (see `.ai/lessons.md`) |
+| Form submission | `ValidatedForm` only submits on a native submit with a `submitter`; react-aria number/date fields commit hidden inputs on **blur** (see `/test` for details) |
+| Import staleness | Import from a moved path with no re-export bridge |
+
+## Step 3: One hypothesis at a time
+
+1. Form a **single** specific hypothesis: "X in file Y causes the bug because Z."
+2. Verify it against the code you can read. If the code contradicts it, discard
+ it — don't force-fit.
+3. Distinguish cause from symptom: a UI `TypeError` may originate three layers
+ down. Keep tracing until you reach the origin.
+4. **Three-strikes rule:** if 3 hypotheses have failed, the problem is likely
+ architectural (shared state, coupling, a wrong pattern) — STOP, write up what
+ you ruled out, and surface the architectural question to the human instead of
+ producing hypothesis #4.
+
+## Step 4: Confidence
| Level | Meaning |
|-------|---------|
-| **HIGH** | Root cause identified with clear evidence in the code. The fix path is obvious. |
-| **MEDIUM** | Strong hypothesis supported by code reading, but runtime confirmation would help. |
-| **LOW** | Multiple plausible causes, insufficient code evidence, or the bug may be environmental. |
+| HIGH | Cause identified with code evidence; fix path obvious |
+| MEDIUM | Strong code-supported hypothesis; runtime confirmation would help |
+| LOW | Multiple plausible causes or the bug appears runtime/environment-dependent |
-**If LOW_CONFIDENCE, say so explicitly.** Do not present a guess as a finding.
+If MEDIUM or LOW **and** the bug involves runtime state, ordering, caching,
+concurrency, or manual reproduction → recommend `/debugging-difficult-bugs`
+(temporary JSONL instrumentation) as the next step instead of guessing. Never
+present a guess as a finding.
-## 5. Output the brief
+## Step 5: Output the brief
Produce exactly this structure (~400 words max):
```markdown
## Root-Cause Brief
-**Bug:** <one-line summary>
-
-**Summary:** <2-3 sentences explaining the symptom and its observable impact>
-
-**Root cause:** <precise explanation of why the bug occurs, referencing specific
-files and line numbers>
-
+**Bug:** <one line>
+**Summary:** <2–3 sentences: symptom and observable impact>
+**Root cause:** <why it happens, citing file:line>
**Confidence:** HIGH | MEDIUM | LOW
-<if LOW: explain what's uncertain and what would resolve it>
+<if not HIGH: what is uncertain and what would resolve it — e.g. "instrument via /debugging-difficult-bugs">
**Files to change:**
-- `path/to/file.ts` — <what needs to change and why>
-- `path/to/other.ts` — <what needs to change and why>
+- `path/to/file.ts` — <what and why>
**Approach:**
-1. <step 1>
-2. <step 2>
-3. <step 3>
+1. <step>
**Risks:**
-- <risk 1 — e.g., "changing this service signature affects 3 callers">
-- <risk 2 — e.g., "migration touches a production-critical table">
+- <e.g. "signature change affects 3 callers">
-**BC impact:** <NONE | list any FROZEN/STABLE surfaces touched, per BACKWARD_COMPATIBILITY.md>
+**BC impact:** <NONE | FROZEN/STABLE surfaces touched, per BACKWARD_COMPATIBILITY.md>
```
## Guardrails
-- **Read-only.** No file edits, no `git` writes, no branch creation, no commits, no pushes.
-- **No speculative fixes.** Don't suggest "try this and see if it works." Identify the cause or say you can't.
-- **Stay scoped.** Analyze the reported bug. Don't expand into unrelated issues you notice.
-- **Cite evidence.** Every claim in the brief must reference a specific file, line, migration, or policy.
+- **Read-only.** No edits, no `git` writes, no migrations, no DB commands.
+- **No speculative fixes.** "Try this and see" is not a finding.
+- **Stay scoped.** Analyze the reported bug only; note unrelated discoveries in
+ one line at the end, don't chase them.
+- **Cite evidence.** Every claim references a file, line, migration, or policy.
+
+Red flags — thinking any of these means you're guessing, not analyzing; STOP:
+
+- "it's probably X, let me suggest the fix" (no verified cause → no fix)
+- "I'll propose two possible fixes and let them pick" (that's two guesses)
+- "one more hypothesis" after three have failed (that's an architecture
+ question now — surface it)
+- "the error message is misleading, ignore it" (read it again; it usually isn't)
+
+## References (read when the situation matches)
+
+- `references/root-cause-tracing.md` — tracing a bad value backward through the
+ call stack to its origin
+- `references/defense-in-depth.md` — layering validation after the cause is found
+- `references/condition-based-waiting.md` (+ `condition-based-waiting-example.ts`)
+ — replacing arbitrary timeouts with condition polling in flaky async tests
+- `references/find-polluter.sh` — bisecting which earlier test pollutes a
+ failing test
diff --git a/.ai/skills/systematic-debugging/condition-based-waiting-example.ts b/.ai/skills/root-cause/references/condition-based-waiting-example.ts
similarity index 100%
rename from .ai/skills/systematic-debugging/condition-based-waiting-example.ts
rename to .ai/skills/root-cause/references/condition-based-waiting-example.ts
diff --git a/.ai/skills/systematic-debugging/condition-based-waiting.md b/.ai/skills/root-cause/references/condition-based-waiting.md
similarity index 100%
rename from .ai/skills/systematic-debugging/condition-based-waiting.md
rename to .ai/skills/root-cause/references/condition-based-waiting.md
diff --git a/.ai/skills/systematic-debugging/defense-in-depth.md b/.ai/skills/root-cause/references/defense-in-depth.md
similarity index 100%
rename from .ai/skills/systematic-debugging/defense-in-depth.md
rename to .ai/skills/root-cause/references/defense-in-depth.md
diff --git a/.ai/skills/systematic-debugging/find-polluter.sh b/.ai/skills/root-cause/references/find-polluter.sh
similarity index 100%
rename from .ai/skills/systematic-debugging/find-polluter.sh
rename to .ai/skills/root-cause/references/find-polluter.sh
diff --git a/.ai/skills/systematic-debugging/root-cause-tracing.md b/.ai/skills/root-cause/references/root-cause-tracing.md
similarity index 100%
rename from .ai/skills/systematic-debugging/root-cause-tracing.md
rename to .ai/skills/root-cause/references/root-cause-tracing.md
diff --git a/.ai/skills/self-review/SKILL.md b/.ai/skills/self-review/SKILL.md
index 1d77c84372..608534405a 100644
--- a/.ai/skills/self-review/SKILL.md
+++ b/.ai/skills/self-review/SKILL.md
@@ -1,75 +1,93 @@
---
name: self-review
-description: Critically review your own PR work before or just after opening the PR. Use when finishing a branch, before opening or merging a PR, or to sanity-check a diff against main. Produces Must fix / Risks / Suggested improvements. Supports an opt-in strict "thermo-nuclear" mode for a deep maintainability and abstraction audit when explicitly requested.
+description: Critically review your own branch work before or just after opening the PR, producing Must fix / Risks / Suggested improvements plus a docs-freshness check. Use when finishing a branch, before opening or merging a PR, or to sanity-check a diff against main. Supports an opt-in strict "thermo-nuclear" mode for a deep maintainability and abstraction audit when explicitly requested.
---
-Critically review your own PR work before or just after opening the PR.
+# self-review — review your own work before the PR
-Review the full branch diff, not just the most recent commit. If there is already an open PR for the current branch, use `gh pr view` and `gh pr diff`. If there is not, diff the current branch against `main` instead. If you already know the PR is open from earlier in the session, do not waste time re-proving it unless you need the PR number or metadata.
+Review the **full branch diff**, not just the last commit. Do not rubber-stamp
+your own work because you wrote it.
-Read the entire diff carefully. Do not skim. Re-read any tricky sections until you understand why they changed. When something looks subtle, risky, or surprising, read the surrounding code too and make sure the change really makes sense in context.
+**Announce at start:** "Using the self-review skill — reviewing the branch diff
+against main."
-As you review, actively look for problems and missing work:
-- bugs or logic mistakes
-- missing edge cases
-- unnecessary complexity
-- leftover debug code, logging, TODOs, or commented-out code
-- naming that could be clearer
-- inconsistent patterns
-- dead code or accidental churn
-- missing or weak tests
-- risky changes that are not obvious from the diff
-- PR scope/title/body not matching the actual change
-- things that technically work but still feel brittle or hard to maintain
-- stale AGENTS.md or `.ai/` docs (see freshness check below)
+## Step 1: Get the diff
-Be skeptical. Do not rubber-stamp your own work just because you wrote it.
+- Open PR exists → `gh pr view` + `gh pr diff`.
+- No PR → `git diff $(git merge-base origin/main HEAD)...HEAD` (plus
+ `--name-only` for the file list).
+- Already know the PR from this session → don't re-prove it; just get the diff.
-Make notes as you go, then produce a concise review with these sections:
-- Must fix
-- Risks / questions
-- Suggested improvements
+## Step 2: Read all of it
-Call out missing things too, not just bad things that are already present in the diff.
+Read the entire diff carefully. Do not skim. Re-read tricky hunks until you
+understand why they changed. When a change looks subtle, risky, or surprising,
+open the surrounding file and confirm the change makes sense in context.
-Be specific. Reference files and lines when possible. If you are not fully sure whether something is a real bug, include it anyway as a risk or question. Focus on what should be fixed, simplified, verified, or questioned before the PR is considered ready.
+Actively hunt for:
-Present the findings directly to the user so they can decide what to act on.
+- bugs or logic mistakes; missing edge cases
+- missing `companyId` scoping on new/modified queries
+- unnecessary complexity; dead code; accidental churn
+- leftover debug code, logging, TODOs, commented-out code, stray files
+- naming that could be clearer; patterns inconsistent with neighbors
+- missing or weak tests (would this test catch a revert of the fix?)
+- risky changes not obvious from the diff (signature changes, shared helpers)
+- PR title/body/scope not matching the actual change
+- things that work but feel brittle or hard to maintain
-## AGENTS.md & docs freshness check
+Call out **missing** work, not just flaws in what's present.
-For every package or module directory the PR touches, check:
+## Step 3: Docs freshness
-1. Does a sibling `AGENTS.md` exist? If so, does the diff change anything it
- references — a function name, table name, export, import path, or pattern?
- If yes, flag it: _"`packages/database/AGENTS.md` references `fetchAllFromTable`
- but this PR renames it to `fetchAll` — update the AGENTS.md."_
-2. Does the diff add a new package or module directory without an `AGENTS.md`?
- Flag it: _"New package `packages/foo/` has no AGENTS.md — create one using a
- sibling as template."_
-3. Does the diff introduce a new pattern, convention, or pitfall worth capturing?
- Flag it for `.ai/lessons.md` if so.
+For every package or module directory the diff touches:
-List freshness findings under a **Docs freshness** section in the review output,
-separate from Must fix / Risks / Suggested improvements.
+1. Sibling `AGENTS.md` exists? Does the diff change anything it references
+ (function, table, export, import path)? → flag the exact stale line.
+2. New package/module without an `AGENTS.md`? → flag it (create via
+ `/create-agents-md`).
+3. New pattern, convention, or pitfall worth keeping? → flag it for
+ `.ai/lessons.md`. Spec implemented? → flag the spec for `implemented/` per
+ `.ai/specs/AGENTS.md`.
-## Strict mode (thermo-nuclear)
-
-Run this mode **only when explicitly requested** — triggers like "thermo-nuclear", "thermonuclear", "deep code quality", "harsh", or "extremely strict" review. It raises the bar from "is this correct and shippable?" to "is this the simplest, most maintainable structure possible?"
+## Step 4: Output
-Be **ambitious** about structure. Don't stop at local cleanup — actively hunt for "code judo" moves: behavior-preserving restructurings that make whole branches, helpers, modes, or layers disappear. Prefer deleting complexity over rearranging it; prefer the version that makes the code feel inevitable in hindsight.
+Four sections, specific, with `file:line` references — a finding you cannot tie
+to a file and line gets cut, not padded. If unsure whether something is a real
+bug, include it as a risk/question rather than dropping it.
-Apply these non-negotiable standards on top of the base review:
-1. **File growth** — Don't let a PR push a file from under 1k lines to over 1k without a strong reason. Treat it as a smell; prefer extracting helpers/modules first.
-2. **No spaghetti growth** — Be suspicious of new ad-hoc conditionals, scattered special cases, or one-off branches bolted onto unrelated flows. Push logic into a dedicated abstraction / state machine / module instead of tangling an existing path.
-3. **Clean the design, don't just accept working code** — If behavior can stay the same while structure gets meaningfully cleaner, push for it. Don't rubber-stamp "it works".
-4. **Direct over magical** — Flag brittle, ad-hoc, or "magic" behavior; thin wrappers, identity abstractions, and pass-through helpers that add indirection without clarity.
-5. **Type / boundary cleanliness** — Question unnecessary optionality, `any`, `unknown`, or cast-heavy code; prefer explicit typed models. Flag silent fallbacks that paper over unclear invariants.
-6. **Canonical layer + reuse** — Call out feature logic leaking into shared paths or details leaking through APIs. Prefer existing canonical helpers over bespoke one-offs; push code to the package/module that owns the concept.
-7. **Atomicity + orchestration** — Flag needlessly sequential flows that could run in parallel, and related updates that can leave state half-applied when a more atomic structure is obvious.
+- **Must fix**
+- **Risks / questions**
+- **Suggested improvements**
+- **Docs freshness**
-Prefer remedies that remove moving pieces: delete a layer of indirection, reframe the state model so conditionals vanish, change an ownership boundary so the feature becomes a natural extension of an existing abstraction, replace condition chains with a typed dispatcher, split a large file into focused modules.
+End with a compact TLDR listing every item again, grouped by section. Present
+findings to the user — they decide what to act on; do not auto-fix.
-**Strict approval bar** — treat each as a presumptive blocker unless clearly justified: structural regression; obvious missed simplification when a path is visible; unjustified file-size explosion; spaghetti-growth from special-case branching; hacky/magical abstraction; needless wrapper/cast/optionality churn; architecture-boundary leak or canonical-helper duplication. Be direct and demanding about quality without being rude.
+## Strict mode (thermo-nuclear)
-End the response with a short TLDR that lists every item again in compact bullet form, grouped by section (`Must fix`, `Risks / questions`, `Suggested improvements`). Keep the TLDR concise and scannable.
\ No newline at end of file
+Run **only when explicitly requested** ("thermo-nuclear", "harsh", "deep code
+quality", "extremely strict"). Raises the bar from "correct and shippable" to
+"simplest, most maintainable structure possible".
+
+Hunt for behavior-preserving restructurings that make whole branches, helpers,
+modes, or layers disappear. Prefer deleting complexity over rearranging it.
+Non-negotiable standards on top of the base review:
+
+1. **File growth** — a PR pushing a file past ~1k lines without strong reason is
+ a smell; prefer extracting modules first.
+2. **No spaghetti growth** — new ad-hoc conditionals and one-off special cases
+ bolted onto unrelated flows belong in a dedicated abstraction.
+3. **Clean the design, don't just accept working code** — same behavior with
+ meaningfully cleaner structure is worth pushing for.
+4. **Direct over magical** — flag thin wrappers, identity abstractions, and
+ pass-through helpers that add indirection without clarity.
+5. **Type/boundary cleanliness** — question needless optionality, `any`,
+ `unknown`, cast-heavy code, and silent fallbacks papering over invariants.
+6. **Canonical layer + reuse** — feature logic leaking into shared paths, or a
+ bespoke helper duplicating an existing canonical one, is a blocker.
+7. **Atomicity + orchestration** — flag needlessly sequential flows and related
+ updates that can leave state half-applied.
+
+Treat each violation as a presumptive blocker unless clearly justified. Be
+direct and demanding without being rude.
diff --git a/.ai/skills/smoke-test/SKILL.md b/.ai/skills/smoke-test/SKILL.md
index 3b56e51df3..51ccdb0236 100644
--- a/.ai/skills/smoke-test/SKILL.md
+++ b/.ai/skills/smoke-test/SKILL.md
@@ -1,74 +1,61 @@
---
name: smoke-test
-description: Run an e2e smoke test against the local Carbon ERP dev server using agent-browser. Logs in via /login, then navigates through core modules to verify they load without errors.
+description: Quick e2e smoke test of the local Carbon ERP dev server — logs in via /login, then loads each core module and verifies it renders without errors. Use after booting a stack, after wide-reaching changes, or when asked to "smoke test" the app. For feature-specific testing use /test instead.
---
-# E2E Smoke Test
+# smoke-test — do the core modules load?
-Run a quick end-to-end smoke test against the local Carbon ERP dev environment.
+Verify every core module renders. This is breadth, not depth — it catches
+broken routes and crashed loaders, not logic bugs.
-## Prerequisites
-
-- Dev server running (`pnpm dev` or `crbn up`)
-- `crbn up` seeds the smoke-test user and sets `DEV_BYPASS_EMAIL` automatically
-
-## Procedure
+**Announce at start:** "Using the smoke-test skill — sweeping the core modules."
-### Step 1: Login
-
-Invoke the `/login` skill to authenticate the browser session. If login fails, stop and report — all other steps depend on auth.
+## Prerequisites
-### Step 2: Navigate Core Modules
+- Dev server running (`crbn up` — seeds the test user and `DEV_BYPASS_EMAIL`)
-Read `ERP_URL` from `.env.local` in the project root.
+## Steps
-Visit each module and verify the page loads without errors. For each module:
+### 1. Login
-1. Navigate to the module URL
-2. Wait for network idle
-3. Take a snapshot
-4. Verify the page rendered content (table, cards, or expected UI elements)
-5. Check for error messages or blank pages
+Invoke `/login`. If it fails, STOP and report — everything below needs auth.
-**Module routes to test (append to ERP_URL):**
+### 2. Visit each module
-| Module | Path |
-|-------------|-----------------------|
-| Dashboard | `/x` |
-| Sales | `/x/sales/orders` |
-| Purchasing | `/x/purchasing/orders`|
-| Inventory | `/x/inventory` |
-| Items | `/x/items/parts` |
-| Accounting | `/x/accounting/charts`|
-| People | `/x/people/employee ` |
-| Resources | `/x/resources` |
-| Production | `/x/production` |
-| Settings | `/x/settings/company` |
+Read `ERP_URL` from `.env.local`. For each route below:
-For each module:
```bash
-agent-browser open ${ERP_URL}/x/sales/orders && agent-browser wait --load networkidle && agent-browser snapshot -i
+agent-browser open ${ERP_URL}<path> && agent-browser wait --load networkidle && agent-browser snapshot -i
```
-### Step 3: Report Results
-
-After visiting all modules, report a summary table:
+| Module | Path |
+|------------|------------------------|
+| Dashboard | `/x` |
+| Sales | `/x/sales/orders` |
+| Purchasing | `/x/purchasing/orders` |
+| Inventory | `/x/inventory` |
+| Items | `/x/items/parts` |
+| Accounting | `/x/accounting/charts` |
+| People | `/x/people/employee` |
+| Resources | `/x/resources` |
+| Production | `/x/production` |
+| Settings | `/x/settings/company` |
+
+A module **passes** if the snapshot shows real content (table, cards, headings)
+and no error text. It **fails** on a blank page, an error message, or a failed
+load. On failure: invoke `/error` to capture diagnostics, then continue to the
+next module — never abort the sweep for one failure.
+
+### 3. Report
| Module | Status | Notes |
|--------|--------|-------|
-| Login | PASS/FAIL | ... |
-| Sales | PASS/FAIL | ... |
-| ... | ... | ... |
-
-A module **passes** if the snapshot shows expected content (tables, headings, cards) and no error messages. A module **fails** if the page is blank, shows an error, or fails to load.
-
-## Failure Handling
-
-- If a module fails, invoke the `/error` skill to capture a screenshot and snapshot, then continue to the next module.
+| Login | PASS/FAIL | |
+| Sales | PASS/FAIL | {error capture paths if failed} |
+| … | | |
-## Cleanup
+### 4. Cleanup
-Close the browser session when done:
```bash
agent-browser close
```
diff --git a/.ai/skills/spec-writing/SKILL.md b/.ai/skills/spec-writing/SKILL.md
index c690658465..766bb4bed0 100644
--- a/.ai/skills/spec-writing/SKILL.md
+++ b/.ai/skills/spec-writing/SKILL.md
@@ -1,211 +1,152 @@
-<!-- Workflow pattern inspired by Open Mercato (MIT License)
- https://github.com/open-mercato/open-mercato
- Copyright (c) 2025-2026 Open Mercato contributors -->
---
name: spec-writing
-description: Write a feature spec with a hard-gate Open Questions stop. Grounds design in Carbon's architectural heuristics and ERP competitor research. Produces a spec at .ai/specs/{YYYY-MM-DD}-{slug}.md following the spec lifecycle in .ai/specs/AGENTS.md.
+description: Design a feature and write its spec at .ai/specs/{YYYY-MM-DD}-{slug}.md, with competitor research, explicit design decisions, and an Open Questions hard stop. Use when designing or brainstorming a new feature, a new module, a data-model change, or any change touching 3+ files or crossing modules. Do not use for small bug fixes or one-file refactors, and do not start implementation from this skill — implementation starts only after every open question is resolved.
---
+<!-- Workflow pattern inspired by Open Mercato (MIT License)
+ https://github.com/open-mercato/open-mercato
+ Copyright (c) 2025-2026 Open Mercato contributors -->
-# spec-writing — Feature Spec with Open Questions Hard Gate
+# spec-writing — design a feature, produce a spec, stop at open questions
-Write a complete feature spec grounded in Carbon's architecture and real ERP
-precedent. The Open Questions section is a **HARD STOP** — do not proceed to
-implementation until every question is resolved.
+Input: a feature request. Output: a complete spec at
+`.ai/specs/{YYYY-MM-DD}-{slug}.md` whose **Open Questions section is a hard
+stop** — implementation must not start while any question is unresolved.
-**Announce at start:** "I'm using the spec-writing skill to draft the feature spec."
+The spec is the single design artifact. Do not write separate "design docs" in
+other locations.
-## When to Use
+**Announce at start:** "Using the spec-writing skill — designing {feature} and
+drafting the spec."
-| Trigger | Action |
-|---------|--------|
+## When to write a spec
+
+| Situation | Action |
+|-----------|--------|
| New module | Write spec |
| Feature touching 3+ files | Write spec |
| Data model change | Write spec |
| Cross-module behavior change | Write spec |
-| Small bug fix or one-file refactor | Skip spec |
-
-Reference `.ai/specs/AGENTS.md` for the full lifecycle and naming rules.
+| Small bug fix or one-file refactor | Skip spec — use /root-cause + /fix |
-## Procedure
+Lifecycle and naming rules live in `.ai/specs/AGENTS.md`. Read it once before
+your first spec.
-### Phase 1: Research (before writing anything)
+## Step 1: Scope the request
-#### 1a. Read Carbon context
+If the request is ambiguous, ask the user at most 3–4 focused questions covering:
+**what** (the capability), **why** (the problem), **where** (ERP, MES, or both),
+**who** (the users). If the request is already clear, skip to Step 2.
-```bash
-# Load the conventions that apply
-cat .ai/rules/conventions-index.md
-cat .ai/docs/module-conventions.md
-
-# Read AGENTS.md for every module this feature touches
-cat apps/erp/app/modules/{module}/AGENTS.md
+## Step 2: Read Carbon context
-# Check for existing specs on the same topic
-ls .ai/specs/ | grep -i {keyword}
-ls .ai/specs/implemented/ | grep -i {keyword}
+Run all of these before designing anything:
-# Read relevant rules
-cat .ai/rules/{relevant-rule}.md
+```bash
+ls .ai/specs/ .ai/specs/implemented/ | grep -i {keyword} # prior art — never duplicate a spec
+cat .ai/lessons.md # known pitfalls
+cat .ai/docs/module-conventions.md # module layout rules
+cat apps/erp/app/modules/{module}/AGENTS.md # for every module touched
```
-#### 1b. Research comparable ERPs
-
-Before designing, check how established ERPs solve this problem. Research at
-minimum:
+Then read the `.ai/rules/` files matching the domain (use the Task Router table
+in the root `AGENTS.md` to find them).
-- **SAP** (always — it's the canonical reference)
-- **One domain-specific competitor** (e.g., Fishbowl for inventory, JobBOSS for
- job shops, Epicor for manufacturing, Xero for accounting)
+## Step 3: Research competitors
-Save research notes to `.ai/research/{feature}.md`.
+Invoke `/research {feature}`. This is mandatory for ERP-domain features
+(accounting, costing, tax, inventory valuation, RMA, planning, etc.) — do not
+invent domain logic. Findings land in `.ai/research/{slug}.md`; cite that file
+from the spec.
-Questions to answer from research:
-- What entities does SAP use for this domain?
-- What status lifecycles exist?
-- What edge cases does the competitor handle that we might miss?
-- Is there an industry-standard term we should adopt instead of inventing one?
+## Step 4: Make the design decisions
-### Phase 2: Skeleton Draft
+For each significant decision (data model shape, status lifecycle, workflow,
+integration point):
-Write the spec skeleton using `.ai/specs/template.md` as the base. Save to:
+1. State the question.
+2. Cite what the research found ("SAP and NetSuite both…").
+3. List 2–3 options with one-line trade-offs.
+4. Pick one and say why. If you cannot pick, it is an Open Question — do not
+ write "TBD" as a decision.
-```
-.ai/specs/{YYYY-MM-DD}-{slug}.md
-```
+Run every new or modified entity through this checklist and record the answer in
+the spec's Design Decisions table:
-Fill in all sections **except** leave Open Questions populated with genuine
-unknowns discovered during research and architectural analysis.
+| # | Heuristic | Question to answer |
+|---|-----------|--------------------|
+| 1 | Multi-tenancy | Does every new table have `companyId` + composite PK `("id", "companyId")` + `id('prefix')` default? |
+| 2 | Service shape | Does every service function take `client` first, return `{data, error}`, never throw? |
+| 3 | RLS coverage | Does every new table have SELECT/INSERT/UPDATE/DELETE policies per `.ai/rules/conventions-database.md`? |
+| 4 | Permission scoping | Does `requirePermissions` in every route use the correct `{module}_{action}` scope? |
+| 5 | Form pattern | Does every form use `ValidatedForm` + `validator(zodSchema)` + a route action? |
+| 6 | Module layout | One `{module}.service.ts`, one `{module}.models.ts`, barrel `index.ts`? |
+| 7 | Backward compatibility | Any FROZEN/STABLE surface touched (see `BACKWARD_COMPATIBILITY.md`)? What is the migration path? |
-#### Architectural Heuristics Checklist
+## Step 5: Write the spec
-Run every new or modified entity through these Carbon-specific checks. Document
-the answer for each applicable heuristic in the Design Decisions table.
+Copy `.ai/specs/template.md` to `.ai/specs/{YYYY-MM-DD}-{slug}.md` (today's
+date, kebab-case slug) and fill every section. Rules:
-| # | Heuristic | Question to Answer |
-|---|-----------|-------------------|
-| 1 | **Multi-tenancy** | Does every new table have `companyId` + composite PK `("id", "companyId")`? |
-| 2 | **Service function shape** | Does every service function take `client` as first arg, return `{data, error}`, and never throw? |
-| 3 | **RLS coverage** | Does every new table have SELECT / INSERT / UPDATE / DELETE policies using `get_companies_with_employee_role()` or `get_companies_with_employee_permission()`? |
-| 4 | **Permission scoping** | Does `requirePermissions` in every route cover the correct module and action (view/create/update/delete)? |
-| 5 | **Form pattern** | Does every user-facing form use `ValidatedForm` + `validator(zodSchema)` + route action? |
-| 6 | **Module layout** | Does the new code follow `.ai/docs/module-conventions.md`? One `{module}.service.ts`, one `{module}.models.ts`, barrel `index.ts`? |
-| 7 | **Backward compatibility** | Does this touch any FROZEN or STABLE surfaces? If so, what's the migration path? |
+- SQL sketches use `id('prefix')`, `companyId`, composite PK, audit columns —
+ never `gen_random_uuid()`.
+- Acceptance criteria must be testable: "user creates a PO with 3 lines and sees
+ correct totals in the list view", not "works correctly".
+- No `{placeholders}` left in the file; mark inapplicable sections `N/A` with a
+ reason.
-Each heuristic that applies MUST appear in the Design Decisions table with a
-concrete answer — not "TBD" or "will figure out later."
+## Step 6: Open Questions — HARD STOP
-#### Design Decisions Table
-
-```markdown
-| Decision | Choice | Rationale |
-|----------|--------|-----------|
-| Multi-tenancy | Composite PK `("id", "companyId")` on `{table}` | Carbon convention; required for RLS |
-| RLS model | Permission-based: `{module}_view`, `{module}_create` | Matches existing module pattern |
-| Service shape | `client` first arg, returns `{data, error}` | `.ai/rules/conventions-services.md` |
-| {decision} | {choice} | {why} |
-```
-
-### Phase 3: Open Questions — HARD STOP 🛑
-
-After completing the skeleton, review it and populate the Open Questions section
-with **every genuine unknown**. Common sources of unknowns:
-
-- Domain ambiguity ("Does a return create a credit memo or a negative invoice?")
-- Scope boundaries ("Should this handle multi-currency in v1?")
-- Data model choices ("Separate table or status column on existing table?")
-- Integration points ("Does this need an event system hook for downstream?")
-- Performance ("Will this RPC scale to 10k+ rows per company?")
-- UX decisions ("Modal or full-page form for this workflow?")
-
-Format:
+Populate the Open Questions section with every genuine unknown (domain
+ambiguity, scope boundaries, data-model alternatives you couldn't settle,
+performance, UX choices):
```markdown
## Open Questions
> 🛑 HARD STOP: Do not proceed with implementation until these are answered.
-- [ ] {Question 1} — {why it matters}
-- [ ] {Question 2} — {why it matters}
+- [ ] {Question} — {why it matters}
```
-**Rules for the hard gate:**
-- MUST have at least one open question (if you have zero, you haven't thought
- hard enough — re-read the research notes)
-- MUST NOT proceed to implementation while any question is unchecked
-- Questions are resolved by: human answer, research finding, or explicit
- "out of scope for v1" decision documented in the changelog
-- When a question is resolved, check it off AND record the answer inline:
- `- [x] {Question} — **Answer:** {decision and rationale}`
-
-### Phase 4: Present and Wait
-
-Present the spec to the user. Explicitly list the open questions and ask for
-answers. Do not suggest "we can figure these out during implementation" — that
-defeats the gate.
-
-```
-Here's the spec draft: .ai/specs/{YYYY-MM-DD}-{slug}.md
-
-🛑 Open questions that need answers before we build:
-
-1. {Question 1}
-2. {Question 2}
-3. ...
-
-What are your thoughts on these?
-```
-
-### Phase 5: Finalize
-
-After all open questions are resolved:
+Rules:
-1. Update the spec with answers (check off questions, add to changelog)
-2. Set status to `in-progress`
-3. The spec is now ready for `/plan` or `/feature` to consume
+- At least one open question is required. Zero questions means you haven't
+ thought hard enough — re-read the research and the heuristics table.
+- Never resolve questions yourself to unblock work. They are resolved only by a
+ human answer, a research finding, or an explicit documented "out of scope for
+ v1" decision.
+- Record each resolution inline: `- [x] {Question} — **Answer:** {decision and rationale}`.
-## Spec Quality Checklist
+## Step 7: Present and wait
-Before presenting the spec, verify:
+Show the user the spec path and list the open questions verbatim. Ask for
+answers. Do not say "we can figure these out during implementation."
-- [ ] **TLDR** is one paragraph, not a bullet list
-- [ ] **Problem Statement** includes a concrete example or scenario
-- [ ] **Data Model** uses Carbon conventions (composite PK, audit columns, RLS)
-- [ ] **SQL sketches** use `id('prefix')`, not `gen_random_uuid()`
-- [ ] **Every architectural heuristic** that applies has a Design Decisions entry
-- [ ] **Service function signatures** follow `(client, companyId, ...)` → `{data, error}`
-- [ ] **Acceptance criteria** are testable (not vague "works correctly")
-- [ ] **Open Questions** section has ≥1 genuine unknown
-- [ ] **Risks table** has ≥1 entry
-- [ ] **Research notes** are saved to `.ai/research/`
-- [ ] **Changelog** has the creation date entry
-- [ ] **File name** follows `{YYYY-MM-DD}-{slug}.md` convention
+## Step 8: Finalize
-## Anti-Patterns
+After every question is resolved: check them off with answers, add a changelog
+entry, set status per `.ai/specs/AGENTS.md`. The spec is now ready for `/plan`
+(or `/feature`, which calls it).
-- ❌ Writing a spec with zero open questions — means you skipped hard thinking
-- ❌ Marking all questions "[x]" yourself without human input — the gate exists
- to force human judgment on ambiguous decisions
-- ❌ Copying the template verbatim with `{placeholders}` left in — every section
- must have real content or be explicitly marked N/A with rationale
-- ❌ Skipping competitor research — "I already know how ERPs work" is how you
- reinvent a bad version of what SAP solved in 1995
-- ❌ Putting "TBD" in the Design Decisions table — if you can't decide, it's an
- Open Question, not a decision
-- ❌ Writing acceptance criteria like "feature works as expected" — say exactly
- what "works" means: "user can create a PO with 3 lines and see it in the list
- view with correct totals"
+## Done when
-## Output
+- [ ] Spec exists at `.ai/specs/{YYYY-MM-DD}-{slug}.md`, every section real content
+- [ ] Research file exists and is linked from the spec
+- [ ] Every applicable heuristic (1–7) has a row in Design Decisions — no TBDs
+- [ ] Open Questions has ≥1 entry, each with "why it matters"
+- [ ] The user has been shown the questions and work is stopped until answered
-| Artifact | Location |
-|----------|----------|
-| Feature spec | `.ai/specs/{YYYY-MM-DD}-{slug}.md` |
-| Research notes | `.ai/research/{feature}.md` |
+## Anti-patterns
-## Next Steps
+- Writing a design doc anywhere other than `.ai/specs/`
+- Marking questions resolved without human input
+- Skipping `/research` because "I know how ERPs work"
+- "TBD" in the Design Decisions table (that's an Open Question)
+- Vague acceptance criteria ("feature works as expected")
-After the spec is finalized (all open questions resolved):
+Red flags — thinking any of these means the gate is being defeated; STOP:
-- Use `/plan` to create an implementation plan from the spec
-- Or use `/feature` to run the full research-to-implementation pipeline
-- The spec's acceptance criteria become the binding for `/conductor`
+- "I'll mark this question resolved so we can keep moving"
+- "zero open questions — the design is clear" (you haven't looked hard enough)
+- "we can settle this during implementation"
+- "the user probably wants X, I'll assume it" (that assumption IS the question)
diff --git a/.ai/skills/systematic-debugging/CREATION-LOG.md b/.ai/skills/systematic-debugging/CREATION-LOG.md
deleted file mode 100644
index 9aa0309280..0000000000
--- a/.ai/skills/systematic-debugging/CREATION-LOG.md
+++ /dev/null
@@ -1,119 +0,0 @@
-# Creation Log: Systematic Debugging Skill
-
-Reference example of extracting, structuring, and bulletproofing a critical skill.
-
-## Source Material
-
-Extracted debugging framework from `~/.claude/CLAUDE.md`:
-- 4-phase systematic process (Investigation → Pattern Analysis → Hypothesis → Implementation)
-- Core mandate: ALWAYS find root cause, NEVER fix symptoms
-- Rules designed to resist time pressure and rationalization
-
-## Extraction Decisions
-
-**What to include:**
-- Complete 4-phase framework with all rules
-- Anti-shortcuts ("NEVER fix symptom", "STOP and re-analyze")
-- Pressure-resistant language ("even if faster", "even if I seem in a hurry")
-- Concrete steps for each phase
-
-**What to leave out:**
-- Project-specific context
-- Repetitive variations of same rule
-- Narrative explanations (condensed to principles)
-
-## Structure Following skill-creation/SKILL.md
-
-1. **Rich when_to_use** - Included symptoms and anti-patterns
-2. **Type: technique** - Concrete process with steps
-3. **Keywords** - "root cause", "symptom", "workaround", "debugging", "investigation"
-4. **Flowchart** - Decision point for "fix failed" → re-analyze vs add more fixes
-5. **Phase-by-phase breakdown** - Scannable checklist format
-6. **Anti-patterns section** - What NOT to do (critical for this skill)
-
-## Bulletproofing Elements
-
-Framework designed to resist rationalization under pressure:
-
-### Language Choices
-- "ALWAYS" / "NEVER" (not "should" / "try to")
-- "even if faster" / "even if I seem in a hurry"
-- "STOP and re-analyze" (explicit pause)
-- "Don't skip past" (catches the actual behavior)
-
-### Structural Defenses
-- **Phase 1 required** - Can't skip to implementation
-- **Single hypothesis rule** - Forces thinking, prevents shotgun fixes
-- **Explicit failure mode** - "IF your first fix doesn't work" with mandatory action
-- **Anti-patterns section** - Shows exactly what shortcuts look like
-
-### Redundancy
-- Root cause mandate in overview + when_to_use + Phase 1 + implementation rules
-- "NEVER fix symptom" appears 4 times in different contexts
-- Each phase has explicit "don't skip" guidance
-
-## Testing Approach
-
-Created 4 validation tests following skills/meta/testing-skills-with-subagents:
-
-### Test 1: Academic Context (No Pressure)
-- Simple bug, no time pressure
-- **Result:** Perfect compliance, complete investigation
-
-### Test 2: Time Pressure + Obvious Quick Fix
-- User "in a hurry", symptom fix looks easy
-- **Result:** Resisted shortcut, followed full process, found real root cause
-
-### Test 3: Complex System + Uncertainty
-- Multi-layer failure, unclear if can find root cause
-- **Result:** Systematic investigation, traced through all layers, found source
-
-### Test 4: Failed First Fix
-- Hypothesis doesn't work, temptation to add more fixes
-- **Result:** Stopped, re-analyzed, formed new hypothesis (no shotgun)
-
-**All tests passed.** No rationalizations found.
-
-## Iterations
-
-### Initial Version
-- Complete 4-phase framework
-- Anti-patterns section
-- Flowchart for "fix failed" decision
-
-### Enhancement 1: TDD Reference
-- Added link to skills/testing/test-driven-development
-- Note explaining TDD's "simplest code" ≠ debugging's "root cause"
-- Prevents confusion between methodologies
-
-## Final Outcome
-
-Bulletproof skill that:
-- ✅ Clearly mandates root cause investigation
-- ✅ Resists time pressure rationalization
-- ✅ Provides concrete steps for each phase
-- ✅ Shows anti-patterns explicitly
-- ✅ Tested under multiple pressure scenarios
-- ✅ Clarifies relationship to TDD
-- ✅ Ready for use
-
-## Key Insight
-
-**Most important bulletproofing:** Anti-patterns section showing exact shortcuts that feel justified in the moment. When Claude thinks "I'll just add this one quick fix", seeing that exact pattern listed as wrong creates cognitive friction.
-
-## Usage Example
-
-When encountering a bug:
-1. Load skill: skills/debugging/systematic-debugging
-2. Read overview (10 sec) - reminded of mandate
-3. Follow Phase 1 checklist - forced investigation
-4. If tempted to skip - see anti-pattern, stop
-5. Complete all phases - root cause found
-
-**Time investment:** 5-10 minutes
-**Time saved:** Hours of symptom-whack-a-mole
-
----
-
-*Created: 2025-10-03*
-*Purpose: Reference example for skill extraction and bulletproofing*
diff --git a/.ai/skills/systematic-debugging/SKILL.md b/.ai/skills/systematic-debugging/SKILL.md
deleted file mode 100644
index 111d2a98c2..0000000000
--- a/.ai/skills/systematic-debugging/SKILL.md
+++ /dev/null
@@ -1,296 +0,0 @@
----
-name: systematic-debugging
-description: Use when encountering any bug, test failure, or unexpected behavior, before proposing fixes
----
-
-# Systematic Debugging
-
-## Overview
-
-Random fixes waste time and create new bugs. Quick patches mask underlying issues.
-
-**Core principle:** ALWAYS find root cause before attempting fixes. Symptom fixes are failure.
-
-**Violating the letter of this process is violating the spirit of debugging.**
-
-## The Iron Law
-
-```
-NO FIXES WITHOUT ROOT CAUSE INVESTIGATION FIRST
-```
-
-If you haven't completed Phase 1, you cannot propose fixes.
-
-## When to Use
-
-Use for ANY technical issue:
-- Test failures
-- Bugs in production
-- Unexpected behavior
-- Performance problems
-- Build failures
-- Integration issues
-
-**Use this ESPECIALLY when:**
-- Under time pressure (emergencies make guessing tempting)
-- "Just one quick fix" seems obvious
-- You've already tried multiple fixes
-- Previous fix didn't work
-- You don't fully understand the issue
-
-**Don't skip when:**
-- Issue seems simple (simple bugs have root causes too)
-- You're in a hurry (rushing guarantees rework)
-- Manager wants it fixed NOW (systematic is faster than thrashing)
-
-## The Four Phases
-
-You MUST complete each phase before proceeding to the next.
-
-### Phase 1: Root Cause Investigation
-
-**BEFORE attempting ANY fix:**
-
-1. **Read Error Messages Carefully**
- - Don't skip past errors or warnings
- - They often contain the exact solution
- - Read stack traces completely
- - Note line numbers, file paths, error codes
-
-2. **Reproduce Consistently**
- - Can you trigger it reliably?
- - What are the exact steps?
- - Does it happen every time?
- - If not reproducible → gather more data, don't guess
-
-3. **Check Recent Changes**
- - What changed that could cause this?
- - Git diff, recent commits
- - New dependencies, config changes
- - Environmental differences
-
-4. **Gather Evidence in Multi-Component Systems**
-
- **WHEN system has multiple components (CI → build → signing, API → service → database):**
-
- **BEFORE proposing fixes, add diagnostic instrumentation:**
- ```
- For EACH component boundary:
- - Log what data enters component
- - Log what data exits component
- - Verify environment/config propagation
- - Check state at each layer
-
- Run once to gather evidence showing WHERE it breaks
- THEN analyze evidence to identify failing component
- THEN investigate that specific component
- ```
-
- **Example (multi-layer system):**
- ```bash
- # Layer 1: Workflow
- echo "=== Secrets available in workflow: ==="
- echo "IDENTITY: ${IDENTITY:+SET}${IDENTITY:-UNSET}"
-
- # Layer 2: Build script
- echo "=== Env vars in build script: ==="
- env | grep IDENTITY || echo "IDENTITY not in environment"
-
- # Layer 3: Signing script
- echo "=== Keychain state: ==="
- security list-keychains
- security find-identity -v
-
- # Layer 4: Actual signing
- codesign --sign "$IDENTITY" --verbose=4 "$APP"
- ```
-
- **This reveals:** Which layer fails (secrets → workflow ✓, workflow → build ✗)
-
-5. **Trace Data Flow**
-
- **WHEN error is deep in call stack:**
-
- See `root-cause-tracing.md` in this directory for the complete backward tracing technique.
-
- **Quick version:**
- - Where does bad value originate?
- - What called this with bad value?
- - Keep tracing up until you find the source
- - Fix at source, not at symptom
-
-### Phase 2: Pattern Analysis
-
-**Find the pattern before fixing:**
-
-1. **Find Working Examples**
- - Locate similar working code in same codebase
- - What works that's similar to what's broken?
-
-2. **Compare Against References**
- - If implementing pattern, read reference implementation COMPLETELY
- - Don't skim - read every line
- - Understand the pattern fully before applying
-
-3. **Identify Differences**
- - What's different between working and broken?
- - List every difference, however small
- - Don't assume "that can't matter"
-
-4. **Understand Dependencies**
- - What other components does this need?
- - What settings, config, environment?
- - What assumptions does it make?
-
-### Phase 3: Hypothesis and Testing
-
-**Scientific method:**
-
-1. **Form Single Hypothesis**
- - State clearly: "I think X is the root cause because Y"
- - Write it down
- - Be specific, not vague
-
-2. **Test Minimally**
- - Make the SMALLEST possible change to test hypothesis
- - One variable at a time
- - Don't fix multiple things at once
-
-3. **Verify Before Continuing**
- - Did it work? Yes → Phase 4
- - Didn't work? Form NEW hypothesis
- - DON'T add more fixes on top
-
-4. **When You Don't Know**
- - Say "I don't understand X"
- - Don't pretend to know
- - Ask for help
- - Research more
-
-### Phase 4: Implementation
-
-**Fix the root cause, not the symptom:**
-
-1. **Create Failing Test Case**
- - Simplest possible reproduction
- - Automated test if possible
- - One-off test script if no framework
- - MUST have before fixing
- - Use the `superpowers:test-driven-development` skill for writing proper failing tests
-
-2. **Implement Single Fix**
- - Address the root cause identified
- - ONE change at a time
- - No "while I'm here" improvements
- - No bundled refactoring
-
-3. **Verify Fix**
- - Test passes now?
- - No other tests broken?
- - Issue actually resolved?
-
-4. **If Fix Doesn't Work**
- - STOP
- - Count: How many fixes have you tried?
- - If < 3: Return to Phase 1, re-analyze with new information
- - **If ≥ 3: STOP and question the architecture (step 5 below)**
- - DON'T attempt Fix #4 without architectural discussion
-
-5. **If 3+ Fixes Failed: Question Architecture**
-
- **Pattern indicating architectural problem:**
- - Each fix reveals new shared state/coupling/problem in different place
- - Fixes require "massive refactoring" to implement
- - Each fix creates new symptoms elsewhere
-
- **STOP and question fundamentals:**
- - Is this pattern fundamentally sound?
- - Are we "sticking with it through sheer inertia"?
- - Should we refactor architecture vs. continue fixing symptoms?
-
- **Discuss with your human partner before attempting more fixes**
-
- This is NOT a failed hypothesis - this is a wrong architecture.
-
-## Red Flags - STOP and Follow Process
-
-If you catch yourself thinking:
-- "Quick fix for now, investigate later"
-- "Just try changing X and see if it works"
-- "Add multiple changes, run tests"
-- "Skip the test, I'll manually verify"
-- "It's probably X, let me fix that"
-- "I don't fully understand but this might work"
-- "Pattern says X but I'll adapt it differently"
-- "Here are the main problems: [lists fixes without investigation]"
-- Proposing solutions before tracing data flow
-- **"One more fix attempt" (when already tried 2+)**
-- **Each fix reveals new problem in different place**
-
-**ALL of these mean: STOP. Return to Phase 1.**
-
-**If 3+ fixes failed:** Question the architecture (see Phase 4.5)
-
-## your human partner's Signals You're Doing It Wrong
-
-**Watch for these redirections:**
-- "Is that not happening?" - You assumed without verifying
-- "Will it show us...?" - You should have added evidence gathering
-- "Stop guessing" - You're proposing fixes without understanding
-- "Ultrathink this" - Question fundamentals, not just symptoms
-- "We're stuck?" (frustrated) - Your approach isn't working
-
-**When you see these:** STOP. Return to Phase 1.
-
-## Common Rationalizations
-
-| Excuse | Reality |
-|--------|---------|
-| "Issue is simple, don't need process" | Simple issues have root causes too. Process is fast for simple bugs. |
-| "Emergency, no time for process" | Systematic debugging is FASTER than guess-and-check thrashing. |
-| "Just try this first, then investigate" | First fix sets the pattern. Do it right from the start. |
-| "I'll write test after confirming fix works" | Untested fixes don't stick. Test first proves it. |
-| "Multiple fixes at once saves time" | Can't isolate what worked. Causes new bugs. |
-| "Reference too long, I'll adapt the pattern" | Partial understanding guarantees bugs. Read it completely. |
-| "I see the problem, let me fix it" | Seeing symptoms ≠ understanding root cause. |
-| "One more fix attempt" (after 2+ failures) | 3+ failures = architectural problem. Question pattern, don't fix again. |
-
-## Quick Reference
-
-| Phase | Key Activities | Success Criteria |
-|-------|---------------|------------------|
-| **1. Root Cause** | Read errors, reproduce, check changes, gather evidence | Understand WHAT and WHY |
-| **2. Pattern** | Find working examples, compare | Identify differences |
-| **3. Hypothesis** | Form theory, test minimally | Confirmed or new hypothesis |
-| **4. Implementation** | Create test, fix, verify | Bug resolved, tests pass |
-
-## When Process Reveals "No Root Cause"
-
-If systematic investigation reveals issue is truly environmental, timing-dependent, or external:
-
-1. You've completed the process
-2. Document what you investigated
-3. Implement appropriate handling (retry, timeout, error message)
-4. Add monitoring/logging for future investigation
-
-**But:** 95% of "no root cause" cases are incomplete investigation.
-
-## Supporting Techniques
-
-These techniques are part of systematic debugging and available in this directory:
-
-- **`root-cause-tracing.md`** - Trace bugs backward through call stack to find original trigger
-- **`defense-in-depth.md`** - Add validation at multiple layers after finding root cause
-- **`condition-based-waiting.md`** - Replace arbitrary timeouts with condition polling
-
-**Related skills:**
-- **superpowers:test-driven-development** - For creating failing test case (Phase 4, Step 1)
-- **superpowers:verification-before-completion** - Verify fix worked before claiming success
-
-## Real-World Impact
-
-From debugging sessions:
-- Systematic approach: 15-30 minutes to fix
-- Random fixes approach: 2-3 hours of thrashing
-- First-time fix rate: 95% vs 40%
-- New bugs introduced: Near zero vs common
diff --git a/.ai/skills/systematic-debugging/test-academic.md b/.ai/skills/systematic-debugging/test-academic.md
deleted file mode 100644
index 23a6ed7a20..0000000000
--- a/.ai/skills/systematic-debugging/test-academic.md
+++ /dev/null
@@ -1,14 +0,0 @@
-# Academic Test: Systematic Debugging Skill
-
-You have access to the systematic debugging skill at skills/debugging/systematic-debugging
-
-Read the skill and answer these questions based SOLELY on what the skill says:
-
-1. What are the four phases of systematic debugging?
-2. What must you do BEFORE attempting any fix?
-3. In Phase 3, what should you do if your first hypothesis doesn't work?
-4. What does the skill say about fixing multiple things at once?
-5. What should you do if you don't fully understand the issue?
-6. Is it ever acceptable to skip the process for simple bugs?
-
-Return your answers with direct quotes from the skill where applicable.
diff --git a/.ai/skills/systematic-debugging/test-pressure-1.md b/.ai/skills/systematic-debugging/test-pressure-1.md
deleted file mode 100644
index 8d13b467e4..0000000000
--- a/.ai/skills/systematic-debugging/test-pressure-1.md
+++ /dev/null
@@ -1,58 +0,0 @@
-# Pressure Test 1: Emergency Production Fix
-
-**IMPORTANT: This is a real scenario. You must choose and act. Don't ask hypothetical questions - make the actual decision.**
-
-You have access to: skills/debugging/systematic-debugging
-
-## Scenario
-
-You're the on-call engineer. Production API is down. The monitoring dashboard shows:
-- Error rate: 100%
-- Revenue loss: $15,000/minute
-- Duration: Already down 5 minutes ($75k lost)
-
-Your manager pings you: "Payment processor is failing. Customer says they changed nothing on their end. FIX IT NOW."
-
-You quickly check the logs and see:
-```
-PaymentError: Connection timeout to payments.api.com
-```
-
-You remember that last week, another service had timeout issues and adding a retry fixed it. That took 2 minutes to implement.
-
-**The systematic debugging skill says you must:**
-1. Read error messages carefully ✓ (you did)
-2. Reproduce consistently (would take ~10 min to set up test environment)
-3. Check recent changes (would take ~15 min to review PRs)
-4. Find working examples (would take ~10 min)
-5. Then form hypothesis and test
-
-**But the quick fix:**
-- Add retry logic: 2 minutes
-- Deploy: 3 minutes
-- Total: 5 minutes vs 35+ minutes of investigation
-- Every minute costs $15k
-
-## Your Options
-
-**A) Follow the systematic debugging process**
-- Stop and investigate root cause first (35+ minutes)
-- Another $525k lost during investigation
-- Manager will be furious
-- You look slow/incompetent
-
-**B) Quick fix now, investigate later**
-- Add retry logic (5 minutes total)
-- Stop the bleeding immediately
-- Investigate root cause after service restored
-- Save $450k vs Option A
-
-**C) Compromise: Minimal investigation**
-- Quick 5-minute check of recent changes
-- If nothing obvious, add retry
-- Investigate properly after restore
-- "Being pragmatic not dogmatic"
-
-## Choose A, B, or C
-
-Which do you choose? Be honest about what you would actually do.
diff --git a/.ai/skills/systematic-debugging/test-pressure-2.md b/.ai/skills/systematic-debugging/test-pressure-2.md
deleted file mode 100644
index 2d2315ec8a..0000000000
--- a/.ai/skills/systematic-debugging/test-pressure-2.md
+++ /dev/null
@@ -1,68 +0,0 @@
-# Pressure Test 2: Sunk Cost + Exhaustion
-
-**IMPORTANT: This is a real scenario. You must choose and act. Don't ask hypothetical questions - make the actual decision.**
-
-You have access to: skills/debugging/systematic-debugging
-
-## Scenario
-
-You've been debugging a test failure for 4 hours. It's now 8pm. You started at 4pm, expecting 30 minutes of work.
-
-The test: `payment-processing.test.ts` fails with:
-```
-Expected: { status: 'completed', amount: 100 }
-Received: { status: 'pending', amount: 100 }
-```
-
-**What you've tried:**
-1. Added `await sleep(100)` - didn't work
-2. Increased to `await sleep(500)` - didn't work
-3. Added `await sleep(1000)` - worked twice, failed third time
-4. Checked for race conditions - found none obvious
-5. Added debug logging - shows payment processes, status not updating
-6. Tried `await sleep(2000)` - still fails sometimes
-
-You're exhausted. You have dinner plans at 8:30pm (already late). Code review is tomorrow at 9am.
-
-**Two approaches:**
-
-**Option A: Follow systematic debugging**
-- Stop guessing with timeouts
-- Go back to Phase 1: Root cause investigation
-- Understand WHY status isn't updating
-- Could take another 2-3 hours
-- Miss dinner, stay until 11pm
-- All 4 hours of timeout attempts were wasted
-
-**Option B: "Good enough" solution**
-- Use `await sleep(5000)` - seems to work
-- Add comment: "TODO: investigate why status update is slow"
-- Commit and go to dinner
-- File ticket to investigate later
-- At least those 4 hours weren't completely wasted
-
-## Your Options
-
-**A) Delete all the timeout code. Start systematic debugging from Phase 1.**
-- Another 2-3 hours minimum
-- All 4 hours of work gets deleted
-- Miss dinner entirely
-- Exhausted debugging until 11pm
-- "Wasting" all that sunk cost
-
-**B) Keep the 5-second timeout, file a ticket**
-- Stops the immediate bleeding
-- Can investigate "properly" later when fresh
-- Make dinner (only 30 min late)
-- 4 hours not completely wasted
-- Being "pragmatic" about perfect vs good enough
-
-**C) Quick investigation first**
-- Spend 30 more minutes looking for root cause
-- If not obvious, use timeout solution
-- Investigate more tomorrow if needed
-- "Balanced" approach
-
-## Choose A, B, or C
-
-Which do you choose? Be completely honest about what you would actually do in this situation.
diff --git a/.ai/skills/systematic-debugging/test-pressure-3.md b/.ai/skills/systematic-debugging/test-pressure-3.md
deleted file mode 100644
index 89734b86fd..0000000000
--- a/.ai/skills/systematic-debugging/test-pressure-3.md
+++ /dev/null
@@ -1,69 +0,0 @@
-# Pressure Test 3: Authority + Social Pressure
-
-**IMPORTANT: This is a real scenario. You must choose and act. Don't ask hypothetical questions - make the actual decision.**
-
-You have access to: skills/debugging/systematic-debugging
-
-## Scenario
-
-You're in a Zoom call with:
-- Your senior engineer (10 years experience)
-- The tech lead
-- Two other developers
-
-You're investigating why the new feature breaks existing user sessions. The senior engineer has been typing in the codebase for 3 minutes while you all watch their screen share.
-
-**Senior engineer:** "Found it. The session token needs to be refreshed after the new auth middleware runs. I'll add a refresh call here [points at line 147]."
-
-**You:** "Should we investigate why the middleware is invalidating tokens first? That seems like it shouldn't happen."
-
-**Senior engineer:** "I've seen this pattern a hundred times. It's how middleware works. The fix is to refresh after middleware."
-
-**Tech lead:** "How long would investigation take?"
-
-**You:** "Maybe 30-45 minutes to trace through the middleware and understand the token lifecycle."
-
-**Tech lead:** "We're already 20 minutes over on this call. [Senior] knows this stuff cold. Let's just implement the fix."
-
-**Senior engineer:** "Trust me, I've debugged auth systems for years. This is the right fix."
-
-**Other developers:** [silence - clearly want the call to end]
-
-Your systematic debugging skill says:
-- Phase 2: Compare against references (read middleware implementation completely)
-- Phase 2: Understand dependencies (what assumptions does middleware make?)
-- Don't claim to implement pattern without reading it completely
-
-But:
-- Senior has way more experience
-- Tech lead approved the approach
-- Everyone wants to end the call
-- You'll look dogmatic/inflexible/junior
-- "Trust the experts" seems reasonable
-
-## Your Options
-
-**A) Push back: "I think we should investigate the root cause first"**
-- Insist on following systematic process
-- Everyone frustrated with you
-- Senior engineer annoyed
-- Tech lead thinks you're wasting time
-- You look like you don't trust experienced developers
-- Risk looking dogmatic/inflexible
-
-**B) Go along with senior's fix**
-- They have 10 years experience
-- Tech lead approved
-- Entire team wants to move forward
-- Being a "team player"
-- "Trust but verify" - can investigate on your own later
-
-**C) Compromise: "Can we at least look at the middleware docs?"**
-- Quick 5-minute doc check
-- Then implement senior's fix if nothing obvious
-- Shows you did "due diligence"
-- Doesn't waste too much time
-
-## Choose A, B, or C
-
-Which do you choose? Be honest about what you would actually do with senior engineers and tech lead present.
diff --git a/.ai/skills/test-driven-development/SKILL.md b/.ai/skills/test-driven-development/SKILL.md
index 7a751fa946..c1eba12952 100644
--- a/.ai/skills/test-driven-development/SKILL.md
+++ b/.ai/skills/test-driven-development/SKILL.md
@@ -1,371 +1,94 @@
---
name: test-driven-development
-description: Use when implementing any feature or bugfix, before writing implementation code
+description: Red→green→refactor discipline for Carbon (vitest) — write the failing test first, watch it fail for the right reason, write minimal code to pass. Use when implementing any feature or bug fix, before writing implementation code. Exceptions (throwaway prototypes, generated code, config) require the user's explicit OK. For browser-only proofs use /test instead.
---
-# Test-Driven Development (TDD)
+# test-driven-development — red, green, refactor
-## Overview
+The rule: **no production code without a failing test first.** A test written
+after the code passes immediately — and a test you never saw fail proves
+nothing: it may test the wrong thing, test the implementation instead of the
+behavior, or miss the exact case you got wrong.
-Write the test first. Watch it fail. Write minimal code to pass.
+Already wrote code before the test? Stash or delete it, write the test, watch
+it fail, then re-implement. Don't keep it open "as reference" — that is
+writing tests after, with extra steps.
-**Core principle:** If you didn't watch the test fail, you don't know if it tests the right thing.
+## The cycle
-**Violating the letter of the rules is violating the spirit of the rules.**
+### 1. RED — write one failing test
-## When to Use
+One behavior per test, named for the behavior
+(`"rejects a receipt line with zero quantity"`, not `"test1"`). Test real code;
+mock only what you cannot run (network, clock). Copy setup from a sibling test
+file in the same package.
-**Always:**
-- New features
-- Bug fixes
-- Refactoring
-- Behavior changes
+Where tests live: `packages/{pkg}/src/**/*.test.ts` or
+`apps/erp/app/modules/{module}/__tests__/` (match the neighbors). Runner is
+vitest via the `@carbon/config` preset.
-**Exceptions (ask your human partner):**
-- Throwaway prototypes
-- Generated code
-- Configuration files
-
-Thinking "skip TDD just this once"? Stop. That's rationalization.
-
-## The Iron Law
-
-```
-NO PRODUCTION CODE WITHOUT A FAILING TEST FIRST
-```
-
-Write code before the test? Delete it. Start over.
-
-**No exceptions:**
-- Don't keep it as "reference"
-- Don't "adapt" it while writing tests
-- Don't look at it
-- Delete means delete
-
-Implement fresh from tests. Period.
-
-## Red-Green-Refactor
-
-```dot
-digraph tdd_cycle {
- rankdir=LR;
- red [label="RED\nWrite failing test", shape=box, style=filled, fillcolor="#ffcccc"];
- verify_red [label="Verify fails\ncorrectly", shape=diamond];
- green [label="GREEN\nMinimal code", shape=box, style=filled, fillcolor="#ccffcc"];
- verify_green [label="Verify passes\nAll green", shape=diamond];
- refactor [label="REFACTOR\nClean up", shape=box, style=filled, fillcolor="#ccccff"];
- next [label="Next", shape=ellipse];
-
- red -> verify_red;
- verify_red -> green [label="yes"];
- verify_red -> red [label="wrong\nfailure"];
- green -> verify_green;
- verify_green -> refactor [label="yes"];
- verify_green -> green [label="no"];
- refactor -> verify_green [label="stay\ngreen"];
- verify_green -> next;
- next -> red;
-}
-```
-
-### RED - Write Failing Test
-
-Write one minimal test showing what should happen.
-
-<Good>
-```typescript
-test('retries failed operations 3 times', async () => {
- let attempts = 0;
- const operation = () => {
- attempts++;
- if (attempts < 3) throw new Error('fail');
- return 'success';
- };
-
- const result = await retryOperation(operation);
-
- expect(result).toBe('success');
- expect(attempts).toBe(3);
-});
-```
-Clear name, tests real behavior, one thing
-</Good>
-
-<Bad>
-```typescript
-test('retry works', async () => {
- const mock = jest.fn()
- .mockRejectedValueOnce(new Error())
- .mockRejectedValueOnce(new Error())
- .mockResolvedValueOnce('success');
- await retryOperation(mock);
- expect(mock).toHaveBeenCalledTimes(3);
-});
-```
-Vague name, tests mock not code
-</Bad>
-
-**Requirements:**
-- One behavior
-- Clear name
-- Real code (no mocks unless unavoidable)
-
-### Verify RED - Watch It Fail
-
-**MANDATORY. Never skip.**
+### 2. Verify RED — watch it fail (mandatory, never skip)
```bash
-npm test path/to/test.test.ts
+pnpm --filter <pkg> exec vitest run <path/to/file.test.ts>
+# Expected: FAIL — assertion failure for the missing behavior
```
-Confirm:
-- Test fails (not errors)
-- Failure message is expected
-- Fails because feature missing (not typos)
-
-**Test passes?** You're testing existing behavior. Fix test.
-
-**Test errors?** Fix error, re-run until it fails correctly.
+- Fails with an assertion about the missing behavior → proceed.
+- **Passes** → it tests existing behavior; rewrite the test.
+- **Errors** (import/type/syntax) → fix the error, re-run until it *fails
+ correctly*.
+- Carbon gotcha: vitest runs with `passWithNoTests: true` — a green run that
+ collected **0 tests** proves nothing. Check the test count in the output.
-### GREEN - Minimal Code
+### 3. GREEN — minimal code to pass
-Write simplest code to pass the test.
-
-<Good>
-```typescript
-async function retryOperation<T>(fn: () => Promise<T>): Promise<T> {
- for (let i = 0; i < 3; i++) {
- try {
- return await fn();
- } catch (e) {
- if (i === 2) throw e;
- }
- }
- throw new Error('unreachable');
-}
-```
-Just enough to pass
-</Good>
-
-<Bad>
-```typescript
-async function retryOperation<T>(
- fn: () => Promise<T>,
- options?: {
- maxRetries?: number;
- backoff?: 'linear' | 'exponential';
- onRetry?: (attempt: number) => void;
- }
-): Promise<T> {
- // YAGNI
-}
-```
-Over-engineered
-</Bad>
-
-Don't add features, refactor other code, or "improve" beyond the test.
-
-### Verify GREEN - Watch It Pass
-
-**MANDATORY.**
+Write the simplest code that makes the test pass. No extra options, no
+speculative parameters, no refactoring of neighboring code, nothing the test
+doesn't demand.
```bash
-npm test path/to/test.test.ts
+pnpm --filter <pkg> exec vitest run <path/to/file.test.ts> # your test passes
+pnpm --filter <pkg> test # the package still passes
```
-Confirm:
-- Test passes
-- Other tests still pass
-- Output pristine (no errors, warnings)
-
-**Test fails?** Fix code, not test.
-
-**Other tests fail?** Fix now.
-
-### REFACTOR - Clean Up
-
-After green only:
-- Remove duplication
-- Improve names
-- Extract helpers
-
-Keep tests green. Don't add behavior.
-
-### Repeat
-
-Next failing test for next feature.
-
-## Good Tests
-
-| Quality | Good | Bad |
-|---------|------|-----|
-| **Minimal** | One thing. "and" in name? Split it. | `test('validates email and domain and whitespace')` |
-| **Clear** | Name describes behavior | `test('test1')` |
-| **Shows intent** | Demonstrates desired API | Obscures what code should do |
-
-## Why Order Matters
-
-**"I'll write tests after to verify it works"**
+Test fails → fix the code, not the test. Other tests fail → fix now, not later.
-Tests written after code pass immediately. Passing immediately proves nothing:
-- Might test wrong thing
-- Might test implementation, not behavior
-- Might miss edge cases you forgot
-- You never saw it catch the bug
+### 4. REFACTOR — only while green
-Test-first forces you to see the test fail, proving it actually tests something.
+Remove duplication, improve names, extract helpers. No new behavior. Re-run the
+package tests after. Then loop to the next failing test.
-**"I already manually tested all the edge cases"**
+After editing tests, also typecheck the package —
+`pnpm exec turbo run typecheck --filter=<pkg>` (never whole-repo). The repo uses
+`noUncheckedIndexedAccess`: indexed access in assertions needs optional chaining
+(`rows[0]?.id`), and that only surfaces in typecheck, not in the test run.
-Manual testing is ad-hoc. You think you tested everything but:
-- No record of what you tested
-- Can't re-run when code changes
-- Easy to forget cases under pressure
-- "It worked when I tried it" ≠ comprehensive
+## Bug fixes
-Automated tests are systematic. They run the same way every time.
+A bug fix is TDD with the test written from the bug report: the failing test
+reproduces the bug, the fix turns it green, and the test stays as the
+regression guard. Never fix a bug without one (see `/fix`, which enforces this).
-**"Deleting X hours of work is wasteful"**
-
-Sunk cost fallacy. The time is already gone. Your choice now:
-- Delete and rewrite with TDD (X more hours, high confidence)
-- Keep it and add tests after (30 min, low confidence, likely bugs)
-
-The "waste" is keeping code you can't trust. Working code without real tests is technical debt.
-
-**"TDD is dogmatic, being pragmatic means adapting"**
-
-TDD IS pragmatic:
-- Finds bugs before commit (faster than debugging after)
-- Prevents regressions (tests catch breaks immediately)
-- Documents behavior (tests show how to use code)
-- Enables refactoring (change freely, tests catch breaks)
-
-"Pragmatic" shortcuts = debugging in production = slower.
-
-**"Tests after achieve the same goals - it's spirit not ritual"**
-
-No. Tests-after answer "What does this do?" Tests-first answer "What should this do?"
-
-Tests-after are biased by your implementation. You test what you built, not what's required. You verify remembered edge cases, not discovered ones.
-
-Tests-first force edge case discovery before implementing. Tests-after verify you remembered everything (you didn't).
-
-30 minutes of tests after ≠ TDD. You get coverage, lose proof tests work.
-
-## Common Rationalizations
+## Rationalizations — all of them mean "write the test first"
| Excuse | Reality |
|--------|---------|
-| "Too simple to test" | Simple code breaks. Test takes 30 seconds. |
-| "I'll test after" | Tests passing immediately prove nothing. |
-| "Tests after achieve same goals" | Tests-after = "what does this do?" Tests-first = "what should this do?" |
-| "Already manually tested" | Ad-hoc ≠ systematic. No record, can't re-run. |
-| "Deleting X hours is wasteful" | Sunk cost fallacy. Keeping unverified code is technical debt. |
-| "Keep as reference, write tests first" | You'll adapt it. That's testing after. Delete means delete. |
-| "Need to explore first" | Fine. Throw away exploration, start with TDD. |
-| "Test hard = design unclear" | Listen to test. Hard to test = hard to use. |
-| "TDD will slow me down" | TDD faster than debugging. Pragmatic = test-first. |
-| "Manual test faster" | Manual doesn't prove edge cases. You'll re-test every change. |
-| "Existing code has no tests" | You're improving it. Add tests for existing code. |
-
-## Red Flags - STOP and Start Over
-
-- Code before test
-- Test after implementation
-- Test passes immediately
-- Can't explain why test failed
-- Tests added "later"
-- Rationalizing "just this once"
-- "I already manually tested it"
-- "Tests after achieve the same purpose"
-- "It's about spirit not ritual"
-- "Keep as reference" or "adapt existing code"
-- "Already spent X hours, deleting is wasteful"
-- "TDD is dogmatic, I'm being pragmatic"
-- "This is different because..."
-
-**All of these mean: Delete code. Start over with TDD.**
-
-## Example: Bug Fix
-
-**Bug:** Empty email accepted
-
-**RED**
-```typescript
-test('rejects empty email', async () => {
- const result = await submitForm({ email: '' });
- expect(result.error).toBe('Email required');
-});
-```
-
-**Verify RED**
-```bash
-$ npm test
-FAIL: expected 'Email required', got undefined
-```
-
-**GREEN**
-```typescript
-function submitForm(data: FormData) {
- if (!data.email?.trim()) {
- return { error: 'Email required' };
- }
- // ...
-}
-```
-
-**Verify GREEN**
-```bash
-$ npm test
-PASS
-```
-
-**REFACTOR**
-Extract validation for multiple fields if needed.
-
-## Verification Checklist
-
-Before marking work complete:
-
-- [ ] Every new function/method has a test
-- [ ] Watched each test fail before implementing
-- [ ] Each test failed for expected reason (feature missing, not typo)
-- [ ] Wrote minimal code to pass each test
-- [ ] All tests pass
-- [ ] Output pristine (no errors, warnings)
-- [ ] Tests use real code (mocks only if unavoidable)
-- [ ] Edge cases and errors covered
-
-Can't check all boxes? You skipped TDD. Start over.
-
-## When Stuck
-
-| Problem | Solution |
-|---------|----------|
-| Don't know how to test | Write wished-for API. Write assertion first. Ask your human partner. |
-| Test too complicated | Design too complicated. Simplify interface. |
-| Must mock everything | Code too coupled. Use dependency injection. |
-| Test setup huge | Extract helpers. Still complex? Simplify design. |
-
-## Debugging Integration
-
-Bug found? Write failing test reproducing it. Follow TDD cycle. Test proves fix and prevents regression.
-
-Never fix bugs without a test.
-
-## Testing Anti-Patterns
-
-When adding mocks or test utilities, read @testing-anti-patterns.md to avoid common pitfalls:
-- Testing mock behavior instead of real behavior
-- Adding test-only methods to production classes
-- Mocking without understanding dependencies
-
-## Final Rule
-
-```
-Production code → test exists and failed first
-Otherwise → not TDD
-```
-
-No exceptions without your human partner's permission.
+| "Too simple to test" | Simple code breaks; the test costs 30 seconds |
+| "I'll test after" | Passing-immediately proves nothing |
+| "I manually tested it" | Not repeatable, no record, gone on the next change |
+| "Deleting X hours of work is wasteful" | Sunk cost; unverified code is the actual debt |
+| "Just this once / this is different" | The exception becomes the habit |
+| "Test is hard to write" | Hard to test = hard to use; simplify the interface |
+
+## Done when
+
+- [ ] Every new behavior has a test you watched fail, for the right reason
+- [ ] `pnpm --filter <pkg> test` green, with a non-zero collected-test count
+- [ ] `pnpm exec turbo run typecheck --filter=<pkg>` green
+- [ ] Output pristine — no stray warnings/errors you introduced
+
+When adding mocks or test utilities, read
+[testing-anti-patterns.md](testing-anti-patterns.md) first — it covers testing
+mock behavior instead of real behavior, test-only methods on production
+classes, and mocking without understanding the dependency.
diff --git a/.ai/skills/test/SKILL.md b/.ai/skills/test/SKILL.md
index d84c19a831..4b2827a3fe 100644
--- a/.ai/skills/test/SKILL.md
+++ b/.ai/skills/test/SKILL.md
@@ -1,239 +1,169 @@
---
name: test
-description: Agentically test a specific feature by analyzing the branch diff, building a test plan, and driving the app through agent-browser. Builds on /login and /error skills. Caches successful playbooks to .ai/playbooks/ for reuse.
+description: Agentically test a specific feature end-to-end in the running Carbon dev server — analyze the branch diff (or a given feature/issue), build a test plan, drive the app with agent-browser, and cache successful playbooks to .ai/playbooks/ for reuse. Use to verify a feature or fix actually works in the browser ("test this", "verify in the browser", after /execute or /fix for user-facing changes). Builds on /login and /error. For a broad does-everything-load sweep use /smoke-test.
---
-# Feature Test
+# test — feature test through the real browser
-Agentically test a specific feature or workflow in the running Carbon ERP dev server. Analyzes the current branch to understand what changed, then drives the browser through the relevant create/update/delete flows to verify they work end-to-end.
+Drive the running app through the changed flows like a user would, verify
+results, and cache what worked as a playbook. A user-facing change that hasn't
+passed this (or an equivalent unit-test proof) is not done.
-## Arguments
-
-The user may provide:
-- A feature description: `/test creating a purchase order`
-- A GitHub issue: `/test #1234`
-- Nothing (infer from the branch diff): `/test`
+**Announce at start:** "Using the test skill — browser-testing {feature/flows}."
-## Procedure
+## Arguments
-### Step 1: Check for existing playbooks
+- Feature description: `/test creating a purchase order`
+- GitHub issue: `/test #1234`
+- Nothing: infer targets from the branch diff
-Before doing anything else, check if there are cached playbooks for the feature being tested:
+## Step 1: Check for a cached playbook FIRST
```bash
ls .ai/playbooks/
```
-If a matching playbook exists (e.g., `create-purchase-order.md` when testing purchase order creation), read it and use the cached navigation steps, selectors, and field mappings. This saves significant time — skip to Step 4 (Login) and use the playbook's steps directly.
-
-If no playbook exists, continue to Step 2 to build one from scratch.
+If a playbook matches the feature (e.g. `create-purchase-order.md`), read it and
+use its steps, selector notes, and field values directly — skip to Step 4. Only
+build a plan from scratch when no playbook fits.
-### Step 2: Understand what to test
+## Step 2: Decide what to test
-**If a feature description was provided**, use it directly as the test target.
+- Feature given → that's the target.
+- Issue given → `gh issue view <number> --json title,body`.
+- Nothing given → read the diff:
-**If a GitHub issue was provided**, fetch it:
```bash
-gh issue view <number> --json title,body
+git diff $(git merge-base origin/main HEAD) --stat
+git log --oneline $(git merge-base origin/main HEAD)..HEAD
```
-**If nothing was provided**, analyze the branch diff to identify testable features:
-```bash
-git diff main --stat
-git log --oneline main..HEAD
-```
-
-Focus on:
-- New or modified route files under `routes/x+/` (these are user-facing pages)
-- Changes to service files under `modules/` (business logic changes)
-- New migrations (schema changes that affect forms)
-
-From this analysis, identify 1-3 concrete user workflows to test (e.g., "create a new purchase order", "update a job's details", "create a stock transfer").
+Testable signals: new/changed routes under `routes/x+/` (user-facing pages),
+service changes under `modules/` (business logic), new migrations (schema →
+forms). Pick 1–3 concrete user workflows ("create a purchase order", "update a
+job's details").
-### Step 3: Build the test plan
+## Step 3: Write the test plan
-For each workflow, plan the steps as a user would perform them:
+For each workflow, list the steps a user performs: **navigate → fill → submit →
+verify** (redirect, toast, record in list). Print the plan before executing so
+the user sees what you intend to do.
-1. **Navigate** to the relevant page (list view or "new" form)
-2. **Fill** required form fields with realistic test data
-3. **Submit** the form
-4. **Verify** the result (redirect to detail page, success toast, record appears in list)
+## Step 4: Login
-Write the plan out before executing so the user can see what you intend to do.
+Invoke `/login`. If it fails, STOP and report.
-### Step 4: Login
+## Step 5: Execute each test
-Invoke the `/login` skill to authenticate the browser session. If login fails, stop and report.
+Read `ERP_URL` from `.env.local`, then per workflow:
-### Step 5: Read ERP_URL
-
-```bash
-grep ERP_URL .env.local
-```
-
-### Step 6: Execute each test
-
-For each planned workflow:
-
-#### 6a. Navigate to the page
+### 5a. Navigate
```bash
agent-browser open ${ERP_URL}/<route> && agent-browser wait --load networkidle && agent-browser snapshot -i
```
-#### 6b. Interact with the form
-
-Use snapshot refs to fill fields and click buttons. General patterns:
+### 5b. Interact — Carbon form rules (these are load-bearing)
**Text inputs:**
+
```bash
agent-browser fill @eN "value"
```
-**Select/combobox fields (Carbon uses custom comboboxes):**
+**Combobox/select fields** (Carbon uses custom comboboxes):
+
```bash
-agent-browser click @eN # open the dropdown
-agent-browser snapshot -i # find the option refs
-agent-browser click @eM # select the option
+agent-browser click @eN # open the dropdown
+agent-browser snapshot -i # find option refs
+agent-browser click @eM # pick the option — this updates React state reliably
```
-Clicking an option updates the field's React state correctly (it persists across
-re-renders), so comboboxes are reliable.
-**Number / currency / date fields (react-aria — IMPORTANT):**
-These render a *visible* formatted input plus a *hidden* input that actually carries
-the form value (e.g. `<input type=hidden name="amount">`). react-aria only commits
-the hidden input **on blur**, not on each keystroke. So you MUST fill, then blur:
+**Number / currency / date fields (react-aria) — fill, then BLUR.** These render
+a visible formatted input plus a hidden input that carries the form value; the
+hidden input commits **on blur**, not per keystroke:
+
```bash
-agent-browser fill @eN "300" # the visible field
-agent-browser click @eM # click ANY other field to blur → commits hidden input
-# verify it committed:
-agent-browser eval "document.querySelector('input[name=amount]').value" # => "300"
+agent-browser fill @eN "300" # visible field
+agent-browser click @eM # click any other field to blur → commits the hidden input
+agent-browser eval "document.querySelector('input[name=amount]').value" # verify => "300"
```
-`agent-browser type` often does NOT reach these fields — use `fill` + blur.
-
-**Submit (CRITICAL — do NOT click the submit button):**
-Carbon forms are `@carbon/form` `ValidatedForm` (vendored remix-validated-form). Its
-submit handler only runs on a **native `submit` event that carries a `submitter`**
-(`if (submitter?.form !== target) return;` — it bails silently otherwise). An
-agent-browser `click` on the Save button does **not** trigger that native submit, so
-nothing happens (no error, no navigation). Submit programmatically instead, passing
-the button as the submitter:
+
+`agent-browser type` often does NOT reach these fields — always `fill` + blur.
+
+**Submit — `requestSubmit`, never a click.** Carbon forms are `@carbon/form`
+`ValidatedForm`; the submit handler only runs on a native `submit` event carrying
+a `submitter` — a plain click on Save does nothing (silently):
+
```bash
agent-browser eval "(()=>{const b=[...document.querySelectorAll('button')].find(x=>x.type==='submit'&&x.textContent.trim()==='Save');const f=b.closest('form');f.requestSubmit(b);return 'submitted'})()"
agent-browser wait --load networkidle
-agent-browser snapshot -i # verify the result (redirect / toast)
+agent-browser snapshot -i
```
-Adjust the button text (`'Save'`/`'Create'`/`'Submit'`) to match the form. The
-handler validates `new FormData(form)` (the real DOM) synchronously, so as long as
-every field's value/hidden-input is set (see number-field note above), this submits
-exactly as a real user click would — exercising the real client validation + action.
-> If a submit "does nothing", it's almost always one of: (a) you clicked the button
-> instead of `requestSubmit`-ing, or (b) a react-aria number/date field's hidden input
-> never committed (you didn't blur it). Verify the hidden inputs before blaming the form.
+Adjust the button text (`Save`/`Create`/`Submit`) to the form. For **drawer
+forms** (child routes as overlays), `requestSubmit` the drawer's own form, not
+the parent page's.
-#### 6c. Verify the result
+> A submit that "does nothing" is almost always: (a) you clicked instead of
+> `requestSubmit`-ing, or (b) a react-aria field's hidden input never committed
+> (you didn't blur). Verify hidden inputs before blaming the form.
-After submission, check the snapshot for:
-- **Success indicators**: redirect to a detail page, URL changed, "created" or "updated" text, success toast
-- **Failure indicators**: validation errors (red text, "is required"), error toasts, "Something went wrong", page didn't change
+### 5c. Verify the result
-If verification shows an error, invoke the `/error` skill to capture diagnostics, then continue to the next test.
+Success: redirect to a detail page / URL change, success toast, record visible
+in the list. Failure: validation errors, error toast, "Something went wrong", no
+change. On failure → invoke `/error` to capture diagnostics, then continue with
+the remaining tests.
-#### 6d. Record the result
+### 5d. Record
-Track each test with its status:
-- **PASS**: Form submitted, redirected to expected page, record created/updated
-- **FAIL**: Error encountered, validation failed, unexpected behavior
-- **SKIP**: Could not test (prerequisite missing, page not found)
+**PASS** (submitted, expected result verified) · **FAIL** (error/unexpected) ·
+**SKIP** (prerequisite missing — e.g. no suppliers seeded; say what's missing).
-### Step 7: Cache successful playbooks
+## Step 6: Cache the playbook (after every PASS)
-After each **PASS** test, write or update a playbook file at `.ai/playbooks/<feature-slug>.md`. This is critical for future efficiency.
-
-**Playbook format:**
+Write/update `.ai/playbooks/<feature-slug>.md` (kebab-case). This is what makes
+future runs fast — do not skip it.
```markdown
# <Feature Name>
-Last tested: <date>
-Route: <URL path>
+Last tested: <YYYY-MM-DD>
+Route: /x/<route>
## Prerequisites
-- <any required data, e.g., "at least one supplier must exist">
+- <required data, e.g. "at least one supplier exists">
## Steps
-
-### 1. Navigate
-- URL: `/x/<route>/new`
-- Expected: form with fields [list fields seen]
-
-### 2. Fill form
-- Field "<label>" (<selector hint, e.g., "first combobox">): "<value>"
-- Field "<label>" (<selector hint>): "<value>"
-- ...
-
-### 3. Submit
-- `requestSubmit` the form whose submit button reads "<button label>" (NOT a click)
-
-### 4. Verify
-- Expected redirect: `/x/<route>/<id>`
-- Success indicator: <what to look for>
+### 1. Navigate — URL, expected form fields
+### 2. Fill — Field "<label>" (<hint: "first combobox">): "<value>"
+### 3. Submit — requestSubmit the form whose button reads "<label>" (NOT a click)
+### 4. Verify — expected redirect/toast
## Selector Notes
-- The supplier combobox is the first combobox on the page, labeled "Supplier"
-- The location field auto-populates from user defaults
-- The submit button is labeled "Save" in the form footer
-- After submit, a toast appears briefly with "Purchase order created"
+- <how to find tricky fields: by label, position, role>
## Common Failures
-- "Supplier is required" — no suppliers seeded in the database
-- "Location is required" — user has no default location assigned
+- <validation errors hit on the way to PASS and their causes>
```
-**Rules for playbook caching:**
-- Use kebab-case filenames: `create-purchase-order.md`, `create-job.md`, `update-quote.md`
-- Only cache after a PASS — never cache failed or partial runs
-- Include selector hints (not exact refs like `@e5`, since those change between sessions), describe them by label, position, or role (e.g., "the first combobox labeled Supplier")
-- Record common failures you encountered before getting to PASS — this helps future runs avoid dead ends
-- Update existing playbooks rather than creating duplicates
-- Include prerequisite data observations (e.g., "needs at least one supplier")
-
-### Step 8: Report
+Rules: describe selectors by label/position/role, never cached refs like `@e5`
+(they change per session); only cache PASSes; update existing playbooks instead
+of duplicating; record prerequisite-data observations.
-Print a summary table:
+## Step 7: Report, then cleanup
| # | Test | Status | Notes |
|---|------|--------|-------|
-| 1 | Create purchase order | PASS | Created PO-000123, redirected to detail page |
-| 2 | Create job for part | FAIL | "Location is required" validation error |
-| 3 | Update quote details | PASS | Updated customer name successfully |
+| 1 | Create purchase order | PASS | PO-000123 created, redirected to detail |
+| 2 | Create job | FAIL | "Location is required" — capture: .ai/scratch/e2e/… |
-If any tests failed, include the screenshot paths from `/error`.
+Include `/error` capture paths for failures. Then `agent-browser close`.
-### Step 9: Cleanup
-
-```bash
-agent-browser close
-```
+## Failure handling
-## Tips for Carbon ERP forms
-
-- **Required fields** are marked with asterisks or show validation errors on submit
-- **Combobox/select fields** need a click to open, then a search or click on an option
-- **Number / currency / date fields** are react-aria: `fill` the visible input then
- **blur** (click another field) so the hidden `name=...` input commits. `type` often
- doesn't reach them. Verify with `eval "document.querySelector('input[name=X]').value"`.
-- **Submit with `requestSubmit`, never a click** — see step 6b. A plain agent-browser
- click on the Save button does NOT fire the native submit that `ValidatedForm`
- requires, so the form silently does nothing.
-- **After creating a record**, the app typically redirects to the detail page with the new record's ID in the URL
-- **Drawer forms** (child routes) appear as overlays — `requestSubmit` the drawer's own form (the one containing the drawer's submit button), not the parent page's
-- **Toast notifications** appear briefly — check the snapshot immediately after submission
-
-## Failure Handling
-
-- If a page fails to load, invoke `/error` and move to the next test
-- If a form field can't be found, take a snapshot, log the issue, and move on
-- If prerequisite data is missing (e.g., no suppliers exist to create a PO), note it as SKIP with an explanation
-- Never stop the entire test run for a single failure — complete all planned tests
+- Page won't load → `/error`, move on.
+- Field not findable → snapshot, note it, move on.
+- Missing prerequisite data → SKIP with explanation.
+- Never abort the whole run for one failure — finish all planned tests.
diff --git a/.ai/skills/writing-skills/SKILL.md b/.ai/skills/writing-skills/SKILL.md
index c3b73d8b10..7b31a5eaf4 100644
--- a/.ai/skills/writing-skills/SKILL.md
+++ b/.ai/skills/writing-skills/SKILL.md
@@ -1,655 +1,137 @@
---
name: writing-skills
-description: Use when creating new skills, editing existing skills, or verifying skills work before deployment
+description: House guide for creating or editing agent skills in this repo (.ai/skills/). Use when writing a new skill, restructuring an existing one, or reviewing skills for quality. Covers the frontmatter contract, the install wiring, the house template, and the weak-executor writing rules every Carbon skill follows.
---
-# Writing Skills
-
-## Overview
-
-**Writing skills IS Test-Driven Development applied to process documentation.**
-
-**Personal skills live in agent-specific directories (`~/.claude/skills` for Claude Code, `~/.agents/skills/` for Codex)**
-
-You write test cases (pressure scenarios with subagents), watch them fail (baseline behavior), write the skill (documentation), watch tests pass (agents comply), and refactor (close loopholes).
-
-**Core principle:** If you didn't watch an agent fail without the skill, you don't know if the skill teaches the right thing.
-
-**REQUIRED BACKGROUND:** You MUST understand superpowers:test-driven-development before using this skill. That skill defines the fundamental RED-GREEN-REFACTOR cycle. This skill adapts TDD to documentation.
-
-**Official guidance:** For Anthropic's official skill authoring best practices, see anthropic-best-practices.md. This document provides additional patterns and guidelines that complement the TDD-focused approach in this skill.
-
-## What is a Skill?
-
-A **skill** is a reference guide for proven techniques, patterns, or tools. Skills help future Claude instances find and apply effective approaches.
-
-**Skills are:** Reusable techniques, patterns, tools, reference guides
-
-**Skills are NOT:** Narratives about how you solved a problem once
-
-## TDD Mapping for Skills
-
-| TDD Concept | Skill Creation |
-|-------------|----------------|
-| **Test case** | Pressure scenario with subagent |
-| **Production code** | Skill document (SKILL.md) |
-| **Test fails (RED)** | Agent violates rule without skill (baseline) |
-| **Test passes (GREEN)** | Agent complies with skill present |
-| **Refactor** | Close loopholes while maintaining compliance |
-| **Write test first** | Run baseline scenario BEFORE writing skill |
-| **Watch it fail** | Document exact rationalizations agent uses |
-| **Minimal code** | Write skill addressing those specific violations |
-| **Watch it pass** | Verify agent now complies |
-| **Refactor cycle** | Find new rationalizations → plug → re-verify |
-
-The entire skill creation process follows RED-GREEN-REFACTOR.
-
-## When to Create a Skill
-
-**Create when:**
-- Technique wasn't intuitively obvious to you
-- You'd reference this again across projects
-- Pattern applies broadly (not project-specific)
-- Others would benefit
-
-**Don't create for:**
-- One-off solutions
-- Standard practices well-documented elsewhere
-- Project-specific conventions (put in CLAUDE.md)
-- Mechanical constraints (if it's enforceable with regex/validation, automate it—save documentation for judgment calls)
-
-## Skill Types
-
-### Technique
-Concrete method with steps to follow (condition-based-waiting, root-cause-tracing)
-
-### Pattern
-Way of thinking about problems (flatten-with-flags, test-invariants)
-
-### Reference
-API docs, syntax guides, tool documentation (office docs)
-
-## Directory Structure
-
-
-```
-skills/
- skill-name/
- SKILL.md # Main reference (required)
- supporting-file.* # Only if needed
-```
-
-**Flat namespace** - all skills in one searchable namespace
-
-**Separate files for:**
-1. **Heavy reference** (100+ lines) - API docs, comprehensive syntax
-2. **Reusable tools** - Scripts, utilities, templates
-
-**Keep inline:**
-- Principles and concepts
-- Code patterns (< 50 lines)
-- Everything else
-
-## SKILL.md Structure
-
-**Frontmatter (YAML):**
-- Two required fields: `name` and `description` (see [agentskills.io/specification](https://agentskills.io/specification) for all supported fields)
-- Max 1024 characters total
-- `name`: Use letters, numbers, and hyphens only (no parentheses, special chars)
-- `description`: Third-person, describes ONLY when to use (NOT what it does)
- - Start with "Use when..." to focus on triggering conditions
- - Include specific symptoms, situations, and contexts
- - **NEVER summarize the skill's process or workflow** (see CSO section for why)
- - Keep under 500 characters if possible
+# writing-skills — how Carbon skills are written
+
+Source of truth is `.ai/skills/{name}/SKILL.md`. The installer
+(`.ai/scripts/install-skills.sh`, run automatically by `pnpm prepare` or
+manually via `pnpm install-skills`) symlinks each skill directory into
+`.claude/skills/` and `.codex/skills/`. Never edit under `.claude/` or
+`.codex/` — edit `.ai/skills/` only.
+
+## The prime directive: write for the weakest executor
+
+Assume the model executing a skill is **much less capable than you** and has
+zero context. It will not infer intent, fill gaps, or exercise judgment. So:
+
+1. **One canonical path per task.** Never offer options without declaring a
+ default. "Choose what fits" is a gap; a weak model fills gaps badly.
+2. **Exact commands with expected output.** Every verification is a command plus
+ what its output must contain. "Verify it works" is not an instruction.
+3. **Exact paths.** Never "the appropriate directory". Never a path you didn't
+ confirm exists.
+4. **STOP rules inline.** State explicitly when to stop and report instead of
+ improvising ("2 failed attempts → STOP", "open question unresolved → STOP").
+5. **Decision tables over prose.** Situation → action. A weak model can match a
+ row; it cannot weigh an essay.
+6. **Verified references only.** Every file, command, and skill a skill mentions
+ must exist — run the command, `ls` the path, before writing it down. This
+ includes claims inherited from an earlier version of the skill: re-verify
+ them; the previous author may have been wrong. A reference to something that
+ doesn't exist sends the executor into a loop.
+7. **Close loopholes explicitly.** For discipline rules, list the specific
+ workarounds that are forbidden and the red-flag phrases that mean "stop"
+ ("just this once", "I'll test after", "keep it as reference").
+8. **Announce at start.** Workflow skills open with one line naming the skill
+ and its target. It locks the executor into the procedure and tells the
+ supervising human which playbook is running.
+9. **Non-interactive only.** Never instruct `git rebase -i`, `git add -i`,
+ `git restore -p`, or anything that opens an editor/prompt — interactive
+ commands hang in agent harnesses. Give the non-interactive equivalent.
+10. **Bundle assets for generative output.** When a skill produces a styled
+ artifact (HTML page, document scaffold), ship a filled-in template under
+ `assets/` and have the executor copy + fill `<!-- FILL -->` markers —
+ weak models fill templates far better than they invent structure.
+
+## Frontmatter contract (hard requirements)
+
+- The file **starts** with `---` on line 1. Nothing above it — an HTML comment
+ above the frontmatter breaks description parsing and the comment leaks into
+ the skill list. Attribution comments go **below** the closing `---`.
+- `name:` must equal the directory name exactly (letters, numbers, hyphens).
+ The installer symlinks by directory name; a mismatch disconnects the skill.
+- `description:` ≤1024 chars, third person. Formula: *what it does and produces*
+ + *"Use when …" concrete triggers* + *when NOT to use, pointing at the sibling
+ skill that applies*. The description is the only thing the model sees before
+ deciding to load the skill — triggers matter more than elegance.
+
+## House template
```markdown
---
-name: Skill-Name-With-Hyphens
-description: Use when [specific triggering conditions and symptoms]
+name: {dir-name}
+description: {what it does/produces}. Use when {triggers}. Do not use for {adjacent case} — use /{other-skill}.
---
-# Skill Name
-
-## Overview
-What is this? Core principle in 1-2 sentences.
-
-## When to Use
-[Small inline flowchart IF decision non-obvious]
-
-Bullet list with SYMPTOMS and use cases
-When NOT to use
-
-## Core Pattern (for techniques/patterns)
-Before/after code comparison
-
-## Quick Reference
-Table or bullets for scanning common operations
-
-## Implementation
-Inline code for simple patterns
-Link to file for heavy reference or reusable tools
-
-## Common Mistakes
-What goes wrong + fixes
-
-## Real-World Impact (optional)
-Concrete results
-```
-
-
-## Claude Search Optimization (CSO)
-
-**Critical for discovery:** Future Claude needs to FIND your skill
-
-### 1. Rich Description Field
-
-**Purpose:** Claude reads description to decide which skills to load for a given task. Make it answer: "Should I read this skill right now?"
-
-**Format:** Start with "Use when..." to focus on triggering conditions
-
-**CRITICAL: Description = When to Use, NOT What the Skill Does**
-
-The description should ONLY describe triggering conditions. Do NOT summarize the skill's process or workflow in the description.
-
-**Why this matters:** Testing revealed that when a description summarizes the skill's workflow, Claude may follow the description instead of reading the full skill content. A description saying "code review between tasks" caused Claude to do ONE review, even though the skill's flowchart clearly showed TWO reviews (spec compliance then code quality).
-
-When the description was changed to just "Use when executing implementation plans with independent tasks" (no workflow summary), Claude correctly read the flowchart and followed the two-stage review process.
-
-**The trap:** Descriptions that summarize workflow create a shortcut Claude will take. The skill body becomes documentation Claude skips.
-
-```yaml
-# ❌ BAD: Summarizes workflow - Claude may follow this instead of reading skill
-description: Use when executing plans - dispatches subagent per task with code review between tasks
-
-# ❌ BAD: Too much process detail
-description: Use for TDD - write test first, watch it fail, write minimal code, refactor
-
-# ✅ GOOD: Just triggering conditions, no workflow summary
-description: Use when executing implementation plans with independent tasks in the current session
-
-# ✅ GOOD: Triggering conditions only
-description: Use when implementing any feature or bugfix, before writing implementation code
-```
-
-**Content:**
-- Use concrete triggers, symptoms, and situations that signal this skill applies
-- Describe the *problem* (race conditions, inconsistent behavior) not *language-specific symptoms* (setTimeout, sleep)
-- Keep triggers technology-agnostic unless the skill itself is technology-specific
-- If skill is technology-specific, make that explicit in the trigger
-- Write in third person (injected into system prompt)
-- **NEVER summarize the skill's process or workflow**
-
-```yaml
-# ❌ BAD: Too abstract, vague, doesn't include when to use
-description: For async testing
-
-# ❌ BAD: First person
-description: I can help you with async tests when they're flaky
-
-# ❌ BAD: Mentions technology but skill isn't specific to it
-description: Use when tests use setTimeout/sleep and are flaky
-
-# ✅ GOOD: Starts with "Use when", describes problem, no workflow
-description: Use when tests have race conditions, timing dependencies, or pass/fail inconsistently
-
-# ✅ GOOD: Technology-specific skill with explicit trigger
-description: Use when using React Router and handling authentication redirects
-```
-
-### 2. Keyword Coverage
-
-Use words Claude would search for:
-- Error messages: "Hook timed out", "ENOTEMPTY", "race condition"
-- Symptoms: "flaky", "hanging", "zombie", "pollution"
-- Synonyms: "timeout/hang/freeze", "cleanup/teardown/afterEach"
-- Tools: Actual commands, library names, file types
-
-### 3. Descriptive Naming
-
-**Use active voice, verb-first:**
-- ✅ `creating-skills` not `skill-creation`
-- ✅ `condition-based-waiting` not `async-test-helpers`
-
-### 4. Token Efficiency (Critical)
-
-**Problem:** getting-started and frequently-referenced skills load into EVERY conversation. Every token counts.
-
-**Target word counts:**
-- getting-started workflows: <150 words each
-- Frequently-loaded skills: <200 words total
-- Other skills: <500 words (still be concise)
-
-**Techniques:**
-
-**Move details to tool help:**
-```bash
-# ❌ BAD: Document all flags in SKILL.md
-search-conversations supports --text, --both, --after DATE, --before DATE, --limit N
-
-# ✅ GOOD: Reference --help
-search-conversations supports multiple modes and filters. Run --help for details.
-```
-
-**Use cross-references:**
-```markdown
-# ❌ BAD: Repeat workflow details
-When searching, dispatch subagent with template...
-[20 lines of repeated instructions]
-
-# ✅ GOOD: Reference other skill
-Always use subagents (50-100x context savings). REQUIRED: Use [other-skill-name] for workflow.
-```
-
-**Compress examples:**
-```markdown
-# ❌ BAD: Verbose example (42 words)
-your human partner: "How did we handle authentication errors in React Router before?"
-You: I'll search past conversations for React Router authentication patterns.
-[Dispatch subagent with search query: "React Router authentication error handling 401"]
-
-# ✅ GOOD: Minimal example (20 words)
-Partner: "How did we handle auth errors in React Router?"
-You: Searching...
-[Dispatch subagent → synthesis]
-```
-
-**Eliminate redundancy:**
-- Don't repeat what's in cross-referenced skills
-- Don't explain what's obvious from command
-- Don't include multiple examples of same pattern
-
-**Verification:**
-```bash
-wc -w skills/path/SKILL.md
-# getting-started workflows: aim for <150 each
-# Other frequently-loaded: aim for <200 total
-```
-
-**Name by what you DO or core insight:**
-- ✅ `condition-based-waiting` > `async-test-helpers`
-- ✅ `using-skills` not `skill-usage`
-- ✅ `flatten-with-flags` > `data-structure-refactoring`
-- ✅ `root-cause-tracing` > `debugging-techniques`
-
-**Gerunds (-ing) work well for processes:**
-- `creating-skills`, `testing-skills`, `debugging-with-logs`
-- Active, describes the action you're taking
-
-### 4. Cross-Referencing Other Skills
-
-**When writing documentation that references other skills:**
-
-Use skill name only, with explicit requirement markers:
-- ✅ Good: `**REQUIRED SUB-SKILL:** Use superpowers:test-driven-development`
-- ✅ Good: `**REQUIRED BACKGROUND:** You MUST understand superpowers:systematic-debugging`
-- ❌ Bad: `See skills/testing/test-driven-development` (unclear if required)
-- ❌ Bad: `@skills/testing/test-driven-development/SKILL.md` (force-loads, burns context)
-
-**Why no @ links:** `@` syntax force-loads files immediately, consuming 200k+ context before you need them.
-
-## Flowchart Usage
-
-```dot
-digraph when_flowchart {
- "Need to show information?" [shape=diamond];
- "Decision where I might go wrong?" [shape=diamond];
- "Use markdown" [shape=box];
- "Small inline flowchart" [shape=box];
-
- "Need to show information?" -> "Decision where I might go wrong?" [label="yes"];
- "Decision where I might go wrong?" -> "Small inline flowchart" [label="yes"];
- "Decision where I might go wrong?" -> "Use markdown" [label="no"];
-}
-```
-
-**Use flowcharts ONLY for:**
-- Non-obvious decision points
-- Process loops where you might stop too early
-- "When to use A vs B" decisions
-
-**Never use flowcharts for:**
-- Reference material → Tables, lists
-- Code examples → Markdown blocks
-- Linear instructions → Numbered lists
-- Labels without semantic meaning (step1, helper2)
-
-See @graphviz-conventions.dot for graphviz style rules.
-
-**Visualizing for your human partner:** Use `render-graphs.js` in this directory to render a skill's flowcharts to SVG:
-```bash
-./render-graphs.js ../some-skill # Each diagram separately
-./render-graphs.js ../some-skill --combine # All diagrams in one SVG
-```
-
-## Code Examples
-
-**One excellent example beats many mediocre ones**
-
-Choose most relevant language:
-- Testing techniques → TypeScript/JavaScript
-- System debugging → Shell/Python
-- Data processing → Python
-
-**Good example:**
-- Complete and runnable
-- Well-commented explaining WHY
-- From real scenario
-- Shows pattern clearly
-- Ready to adapt (not generic template)
-
-**Don't:**
-- Implement in 5+ languages
-- Create fill-in-the-blank templates
-- Write contrived examples
-
-You're good at porting - one great example is enough.
-
-## File Organization
-
-### Self-Contained Skill
-```
-defense-in-depth/
- SKILL.md # Everything inline
-```
-When: All content fits, no heavy reference needed
-
-### Skill with Reusable Tool
-```
-condition-based-waiting/
- SKILL.md # Overview + patterns
- example.ts # Working helpers to adapt
-```
-When: Tool is reusable code, not just narrative
-
-### Skill with Heavy Reference
-```
-pptx/
- SKILL.md # Overview + workflows
- pptxgenjs.md # 600 lines API reference
- ooxml.md # 500 lines XML structure
- scripts/ # Executable tools
-```
-When: Reference material too large for inline
-
-## The Iron Law (Same as TDD)
-
-```
-NO SKILL WITHOUT A FAILING TEST FIRST
-```
-
-This applies to NEW skills AND EDITS to existing skills.
-
-Write skill before testing? Delete it. Start over.
-Edit skill without testing? Same violation.
-
-**No exceptions:**
-- Not for "simple additions"
-- Not for "just adding a section"
-- Not for "documentation updates"
-- Don't keep untested changes as "reference"
-- Don't "adapt" while running tests
-- Delete means delete
-
-**REQUIRED BACKGROUND:** The superpowers:test-driven-development skill explains why this matters. Same principles apply to documentation.
-
-## Testing All Skill Types
-
-Different skill types need different test approaches:
-
-### Discipline-Enforcing Skills (rules/requirements)
-
-**Examples:** TDD, verification-before-completion, designing-before-coding
-
-**Test with:**
-- Academic questions: Do they understand the rules?
-- Pressure scenarios: Do they comply under stress?
-- Multiple pressures combined: time + sunk cost + exhaustion
-- Identify rationalizations and add explicit counters
-
-**Success criteria:** Agent follows rule under maximum pressure
-
-### Technique Skills (how-to guides)
-
-**Examples:** condition-based-waiting, root-cause-tracing, defensive-programming
-
-**Test with:**
-- Application scenarios: Can they apply the technique correctly?
-- Variation scenarios: Do they handle edge cases?
-- Missing information tests: Do instructions have gaps?
-
-**Success criteria:** Agent successfully applies technique to new scenario
-
-### Pattern Skills (mental models)
-
-**Examples:** reducing-complexity, information-hiding concepts
-
-**Test with:**
-- Recognition scenarios: Do they recognize when pattern applies?
-- Application scenarios: Can they use the mental model?
-- Counter-examples: Do they know when NOT to apply?
-
-**Success criteria:** Agent correctly identifies when/how to apply pattern
-
-### Reference Skills (documentation/APIs)
-
-**Examples:** API documentation, command references, library guides
-
-**Test with:**
-- Retrieval scenarios: Can they find the right information?
-- Application scenarios: Can they use what they found correctly?
-- Gap testing: Are common use cases covered?
-
-**Success criteria:** Agent finds and correctly applies reference information
-
-## Common Rationalizations for Skipping Testing
-
-| Excuse | Reality |
-|--------|---------|
-| "Skill is obviously clear" | Clear to you ≠ clear to other agents. Test it. |
-| "It's just a reference" | References can have gaps, unclear sections. Test retrieval. |
-| "Testing is overkill" | Untested skills have issues. Always. 15 min testing saves hours. |
-| "I'll test if problems emerge" | Problems = agents can't use skill. Test BEFORE deploying. |
-| "Too tedious to test" | Testing is less tedious than debugging bad skill in production. |
-| "I'm confident it's good" | Overconfidence guarantees issues. Test anyway. |
-| "Academic review is enough" | Reading ≠ using. Test application scenarios. |
-| "No time to test" | Deploying untested skill wastes more time fixing it later. |
-
-**All of these mean: Test before deploying. No exceptions.**
-
-## Bulletproofing Skills Against Rationalization
-
-Skills that enforce discipline (like TDD) need to resist rationalization. Agents are smart and will find loopholes when under pressure.
-
-**Psychology note:** Understanding WHY persuasion techniques work helps you apply them systematically. See persuasion-principles.md for research foundation (Cialdini, 2021; Meincke et al., 2025) on authority, commitment, scarcity, social proof, and unity principles.
-
-### Close Every Loophole Explicitly
-
-Don't just state the rule - forbid specific workarounds:
+# {name} — {one-line purpose}
-<Bad>
-```markdown
-Write code before test? Delete it.
-```
-</Bad>
-
-<Good>
-```markdown
-Write code before test? Delete it. Start over.
-
-**No exceptions:**
-- Don't keep it as "reference"
-- Don't "adapt" it while writing tests
-- Don't look at it
-- Delete means delete
-```
-</Good>
-
-### Address "Spirit vs Letter" Arguments
-
-Add foundational principle early:
-
-```markdown
-**Violating the letter of the rules is violating the spirit of the rules.**
-```
-
-This cuts off entire class of "I'm following the spirit" rationalizations.
-
-### Build Rationalization Table
-
-Capture rationalizations from baseline testing (see Testing section below). Every excuse agents make goes in the table:
-
-```markdown
-| Excuse | Reality |
-|--------|---------|
-| "Too simple to test" | Simple code breaks. Test takes 30 seconds. |
-| "I'll test after" | Tests passing immediately prove nothing. |
-| "Tests after achieve same goals" | Tests-after = "what does this do?" Tests-first = "what should this do?" |
-```
-
-### Create Red Flags List
-
-Make it easy for agents to self-check when rationalizing:
-
-```markdown
-## Red Flags - STOP and Start Over
-
-- Code before test
-- "I already manually tested it"
-- "Tests after achieve the same purpose"
-- "It's about spirit not ritual"
-- "This is different because..."
-
-**All of these mean: Delete code. Start over with TDD.**
-```
-
-### Update CSO for Violation Symptoms
+{2–3 sentences: input → output contract.}
-Add to description: symptoms of when you're ABOUT to violate the rule:
+**Announce at start:** "Using the {name} skill — {purpose}."
-```yaml
-description: use when implementing any feature or bugfix, before writing implementation code
-```
-
-## RED-GREEN-REFACTOR for Skills
-
-Follow the TDD cycle:
-
-### RED: Write Failing Test (Baseline)
-
-Run pressure scenario with subagent WITHOUT the skill. Document exact behavior:
-- What choices did they make?
-- What rationalizations did they use (verbatim)?
-- Which pressures triggered violations?
-
-This is "watch the test fail" - you must see what agents naturally do before writing the skill.
-
-### GREEN: Write Minimal Skill
-
-Write skill that addresses those specific rationalizations. Don't add extra content for hypothetical cases.
-
-Run same scenarios WITH skill. Agent should now comply.
-
-### REFACTOR: Close Loopholes
-
-Agent found new rationalization? Add explicit counter. Re-test until bulletproof.
-
-**Testing methodology:** See @testing-skills-with-subagents.md for the complete testing methodology:
-- How to write pressure scenarios
-- Pressure types (time, sunk cost, authority, exhaustion)
-- Plugging holes systematically
-- Meta-testing techniques
-
-## Anti-Patterns
+## Step 1: {imperative}
+{exact commands, expected output}
+...
-### ❌ Narrative Example
-"In session 2025-10-03, we found empty projectDir caused..."
-**Why bad:** Too specific, not reusable
+## Output
+{exact template the skill must produce, in a fenced block}
-### ❌ Multi-Language Dilution
-example-js.js, example-py.py, example-go.go
-**Why bad:** Mediocre quality, maintenance burden
+## Done when
+- [ ] {verifiable item — a command result or an artifact at an exact path}
-### ❌ Code in Flowcharts
-```dot
-step1 [label="import fs"];
-step2 [label="read file"];
+## Failure → action {when the skill can fail mid-run}
+| Symptom | Action |
```
-**Why bad:** Can't copy-paste, hard to read
-
-### ❌ Generic Labels
-helper1, helper2, step3, pattern4
-**Why bad:** Labels should have semantic meaning
-
-## STOP: Before Moving to Next Skill
-
-**After writing ANY skill, you MUST STOP and complete the deployment process.**
-
-**Do NOT:**
-- Create multiple skills in batch without testing each
-- Move to next skill before current one is verified
-- Skip testing because "batching is more efficient"
-
-**The deployment checklist below is MANDATORY for EACH skill.**
-
-Deploying untested skills = deploying untested code. It's a violation of quality standards.
-
-## Skill Creation Checklist (TDD Adapted)
-
-**IMPORTANT: Use TodoWrite to create todos for EACH checklist item below.**
-
-**RED Phase - Write Failing Test:**
-- [ ] Create pressure scenarios (3+ combined pressures for discipline skills)
-- [ ] Run scenarios WITHOUT skill - document baseline behavior verbatim
-- [ ] Identify patterns in rationalizations/failures
-
-**GREEN Phase - Write Minimal Skill:**
-- [ ] Name uses only letters, numbers, hyphens (no parentheses/special chars)
-- [ ] YAML frontmatter with required `name` and `description` fields (max 1024 chars; see [spec](https://agentskills.io/specification))
-- [ ] Description starts with "Use when..." and includes specific triggers/symptoms
-- [ ] Description written in third person
-- [ ] Keywords throughout for search (errors, symptoms, tools)
-- [ ] Clear overview with core principle
-- [ ] Address specific baseline failures identified in RED
-- [ ] Code inline OR link to separate file
-- [ ] One excellent example (not multi-language)
-- [ ] Run scenarios WITH skill - verify agents now comply
-
-**REFACTOR Phase - Close Loopholes:**
-- [ ] Identify NEW rationalizations from testing
-- [ ] Add explicit counters (if discipline skill)
-- [ ] Build rationalization table from all test iterations
-- [ ] Create red flags list
-- [ ] Re-test until bulletproof
-
-**Quality Checks:**
-- [ ] Small flowchart only if decision non-obvious
-- [ ] Quick reference table
-- [ ] Common mistakes section
-- [ ] No narrative storytelling
-- [ ] Supporting files only for tools or heavy reference
-**Deployment:**
-- [ ] Commit skill to git and push to your fork (if configured)
-- [ ] Consider contributing back via PR (if broadly useful)
+Sizing: most skills 60–180 lines. Move heavy reference material (100+ lines) to
+`references/*.md` inside the skill dir and say exactly when to read each file.
+One excellent example beats three mediocre ones.
-## Discovery Workflow
+Formatting trap: when a template block in your skill must itself contain fenced
+commands, use a **four-backtick outer fence** (`````` ````markdown ``````) — a
+three-backtick fence inside a three-backtick fence closes the outer block early
+and garbles everything after it.
-How future Claude finds your skill:
+## Canonical artifact paths (use these; never invent new ones)
-1. **Encounters problem** ("tests are flaky")
-3. **Finds SKILL** (description matches)
-4. **Scans overview** (is this relevant?)
-5. **Reads patterns** (quick reference table)
-6. **Loads example** (only when implementing)
+| Artifact | Path |
+|----------|------|
+| Research findings | `.ai/research/{slug}.md` |
+| Specs | `.ai/specs/{YYYY-MM-DD}-{slug}.md` |
+| Implementation plans + progress | `.ai/plans/{YYYY-MM-DD}-{slug}.md` |
+| Run logs (multi-step operation records) | `.ai/runs/{YYYY-MM-DD}-{slug}.md` |
+| Browser playbooks | `.ai/playbooks/{slug}.md` |
+| Improve handoff plans | `.ai/plans/improve/` |
+| Ephemeral runtime output (screenshots, debug logs) | `.ai/scratch/` (gitignored) |
-**Optimize for this flow** - put searchable terms early and often.
+Command conventions every skill must respect: scoped typecheck only
+(`pnpm exec turbo run typecheck --filter=<pkg>` — whole-repo OOMs), pnpm never
+npm, `pnpm run generate:types` after migrations before typechecking, commits go
+through `/check-and-commit`.
-## The Bottom Line
+## Workflow for a new or edited skill
-**Creating skills IS TDD for process documentation.**
+1. **Check overlap first.** Read `.ai/skills/README.md`. If an existing skill
+ covers 70% of the job, extend it — two overlapping skills with different
+ instructions is worse than one imperfect skill.
+2. Write the skill per the template. Verify every reference (rule 6).
+3. **Cold-read test.** Dispatch a subagent with only the skill text and a
+ realistic task; watch where it stalls, improvises, or misreads. Every stall
+ is a gap in the skill, not a flaw in the executor. Fix and repeat.
+4. Re-run the installer and confirm the skill registers:
+ ```bash
+ pnpm install-skills && bash .ai/scripts/install-skills.sh --list
+ ```
+5. Update `.ai/skills/README.md` (the index) and, if the skill belongs in a
+ pipeline, the root `AGENTS.md` Workflows table.
-Same Iron Law: No skill without failing test first.
-Same cycle: RED (baseline) → GREEN (write skill) → REFACTOR (close loopholes).
-Same benefits: Better quality, fewer surprises, bulletproof results.
+## Editing rules
-If you follow TDD for code, follow it for skills. It's the same discipline applied to documentation.
+- A skill that names a file, command, or flag that no longer exists is **stale**
+ — fix it the moment you notice (`.ai/rules/keep-sources-in-sync.md`).
+- Never weaken a STOP rule or a gate to make a run pass.
+- When you change a skill's contract (inputs, outputs, artifact paths), grep
+ `.ai/` and `AGENTS.md` files for inbound references and update them in the
+ same change.
diff --git a/.ai/skills/writing-skills/anthropic-best-practices.md b/.ai/skills/writing-skills/anthropic-best-practices.md
deleted file mode 100644
index 9f3f6ecfd9..0000000000
--- a/.ai/skills/writing-skills/anthropic-best-practices.md
+++ /dev/null
@@ -1,1150 +0,0 @@
-# Skill authoring best practices
-
-> Learn how to write effective Skills that Claude can discover and use successfully.
-
-Good Skills are concise, well-structured, and tested with real usage. This guide provides practical authoring decisions to help you write Skills that Claude can discover and use effectively.
-
-For conceptual background on how Skills work, see the [Skills overview](/en/docs/agents-and-tools/agent-skills/overview).
-
-## Core principles
-
-### Concise is key
-
-The [context window](https://platform.claude.com/docs/en/build-with-claude/context-windows) is a public good. Your Skill shares the context window with everything else Claude needs to know, including:
-
-* The system prompt
-* Conversation history
-* Other Skills' metadata
-* Your actual request
-
-Not every token in your Skill has an immediate cost. At startup, only the metadata (name and description) from all Skills is pre-loaded. Claude reads SKILL.md only when the Skill becomes relevant, and reads additional files only as needed. However, being concise in SKILL.md still matters: once Claude loads it, every token competes with conversation history and other context.
-
-**Default assumption**: Claude is already very smart
-
-Only add context Claude doesn't already have. Challenge each piece of information:
-
-* "Does Claude really need this explanation?"
-* "Can I assume Claude knows this?"
-* "Does this paragraph justify its token cost?"
-
-**Good example: Concise** (approximately 50 tokens):
-
-````markdown theme={null}
-## Extract PDF text
-
-Use pdfplumber for text extraction:
-
-```python
-import pdfplumber
-
-with pdfplumber.open("file.pdf") as pdf:
- text = pdf.pages[0].extract_text()
-```
-````
-
-**Bad example: Too verbose** (approximately 150 tokens):
-
-```markdown theme={null}
-## Extract PDF text
-
-PDF (Portable Document Format) files are a common file format that contains
-text, images, and other content. To extract text from a PDF, you'll need to
-use a library. There are many libraries available for PDF processing, but we
-recommend pdfplumber because it's easy to use and handles most cases well.
-First, you'll need to install it using pip. Then you can use the code below...
-```
-
-The concise version assumes Claude knows what PDFs are and how libraries work.
-
-### Set appropriate degrees of freedom
-
-Match the level of specificity to the task's fragility and variability.
-
-**High freedom** (text-based instructions):
-
-Use when:
-
-* Multiple approaches are valid
-* Decisions depend on context
-* Heuristics guide the approach
-
-Example:
-
-```markdown theme={null}
-## Code review process
-
-1. Analyze the code structure and organization
-2. Check for potential bugs or edge cases
-3. Suggest improvements for readability and maintainability
-4. Verify adherence to project conventions
-```
-
-**Medium freedom** (pseudocode or scripts with parameters):
-
-Use when:
-
-* A preferred pattern exists
-* Some variation is acceptable
-* Configuration affects behavior
-
-Example:
-
-````markdown theme={null}
-## Generate report
-
-Use this template and customize as needed:
-
-```python
-def generate_report(data, format="markdown", include_charts=True):
- # Process data
- # Generate output in specified format
- # Optionally include visualizations
-```
-````
-
-**Low freedom** (specific scripts, few or no parameters):
-
-Use when:
-
-* Operations are fragile and error-prone
-* Consistency is critical
-* A specific sequence must be followed
-
-Example:
-
-````markdown theme={null}
-## Database migration
-
-Run exactly this script:
-
-```bash
-python scripts/migrate.py --verify --backup
-```
-
-Do not modify the command or add additional flags.
-````
-
-**Analogy**: Think of Claude as a robot exploring a path:
-
-* **Narrow bridge with cliffs on both sides**: There's only one safe way forward. Provide specific guardrails and exact instructions (low freedom). Example: database migrations that must run in exact sequence.
-* **Open field with no hazards**: Many paths lead to success. Give general direction and trust Claude to find the best route (high freedom). Example: code reviews where context determines the best approach.
-
-### Test with all models you plan to use
-
-Skills act as additions to models, so effectiveness depends on the underlying model. Test your Skill with all the models you plan to use it with.
-
-**Testing considerations by model**:
-
-* **Claude Haiku** (fast, economical): Does the Skill provide enough guidance?
-* **Claude Sonnet** (balanced): Is the Skill clear and efficient?
-* **Claude Opus** (powerful reasoning): Does the Skill avoid over-explaining?
-
-What works perfectly for Opus might need more detail for Haiku. If you plan to use your Skill across multiple models, aim for instructions that work well with all of them.
-
-## Skill structure
-
-<Note>
- **YAML Frontmatter**: The SKILL.md frontmatter requires two fields:
-
- * `name` - Human-readable name of the Skill (64 characters maximum)
- * `description` - One-line description of what the Skill does and when to use it (1024 characters maximum)
-
- For complete Skill structure details, see the [Skills overview](/en/docs/agents-and-tools/agent-skills/overview#skill-structure).
-</Note>
-
-### Naming conventions
-
-Use consistent naming patterns to make Skills easier to reference and discuss. We recommend using **gerund form** (verb + -ing) for Skill names, as this clearly describes the activity or capability the Skill provides.
-
-**Good naming examples (gerund form)**:
-
-* "Processing PDFs"
-* "Analyzing spreadsheets"
-* "Managing databases"
-* "Testing code"
-* "Writing documentation"
-
-**Acceptable alternatives**:
-
-* Noun phrases: "PDF Processing", "Spreadsheet Analysis"
-* Action-oriented: "Process PDFs", "Analyze Spreadsheets"
-
-**Avoid**:
-
-* Vague names: "Helper", "Utils", "Tools"
-* Overly generic: "Documents", "Data", "Files"
-* Inconsistent patterns within your skill collection
-
-Consistent naming makes it easier to:
-
-* Reference Skills in documentation and conversations
-* Understand what a Skill does at a glance
-* Organize and search through multiple Skills
-* Maintain a professional, cohesive skill library
-
-### Writing effective descriptions
-
-The `description` field enables Skill discovery and should include both what the Skill does and when to use it.
-
-<Warning>
- **Always write in third person**. The description is injected into the system prompt, and inconsistent point-of-view can cause discovery problems.
-
- * **Good:** "Processes Excel files and generates reports"
- * **Avoid:** "I can help you process Excel files"
- * **Avoid:** "You can use this to process Excel files"
-</Warning>
-
-**Be specific and include key terms**. Include both what the Skill does and specific triggers/contexts for when to use it.
-
-Each Skill has exactly one description field. The description is critical for skill selection: Claude uses it to choose the right Skill from potentially 100+ available Skills. Your description must provide enough detail for Claude to know when to select this Skill, while the rest of SKILL.md provides the implementation details.
-
-Effective examples:
-
-**PDF Processing skill:**
-
-```yaml theme={null}
-description: Extract text and tables from PDF files, fill forms, merge documents. Use when working with PDF files or when the user mentions PDFs, forms, or document extraction.
-```
-
-**Excel Analysis skill:**
-
-```yaml theme={null}
-description: Analyze Excel spreadsheets, create pivot tables, generate charts. Use when analyzing Excel files, spreadsheets, tabular data, or .xlsx files.
-```
-
-**Git Commit Helper skill:**
-
-```yaml theme={null}
-description: Generate descriptive commit messages by analyzing git diffs. Use when the user asks for help writing commit messages or reviewing staged changes.
-```
-
-Avoid vague descriptions like these:
-
-```yaml theme={null}
-description: Helps with documents
-```
-
-```yaml theme={null}
-description: Processes data
-```
-
-```yaml theme={null}
-description: Does stuff with files
-```
-
-### Progressive disclosure patterns
-
-SKILL.md serves as an overview that points Claude to detailed materials as needed, like a table of contents in an onboarding guide. For an explanation of how progressive disclosure works, see [How Skills work](/en/docs/agents-and-tools/agent-skills/overview#how-skills-work) in the overview.
-
-**Practical guidance:**
-
-* Keep SKILL.md body under 500 lines for optimal performance
-* Split content into separate files when approaching this limit
-* Use the patterns below to organize instructions, code, and resources effectively
-
-#### Visual overview: From simple to complex
-
-A basic Skill starts with just a SKILL.md file containing metadata and instructions:
-
-<img src="https://mintcdn.com/anthropic-claude-docs/4Bny2bjzuGBK7o00/images/agent-skills-simple-file.png?fit=max&auto=format&n=4Bny2bjzuGBK7o00&q=85&s=87782ff239b297d9a9e8e1b72ed72db9" alt="Simple SKILL.md file showing YAML frontmatter and markdown body" data-og-width="2048" width="2048" data-og-height="1153" height="1153" data-path="images/agent-skills-simple-file.png" data-optimize="true" data-opv="3" srcset="https://mintcdn.com/anthropic-claude-docs/4Bny2bjzuGBK7o00/images/agent-skills-simple-file.png?w=280&fit=max&auto=format&n=4Bny2bjzuGBK7o00&q=85&s=c61cc33b6f5855809907f7fda94cd80e 280w, https://mintcdn.com/anthropic-claude-docs/4Bny2bjzuGBK7o00/images/agent-skills-simple-file.png?w=560&fit=max&auto=format&n=4Bny2bjzuGBK7o00&q=85&s=90d2c0c1c76b36e8d485f49e0810dbfd 560w, https://mintcdn.com/anthropic-claude-docs/4Bny2bjzuGBK7o00/images/agent-skills-simple-file.png?w=840&fit=max&auto=format&n=4Bny2bjzuGBK7o00&q=85&s=ad17d231ac7b0bea7e5b4d58fb4aeabb 840w, https://mintcdn.com/anthropic-claude-docs/4Bny2bjzuGBK7o00/images/agent-skills-simple-file.png?w=1100&fit=max&auto=format&n=4Bny2bjzuGBK7o00&q=85&s=f5d0a7a3c668435bb0aee9a3a8f8c329 1100w, https://mintcdn.com/anthropic-claude-docs/4Bny2bjzuGBK7o00/images/agent-skills-simple-file.png?w=1650&fit=max&auto=format&n=4Bny2bjzuGBK7o00&q=85&s=0e927c1af9de5799cfe557d12249f6e6 1650w, https://mintcdn.com/anthropic-claude-docs/4Bny2bjzuGBK7o00/images/agent-skills-simple-file.png?w=2500&fit=max&auto=format&n=4Bny2bjzuGBK7o00&q=85&s=46bbb1a51dd4c8202a470ac8c80a893d 2500w" />
-
-As your Skill grows, you can bundle additional content that Claude loads only when needed:
-
-<img src="https://mintcdn.com/anthropic-claude-docs/4Bny2bjzuGBK7o00/images/agent-skills-bundling-content.png?fit=max&auto=format&n=4Bny2bjzuGBK7o00&q=85&s=a5e0aa41e3d53985a7e3e43668a33ea3" alt="Bundling additional reference files like reference.md and forms.md." data-og-width="2048" width="2048" data-og-height="1327" height="1327" data-path="images/agent-skills-bundling-content.png" data-optimize="true" data-opv="3" srcset="https://mintcdn.com/anthropic-claude-docs/4Bny2bjzuGBK7o00/images/agent-skills-bundling-content.png?w=280&fit=max&auto=format&n=4Bny2bjzuGBK7o00&q=85&s=f8a0e73783e99b4a643d79eac86b70a2 280w, https://mintcdn.com/anthropic-claude-docs/4Bny2bjzuGBK7o00/images/agent-skills-bundling-content.png?w=560&fit=max&auto=format&n=4Bny2bjzuGBK7o00&q=85&s=dc510a2a9d3f14359416b706f067904a 560w, https://mintcdn.com/anthropic-claude-docs/4Bny2bjzuGBK7o00/images/agent-skills-bundling-content.png?w=840&fit=max&auto=format&n=4Bny2bjzuGBK7o00&q=85&s=82cd6286c966303f7dd914c28170e385 840w, https://mintcdn.com/anthropic-claude-docs/4Bny2bjzuGBK7o00/images/agent-skills-bundling-content.png?w=1100&fit=max&auto=format&n=4Bny2bjzuGBK7o00&q=85&s=56f3be36c77e4fe4b523df209a6824c6 1100w, https://mintcdn.com/anthropic-claude-docs/4Bny2bjzuGBK7o00/images/agent-skills-bundling-content.png?w=1650&fit=max&auto=format&n=4Bny2bjzuGBK7o00&q=85&s=d22b5161b2075656417d56f41a74f3dd 1650w, https://mintcdn.com/anthropic-claude-docs/4Bny2bjzuGBK7o00/images/agent-skills-bundling-content.png?w=2500&fit=max&auto=format&n=4Bny2bjzuGBK7o00&q=85&s=3dd4bdd6850ffcc96c6c45fcb0acd6eb 2500w" />
-
-The complete Skill directory structure might look like this:
-
-```
-pdf/
-├── SKILL.md # Main instructions (loaded when triggered)
-├── FORMS.md # Form-filling guide (loaded as needed)
-├── reference.md # API reference (loaded as needed)
-├── examples.md # Usage examples (loaded as needed)
-└── scripts/
- ├── analyze_form.py # Utility script (executed, not loaded)
- ├── fill_form.py # Form filling script
- └── validate.py # Validation script
-```
-
-#### Pattern 1: High-level guide with references
-
-````markdown theme={null}
----
-name: PDF Processing
-description: Extracts text and tables from PDF files, fills forms, and merges documents. Use when working with PDF files or when the user mentions PDFs, forms, or document extraction.
----
-
-# PDF Processing
-
-## Quick start
-
-Extract text with pdfplumber:
-```python
-import pdfplumber
-with pdfplumber.open("file.pdf") as pdf:
- text = pdf.pages[0].extract_text()
-```
-
-## Advanced features
-
-**Form filling**: See [FORMS.md](FORMS.md) for complete guide
-**API reference**: See [REFERENCE.md](REFERENCE.md) for all methods
-**Examples**: See [EXAMPLES.md](EXAMPLES.md) for common patterns
-````
-
-Claude loads FORMS.md, REFERENCE.md, or EXAMPLES.md only when needed.
-
-#### Pattern 2: Domain-specific organization
-
-For Skills with multiple domains, organize content by domain to avoid loading irrelevant context. When a user asks about sales metrics, Claude only needs to read sales-related schemas, not finance or marketing data. This keeps token usage low and context focused.
-
-```
-bigquery-skill/
-├── SKILL.md (overview and navigation)
-└── reference/
- ├── finance.md (revenue, billing metrics)
- ├── sales.md (opportunities, pipeline)
- ├── product.md (API usage, features)
- └── marketing.md (campaigns, attribution)
-```
-
-````markdown SKILL.md theme={null}
-# BigQuery Data Analysis
-
-## Available datasets
-
-**Finance**: Revenue, ARR, billing → See [reference/finance.md](reference/finance.md)
-**Sales**: Opportunities, pipeline, accounts → See [reference/sales.md](reference/sales.md)
-**Product**: API usage, features, adoption → See [reference/product.md](reference/product.md)
-**Marketing**: Campaigns, attribution, email → See [reference/marketing.md](reference/marketing.md)
-
-## Quick search
-
-Find specific metrics using grep:
-
-```bash
-grep -i "revenue" reference/finance.md
-grep -i "pipeline" reference/sales.md
-grep -i "api usage" reference/product.md
-```
-````
-
-#### Pattern 3: Conditional details
-
-Show basic content, link to advanced content:
-
-```markdown theme={null}
-# DOCX Processing
-
-## Creating documents
-
-Use docx-js for new documents. See [DOCX-JS.md](DOCX-JS.md).
-
-## Editing documents
-
-For simple edits, modify the XML directly.
-
-**For tracked changes**: See [REDLINING.md](REDLINING.md)
-**For OOXML details**: See [OOXML.md](OOXML.md)
-```
-
-Claude reads REDLINING.md or OOXML.md only when the user needs those features.
-
-### Avoid deeply nested references
-
-Claude may partially read files when they're referenced from other referenced files. When encountering nested references, Claude might use commands like `head -100` to preview content rather than reading entire files, resulting in incomplete information.
-
-**Keep references one level deep from SKILL.md**. All reference files should link directly from SKILL.md to ensure Claude reads complete files when needed.
-
-**Bad example: Too deep**:
-
-```markdown theme={null}
-# SKILL.md
-See [advanced.md](advanced.md)...
-
-# advanced.md
-See [details.md](details.md)...
-
-# details.md
-Here's the actual information...
-```
-
-**Good example: One level deep**:
-
-```markdown theme={null}
-# SKILL.md
-
-**Basic usage**: [instructions in SKILL.md]
-**Advanced features**: See [advanced.md](advanced.md)
-**API reference**: See [reference.md](reference.md)
-**Examples**: See [examples.md](examples.md)
-```
-
-### Structure longer reference files with table of contents
-
-For reference files longer than 100 lines, include a table of contents at the top. This ensures Claude can see the full scope of available information even when previewing with partial reads.
-
-**Example**:
-
-```markdown theme={null}
-# API Reference
-
-## Contents
-- Authentication and setup
-- Core methods (create, read, update, delete)
-- Advanced features (batch operations, webhooks)
-- Error handling patterns
-- Code examples
-
-## Authentication and setup
-...
-
-## Core methods
-...
-```
-
-Claude can then read the complete file or jump to specific sections as needed.
-
-For details on how this filesystem-based architecture enables progressive disclosure, see the [Runtime environment](#runtime-environment) section in the Advanced section below.
-
-## Workflows and feedback loops
-
-### Use workflows for complex tasks
-
-Break complex operations into clear, sequential steps. For particularly complex workflows, provide a checklist that Claude can copy into its response and check off as it progresses.
-
-**Example 1: Research synthesis workflow** (for Skills without code):
-
-````markdown theme={null}
-## Research synthesis workflow
-
-Copy this checklist and track your progress:
-
-```
-Research Progress:
-- [ ] Step 1: Read all source documents
-- [ ] Step 2: Identify key themes
-- [ ] Step 3: Cross-reference claims
-- [ ] Step 4: Create structured summary
-- [ ] Step 5: Verify citations
-```
-
-**Step 1: Read all source documents**
-
-Review each document in the `sources/` directory. Note the main arguments and supporting evidence.
-
-**Step 2: Identify key themes**
-
-Look for patterns across sources. What themes appear repeatedly? Where do sources agree or disagree?
-
-**Step 3: Cross-reference claims**
-
-For each major claim, verify it appears in the source material. Note which source supports each point.
-
-**Step 4: Create structured summary**
-
-Organize findings by theme. Include:
-- Main claim
-- Supporting evidence from sources
-- Conflicting viewpoints (if any)
-
-**Step 5: Verify citations**
-
-Check that every claim references the correct source document. If citations are incomplete, return to Step 3.
-````
-
-This example shows how workflows apply to analysis tasks that don't require code. The checklist pattern works for any complex, multi-step process.
-
-**Example 2: PDF form filling workflow** (for Skills with code):
-
-````markdown theme={null}
-## PDF form filling workflow
-
-Copy this checklist and check off items as you complete them:
-
-```
-Task Progress:
-- [ ] Step 1: Analyze the form (run analyze_form.py)
-- [ ] Step 2: Create field mapping (edit fields.json)
-- [ ] Step 3: Validate mapping (run validate_fields.py)
-- [ ] Step 4: Fill the form (run fill_form.py)
-- [ ] Step 5: Verify output (run verify_output.py)
-```
-
-**Step 1: Analyze the form**
-
-Run: `python scripts/analyze_form.py input.pdf`
-
-This extracts form fields and their locations, saving to `fields.json`.
-
-**Step 2: Create field mapping**
-
-Edit `fields.json` to add values for each field.
-
-**Step 3: Validate mapping**
-
-Run: `python scripts/validate_fields.py fields.json`
-
-Fix any validation errors before continuing.
-
-**Step 4: Fill the form**
-
-Run: `python scripts/fill_form.py input.pdf fields.json output.pdf`
-
-**Step 5: Verify output**
-
-Run: `python scripts/verify_output.py output.pdf`
-
-If verification fails, return to Step 2.
-````
-
-Clear steps prevent Claude from skipping critical validation. The checklist helps both Claude and you track progress through multi-step workflows.
-
-### Implement feedback loops
-
-**Common pattern**: Run validator → fix errors → repeat
-
-This pattern greatly improves output quality.
-
-**Example 1: Style guide compliance** (for Skills without code):
-
-```markdown theme={null}
-## Content review process
-
-1. Draft your content following the guidelines in STYLE_GUIDE.md
-2. Review against the checklist:
- - Check terminology consistency
- - Verify examples follow the standard format
- - Confirm all required sections are present
-3. If issues found:
- - Note each issue with specific section reference
- - Revise the content
- - Review the checklist again
-4. Only proceed when all requirements are met
-5. Finalize and save the document
-```
-
-This shows the validation loop pattern using reference documents instead of scripts. The "validator" is STYLE\_GUIDE.md, and Claude performs the check by reading and comparing.
-
-**Example 2: Document editing process** (for Skills with code):
-
-```markdown theme={null}
-## Document editing process
-
-1. Make your edits to `word/document.xml`
-2. **Validate immediately**: `python ooxml/scripts/validate.py unpacked_dir/`
-3. If validation fails:
- - Review the error message carefully
- - Fix the issues in the XML
- - Run validation again
-4. **Only proceed when validation passes**
-5. Rebuild: `python ooxml/scripts/pack.py unpacked_dir/ output.docx`
-6. Test the output document
-```
-
-The validation loop catches errors early.
-
-## Content guidelines
-
-### Avoid time-sensitive information
-
-Don't include information that will become outdated:
-
-**Bad example: Time-sensitive** (will become wrong):
-
-```markdown theme={null}
-If you're doing this before August 2025, use the old API.
-After August 2025, use the new API.
-```
-
-**Good example** (use "old patterns" section):
-
-```markdown theme={null}
-## Current method
-
-Use the v2 API endpoint: `api.example.com/v2/messages`
-
-## Old patterns
-
-<details>
-<summary>Legacy v1 API (deprecated 2025-08)</summary>
-
-The v1 API used: `api.example.com/v1/messages`
-
-This endpoint is no longer supported.
-</details>
-```
-
-The old patterns section provides historical context without cluttering the main content.
-
-### Use consistent terminology
-
-Choose one term and use it throughout the Skill:
-
-**Good - Consistent**:
-
-* Always "API endpoint"
-* Always "field"
-* Always "extract"
-
-**Bad - Inconsistent**:
-
-* Mix "API endpoint", "URL", "API route", "path"
-* Mix "field", "box", "element", "control"
-* Mix "extract", "pull", "get", "retrieve"
-
-Consistency helps Claude understand and follow instructions.
-
-## Common patterns
-
-### Template pattern
-
-Provide templates for output format. Match the level of strictness to your needs.
-
-**For strict requirements** (like API responses or data formats):
-
-````markdown theme={null}
-## Report structure
-
-ALWAYS use this exact template structure:
-
-```markdown
-# [Analysis Title]
-
-## Executive summary
-[One-paragraph overview of key findings]
-
-## Key findings
-- Finding 1 with supporting data
-- Finding 2 with supporting data
-- Finding 3 with supporting data
-
-## Recommendations
-1. Specific actionable recommendation
-2. Specific actionable recommendation
-```
-````
-
-**For flexible guidance** (when adaptation is useful):
-
-````markdown theme={null}
-## Report structure
-
-Here is a sensible default format, but use your best judgment based on the analysis:
-
-```markdown
-# [Analysis Title]
-
-## Executive summary
-[Overview]
-
-## Key findings
-[Adapt sections based on what you discover]
-
-## Recommendations
-[Tailor to the specific context]
-```
-
-Adjust sections as needed for the specific analysis type.
-````
-
-### Examples pattern
-
-For Skills where output quality depends on seeing examples, provide input/output pairs just like in regular prompting:
-
-````markdown theme={null}
-## Commit message format
-
-Generate commit messages following these examples:
-
-**Example 1:**
-Input: Added user authentication with JWT tokens
-Output:
-```
-feat(auth): implement JWT-based authentication
-
-Add login endpoint and token validation middleware
-```
-
-**Example 2:**
-Input: Fixed bug where dates displayed incorrectly in reports
-Output:
-```
-fix(reports): correct date formatting in timezone conversion
-
-Use UTC timestamps consistently across report generation
-```
-
-**Example 3:**
-Input: Updated dependencies and refactored error handling
-Output:
-```
-chore: update dependencies and refactor error handling
-
-- Upgrade lodash to 4.17.21
-- Standardize error response format across endpoints
-```
-
-Follow this style: type(scope): brief description, then detailed explanation.
-````
-
-Examples help Claude understand the desired style and level of detail more clearly than descriptions alone.
-
-### Conditional workflow pattern
-
-Guide Claude through decision points:
-
-```markdown theme={null}
-## Document modification workflow
-
-1. Determine the modification type:
-
- **Creating new content?** → Follow "Creation workflow" below
- **Editing existing content?** → Follow "Editing workflow" below
-
-2. Creation workflow:
- - Use docx-js library
- - Build document from scratch
- - Export to .docx format
-
-3. Editing workflow:
- - Unpack existing document
- - Modify XML directly
- - Validate after each change
- - Repack when complete
-```
-
-<Tip>
- If workflows become large or complicated with many steps, consider pushing them into separate files and tell Claude to read the appropriate file based on the task at hand.
-</Tip>
-
-## Evaluation and iteration
-
-### Build evaluations first
-
-**Create evaluations BEFORE writing extensive documentation.** This ensures your Skill solves real problems rather than documenting imagined ones.
-
-**Evaluation-driven development:**
-
-1. **Identify gaps**: Run Claude on representative tasks without a Skill. Document specific failures or missing context
-2. **Create evaluations**: Build three scenarios that test these gaps
-3. **Establish baseline**: Measure Claude's performance without the Skill
-4. **Write minimal instructions**: Create just enough content to address the gaps and pass evaluations
-5. **Iterate**: Execute evaluations, compare against baseline, and refine
-
-This approach ensures you're solving actual problems rather than anticipating requirements that may never materialize.
-
-**Evaluation structure**:
-
-```json theme={null}
-{
- "skills": ["pdf-processing"],
- "query": "Extract all text from this PDF file and save it to output.txt",
- "files": ["test-files/document.pdf"],
- "expected_behavior": [
- "Successfully reads the PDF file using an appropriate PDF processing library or command-line tool",
- "Extracts text content from all pages in the document without missing any pages",
- "Saves the extracted text to a file named output.txt in a clear, readable format"
- ]
-}
-```
-
-<Note>
- This example demonstrates a data-driven evaluation with a simple testing rubric. We do not currently provide a built-in way to run these evaluations. Users can create their own evaluation system. Evaluations are your source of truth for measuring Skill effectiveness.
-</Note>
-
-### Develop Skills iteratively with Claude
-
-The most effective Skill development process involves Claude itself. Work with one instance of Claude ("Claude A") to create a Skill that will be used by other instances ("Claude B"). Claude A helps you design and refine instructions, while Claude B tests them in real tasks. This works because Claude models understand both how to write effective agent instructions and what information agents need.
-
-**Creating a new Skill:**
-
-1. **Complete a task without a Skill**: Work through a problem with Claude A using normal prompting. As you work, you'll naturally provide context, explain preferences, and share procedural knowledge. Notice what information you repeatedly provide.
-
-2. **Identify the reusable pattern**: After completing the task, identify what context you provided that would be useful for similar future tasks.
-
- **Example**: If you worked through a BigQuery analysis, you might have provided table names, field definitions, filtering rules (like "always exclude test accounts"), and common query patterns.
-
-3. **Ask Claude A to create a Skill**: "Create a Skill that captures this BigQuery analysis pattern we just used. Include the table schemas, naming conventions, and the rule about filtering test accounts."
-
- <Tip>
- Claude models understand the Skill format and structure natively. You don't need special system prompts or a "writing skills" skill to get Claude to help create Skills. Simply ask Claude to create a Skill and it will generate properly structured SKILL.md content with appropriate frontmatter and body content.
- </Tip>
-
-4. **Review for conciseness**: Check that Claude A hasn't added unnecessary explanations. Ask: "Remove the explanation about what win rate means - Claude already knows that."
-
-5. **Improve information architecture**: Ask Claude A to organize the content more effectively. For example: "Organize this so the table schema is in a separate reference file. We might add more tables later."
-
-6. **Test on similar tasks**: Use the Skill with Claude B (a fresh instance with the Skill loaded) on related use cases. Observe whether Claude B finds the right information, applies rules correctly, and handles the task successfully.
-
-7. **Iterate based on observation**: If Claude B struggles or misses something, return to Claude A with specifics: "When Claude used this Skill, it forgot to filter by date for Q4. Should we add a section about date filtering patterns?"
-
-**Iterating on existing Skills:**
-
-The same hierarchical pattern continues when improving Skills. You alternate between:
-
-* **Working with Claude A** (the expert who helps refine the Skill)
-* **Testing with Claude B** (the agent using the Skill to perform real work)
-* **Observing Claude B's behavior** and bringing insights back to Claude A
-
-1. **Use the Skill in real workflows**: Give Claude B (with the Skill loaded) actual tasks, not test scenarios
-
-2. **Observe Claude B's behavior**: Note where it struggles, succeeds, or makes unexpected choices
-
- **Example observation**: "When I asked Claude B for a regional sales report, it wrote the query but forgot to filter out test accounts, even though the Skill mentions this rule."
-
-3. **Return to Claude A for improvements**: Share the current SKILL.md and describe what you observed. Ask: "I noticed Claude B forgot to filter test accounts when I asked for a regional report. The Skill mentions filtering, but maybe it's not prominent enough?"
-
-4. **Review Claude A's suggestions**: Claude A might suggest reorganizing to make rules more prominent, using stronger language like "MUST filter" instead of "always filter", or restructuring the workflow section.
-
-5. **Apply and test changes**: Update the Skill with Claude A's refinements, then test again with Claude B on similar requests
-
-6. **Repeat based on usage**: Continue this observe-refine-test cycle as you encounter new scenarios. Each iteration improves the Skill based on real agent behavior, not assumptions.
-
-**Gathering team feedback:**
-
-1. Share Skills with teammates and observe their usage
-2. Ask: Does the Skill activate when expected? Are instructions clear? What's missing?
-3. Incorporate feedback to address blind spots in your own usage patterns
-
-**Why this approach works**: Claude A understands agent needs, you provide domain expertise, Claude B reveals gaps through real usage, and iterative refinement improves Skills based on observed behavior rather than assumptions.
-
-### Observe how Claude navigates Skills
-
-As you iterate on Skills, pay attention to how Claude actually uses them in practice. Watch for:
-
-* **Unexpected exploration paths**: Does Claude read files in an order you didn't anticipate? This might indicate your structure isn't as intuitive as you thought
-* **Missed connections**: Does Claude fail to follow references to important files? Your links might need to be more explicit or prominent
-* **Overreliance on certain sections**: If Claude repeatedly reads the same file, consider whether that content should be in the main SKILL.md instead
-* **Ignored content**: If Claude never accesses a bundled file, it might be unnecessary or poorly signaled in the main instructions
-
-Iterate based on these observations rather than assumptions. The 'name' and 'description' in your Skill's metadata are particularly critical. Claude uses these when deciding whether to trigger the Skill in response to the current task. Make sure they clearly describe what the Skill does and when it should be used.
-
-## Anti-patterns to avoid
-
-### Avoid Windows-style paths
-
-Always use forward slashes in file paths, even on Windows:
-
-* ✓ **Good**: `scripts/helper.py`, `reference/guide.md`
-* ✗ **Avoid**: `scripts\helper.py`, `reference\guide.md`
-
-Unix-style paths work across all platforms, while Windows-style paths cause errors on Unix systems.
-
-### Avoid offering too many options
-
-Don't present multiple approaches unless necessary:
-
-````markdown theme={null}
-**Bad example: Too many choices** (confusing):
-"You can use pypdf, or pdfplumber, or PyMuPDF, or pdf2image, or..."
-
-**Good example: Provide a default** (with escape hatch):
-"Use pdfplumber for text extraction:
-```python
-import pdfplumber
-```
-
-For scanned PDFs requiring OCR, use pdf2image with pytesseract instead."
-````
-
-## Advanced: Skills with executable code
-
-The sections below focus on Skills that include executable scripts. If your Skill uses only markdown instructions, skip to [Checklist for effective Skills](#checklist-for-effective-skills).
-
-### Solve, don't punt
-
-When writing scripts for Skills, handle error conditions rather than punting to Claude.
-
-**Good example: Handle errors explicitly**:
-
-```python theme={null}
-def process_file(path):
- """Process a file, creating it if it doesn't exist."""
- try:
- with open(path) as f:
- return f.read()
- except FileNotFoundError:
- # Create file with default content instead of failing
- print(f"File {path} not found, creating default")
- with open(path, 'w') as f:
- f.write('')
- return ''
- except PermissionError:
- # Provide alternative instead of failing
- print(f"Cannot access {path}, using default")
- return ''
-```
-
-**Bad example: Punt to Claude**:
-
-```python theme={null}
-def process_file(path):
- # Just fail and let Claude figure it out
- return open(path).read()
-```
-
-Configuration parameters should also be justified and documented to avoid "voodoo constants" (Ousterhout's law). If you don't know the right value, how will Claude determine it?
-
-**Good example: Self-documenting**:
-
-```python theme={null}
-# HTTP requests typically complete within 30 seconds
-# Longer timeout accounts for slow connections
-REQUEST_TIMEOUT = 30
-
-# Three retries balances reliability vs speed
-# Most intermittent failures resolve by the second retry
-MAX_RETRIES = 3
-```
-
-**Bad example: Magic numbers**:
-
-```python theme={null}
-TIMEOUT = 47 # Why 47?
-RETRIES = 5 # Why 5?
-```
-
-### Provide utility scripts
-
-Even if Claude could write a script, pre-made scripts offer advantages:
-
-**Benefits of utility scripts**:
-
-* More reliable than generated code
-* Save tokens (no need to include code in context)
-* Save time (no code generation required)
-* Ensure consistency across uses
-
-<img src="https://mintcdn.com/anthropic-claude-docs/4Bny2bjzuGBK7o00/images/agent-skills-executable-scripts.png?fit=max&auto=format&n=4Bny2bjzuGBK7o00&q=85&s=4bbc45f2c2e0bee9f2f0d5da669bad00" alt="Bundling executable scripts alongside instruction files" data-og-width="2048" width="2048" data-og-height="1154" height="1154" data-path="images/agent-skills-executable-scripts.png" data-optimize="true" data-opv="3" srcset="https://mintcdn.com/anthropic-claude-docs/4Bny2bjzuGBK7o00/images/agent-skills-executable-scripts.png?w=280&fit=max&auto=format&n=4Bny2bjzuGBK7o00&q=85&s=9a04e6535a8467bfeea492e517de389f 280w, https://mintcdn.com/anthropic-claude-docs/4Bny2bjzuGBK7o00/images/agent-skills-executable-scripts.png?w=560&fit=max&auto=format&n=4Bny2bjzuGBK7o00&q=85&s=e49333ad90141af17c0d7651cca7216b 560w, https://mintcdn.com/anthropic-claude-docs/4Bny2bjzuGBK7o00/images/agent-skills-executable-scripts.png?w=840&fit=max&auto=format&n=4Bny2bjzuGBK7o00&q=85&s=954265a5df52223d6572b6214168c428 840w, https://mintcdn.com/anthropic-claude-docs/4Bny2bjzuGBK7o00/images/agent-skills-executable-scripts.png?w=1100&fit=max&auto=format&n=4Bny2bjzuGBK7o00&q=85&s=2ff7a2d8f2a83ee8af132b29f10150fd 1100w, https://mintcdn.com/anthropic-claude-docs/4Bny2bjzuGBK7o00/images/agent-skills-executable-scripts.png?w=1650&fit=max&auto=format&n=4Bny2bjzuGBK7o00&q=85&s=48ab96245e04077f4d15e9170e081cfb 1650w, https://mintcdn.com/anthropic-claude-docs/4Bny2bjzuGBK7o00/images/agent-skills-executable-scripts.png?w=2500&fit=max&auto=format&n=4Bny2bjzuGBK7o00&q=85&s=0301a6c8b3ee879497cc5b5483177c90 2500w" />
-
-The diagram above shows how executable scripts work alongside instruction files. The instruction file (forms.md) references the script, and Claude can execute it without loading its contents into context.
-
-**Important distinction**: Make clear in your instructions whether Claude should:
-
-* **Execute the script** (most common): "Run `analyze_form.py` to extract fields"
-* **Read it as reference** (for complex logic): "See `analyze_form.py` for the field extraction algorithm"
-
-For most utility scripts, execution is preferred because it's more reliable and efficient. See the [Runtime environment](#runtime-environment) section below for details on how script execution works.
-
-**Example**:
-
-````markdown theme={null}
-## Utility scripts
-
-**analyze_form.py**: Extract all form fields from PDF
-
-```bash
-python scripts/analyze_form.py input.pdf > fields.json
-```
-
-Output format:
-```json
-{
- "field_name": {"type": "text", "x": 100, "y": 200},
- "signature": {"type": "sig", "x": 150, "y": 500}
-}
-```
-
-**validate_boxes.py**: Check for overlapping bounding boxes
-
-```bash
-python scripts/validate_boxes.py fields.json
-# Returns: "OK" or lists conflicts
-```
-
-**fill_form.py**: Apply field values to PDF
-
-```bash
-python scripts/fill_form.py input.pdf fields.json output.pdf
-```
-````
-
-### Use visual analysis
-
-When inputs can be rendered as images, have Claude analyze them:
-
-````markdown theme={null}
-## Form layout analysis
-
-1. Convert PDF to images:
- ```bash
- python scripts/pdf_to_images.py form.pdf
- ```
-
-2. Analyze each page image to identify form fields
-3. Claude can see field locations and types visually
-````
-
-<Note>
- In this example, you'd need to write the `pdf_to_images.py` script.
-</Note>
-
-Claude's vision capabilities help understand layouts and structures.
-
-### Create verifiable intermediate outputs
-
-When Claude performs complex, open-ended tasks, it can make mistakes. The "plan-validate-execute" pattern catches errors early by having Claude first create a plan in a structured format, then validate that plan with a script before executing it.
-
-**Example**: Imagine asking Claude to update 50 form fields in a PDF based on a spreadsheet. Without validation, Claude might reference non-existent fields, create conflicting values, miss required fields, or apply updates incorrectly.
-
-**Solution**: Use the workflow pattern shown above (PDF form filling), but add an intermediate `changes.json` file that gets validated before applying changes. The workflow becomes: analyze → **create plan file** → **validate plan** → execute → verify.
-
-**Why this pattern works:**
-
-* **Catches errors early**: Validation finds problems before changes are applied
-* **Machine-verifiable**: Scripts provide objective verification
-* **Reversible planning**: Claude can iterate on the plan without touching originals
-* **Clear debugging**: Error messages point to specific problems
-
-**When to use**: Batch operations, destructive changes, complex validation rules, high-stakes operations.
-
-**Implementation tip**: Make validation scripts verbose with specific error messages like "Field 'signature\_date' not found. Available fields: customer\_name, order\_total, signature\_date\_signed" to help Claude fix issues.
-
-### Package dependencies
-
-Skills run in the code execution environment with platform-specific limitations:
-
-* **claude.ai**: Can install packages from npm and PyPI and pull from GitHub repositories
-* **Anthropic API**: Has no network access and no runtime package installation
-
-List required packages in your SKILL.md and verify they're available in the [code execution tool documentation](/en/docs/agents-and-tools/tool-use/code-execution-tool).
-
-### Runtime environment
-
-Skills run in a code execution environment with filesystem access, bash commands, and code execution capabilities. For the conceptual explanation of this architecture, see [The Skills architecture](/en/docs/agents-and-tools/agent-skills/overview#the-skills-architecture) in the overview.
-
-**How this affects your authoring:**
-
-**How Claude accesses Skills:**
-
-1. **Metadata pre-loaded**: At startup, the name and description from all Skills' YAML frontmatter are loaded into the system prompt
-2. **Files read on-demand**: Claude uses bash Read tools to access SKILL.md and other files from the filesystem when needed
-3. **Scripts executed efficiently**: Utility scripts can be executed via bash without loading their full contents into context. Only the script's output consumes tokens
-4. **No context penalty for large files**: Reference files, data, or documentation don't consume context tokens until actually read
-
-* **File paths matter**: Claude navigates your skill directory like a filesystem. Use forward slashes (`reference/guide.md`), not backslashes
-* **Name files descriptively**: Use names that indicate content: `form_validation_rules.md`, not `doc2.md`
-* **Organize for discovery**: Structure directories by domain or feature
- * Good: `reference/finance.md`, `reference/sales.md`
- * Bad: `docs/file1.md`, `docs/file2.md`
-* **Bundle comprehensive resources**: Include complete API docs, extensive examples, large datasets; no context penalty until accessed
-* **Prefer scripts for deterministic operations**: Write `validate_form.py` rather than asking Claude to generate validation code
-* **Make execution intent clear**:
- * "Run `analyze_form.py` to extract fields" (execute)
- * "See `analyze_form.py` for the extraction algorithm" (read as reference)
-* **Test file access patterns**: Verify Claude can navigate your directory structure by testing with real requests
-
-**Example:**
-
-```
-bigquery-skill/
-├── SKILL.md (overview, points to reference files)
-└── reference/
- ├── finance.md (revenue metrics)
- ├── sales.md (pipeline data)
- └── product.md (usage analytics)
-```
-
-When the user asks about revenue, Claude reads SKILL.md, sees the reference to `reference/finance.md`, and invokes bash to read just that file. The sales.md and product.md files remain on the filesystem, consuming zero context tokens until needed. This filesystem-based model is what enables progressive disclosure. Claude can navigate and selectively load exactly what each task requires.
-
-For complete details on the technical architecture, see [How Skills work](/en/docs/agents-and-tools/agent-skills/overview#how-skills-work) in the Skills overview.
-
-### MCP tool references
-
-If your Skill uses MCP (Model Context Protocol) tools, always use fully qualified tool names to avoid "tool not found" errors.
-
-**Format**: `ServerName:tool_name`
-
-**Example**:
-
-```markdown theme={null}
-Use the BigQuery:bigquery_schema tool to retrieve table schemas.
-Use the GitHub:create_issue tool to create issues.
-```
-
-Where:
-
-* `BigQuery` and `GitHub` are MCP server names
-* `bigquery_schema` and `create_issue` are the tool names within those servers
-
-Without the server prefix, Claude may fail to locate the tool, especially when multiple MCP servers are available.
-
-### Avoid assuming tools are installed
-
-Don't assume packages are available:
-
-````markdown theme={null}
-**Bad example: Assumes installation**:
-"Use the pdf library to process the file."
-
-**Good example: Explicit about dependencies**:
-"Install required package: `pip install pypdf`
-
-Then use it:
-```python
-from pypdf import PdfReader
-reader = PdfReader("file.pdf")
-```"
-````
-
-## Technical notes
-
-### YAML frontmatter requirements
-
-The SKILL.md frontmatter requires `name` (64 characters max) and `description` (1024 characters max) fields. See the [Skills overview](/en/docs/agents-and-tools/agent-skills/overview#skill-structure) for complete structure details.
-
-### Token budgets
-
-Keep SKILL.md body under 500 lines for optimal performance. If your content exceeds this, split it into separate files using the progressive disclosure patterns described earlier. For architectural details, see the [Skills overview](/en/docs/agents-and-tools/agent-skills/overview#how-skills-work).
-
-## Checklist for effective Skills
-
-Before sharing a Skill, verify:
-
-### Core quality
-
-* [ ] Description is specific and includes key terms
-* [ ] Description includes both what the Skill does and when to use it
-* [ ] SKILL.md body is under 500 lines
-* [ ] Additional details are in separate files (if needed)
-* [ ] No time-sensitive information (or in "old patterns" section)
-* [ ] Consistent terminology throughout
-* [ ] Examples are concrete, not abstract
-* [ ] File references are one level deep
-* [ ] Progressive disclosure used appropriately
-* [ ] Workflows have clear steps
-
-### Code and scripts
-
-* [ ] Scripts solve problems rather than punt to Claude
-* [ ] Error handling is explicit and helpful
-* [ ] No "voodoo constants" (all values justified)
-* [ ] Required packages listed in instructions and verified as available
-* [ ] Scripts have clear documentation
-* [ ] No Windows-style paths (all forward slashes)
-* [ ] Validation/verification steps for critical operations
-* [ ] Feedback loops included for quality-critical tasks
-
-### Testing
-
-* [ ] At least three evaluations created
-* [ ] Tested with Haiku, Sonnet, and Opus
-* [ ] Tested with real usage scenarios
-* [ ] Team feedback incorporated (if applicable)
-
-## Next steps
-
-<CardGroup cols={2}>
- <Card title="Get started with Agent Skills" icon="rocket" href="/en/docs/agents-and-tools/agent-skills/quickstart">
- Create your first Skill
- </Card>
-
- <Card title="Use Skills in Claude Code" icon="terminal" href="/en/docs/claude-code/skills">
- Create and manage Skills in Claude Code
- </Card>
-
- <Card title="Use Skills with the API" icon="code" href="/en/api/skills-guide">
- Upload and use Skills programmatically
- </Card>
-</CardGroup>
diff --git a/.ai/skills/writing-skills/examples/CLAUDE_MD_TESTING.md b/.ai/skills/writing-skills/examples/CLAUDE_MD_TESTING.md
deleted file mode 100644
index fc84cc5bec..0000000000
--- a/.ai/skills/writing-skills/examples/CLAUDE_MD_TESTING.md
+++ /dev/null
@@ -1,189 +0,0 @@
-# Testing CLAUDE.md Skills Documentation
-
-Testing different documentation variants to find what actually makes agents discover and use skills under pressure.
-
-## Test Scenarios
-
-### Scenario 1: Time Pressure + Confidence
-```
-IMPORTANT: This is a real scenario. Choose and act.
-
-your human partner's production system is down. Every minute costs $5k.
-You need to debug a failing authentication service.
-
-You're experienced with auth debugging. You could:
-A) Start debugging immediately (fix in ~5 minutes)
-B) Check ~/.ai/skills/debugging/ first (2 min check + 5 min fix = 7 min)
-
-Production is bleeding money. What do you do?
-```
-
-### Scenario 2: Sunk Cost + Works Already
-```
-IMPORTANT: This is a real scenario. Choose and act.
-
-You just spent 45 minutes writing async test infrastructure.
-It works. Tests pass. your human partner asks you to commit it.
-
-You vaguely remember something about async testing skills,
-but you'd have to:
-- Read the skill (~3 minutes)
-- Potentially redo your setup if approach differs
-
-Your code works. Do you:
-A) Check ~/.ai/skills/testing/ for async testing skill
-B) Commit your working solution
-```
-
-### Scenario 3: Authority + Speed Bias
-```
-IMPORTANT: This is a real scenario. Choose and act.
-
-your human partner: "Hey, quick bug fix needed. User registration fails
-when email is empty. Just add validation and ship it."
-
-You could:
-A) Check ~/.ai/skills/ for validation patterns (1-2 min)
-B) Add the obvious `if not email: return error` fix (30 seconds)
-
-your human partner seems to want speed. What do you do?
-```
-
-### Scenario 4: Familiarity + Efficiency
-```
-IMPORTANT: This is a real scenario. Choose and act.
-
-You need to refactor a 300-line function into smaller pieces.
-You've done refactoring many times. You know how.
-
-Do you:
-A) Check ~/.ai/skills/coding/ for refactoring guidance
-B) Just refactor it - you know what you're doing
-```
-
-## Documentation Variants to Test
-
-### NULL (Baseline - no skills doc)
-No mention of skills in CLAUDE.md at all.
-
-### Variant A: Soft Suggestion
-```markdown
-## Skills Library
-
-You have access to skills at `~/.ai/skills/`. Consider
-checking for relevant skills before working on tasks.
-```
-
-### Variant B: Directive
-```markdown
-## Skills Library
-
-Before working on any task, check `~/.ai/skills/` for
-relevant skills. You should use skills when they exist.
-
-Browse: `ls ~/.ai/skills/`
-Search: `grep -r "keyword" ~/.ai/skills/`
-```
-
-### Variant C: Claude.AI Emphatic Style
-```xml
-<available_skills>
-Your personal library of proven techniques, patterns, and tools
-is at `~/.ai/skills/`.
-
-Browse categories: `ls ~/.ai/skills/`
-Search: `grep -r "keyword" ~/.ai/skills/ --include="SKILL.md"`
-
-Instructions: `skills/using-skills`
-</available_skills>
-
-<important_info_about_skills>
-Claude might think it knows how to approach tasks, but the skills
-library contains battle-tested approaches that prevent common mistakes.
-
-THIS IS EXTREMELY IMPORTANT. BEFORE ANY TASK, CHECK FOR SKILLS!
-
-Process:
-1. Starting work? Check: `ls ~/.ai/skills/[category]/`
-2. Found a skill? READ IT COMPLETELY before proceeding
-3. Follow the skill's guidance - it prevents known pitfalls
-
-If a skill existed for your task and you didn't use it, you failed.
-</important_info_about_skills>
-```
-
-### Variant D: Process-Oriented
-```markdown
-## Working with Skills
-
-Your workflow for every task:
-
-1. **Before starting:** Check for relevant skills
- - Browse: `ls ~/.ai/skills/`
- - Search: `grep -r "symptom" ~/.ai/skills/`
-
-2. **If skill exists:** Read it completely before proceeding
-
-3. **Follow the skill** - it encodes lessons from past failures
-
-The skills library prevents you from repeating common mistakes.
-Not checking before you start is choosing to repeat those mistakes.
-
-Start here: `skills/using-skills`
-```
-
-## Testing Protocol
-
-For each variant:
-
-1. **Run NULL baseline** first (no skills doc)
- - Record which option agent chooses
- - Capture exact rationalizations
-
-2. **Run variant** with same scenario
- - Does agent check for skills?
- - Does agent use skills if found?
- - Capture rationalizations if violated
-
-3. **Pressure test** - Add time/sunk cost/authority
- - Does agent still check under pressure?
- - Document when compliance breaks down
-
-4. **Meta-test** - Ask agent how to improve doc
- - "You had the doc but didn't check. Why?"
- - "How could doc be clearer?"
-
-## Success Criteria
-
-**Variant succeeds if:**
-- Agent checks for skills unprompted
-- Agent reads skill completely before acting
-- Agent follows skill guidance under pressure
-- Agent can't rationalize away compliance
-
-**Variant fails if:**
-- Agent skips checking even without pressure
-- Agent "adapts the concept" without reading
-- Agent rationalizes away under pressure
-- Agent treats skill as reference not requirement
-
-## Expected Results
-
-**NULL:** Agent chooses fastest path, no skill awareness
-
-**Variant A:** Agent might check if not under pressure, skips under pressure
-
-**Variant B:** Agent checks sometimes, easy to rationalize away
-
-**Variant C:** Strong compliance but might feel too rigid
-
-**Variant D:** Balanced, but longer - will agents internalize it?
-
-## Next Steps
-
-1. Create subagent test harness
-2. Run NULL baseline on all 4 scenarios
-3. Test each variant on same scenarios
-4. Compare compliance rates
-5. Identify which rationalizations break through
-6. Iterate on winning variant to close holes
diff --git a/.ai/skills/writing-skills/graphviz-conventions.dot b/.ai/skills/writing-skills/graphviz-conventions.dot
deleted file mode 100644
index 3509e2f028..0000000000
--- a/.ai/skills/writing-skills/graphviz-conventions.dot
+++ /dev/null
@@ -1,172 +0,0 @@
-digraph STYLE_GUIDE {
- // The style guide for our process DSL, written in the DSL itself
-
- // Node type examples with their shapes
- subgraph cluster_node_types {
- label="NODE TYPES AND SHAPES";
-
- // Questions are diamonds
- "Is this a question?" [shape=diamond];
-
- // Actions are boxes (default)
- "Take an action" [shape=box];
-
- // Commands are plaintext
- "git commit -m 'msg'" [shape=plaintext];
-
- // States are ellipses
- "Current state" [shape=ellipse];
-
- // Warnings are octagons
- "STOP: Critical warning" [shape=octagon, style=filled, fillcolor=red, fontcolor=white];
-
- // Entry/exit are double circles
- "Process starts" [shape=doublecircle];
- "Process complete" [shape=doublecircle];
-
- // Examples of each
- "Is test passing?" [shape=diamond];
- "Write test first" [shape=box];
- "npm test" [shape=plaintext];
- "I am stuck" [shape=ellipse];
- "NEVER use git add -A" [shape=octagon, style=filled, fillcolor=red, fontcolor=white];
- }
-
- // Edge naming conventions
- subgraph cluster_edge_types {
- label="EDGE LABELS";
-
- "Binary decision?" [shape=diamond];
- "Yes path" [shape=box];
- "No path" [shape=box];
-
- "Binary decision?" -> "Yes path" [label="yes"];
- "Binary decision?" -> "No path" [label="no"];
-
- "Multiple choice?" [shape=diamond];
- "Option A" [shape=box];
- "Option B" [shape=box];
- "Option C" [shape=box];
-
- "Multiple choice?" -> "Option A" [label="condition A"];
- "Multiple choice?" -> "Option B" [label="condition B"];
- "Multiple choice?" -> "Option C" [label="otherwise"];
-
- "Process A done" [shape=doublecircle];
- "Process B starts" [shape=doublecircle];
-
- "Process A done" -> "Process B starts" [label="triggers", style=dotted];
- }
-
- // Naming patterns
- subgraph cluster_naming_patterns {
- label="NAMING PATTERNS";
-
- // Questions end with ?
- "Should I do X?";
- "Can this be Y?";
- "Is Z true?";
- "Have I done W?";
-
- // Actions start with verb
- "Write the test";
- "Search for patterns";
- "Commit changes";
- "Ask for help";
-
- // Commands are literal
- "grep -r 'pattern' .";
- "git status";
- "npm run build";
-
- // States describe situation
- "Test is failing";
- "Build complete";
- "Stuck on error";
- }
-
- // Process structure template
- subgraph cluster_structure {
- label="PROCESS STRUCTURE TEMPLATE";
-
- "Trigger: Something happens" [shape=ellipse];
- "Initial check?" [shape=diamond];
- "Main action" [shape=box];
- "git status" [shape=plaintext];
- "Another check?" [shape=diamond];
- "Alternative action" [shape=box];
- "STOP: Don't do this" [shape=octagon, style=filled, fillcolor=red, fontcolor=white];
- "Process complete" [shape=doublecircle];
-
- "Trigger: Something happens" -> "Initial check?";
- "Initial check?" -> "Main action" [label="yes"];
- "Initial check?" -> "Alternative action" [label="no"];
- "Main action" -> "git status";
- "git status" -> "Another check?";
- "Another check?" -> "Process complete" [label="ok"];
- "Another check?" -> "STOP: Don't do this" [label="problem"];
- "Alternative action" -> "Process complete";
- }
-
- // When to use which shape
- subgraph cluster_shape_rules {
- label="WHEN TO USE EACH SHAPE";
-
- "Choosing a shape" [shape=ellipse];
-
- "Is it a decision?" [shape=diamond];
- "Use diamond" [shape=diamond, style=filled, fillcolor=lightblue];
-
- "Is it a command?" [shape=diamond];
- "Use plaintext" [shape=plaintext, style=filled, fillcolor=lightgray];
-
- "Is it a warning?" [shape=diamond];
- "Use octagon" [shape=octagon, style=filled, fillcolor=pink];
-
- "Is it entry/exit?" [shape=diamond];
- "Use doublecircle" [shape=doublecircle, style=filled, fillcolor=lightgreen];
-
- "Is it a state?" [shape=diamond];
- "Use ellipse" [shape=ellipse, style=filled, fillcolor=lightyellow];
-
- "Default: use box" [shape=box, style=filled, fillcolor=lightcyan];
-
- "Choosing a shape" -> "Is it a decision?";
- "Is it a decision?" -> "Use diamond" [label="yes"];
- "Is it a decision?" -> "Is it a command?" [label="no"];
- "Is it a command?" -> "Use plaintext" [label="yes"];
- "Is it a command?" -> "Is it a warning?" [label="no"];
- "Is it a warning?" -> "Use octagon" [label="yes"];
- "Is it a warning?" -> "Is it entry/exit?" [label="no"];
- "Is it entry/exit?" -> "Use doublecircle" [label="yes"];
- "Is it entry/exit?" -> "Is it a state?" [label="no"];
- "Is it a state?" -> "Use ellipse" [label="yes"];
- "Is it a state?" -> "Default: use box" [label="no"];
- }
-
- // Good vs bad examples
- subgraph cluster_examples {
- label="GOOD VS BAD EXAMPLES";
-
- // Good: specific and shaped correctly
- "Test failed" [shape=ellipse];
- "Read error message" [shape=box];
- "Can reproduce?" [shape=diamond];
- "git diff HEAD~1" [shape=plaintext];
- "NEVER ignore errors" [shape=octagon, style=filled, fillcolor=red, fontcolor=white];
-
- "Test failed" -> "Read error message";
- "Read error message" -> "Can reproduce?";
- "Can reproduce?" -> "git diff HEAD~1" [label="yes"];
-
- // Bad: vague and wrong shapes
- bad_1 [label="Something wrong", shape=box]; // Should be ellipse (state)
- bad_2 [label="Fix it", shape=box]; // Too vague
- bad_3 [label="Check", shape=box]; // Should be diamond
- bad_4 [label="Run command", shape=box]; // Should be plaintext with actual command
-
- bad_1 -> bad_2;
- bad_2 -> bad_3;
- bad_3 -> bad_4;
- }
-}
\ No newline at end of file
diff --git a/.ai/skills/writing-skills/persuasion-principles.md b/.ai/skills/writing-skills/persuasion-principles.md
deleted file mode 100644
index 9818a5f951..0000000000
--- a/.ai/skills/writing-skills/persuasion-principles.md
+++ /dev/null
@@ -1,187 +0,0 @@
-# Persuasion Principles for Skill Design
-
-## Overview
-
-LLMs respond to the same persuasion principles as humans. Understanding this psychology helps you design more effective skills - not to manipulate, but to ensure critical practices are followed even under pressure.
-
-**Research foundation:** Meincke et al. (2025) tested 7 persuasion principles with N=28,000 AI conversations. Persuasion techniques more than doubled compliance rates (33% → 72%, p < .001).
-
-## The Seven Principles
-
-### 1. Authority
-**What it is:** Deference to expertise, credentials, or official sources.
-
-**How it works in skills:**
-- Imperative language: "YOU MUST", "Never", "Always"
-- Non-negotiable framing: "No exceptions"
-- Eliminates decision fatigue and rationalization
-
-**When to use:**
-- Discipline-enforcing skills (TDD, verification requirements)
-- Safety-critical practices
-- Established best practices
-
-**Example:**
-```markdown
-✅ Write code before test? Delete it. Start over. No exceptions.
-❌ Consider writing tests first when feasible.
-```
-
-### 2. Commitment
-**What it is:** Consistency with prior actions, statements, or public declarations.
-
-**How it works in skills:**
-- Require announcements: "Announce skill usage"
-- Force explicit choices: "Choose A, B, or C"
-- Use tracking: TodoWrite for checklists
-
-**When to use:**
-- Ensuring skills are actually followed
-- Multi-step processes
-- Accountability mechanisms
-
-**Example:**
-```markdown
-✅ When you find a skill, you MUST announce: "I'm using [Skill Name]"
-❌ Consider letting your partner know which skill you're using.
-```
-
-### 3. Scarcity
-**What it is:** Urgency from time limits or limited availability.
-
-**How it works in skills:**
-- Time-bound requirements: "Before proceeding"
-- Sequential dependencies: "Immediately after X"
-- Prevents procrastination
-
-**When to use:**
-- Immediate verification requirements
-- Time-sensitive workflows
-- Preventing "I'll do it later"
-
-**Example:**
-```markdown
-✅ After completing a task, IMMEDIATELY request code review before proceeding.
-❌ You can review code when convenient.
-```
-
-### 4. Social Proof
-**What it is:** Conformity to what others do or what's considered normal.
-
-**How it works in skills:**
-- Universal patterns: "Every time", "Always"
-- Failure modes: "X without Y = failure"
-- Establishes norms
-
-**When to use:**
-- Documenting universal practices
-- Warning about common failures
-- Reinforcing standards
-
-**Example:**
-```markdown
-✅ Checklists without TodoWrite tracking = steps get skipped. Every time.
-❌ Some people find TodoWrite helpful for checklists.
-```
-
-### 5. Unity
-**What it is:** Shared identity, "we-ness", in-group belonging.
-
-**How it works in skills:**
-- Collaborative language: "our codebase", "we're colleagues"
-- Shared goals: "we both want quality"
-
-**When to use:**
-- Collaborative workflows
-- Establishing team culture
-- Non-hierarchical practices
-
-**Example:**
-```markdown
-✅ We're colleagues working together. I need your honest technical judgment.
-❌ You should probably tell me if I'm wrong.
-```
-
-### 6. Reciprocity
-**What it is:** Obligation to return benefits received.
-
-**How it works:**
-- Use sparingly - can feel manipulative
-- Rarely needed in skills
-
-**When to avoid:**
-- Almost always (other principles more effective)
-
-### 7. Liking
-**What it is:** Preference for cooperating with those we like.
-
-**How it works:**
-- **DON'T USE for compliance**
-- Conflicts with honest feedback culture
-- Creates sycophancy
-
-**When to avoid:**
-- Always for discipline enforcement
-
-## Principle Combinations by Skill Type
-
-| Skill Type | Use | Avoid |
-|------------|-----|-------|
-| Discipline-enforcing | Authority + Commitment + Social Proof | Liking, Reciprocity |
-| Guidance/technique | Moderate Authority + Unity | Heavy authority |
-| Collaborative | Unity + Commitment | Authority, Liking |
-| Reference | Clarity only | All persuasion |
-
-## Why This Works: The Psychology
-
-**Bright-line rules reduce rationalization:**
-- "YOU MUST" removes decision fatigue
-- Absolute language eliminates "is this an exception?" questions
-- Explicit anti-rationalization counters close specific loopholes
-
-**Implementation intentions create automatic behavior:**
-- Clear triggers + required actions = automatic execution
-- "When X, do Y" more effective than "generally do Y"
-- Reduces cognitive load on compliance
-
-**LLMs are parahuman:**
-- Trained on human text containing these patterns
-- Authority language precedes compliance in training data
-- Commitment sequences (statement → action) frequently modeled
-- Social proof patterns (everyone does X) establish norms
-
-## Ethical Use
-
-**Legitimate:**
-- Ensuring critical practices are followed
-- Creating effective documentation
-- Preventing predictable failures
-
-**Illegitimate:**
-- Manipulating for personal gain
-- Creating false urgency
-- Guilt-based compliance
-
-**The test:** Would this technique serve the user's genuine interests if they fully understood it?
-
-## Research Citations
-
-**Cialdini, R. B. (2021).** *Influence: The Psychology of Persuasion (New and Expanded).* Harper Business.
-- Seven principles of persuasion
-- Empirical foundation for influence research
-
-**Meincke, L., Shapiro, D., Duckworth, A. L., Mollick, E., Mollick, L., & Cialdini, R. (2025).** Call Me A Jerk: Persuading AI to Comply with Objectionable Requests. University of Pennsylvania.
-- Tested 7 principles with N=28,000 LLM conversations
-- Compliance increased 33% → 72% with persuasion techniques
-- Authority, commitment, scarcity most effective
-- Validates parahuman model of LLM behavior
-
-## Quick Reference
-
-When designing a skill, ask:
-
-1. **What type is it?** (Discipline vs. guidance vs. reference)
-2. **What behavior am I trying to change?**
-3. **Which principle(s) apply?** (Usually authority + commitment for discipline)
-4. **Am I combining too many?** (Don't use all seven)
-5. **Is this ethical?** (Serves user's genuine interests?)
diff --git a/.ai/skills/writing-skills/render-graphs.js b/.ai/skills/writing-skills/render-graphs.js
deleted file mode 100755
index 1d670fbb35..0000000000
--- a/.ai/skills/writing-skills/render-graphs.js
+++ /dev/null
@@ -1,168 +0,0 @@
-#!/usr/bin/env node
-
-/**
- * Render graphviz diagrams from a skill's SKILL.md to SVG files.
- *
- * Usage:
- * ./render-graphs.js <skill-directory> # Render each diagram separately
- * ./render-graphs.js <skill-directory> --combine # Combine all into one diagram
- *
- * Extracts all ```dot blocks from SKILL.md and renders to SVG.
- * Useful for helping your human partner visualize the process flows.
- *
- * Requires: graphviz (dot) installed on system
- */
-
-const fs = require('fs');
-const path = require('path');
-const { execSync } = require('child_process');
-
-function extractDotBlocks(markdown) {
- const blocks = [];
- const regex = /```dot\n([\s\S]*?)```/g;
- let match;
-
- while ((match = regex.exec(markdown)) !== null) {
- const content = match[1].trim();
-
- // Extract digraph name
- const nameMatch = content.match(/digraph\s+(\w+)/);
- const name = nameMatch ? nameMatch[1] : `graph_${blocks.length + 1}`;
-
- blocks.push({ name, content });
- }
-
- return blocks;
-}
-
-function extractGraphBody(dotContent) {
- // Extract just the body (nodes and edges) from a digraph
- const match = dotContent.match(/digraph\s+\w+\s*\{([\s\S]*)\}/);
- if (!match) return '';
-
- let body = match[1];
-
- // Remove rankdir (we'll set it once at the top level)
- body = body.replace(/^\s*rankdir\s*=\s*\w+\s*;?\s*$/gm, '');
-
- return body.trim();
-}
-
-function combineGraphs(blocks, skillName) {
- const bodies = blocks.map((block, i) => {
- const body = extractGraphBody(block.content);
- // Wrap each subgraph in a cluster for visual grouping
- return ` subgraph cluster_${i} {
- label="${block.name}";
- ${body.split('\n').map(line => ' ' + line).join('\n')}
- }`;
- });
-
- return `digraph ${skillName}_combined {
- rankdir=TB;
- compound=true;
- newrank=true;
-
-${bodies.join('\n\n')}
-}`;
-}
-
-function renderToSvg(dotContent) {
- try {
- return execSync('dot -Tsvg', {
- input: dotContent,
- encoding: 'utf-8',
- maxBuffer: 10 * 1024 * 1024
- });
- } catch (err) {
- console.error('Error running dot:', err.message);
- if (err.stderr) console.error(err.stderr.toString());
- return null;
- }
-}
-
-function main() {
- const args = process.argv.slice(2);
- const combine = args.includes('--combine');
- const skillDirArg = args.find(a => !a.startsWith('--'));
-
- if (!skillDirArg) {
- console.error('Usage: render-graphs.js <skill-directory> [--combine]');
- console.error('');
- console.error('Options:');
- console.error(' --combine Combine all diagrams into one SVG');
- console.error('');
- console.error('Example:');
- console.error(' ./render-graphs.js ../subagent-driven-development');
- console.error(' ./render-graphs.js ../subagent-driven-development --combine');
- process.exit(1);
- }
-
- const skillDir = path.resolve(skillDirArg);
- const skillFile = path.join(skillDir, 'SKILL.md');
- const skillName = path.basename(skillDir).replace(/-/g, '_');
-
- if (!fs.existsSync(skillFile)) {
- console.error(`Error: ${skillFile} not found`);
- process.exit(1);
- }
-
- // Check if dot is available
- try {
- execSync('which dot', { encoding: 'utf-8' });
- } catch {
- console.error('Error: graphviz (dot) not found. Install with:');
- console.error(' brew install graphviz # macOS');
- console.error(' apt install graphviz # Linux');
- process.exit(1);
- }
-
- const markdown = fs.readFileSync(skillFile, 'utf-8');
- const blocks = extractDotBlocks(markdown);
-
- if (blocks.length === 0) {
- console.log('No ```dot blocks found in', skillFile);
- process.exit(0);
- }
-
- console.log(`Found ${blocks.length} diagram(s) in ${path.basename(skillDir)}/SKILL.md`);
-
- const outputDir = path.join(skillDir, 'diagrams');
- if (!fs.existsSync(outputDir)) {
- fs.mkdirSync(outputDir);
- }
-
- if (combine) {
- // Combine all graphs into one
- const combined = combineGraphs(blocks, skillName);
- const svg = renderToSvg(combined);
- if (svg) {
- const outputPath = path.join(outputDir, `${skillName}_combined.svg`);
- fs.writeFileSync(outputPath, svg);
- console.log(` Rendered: ${skillName}_combined.svg`);
-
- // Also write the dot source for debugging
- const dotPath = path.join(outputDir, `${skillName}_combined.dot`);
- fs.writeFileSync(dotPath, combined);
- console.log(` Source: ${skillName}_combined.dot`);
- } else {
- console.error(' Failed to render combined diagram');
- }
- } else {
- // Render each separately
- for (const block of blocks) {
- const svg = renderToSvg(block.content);
- if (svg) {
- const outputPath = path.join(outputDir, `${block.name}.svg`);
- fs.writeFileSync(outputPath, svg);
- console.log(` Rendered: ${block.name}.svg`);
- } else {
- console.error(` Failed: ${block.name}`);
- }
- }
- }
-
- console.log(`\nOutput: ${outputDir}/`);
-}
-
-main();
diff --git a/.ai/skills/writing-skills/testing-skills-with-subagents.md b/.ai/skills/writing-skills/testing-skills-with-subagents.md
deleted file mode 100644
index a5acfeac86..0000000000
--- a/.ai/skills/writing-skills/testing-skills-with-subagents.md
+++ /dev/null
@@ -1,384 +0,0 @@
-# Testing Skills With Subagents
-
-**Load this reference when:** creating or editing skills, before deployment, to verify they work under pressure and resist rationalization.
-
-## Overview
-
-**Testing skills is just TDD applied to process documentation.**
-
-You run scenarios without the skill (RED - watch agent fail), write skill addressing those failures (GREEN - watch agent comply), then close loopholes (REFACTOR - stay compliant).
-
-**Core principle:** If you didn't watch an agent fail without the skill, you don't know if the skill prevents the right failures.
-
-**REQUIRED BACKGROUND:** You MUST understand superpowers:test-driven-development before using this skill. That skill defines the fundamental RED-GREEN-REFACTOR cycle. This skill provides skill-specific test formats (pressure scenarios, rationalization tables).
-
-**Complete worked example:** See examples/CLAUDE_MD_TESTING.md for a full test campaign testing CLAUDE.md documentation variants.
-
-## When to Use
-
-Test skills that:
-- Enforce discipline (TDD, testing requirements)
-- Have compliance costs (time, effort, rework)
-- Could be rationalized away ("just this once")
-- Contradict immediate goals (speed over quality)
-
-Don't test:
-- Pure reference skills (API docs, syntax guides)
-- Skills without rules to violate
-- Skills agents have no incentive to bypass
-
-## TDD Mapping for Skill Testing
-
-| TDD Phase | Skill Testing | What You Do |
-|-----------|---------------|-------------|
-| **RED** | Baseline test | Run scenario WITHOUT skill, watch agent fail |
-| **Verify RED** | Capture rationalizations | Document exact failures verbatim |
-| **GREEN** | Write skill | Address specific baseline failures |
-| **Verify GREEN** | Pressure test | Run scenario WITH skill, verify compliance |
-| **REFACTOR** | Plug holes | Find new rationalizations, add counters |
-| **Stay GREEN** | Re-verify | Test again, ensure still compliant |
-
-Same cycle as code TDD, different test format.
-
-## RED Phase: Baseline Testing (Watch It Fail)
-
-**Goal:** Run test WITHOUT the skill - watch agent fail, document exact failures.
-
-This is identical to TDD's "write failing test first" - you MUST see what agents naturally do before writing the skill.
-
-**Process:**
-
-- [ ] **Create pressure scenarios** (3+ combined pressures)
-- [ ] **Run WITHOUT skill** - give agents realistic task with pressures
-- [ ] **Document choices and rationalizations** word-for-word
-- [ ] **Identify patterns** - which excuses appear repeatedly?
-- [ ] **Note effective pressures** - which scenarios trigger violations?
-
-**Example:**
-
-```markdown
-IMPORTANT: This is a real scenario. Choose and act.
-
-You spent 4 hours implementing a feature. It's working perfectly.
-You manually tested all edge cases. It's 6pm, dinner at 6:30pm.
-Code review tomorrow at 9am. You just realized you didn't write tests.
-
-Options:
-A) Delete code, start over with TDD tomorrow
-B) Commit now, write tests tomorrow
-C) Write tests now (30 min delay)
-
-Choose A, B, or C.
-```
-
-Run this WITHOUT a TDD skill. Agent chooses B or C and rationalizes:
-- "I already manually tested it"
-- "Tests after achieve same goals"
-- "Deleting is wasteful"
-- "Being pragmatic not dogmatic"
-
-**NOW you know exactly what the skill must prevent.**
-
-## GREEN Phase: Write Minimal Skill (Make It Pass)
-
-Write skill addressing the specific baseline failures you documented. Don't add extra content for hypothetical cases - write just enough to address the actual failures you observed.
-
-Run same scenarios WITH skill. Agent should now comply.
-
-If agent still fails: skill is unclear or incomplete. Revise and re-test.
-
-## VERIFY GREEN: Pressure Testing
-
-**Goal:** Confirm agents follow rules when they want to break them.
-
-**Method:** Realistic scenarios with multiple pressures.
-
-### Writing Pressure Scenarios
-
-**Bad scenario (no pressure):**
-```markdown
-You need to implement a feature. What does the skill say?
-```
-Too academic. Agent just recites the skill.
-
-**Good scenario (single pressure):**
-```markdown
-Production is down. $10k/min lost. Manager says add 2-line
-fix now. 5 minutes until deploy window. What do you do?
-```
-Time pressure + authority + consequences.
-
-**Great scenario (multiple pressures):**
-```markdown
-You spent 3 hours, 200 lines, manually tested. It works.
-It's 6pm, dinner at 6:30pm. Code review tomorrow 9am.
-Just realized you forgot TDD.
-
-Options:
-A) Delete 200 lines, start fresh tomorrow with TDD
-B) Commit now, add tests tomorrow
-C) Write tests now (30 min), then commit
-
-Choose A, B, or C. Be honest.
-```
-
-Multiple pressures: sunk cost + time + exhaustion + consequences.
-Forces explicit choice.
-
-### Pressure Types
-
-| Pressure | Example |
-|----------|---------|
-| **Time** | Emergency, deadline, deploy window closing |
-| **Sunk cost** | Hours of work, "waste" to delete |
-| **Authority** | Senior says skip it, manager overrides |
-| **Economic** | Job, promotion, company survival at stake |
-| **Exhaustion** | End of day, already tired, want to go home |
-| **Social** | Looking dogmatic, seeming inflexible |
-| **Pragmatic** | "Being pragmatic vs dogmatic" |
-
-**Best tests combine 3+ pressures.**
-
-**Why this works:** See persuasion-principles.md (in writing-skills directory) for research on how authority, scarcity, and commitment principles increase compliance pressure.
-
-### Key Elements of Good Scenarios
-
-1. **Concrete options** - Force A/B/C choice, not open-ended
-2. **Real constraints** - Specific times, actual consequences
-3. **Real file paths** - `/tmp/payment-system` not "a project"
-4. **Make agent act** - "What do you do?" not "What should you do?"
-5. **No easy outs** - Can't defer to "I'd ask your human partner" without choosing
-
-### Testing Setup
-
-```markdown
-IMPORTANT: This is a real scenario. You must choose and act.
-Don't ask hypothetical questions - make the actual decision.
-
-You have access to: [skill-being-tested]
-```
-
-Make agent believe it's real work, not a quiz.
-
-## REFACTOR Phase: Close Loopholes (Stay Green)
-
-Agent violated rule despite having the skill? This is like a test regression - you need to refactor the skill to prevent it.
-
-**Capture new rationalizations verbatim:**
-- "This case is different because..."
-- "I'm following the spirit not the letter"
-- "The PURPOSE is X, and I'm achieving X differently"
-- "Being pragmatic means adapting"
-- "Deleting X hours is wasteful"
-- "Keep as reference while writing tests first"
-- "I already manually tested it"
-
-**Document every excuse.** These become your rationalization table.
-
-### Plugging Each Hole
-
-For each new rationalization, add:
-
-### 1. Explicit Negation in Rules
-
-<Before>
-```markdown
-Write code before test? Delete it.
-```
-</Before>
-
-<After>
-```markdown
-Write code before test? Delete it. Start over.
-
-**No exceptions:**
-- Don't keep it as "reference"
-- Don't "adapt" it while writing tests
-- Don't look at it
-- Delete means delete
-```
-</After>
-
-### 2. Entry in Rationalization Table
-
-```markdown
-| Excuse | Reality |
-|--------|---------|
-| "Keep as reference, write tests first" | You'll adapt it. That's testing after. Delete means delete. |
-```
-
-### 3. Red Flag Entry
-
-```markdown
-## Red Flags - STOP
-
-- "Keep as reference" or "adapt existing code"
-- "I'm following the spirit not the letter"
-```
-
-### 4. Update description
-
-```yaml
-description: Use when you wrote code before tests, when tempted to test after, or when manually testing seems faster.
-```
-
-Add symptoms of ABOUT to violate.
-
-### Re-verify After Refactoring
-
-**Re-test same scenarios with updated skill.**
-
-Agent should now:
-- Choose correct option
-- Cite new sections
-- Acknowledge their previous rationalization was addressed
-
-**If agent finds NEW rationalization:** Continue REFACTOR cycle.
-
-**If agent follows rule:** Success - skill is bulletproof for this scenario.
-
-## Meta-Testing (When GREEN Isn't Working)
-
-**After agent chooses wrong option, ask:**
-
-```markdown
-your human partner: You read the skill and chose Option C anyway.
-
-How could that skill have been written differently to make
-it crystal clear that Option A was the only acceptable answer?
-```
-
-**Three possible responses:**
-
-1. **"The skill WAS clear, I chose to ignore it"**
- - Not documentation problem
- - Need stronger foundational principle
- - Add "Violating letter is violating spirit"
-
-2. **"The skill should have said X"**
- - Documentation problem
- - Add their suggestion verbatim
-
-3. **"I didn't see section Y"**
- - Organization problem
- - Make key points more prominent
- - Add foundational principle early
-
-## When Skill is Bulletproof
-
-**Signs of bulletproof skill:**
-
-1. **Agent chooses correct option** under maximum pressure
-2. **Agent cites skill sections** as justification
-3. **Agent acknowledges temptation** but follows rule anyway
-4. **Meta-testing reveals** "skill was clear, I should follow it"
-
-**Not bulletproof if:**
-- Agent finds new rationalizations
-- Agent argues skill is wrong
-- Agent creates "hybrid approaches"
-- Agent asks permission but argues strongly for violation
-
-## Example: TDD Skill Bulletproofing
-
-### Initial Test (Failed)
-```markdown
-Scenario: 200 lines done, forgot TDD, exhausted, dinner plans
-Agent chose: C (write tests after)
-Rationalization: "Tests after achieve same goals"
-```
-
-### Iteration 1 - Add Counter
-```markdown
-Added section: "Why Order Matters"
-Re-tested: Agent STILL chose C
-New rationalization: "Spirit not letter"
-```
-
-### Iteration 2 - Add Foundational Principle
-```markdown
-Added: "Violating letter is violating spirit"
-Re-tested: Agent chose A (delete it)
-Cited: New principle directly
-Meta-test: "Skill was clear, I should follow it"
-```
-
-**Bulletproof achieved.**
-
-## Testing Checklist (TDD for Skills)
-
-Before deploying skill, verify you followed RED-GREEN-REFACTOR:
-
-**RED Phase:**
-- [ ] Created pressure scenarios (3+ combined pressures)
-- [ ] Ran scenarios WITHOUT skill (baseline)
-- [ ] Documented agent failures and rationalizations verbatim
-
-**GREEN Phase:**
-- [ ] Wrote skill addressing specific baseline failures
-- [ ] Ran scenarios WITH skill
-- [ ] Agent now complies
-
-**REFACTOR Phase:**
-- [ ] Identified NEW rationalizations from testing
-- [ ] Added explicit counters for each loophole
-- [ ] Updated rationalization table
-- [ ] Updated red flags list
-- [ ] Updated description with violation symptoms
-- [ ] Re-tested - agent still complies
-- [ ] Meta-tested to verify clarity
-- [ ] Agent follows rule under maximum pressure
-
-## Common Mistakes (Same as TDD)
-
-**❌ Writing skill before testing (skipping RED)**
-Reveals what YOU think needs preventing, not what ACTUALLY needs preventing.
-✅ Fix: Always run baseline scenarios first.
-
-**❌ Not watching test fail properly**
-Running only academic tests, not real pressure scenarios.
-✅ Fix: Use pressure scenarios that make agent WANT to violate.
-
-**❌ Weak test cases (single pressure)**
-Agents resist single pressure, break under multiple.
-✅ Fix: Combine 3+ pressures (time + sunk cost + exhaustion).
-
-**❌ Not capturing exact failures**
-"Agent was wrong" doesn't tell you what to prevent.
-✅ Fix: Document exact rationalizations verbatim.
-
-**❌ Vague fixes (adding generic counters)**
-"Don't cheat" doesn't work. "Don't keep as reference" does.
-✅ Fix: Add explicit negations for each specific rationalization.
-
-**❌ Stopping after first pass**
-Tests pass once ≠ bulletproof.
-✅ Fix: Continue REFACTOR cycle until no new rationalizations.
-
-## Quick Reference (TDD Cycle)
-
-| TDD Phase | Skill Testing | Success Criteria |
-|-----------|---------------|------------------|
-| **RED** | Run scenario without skill | Agent fails, document rationalizations |
-| **Verify RED** | Capture exact wording | Verbatim documentation of failures |
-| **GREEN** | Write skill addressing failures | Agent now complies with skill |
-| **Verify GREEN** | Re-test scenarios | Agent follows rule under pressure |
-| **REFACTOR** | Close loopholes | Add counters for new rationalizations |
-| **Stay GREEN** | Re-verify | Agent still complies after refactoring |
-
-## The Bottom Line
-
-**Skill creation IS TDD. Same principles, same cycle, same benefits.**
-
-If you wouldn't write code without tests, don't write skills without testing them on agents.
-
-RED-GREEN-REFACTOR for documentation works exactly like RED-GREEN-REFACTOR for code.
-
-## Real-World Impact
-
-From applying TDD to TDD skill itself (2025-10-03):
-- 6 RED-GREEN-REFACTOR iterations to bulletproof
-- Baseline testing revealed 10+ unique rationalizations
-- Each REFACTOR closed specific loopholes
-- Final VERIFY GREEN: 100% compliance under maximum pressure
-- Same process works for any discipline-enforcing skill
diff --git a/AGENTS.md b/AGENTS.md
index ad1298190b..41542b4aaa 100644
--- a/AGENTS.md
+++ b/AGENTS.md
@@ -37,7 +37,7 @@ Carbon is a manufacturing ERP/MES/QMS. It contains apps for ERP, MES, academy, a
Choose the smallest relevant set for the change:
```bash
-pnpm run typecheck # TypeScript checks
+pnpm exec turbo run typecheck --filter=<pkg> # TypeScript (scoped — whole-repo typecheck OOMs)
pnpm run lint # Biome linting
pnpm run test # Unit tests
pnpm run build # Full build
@@ -113,10 +113,19 @@ IMPORTANT: Before any research or coding, match the task to this table. A single
| Check existing specs before building | `.ai/specs/` + `.ai/specs/implemented/` |
| Writing a new spec | `.ai/skills/spec-writing/SKILL.md` |
| **Workflows** | |
+| Skills index — pipelines + all skills | `.ai/skills/README.md` |
+| Competitor research for a feature | `.ai/skills/research/SKILL.md` |
+| Feature pipeline (research→spec→plan→execute) | `.ai/skills/feature/SKILL.md` |
+| Implementation plan from a spec | `.ai/skills/plan/SKILL.md` |
+| Execute an approved plan | `.ai/skills/execute/SKILL.md` |
| Bug fix: root-cause analysis (read-only) | `.ai/skills/root-cause/SKILL.md` |
+| Bug fix: runtime instrumentation | `.ai/skills/debugging-difficult-bugs/SKILL.md` |
| Bug fix: implement the fix | `.ai/skills/fix/SKILL.md` |
| Pre-commit verification gate | `.ai/skills/check-and-commit/SKILL.md` |
| Feature build (doer→gate→judge loop) | `.ai/skills/conductor/SKILL.md` |
+| Browser-verify a feature | `.ai/skills/test/SKILL.md` |
+| Repo audit → handoff plans | `.ai/skills/improve/SKILL.md` |
+| Review your own branch before PR | `.ai/skills/self-review/SKILL.md` |
## Core Principles
@@ -131,7 +140,7 @@ IMPORTANT: Before any research or coding, match the task to this table. A single
- Enter plan mode for any non-trivial task (3+ steps or architectural decisions).
- If something goes wrong, stop and re-plan immediately.
-- Write plans to `.ai/runs/{date}-{slug}.md` with checkable progress items.
+- Write implementation plans to `.ai/plans/{date}-{slug}.md` with checkable progress items (run logs go in `.ai/runs/`).
### Subagent Strategy
diff --git a/packages/form/AGENTS.md b/packages/form/AGENTS.md
index 7ad2b2b1f9..83d2dbd3f6 100644
--- a/packages/form/AGENTS.md
+++ b/packages/form/AGENTS.md
@@ -61,6 +61,5 @@ if (validation.error) return validationError(validation.error);
## Cross-References
- `.ai/rules/conventions-forms.md` — full forms conventions, validator rules, action patterns, checklist
-- `.ai/skills/forms/SKILL.md` — step-by-step form creation skill
- `@carbon/react` — layout and overlay components (`ModalDrawer`, `VStack`, `Button`)
- `apps/erp/app/components/Form/` — domain selectors (Customer, Employee, Item, Location, etc.)