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.

feat: add composable feature development skills with research-driven design (#867)

Brad Barbin23957078e7aa
diff --git a/.claude/skills/brainstorm/SKILL.md b/.claude/skills/brainstorm/SKILL.md
new file mode 100644
index 0000000000..ca4aee5dd9
--- /dev/null
+++ b/.claude/skills/brainstorm/SKILL.md
@@ -0,0 +1,171 @@
+---
+name: brainstorm
+description: Research-driven brainstorming for feature design. Use when designing a new feature, exploring approaches, or making design decisions. Automatically researches competitors before asking design questions. Triggers on "brainstorm", "design 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 `llm/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 `docs/specs/[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 | `llm/research/[feature-slug].md` |
+| Design specification | `docs/specs/[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/.claude/skills/design/SKILL.md b/.claude/skills/design/SKILL.md
new file mode 100644
index 0000000000..7089870fac
--- /dev/null
+++ b/.claude/skills/design/SKILL.md
@@ -0,0 +1,141 @@
+---
+name: design
+description: Research-driven feature design with implementation plan. Combines brainstorming and planning into one flow. Use when designing a new feature. Triggers on "design", "brainstorm", "plan a feature", "how should we build X".
+---
+
+# Design: Research-Driven Feature Design
+
+Research competitors → design the feature → create implementation plan → get approval.
+
+**Announce at start:** "I'm using the design skill."
+
+## Workflow
+
+```
+┌───────────┐ ┌───────────┐ ┌───────────┐ ┌───────────┐
+│ 1. Scope │───▶│ 2. Research│───▶│ 3. Design │───▶│ 4. Plan │
+└───────────┘ └───────────┘ └───────────┘ └───────────┘
+```
+
+## Step 1: Scope
+
+Ask focused questions (max 3-4):
+- **What** — Core capability
+- **Why** — Problem it solves
+- **Where** — ERP, MES, or Academy
+- **Who** — Primary users
+
+Classify domain for research:
+
+| Domain | Keywords | Competitors |
+|--------|----------|-------------|
+| Accounting | GL, AP, AR, invoicing | SAP, NetSuite |
+| Manufacturing | Jobs, BOMs, routing | SAP, Epicor |
+| MES | Tracking, scheduling | SAP, Manufacturo, First Resonance |
+| CNC/Sheet Metal | Quoting, nesting | SAP, Fulcrum, Paperless Parts |
+| Quality | Inspection, SPC, FAI | SAP, 1factory, HighQA |
+| Inventory | Valuation, lots | SAP, NetSuite, Fishbowl |
+
+## Step 2: Research
+
+Invoke `/research [feature]` to survey competitors.
+
+Save to `llm/research/[feature].md`.
+
+## Step 3: Design
+
+With research in hand, design the feature:
+
+### 3.1 Design Decisions
+
+For each decision:
+1. State the question
+2. Reference research — "SAP and NetSuite both..."
+3. Recommend approach
+
+### 3.2 Write Spec
+
+Save to `docs/specs/[feature]-design.md`:
+
+```markdown
+# [Feature] Design
+
+## Summary
+[One paragraph]
+
+## Research
+Key findings from [llm/research/[feature].md]:
+- [Pattern 1]
+- [Pattern 2]
+
+## Decisions
+
+### [Decision 1]
+**Question:** ...
+**Industry:** ...
+**Our Approach:** ...
+
+## Data Model
+[Tables, columns, relationships]
+
+## Workflows
+[User journeys, state transitions]
+
+## Edge Cases
+[Tricky stuff, informed by competitors]
+```
+
+## Step 4: Plan
+
+Create implementation plan in `llm/tasks/[feature]-plan.md`.
+
+### Load Conventions
+
+Before writing tasks, load from `llm/conventions/`:
+- `database.md` — Migrations, RLS, transactions
+- `forms.md` — ValidatedForm, validators, actions
+- `services.md` — Service function patterns
+- `ui.md` — Components, polish
+
+### Task Structure
+
+Each task is **2-5 minutes**, one discrete action:
+
+```markdown
+## Task 1: Create migration
+
+**Files:**
+- Create: `packages/database/supabase/migrations/20240115041739_add_thing.sql`
+
+**Steps:**
+1. Create migration following `llm/conventions/database.md`
+2. Run: `npm run db:build`
+3. Commit
+```
+
+### Task Order
+
+1. Database migrations
+2. Types and validators
+3. Service functions
+4. Route handlers
+5. UI components
+6. Tests
+
+## Output
+
+| Artifact | Location |
+|----------|----------|
+| Research | `llm/research/[feature].md` |
+| Design spec | `docs/specs/[feature]-design.md` |
+| Implementation plan | `llm/tasks/[feature]-plan.md` |
+
+## Approval Gate
+
+Present spec and plan together. Wait for explicit approval before handing off to `/execute`.
+
+## When to Stop
+
+- Feature is more complex than expected
+- Research reveals conflicting patterns
+- Need business input (not just technical)
diff --git a/.claude/skills/execute/SKILL.md b/.claude/skills/execute/SKILL.md
new file mode 100644
index 0000000000..521d9ac459
--- /dev/null
+++ b/.claude/skills/execute/SKILL.md
@@ -0,0 +1,201 @@
+---
+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.
+---
+
+# Execute: Plan Implementation
+
+Execute implementation plans task by task. Follow each step exactly, run all verifications, commit after each task.
+
+**Announce at start:** "I'm using the execute skill to implement this plan."
+
+## Prerequisites
+
+Before executing:
+1. An implementation plan exists (from `/plan`)
+2. The plan has been approved
+3. You're on the correct branch
+
+If no plan exists, suggest running `/plan` first.
+
+## Workflow
+
+```
+┌──────────────┐ ┌──────────────┐ ┌──────────────┐ ┌──────────────┐
+│ 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 `llm/tasks/[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 `llm/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 | `llm/workflows/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 `llm/workflows/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 `llm/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
+
+**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
+
+### What to Do
+
+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 Blocker Resolution
+
+Return to the task and continue.
+
+## Step 4: Complete & Review
+
+### 4.1 Final Verification
+
+After all tasks:
+- [ ] All tests pass: `pnpm test`
+- [ ] TypeScript compiles: `pnpm typecheck`
+- [ ] Lint passes: `pnpm lint`
+
+### 4.2 Feature Verification
+
+Use `/verify` to test the feature in the browser:
+- Happy path works
+- Edge cases handled
+- No regressions
+
+### 4.3 Self-Review
+
+Use `/self-review` to check your work before declaring done.
+
+### 4.4 Report Completion
+
+```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:
+
+```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
+```
+
+Use the Agent tool with clear context for each subagent.
+
+## Output
+
+| Artifact | Location |
+|----------|----------|
+| Working code | Feature branch |
+| Progress tracker | `llm/tasks/todo.md` |
+| Commits | Git history |
+
+## Next Steps
+
+After execution:
+- Create PR (if ready)
+- Run `/self-review`
+- Use `/verify` for browser testing
diff --git a/.claude/skills/feature/SKILL.md b/.claude/skills/feature/SKILL.md
new file mode 100644
index 0000000000..94bca56cf8
--- /dev/null
+++ b/.claude/skills/feature/SKILL.md
@@ -0,0 +1,120 @@
+---
+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".
+---
+
+# Feature: End-to-End Development Orchestrator
+
+Orchestrates the full feature development lifecycle by composing smaller skills:
+
+```
+/research → /brainstorm → /plan → /execute → /verify
+```
+
+**Announce at start:** "I'm using the feature skill to orchestrate end-to-end development."
+
+## When to Use This vs Individual Skills
+
+| 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 |
+
+## The Pipeline
+
+### Phase 1: Research (`/research`)
+
+Identify the domain and research competitors:
+- SAP (always)
+- Domain-specific best-in-class competitors
+- Save to `llm/research/[feature].md`
+
+### Phase 2: Brainstorm (`/brainstorm`)
+
+Design with research in hand:
+- Use competitor patterns to inform decisions
+- Document design choices with rationale
+- Save to `docs/specs/[feature]-design.md`
+- **Gate:** User approval required
+
+### Phase 3: Plan (`/plan`)
+
+Create implementation plan:
+- Break into 2-5 minute tasks
+- Complete code, no pseudocode
+- Save to `llm/tasks/[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 llm/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 | `llm/research/[feature].md` |
+| Brainstorm | Design spec | `docs/specs/[feature]-design.md` |
+| Plan | Implementation plan | `llm/tasks/[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`
diff --git a/.claude/skills/plan/SKILL.md b/.claude/skills/plan/SKILL.md
new file mode 100644
index 0000000000..7dabfe22e4
--- /dev/null
+++ b/.claude/skills/plan/SKILL.md
@@ -0,0 +1,252 @@
+---
+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.
+---
+
+# Plan: Implementation Planning
+
+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."
+
+**Announce at start:** "I'm using the plan skill to create the implementation plan."
+
+## Prerequisites
+
+Before planning:
+1. A design spec exists (from `/brainstorm` or provided by user)
+2. The design has been approved
+3. Key decisions are documented
+
+If no spec exists, suggest running `/brainstorm` first.
+
+## Workflow
+
+```
+┌──────────────┐ ┌──────────────┐ ┌──────────────┐ ┌──────────────┐
+│ 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 `docs/specs/[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 | `llm/workflows/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 |
+
+### Migration Tasks Must Follow
+
+From `llm/workflows/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
+
+### 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
+```
+
+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
+**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
+
+```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 `llm/tasks/[feature-name]-plan.md`:
+
+```markdown
+# [Feature] Implementation Plan
+
+## Overview
+- **Design Spec:** `docs/specs/[feature-name]-design.md`
+- **Tasks:** N tasks, estimated M minutes
+- **Dependencies:** [diagram or list]
+
+## Task 1: [Title]
+**Files:**
+- ...
+
+**Steps:**
+1. ...
+
+## Task 2: [Title]
+...
+```
+
+### 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 `llm/workflows/database-migration.md`
+- [ ] Form tasks reference `/forms` skill patterns
+
+### 4.3 Get Approval
+
+Present the plan and wait for explicit approval.
+
+## Output
+
+| Artifact | Location |
+|----------|----------|
+| Implementation plan | `llm/tasks/[feature-name]-plan.md` |
+
+## Next Step
+
+After approval, hand off to `/execute` to run the plan.
+
+## Plan Format Reference
+
+```markdown
+# [Feature] Implementation Plan
+
+## Overview
+- **Design Spec:** [path]
+- **Research:** [path]
+- **Estimated Time:** N tasks × 3 min avg = ~M minutes
+- **Branch:** feature/[feature-name]
+
+## Dependencies
+Task 2 depends on Task 1 (migration must exist)
+Tasks 3-5 are independent (can parallelize)
+
+---
+
+## 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
+ ```
+
+4. Commit:
+ ```bash
+ git add -A && git commit -m "feat(module): add X table"
+ ```
+
+---
+
+## Task 2: Add TypeScript types
+...
+```
diff --git a/.claude/skills/research/SKILL.md b/.claude/skills/research/SKILL.md
new file mode 100644
index 0000000000..b4e0711695
--- /dev/null
+++ b/.claude/skills/research/SKILL.md
@@ -0,0 +1,119 @@
+---
+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.
+---
+
+# Research: Competitor Best Practices
+
+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.
+
+## Domain-to-Competitor Mapping
+
+| 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 |
+
+**SAP is always included** — it's the gold standard for enterprise patterns, even when point solutions are more innovative.
+
+## Workflow
+
+### Step 1: Classify the Domain
+
+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: Identify Competitors to Research
+
+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
+
+### Step 3: Execute Targeted Searches
+
+For each competitor, search for:
+- `[Competitor] [feature] documentation`
+- `[Competitor] [feature] how it works`
+- `[Competitor] [feature] best practices`
+
+Example for "inventory valuation":
+- `SAP S/4HANA inventory valuation methods`
+- `NetSuite inventory costing FIFO LIFO average`
+- `SAP inventory valuation configuration`
+
+### Step 4: Synthesize Findings
+
+Structure research as actionable patterns:
+
+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 5: Save Output
+
+Save the research to `llm/research/[feature-slug].md` using the output format below.
+
+## Output Format
+
+```markdown
+# [Feature] Research: Best Practices Survey
+
+## Summary
+One paragraph describing what was researched and key findings.
+
+## Competitors Surveyed
+- **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]
+
+### 2. [Pattern Name]
+...
+
+## Competitor-Specific Details
+
+### SAP
+[Notable implementation details, configuration options, terminology]
+
+### [Competitor]
+[Notable implementation details, unique approaches]
+
+## Recommended Approach for Carbon
+
+Based on the research:
+1. [Recommendation with rationale]
+2. [Recommendation with rationale]
+
+## Sources
+- [Link 1]
+- [Link 2]
+```
+
+## Example Research
+
+See `llm/tasks/accrual-accounting-research.md` for an example of well-structured competitor research covering NetSuite and SAP accounting patterns.
+
+## 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
+
+## Tips
+
+- **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
diff --git a/llm/conventions/database.md b/llm/conventions/database.md
new file mode 100644
index 0000000000..57359c103e
--- /dev/null
+++ b/llm/conventions/database.md
@@ -0,0 +1,200 @@
+# Database Conventions
+
+## Migrations
+
+Location: `packages/database/supabase/migrations/`
+
+### Generate Migration
+
+```bash
+npm run db:migrate <name-of-migration>
+```
+
+**WARNING:** Never use `000000` as HHMMSS in filename. Use random digits to avoid cross-branch collisions.
+
+### Table Template
+
+```sql
+CREATE TABLE "entityName" (
+ "id" TEXT NOT NULL DEFAULT id('entity'),
+ "companyId" TEXT NOT NULL,
+
+ -- Business columns
+ "name" TEXT NOT NULL,
+ "description" TEXT,
+ "active" BOOLEAN NOT NULL DEFAULT TRUE,
+
+ -- Audit columns (required)
+ "createdBy" TEXT NOT NULL REFERENCES "user"("id"),
+ "createdAt" TIMESTAMP WITH TIME ZONE NOT NULL DEFAULT NOW(),
+ "updatedBy" TEXT REFERENCES "user"("id"),
+ "updatedAt" TIMESTAMP WITH TIME ZONE,
+
+ -- Optional extensibility
+ "customFields" JSONB,
+ "tags" TEXT[],
+
+ PRIMARY KEY ("id", "companyId"),
+ FOREIGN KEY ("companyId") REFERENCES "company"("id") ON DELETE CASCADE
+);
+
+-- Required indexes
+CREATE INDEX "entityName_companyId_idx" ON "entityName" ("companyId");
+CREATE INDEX "entityName_createdBy_idx" ON "entityName" ("createdBy");
+```
+
+### Required Patterns
+
+| Pattern | Rule |
+|---------|------|
+| Primary key | `id TEXT NOT NULL DEFAULT id('prefix')` |
+| Multi-tenancy | `companyId TEXT NOT NULL` + composite PK |
+| Audit columns | `createdBy`, `createdAt`, `updatedBy`, `updatedAt` |
+| Foreign keys | Always index them |
+| Never | `itemReadableId` field, decimal precision in NUMERIC |
+
+### Column Types
+
+| Type | Use For |
+|------|---------|
+| `TEXT` | IDs, names, strings |
+| `NUMERIC` | Financial amounts |
+| `INTEGER` | Quantities |
+| `TIMESTAMP WITH TIME ZONE` | Dates/times |
+| `BOOLEAN NOT NULL DEFAULT` | Flags |
+| `JSONB` | Custom fields |
+| `TEXT[]` | Tags |
+
+### RLS Policies
+
+Use standardized names and pattern:
+
+```sql
+ALTER TABLE "public"."entityName" ENABLE ROW LEVEL SECURITY;
+
+CREATE POLICY "SELECT" ON "public"."entityName"
+FOR SELECT USING (
+ "companyId" = ANY ((SELECT get_companies_with_employee_role())::text[])
+);
+
+CREATE POLICY "INSERT" ON "public"."entityName"
+FOR INSERT WITH CHECK (
+ "companyId" = ANY ((SELECT get_companies_with_employee_permission('module_create'))::text[])
+);
+
+CREATE POLICY "UPDATE" ON "public"."entityName"
+FOR UPDATE USING (
+ "companyId" = ANY ((SELECT get_companies_with_employee_permission('module_update'))::text[])
+);
+
+CREATE POLICY "DELETE" ON "public"."entityName"
+FOR DELETE USING (
+ "companyId" = ANY ((SELECT get_companies_with_employee_permission('module_delete'))::text[])
+);
+```
+
+### Views
+
+```sql
+CREATE VIEW "module_entityView" WITH(SECURITY_INVOKER=true) AS
+SELECT e.*, u."fullName" as "createdByFullName"
+FROM "entityName" e
+LEFT JOIN "user" u ON u."id" = e."createdBy";
+```
+
+### Test Migration
+
+```bash
+npm run db:build
+```
+
+## Transactions (Kysely)
+
+Use Kysely transactions for multi-row writes. Supabase `Promise.all` can leave data half-applied.
+
+### When to Use
+
+- Bulk reorder / sortOrder updates
+- Multi-table writes (parent + children)
+- Any operation where partial failure is a bug
+
+### When NOT to Use
+
+- Single writes (already atomic)
+- Reads (use Supabase client for RLS)
+- Idempotent fan-out where retry is cheap
+
+### Pattern
+
+```typescript
+// Service function
+import type { Kysely, KyselyDatabase } from "@carbon/database/client";
+
+export async function updateLineOrder(
+ db: Kysely<KyselyDatabase>,
+ updates: { id: string; sortOrder: number; updatedBy: string }[]
+) {
+ return db.transaction().execute(async (trx) => {
+ for (const { id, sortOrder, updatedBy } of updates) {
+ await trx
+ .updateTable("tableName")
+ .set({ sortOrder, updatedBy })
+ .where("id", "=", id)
+ .execute();
+ }
+ });
+}
+
+// Route handler
+import { getDatabaseClient } from "~/services/database.server";
+
+export async function action({ request }: ActionFunctionArgs) {
+ const { userId } = await requirePermissions(request, { update: "module" });
+ try {
+ await updateLineOrder(getDatabaseClient(), updates);
+ } catch (err) {
+ return data({}, await flash(request, error(err, "Failed to update")));
+ }
+ return { success: true };
+}
+```
+
+### Key Notes
+
+- First arg is `db: Kysely<KyselyDatabase>`, route passes `getDatabaseClient()`
+- Kysely throws on rollback — use try/catch, not `{ error }` return
+- Kysely bypasses RLS — enforce auth at route via `requirePermissions()`
+
+## Zod Validators
+
+After migration, update `.models.ts`:
+
+```typescript
+import { z } from "zod";
+import { zfd } from "zod-form-data";
+
+export const entityValidator = z.object({
+ id: z.string(),
+ companyId: z.string(),
+ name: z.string().min(1),
+ description: z.string().optional(),
+ active: z.boolean().default(true),
+});
+
+export const entityFormValidator = zfd.formData({
+ name: zfd.text(z.string().min(1)),
+ description: zfd.text(z.string().optional()),
+ active: zfd.checkbox(),
+});
+```
+
+## Migration Checklist
+
+- [ ] File created with `npm run db:migrate <name>`
+- [ ] Uses `id('prefix')` for primary key
+- [ ] Has `companyId` with composite PK
+- [ ] Has audit columns
+- [ ] Indexes on companyId and foreign keys
+- [ ] RLS with standardized policy names
+- [ ] Zod validators in `.models.ts`
+- [ ] Tested with `npm run db:build`
diff --git a/llm/conventions/forms.md b/llm/conventions/forms.md
new file mode 100644
index 0000000000..d434d94118
--- /dev/null
+++ b/llm/conventions/forms.md
@@ -0,0 +1,218 @@
+# Forms Conventions
+
+Forms in Carbon follow a three-part pattern: **zod validator** → **form component** → **route action**.
+
+## File Locations
+
+| Piece | ERP Location |
+|-------|-------------|
+| Validator | `app/modules/{module}/{module}.models.ts` |
+| Form UI | `app/modules/{module}/ui/{Feature}/{Feature}Form.tsx` |
+| Route action | `app/routes/x+/{module}+/{resource}.new.tsx` |
+| Components | `~/components/Form` (re-exports `@carbon/form` + selectors) |
+
+## 1. Validator
+
+Define in module's `.models.ts`:
+
+```typescript
+import { z } from "zod";
+import { zfd } from "zod-form-data";
+
+export const thingValidator = z.object({
+ id: zfd.text(z.string().optional()),
+ name: z.string().min(1, { message: "Name is required" }),
+ type: z.enum(thingTypes, {
+ errorMap: () => ({ message: "Type is required" })
+ }),
+ quantity: zfd.numeric(z.number().min(0)),
+ isActive: zfd.checkbox(),
+ notes: zfd.text(z.string().optional()),
+ items: z.array(z.string().min(1)).min(1, {
+ message: "At least one item is required"
+ }),
+});
+```
+
+### Validator Rules
+
+| Field Type | Use |
+|------------|-----|
+| Optional string | `zfd.text(z.string().optional())` |
+| Number from FormData | `zfd.numeric(z.number())` |
+| Checkbox boolean | `zfd.checkbox()` |
+| Enum | `z.enum(values, { errorMap: ... })` |
+| Cross-field | `.refine()` |
+
+## 2. Form Component
+
+```typescript
+import { ValidatedForm } from "@carbon/form";
+import { Button, HStack, VStack } from "@carbon/react";
+import { useNavigate } from "react-router";
+import type { z } from "zod";
+import { Hidden, Input, Select, Submit } from "~/components/Form";
+import { usePermissions } from "~/hooks";
+import { thingValidator } from "~/modules/things";
+import { path } from "~/utils/path";
+
+type ThingFormProps = {
+ initialValues: z.infer<typeof thingValidator>;
+};
+
+const ThingForm = ({ initialValues }: ThingFormProps) => {
+ const permissions = usePermissions();
+ const navigate = useNavigate();
+ const onClose = () => navigate(-1);
+
+ const isEditing = !!initialValues.id;
+ const isDisabled = isEditing
+ ? !permissions.can("update", "things")
+ : !permissions.can("create", "things");
+
+ return (
+ <ValidatedForm
+ validator={thingValidator}
+ method="post"
+ action={isEditing ? path.to.thing(initialValues.id!) : path.to.newThing}
+ defaultValues={initialValues}
+ >
+ <Hidden name="id" />
+ <VStack spacing={4}>
+ <Input name="name" label="Name" />
+ <Select name="type" label="Type" options={typeOptions} />
+ </VStack>
+ <HStack>
+ <Submit isDisabled={isDisabled}>Save</Submit>
+ <Button size="md" variant="solid" onClick={onClose}>Cancel</Button>
+ </HStack>
+ </ValidatedForm>
+ );
+};
+```
+
+### Form Component Rules
+
+- Always include `<Hidden name="id" />` for edit support
+- Use `VStack spacing={4}` for vertical layout
+- Use `grid grid-cols-1 lg:grid-cols-3 gap-x-8 gap-y-4` for multi-column
+- Permission check determines `isDisabled` on Submit
+- Type props with `z.infer<typeof validator>`
+
+## 3. Route Action
+
+```typescript
+import { assertIsPost, error, success } from "@carbon/auth";
+import { requirePermissions } from "@carbon/auth/auth.server";
+import { flash } from "@carbon/auth/session.server";
+import { validationError, validator } from "@carbon/form";
+import type { ActionFunctionArgs } from "react-router";
+import { data, redirect } from "react-router";
+import { thingValidator, insertThing } from "~/modules/things";
+import { path } from "~/utils/path";
+
+export async function action({ request }: ActionFunctionArgs) {
+ assertIsPost(request);
+ const { client, companyId, userId } = await requirePermissions(request, {
+ create: "things"
+ });
+
+ const validation = await validator(thingValidator).validate(
+ await request.formData()
+ );
+
+ if (validation.error) {
+ return validationError(validation.error);
+ }
+
+ const result = await insertThing(client, {
+ ...validation.data,
+ companyId,
+ createdBy: userId
+ });
+
+ if (result.error) {
+ return data({}, await flash(request, error(result.error, "Failed to create")));
+ }
+
+ throw redirect(path.to.things, await flash(request, success("Created")));
+}
+```
+
+### Route Action Rules
+
+| Step | Pattern |
+|------|---------|
+| First | `assertIsPost(request)` |
+| Auth | `requirePermissions(request, { action: "module" })` |
+| Validate | `validator(schema).validate(formData)` — NOT `schema.parse()` |
+| Validation error | `return validationError(validation.error)` |
+| Service error | `return data({}, await flash(request, error(...)))` |
+| Success | `throw redirect(...)` — NOT `return redirect()` |
+
+## Available Components
+
+### Base (`@carbon/form`)
+
+| Component | Props | Use For |
+|-----------|-------|---------|
+| `Input` | `name, label, prefix?, suffix?` | Text |
+| `Number` | `name, label, formatOptions?` | Numeric with steppers |
+| `TextArea` | `name, label, characterLimit?` | Multi-line |
+| `Select` | `name, label, options` | Dropdown |
+| `Combobox` | `name, label, options` | Searchable dropdown |
+| `CreatableCombobox` | `name, label, options, onCreateOption?` | Searchable + create |
+| `MultiSelect` | `name, label, options` | Multi-select |
+| `Boolean` | `name, label, description?` | Toggle |
+| `DatePicker` | `name, label` | Date |
+| `Hidden` | `name, value?` | Hidden field |
+| `Submit` | `isDisabled?` | Submit button |
+
+### Domain Selectors (`~/components/Form`)
+
+Auto-load options from stores:
+
+`Customer`, `Supplier`, `Employee`, `Item`, `Part`, `Location`, `Account`, `Currency`, `Department`, `WorkCenter`, `UnitOfMeasure`, `PaymentTerm`, `ShippingMethod`, `Tags`
+
+## Common Patterns
+
+### Dependent Fields
+
+```typescript
+const [categoryId, setCategoryId] = useState(initialValues.categoryId ?? "");
+
+<AccountCategory name="categoryId" onChange={(cat) => setCategoryId(cat?.id ?? "")} />
+<AccountSubcategory name="subcategoryId" accountCategoryId={categoryId} />
+```
+
+### Enum Options
+
+```typescript
+const typeOptions = thingTypes.map((t) => ({ label: t, value: t }));
+<Select name="type" label="Type" options={typeOptions} />
+```
+
+### Client Action (Cache Invalidation)
+
+```typescript
+export async function clientAction({ serverAction }: ClientActionFunctionArgs) {
+ const companyId = getCompanyId();
+ window.clientCache?.invalidateQueries({
+ predicate: (query) => {
+ const queryKey = query.queryKey as string[];
+ return queryKey[0] === "things" && queryKey[1] === companyId;
+ }
+ });
+ return await serverAction();
+}
+```
+
+## Checklist
+
+- [ ] Zod validator in `{module}.models.ts`
+- [ ] Validator exported from module index
+- [ ] Form component with `ValidatedForm`
+- [ ] Route with action + default export
+- [ ] `clientAction` if entity is cached
+- [ ] Path helpers in `~/utils/path`
+- [ ] Container matches neighboring routes (Drawer, Card, etc.)
diff --git a/llm/conventions/index.md b/llm/conventions/index.md
new file mode 100644
index 0000000000..afe0a5d1d3
--- /dev/null
+++ b/llm/conventions/index.md
@@ -0,0 +1,20 @@
+# Carbon Conventions
+
+Quick reference for all Carbon-specific patterns. Load the relevant file before writing code.
+
+| Convention | File | When to Load |
+|------------|------|--------------|
+| Database | [database.md](database.md) | Migrations, RLS, multi-tenancy, transactions |
+| Forms | [forms.md](forms.md) | ValidatedForm, zod validators, route actions |
+| Services | [services.md](services.md) | Service functions, upserts, error handling |
+| UI | [ui.md](ui.md) | Components, animations, polish |
+
+## The Golden Rules
+
+1. **Multi-tenancy**: Every table has `companyId` with composite PK `("id", "companyId")`
+2. **IDs**: Use `id('prefix')` function, never UUID directly
+3. **Audit**: Include `createdBy`, `createdAt`, `updatedBy`, `updatedAt`
+4. **RLS**: Standardized policy names: SELECT, INSERT, UPDATE, DELETE
+5. **Forms**: `ValidatedForm` + zod validator + route action
+6. **Transactions**: Use Kysely for multi-row writes, not Promise.all
+7. **Errors**: Use `flash(request, error(...))` pattern, throw redirects on success
diff --git a/llm/conventions/services.md b/llm/conventions/services.md
new file mode 100644
index 0000000000..d2438cedb0
--- /dev/null
+++ b/llm/conventions/services.md
@@ -0,0 +1,246 @@
+# Services Conventions
+
+Service functions live in `app/modules/{module}/{module}.service.ts` and handle database operations.
+
+## File Structure
+
+```
+app/modules/{module}/
+├── {module}.models.ts # Zod validators, types
+├── {module}.service.ts # Database operations
+├── index.ts # Re-exports
+└── ui/ # Components
+```
+
+## Service Function Pattern
+
+```typescript
+import type { Database } from "@carbon/database";
+import type { SupabaseClient } from "@supabase/supabase-js";
+
+export async function getThing(
+ client: SupabaseClient<Database>,
+ id: string
+) {
+ return client
+ .from("thing")
+ .select("*")
+ .eq("id", id)
+ .single();
+}
+
+export async function insertThing(
+ client: SupabaseClient<Database>,
+ data: {
+ name: string;
+ companyId: string;
+ createdBy: string;
+ }
+) {
+ return client
+ .from("thing")
+ .insert(data)
+ .select("id")
+ .single();
+}
+
+export async function updateThing(
+ client: SupabaseClient<Database>,
+ id: string,
+ data: {
+ name?: string;
+ updatedBy: string;
+ }
+) {
+ return client
+ .from("thing")
+ .update(data)
+ .eq("id", id)
+ .select("id")
+ .single();
+}
+
+export async function deleteThing(
+ client: SupabaseClient<Database>,
+ id: string
+) {
+ return client
+ .from("thing")
+ .delete()
+ .eq("id", id);
+}
+```
+
+## Return Pattern
+
+All Supabase operations return `{ data, error }`. The route handler checks:
+
+```typescript
+const result = await insertThing(client, data);
+
+if (result.error) {
+ return data({}, await flash(request, error(result.error, "Failed")));
+}
+
+// Use result.data
+```
+
+## Upsert Pattern
+
+For create/update in one function:
+
+```typescript
+export async function upsertThing(
+ client: SupabaseClient<Database>,
+ data: {
+ id?: string;
+ name: string;
+ companyId: string;
+ createdBy: string;
+ updatedBy?: string;
+ }
+) {
+ if (data.id) {
+ return client
+ .from("thing")
+ .update({
+ name: data.name,
+ updatedBy: data.updatedBy,
+ updatedAt: new Date().toISOString(),
+ })
+ .eq("id", data.id)
+ .select("id")
+ .single();
+ }
+
+ return client
+ .from("thing")
+ .insert({
+ name: data.name,
+ companyId: data.companyId,
+ createdBy: data.createdBy,
+ })
+ .select("id")
+ .single();
+}
+```
+
+## Transaction Pattern
+
+For multi-row writes, use Kysely (see [database.md](database.md#transactions-kysely)):
+
+```typescript
+import type { Kysely, KyselyDatabase } from "@carbon/database/client";
+
+export async function updateThingOrder(
+ db: Kysely<KyselyDatabase>,
+ updates: { id: string; sortOrder: number; updatedBy: string }[]
+) {
+ return db.transaction().execute(async (trx) => {
+ for (const { id, sortOrder, updatedBy } of updates) {
+ await trx
+ .updateTable("thing")
+ .set({ sortOrder, updatedBy })
+ .where("id", "=", id)
+ .execute();
+ }
+ });
+}
+```
+
+## List with Filters
+
+```typescript
+export async function getThings(
+ client: SupabaseClient<Database>,
+ args: {
+ companyId: string;
+ search?: string;
+ active?: boolean;
+ limit?: number;
+ offset?: number;
+ }
+) {
+ let query = client
+ .from("thing")
+ .select("*", { count: "exact" })
+ .eq("companyId", args.companyId);
+
+ if (args.search) {
+ query = query.ilike("name", `%${args.search}%`);
+ }
+
+ if (args.active !== undefined) {
+ query = query.eq("active", args.active);
+ }
+
+ if (args.limit) {
+ query = query.limit(args.limit);
+ }
+
+ if (args.offset) {
+ query = query.range(args.offset, args.offset + (args.limit ?? 10) - 1);
+ }
+
+ return query.order("name");
+}
+```
+
+## Sequence Numbers
+
+For documents that need sequential numbers:
+
+```typescript
+import { getNextSequence } from "~/modules/settings";
+
+export async function insertOrder(
+ client: SupabaseClient<Database>,
+ data: { ... }
+) {
+ const orderNumber = await getNextSequence(client, data.companyId, "salesOrder");
+
+ return client
+ .from("salesOrder")
+ .insert({
+ ...data,
+ orderNumber,
+ })
+ .select("id")
+ .single();
+}
+```
+
+## Error Handling
+
+Services return `{ data, error }` — they don't throw. Route handlers convert to flash messages:
+
+```typescript
+// In route action
+const result = await insertThing(client, data);
+
+if (result.error) {
+ // Supabase error object has message
+ return data({}, await flash(request, error(result.error, "Failed to create thing")));
+}
+```
+
+## Naming Conventions
+
+| Operation | Name |
+|-----------|------|
+| Get one | `getThing(client, id)` |
+| Get list | `getThings(client, args)` |
+| Insert | `insertThing(client, data)` |
+| Update | `updateThing(client, id, data)` |
+| Upsert | `upsertThing(client, data)` |
+| Delete | `deleteThing(client, id)` |
+| Bulk order | `updateThingOrder(db, updates)` |
+
+## Checklist
+
+- [ ] First arg is `client: SupabaseClient<Database>` (or `db: Kysely<...>` for transactions)
+- [ ] Returns `{ data, error }` pattern
+- [ ] Uses `.select()` after insert/update to return created/updated row
+- [ ] Uses `.single()` when expecting one row
+- [ ] Exported from module index
+- [ ] Multi-row writes use Kysely transactions
diff --git a/llm/conventions/ui.md b/llm/conventions/ui.md
new file mode 100644
index 0000000000..1c1feb7fd5
--- /dev/null
+++ b/llm/conventions/ui.md
@@ -0,0 +1,146 @@
+# UI Conventions
+
+## Component Library
+
+Use `@carbon/react` for components, `@carbon/form` for form fields.
+
+```typescript
+import { Button, Card, HStack, VStack, Table } from "@carbon/react";
+import { Input, Select, Submit } from "~/components/Form";
+```
+
+## Layout Patterns
+
+### Vertical Stack
+```typescript
+<VStack spacing={4}>
+ <Input name="name" label="Name" />
+ <Input name="description" label="Description" />
+</VStack>
+```
+
+### Grid Layout
+```typescript
+<div className="grid grid-cols-1 lg:grid-cols-3 gap-x-8 gap-y-4">
+ <Input name="field1" />
+ <Input name="field2" />
+ <Input name="field3" />
+</div>
+```
+
+### Button Row
+```typescript
+<HStack>
+ <Submit isDisabled={isDisabled}>Save</Submit>
+ <Button variant="solid" onClick={onClose}>Cancel</Button>
+</HStack>
+```
+
+## Polish Principles
+
+Apply these when building or reviewing UI.
+
+### 1. Concentric Border Radius
+
+Outer radius = inner radius + padding.
+
+```typescript
+// Bad: same radius on parent and child
+<div className="rounded-xl p-2">
+ <button className="rounded-xl">...</button>
+</div>
+
+// Good: outer is larger
+<div className="rounded-2xl p-2">
+ <button className="rounded-lg">...</button>
+</div>
+```
+
+### 2. Shadows Over Borders
+
+Use layered `box-shadow` instead of solid borders for depth.
+
+### 3. Tabular Numbers
+
+For dynamic numbers, prevent layout shift:
+
+```typescript
+<span className="tabular-nums">{count}</span>
+```
+
+### 4. Scale on Press
+
+Tactile button feedback:
+
+```typescript
+<button className="active:scale-[0.96] transition-transform">
+```
+
+Always use `0.96`. Never below `0.95`.
+
+### 5. Minimum Hit Area
+
+Interactive elements need 40×40px minimum. Extend with pseudo-element if needed.
+
+### 6. Animations
+
+- Use CSS transitions for interactive states (interruptible)
+- Use keyframes for staged sequences
+- Never use `transition: all` — specify exact properties
+- Stagger enter animations ~100ms
+- Keep exit animations subtle
+
+```typescript
+// Good
+className="transition-transform"
+
+// Bad
+className="transition-all"
+```
+
+### 7. AnimatePresence
+
+Skip animation on page load:
+
+```typescript
+<AnimatePresence initial={false}>
+ ...
+</AnimatePresence>
+```
+
+### 8. Font Smoothing
+
+Applied at root level with `-webkit-font-smoothing: antialiased`.
+
+### 9. Text Wrapping
+
+```typescript
+// Headings
+<h1 className="text-wrap-balance">...</h1>
+
+// Body text
+<p className="text-wrap-pretty">...</p>
+```
+
+## Common Mistakes
+
+| Mistake | Fix |
+|---------|-----|
+| Same border radius on parent/child | `outerRadius = innerRadius + padding` |
+| Numbers cause layout shift | `tabular-nums` |
+| `transition: all` | Specify exact properties |
+| Animation on page load | `initial={false}` on AnimatePresence |
+| Tiny hit areas | Extend to 40×40px |
+| Hard borders | Use layered shadows |
+
+## Review Checklist
+
+- [ ] Concentric border radius on nested elements
+- [ ] Icons optically centered
+- [ ] Shadows instead of borders where appropriate
+- [ ] Dynamic numbers use `tabular-nums`
+- [ ] Buttons have scale on press
+- [ ] No `transition: all`
+- [ ] Interactive elements have 40×40px hit area
+- [ ] Enter animations staggered
+- [ ] Exit animations subtle
diff --git a/llm/research/.gitkeep b/llm/research/.gitkeep
new file mode 100644
index 0000000000..e69de29bb2