@mindfoldhq/trellis 0.1.7 → 0.1.9

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md DELETED
@@ -1,818 +0,0 @@
1
- # Trellis
2
-
3
- English | [中文](./README-zh.md)
4
-
5
- ![Trellis](./trellis.png)
6
-
7
- > AI capabilities grow like vines — full of vitality but spreading in all directions. Trellis provides structure, guiding them along a disciplined path.
8
-
9
- ## What Problems Does It Solve
10
-
11
- ### 1. AI Lacks Project Context
12
-
13
- AI doesn't know what this project is, doesn't know the project's specialized coding standards, architectural constraints, or previous development decisions. Every session starts with repeating "what this project is, what tech stack it uses, what we're doing next..." — and mistakes made in one session will be repeated in the next.
14
-
15
- **Trellis Solution**:
16
- - Development guidelines are persistently stored in `.trellis/structure/`. Developers within the project can share and maintain them together. Once one developer writes high-quality guidelines, the entire team's code quality improves
17
- - Session records are stored in `.trellis/agent-traces/`. New sessions can quickly review what you worked on previously, what code was changed, providing better project awareness without repeatedly explaining "what this project is"
18
-
19
- ### 2. Guidelines Written but Not Followed
20
-
21
- `.cursorrules`, `CLAUDE.md`, `AGENTS.md` have limited space, and AI tends to forget mid-conversation. Guidelines and code are separated, making synchronization difficult. An all-in-one file forces AI to read potentially irrelevant context each time, wasting context window space, and a multi-thousand-line file is inconvenient to update and maintain.
22
-
23
- **Trellis Solution**: Guidelines can be loaded on-demand, injected into the corresponding Agent's context window, allowing each specialized agent to receive only the project-specific domain knowledge and guidelines it needs.
24
-
25
- ### 3. Workflow Requires Human Supervision
26
-
27
- Requires humans to guide AI step by step: first read guidelines, then implement, then check, then commit.
28
-
29
- **Trellis Solution**: Slash Commands encapsulate complete workflows. Users only need to type `/start` or `/parallel`. Task distribution, script invocation, Hook interception, and other mechanisms are invisible to users — AI automatically executes according to predefined processes.
30
-
31
- ### 4. High Barrier for Multi-Agent Parallelism
32
-
33
- Some tools support multi-Agent parallel development, but learning costs are high, configuration is complex, and multiple Agents working simultaneously can easily conflict.
34
-
35
- **Trellis Solution**: One-click launch with `/parallel`. Uses Git Worktree for physical isolation underneath, with each Agent working in an independent directory without interference.
36
-
37
- ---
38
-
39
- ## Quick Start
40
-
41
- ### 1. Installation
42
-
43
- ```bash
44
- npm install -g @mindfoldhq/trellis@latest
45
- ```
46
-
47
- ### 2. Initialize Project
48
-
49
- ```bash
50
- cd your-project
51
- trellis init -u your-name
52
- ```
53
-
54
- ### 3. Configure worktree.yaml (if using `/parallel`)
55
-
56
- Edit `.trellis/worktree.yaml` according to your project:
57
- - `worktree_dir`: Worktree storage directory (relative to project root, e.g., `../trellis-worktrees`)
58
- - `copy`: Environment variable files to copy to Worktree (e.g., `.env`, `.trellis/.developer`)
59
- - `post_create`: Initialization commands to run after Worktree creation (e.g., `pnpm install --frozen-lockfile`)
60
- - `verify`: Verification commands that must pass before Check Agent finishes (e.g., `pnpm lint`, `pnpm typecheck`)
61
-
62
- ### 4. Start Using
63
-
64
- #### Claude Code Workflow
65
-
66
- **Simple tasks**:
67
- ```
68
- /start → describe requirement → /record-agent-flow
69
- ```
70
-
71
- **Complex features** (Multi-Agent Pipeline):
72
- ```
73
- /parallel → describe requirement → /record-agent-flow
74
- ```
75
-
76
- #### Cursor Workflow
77
-
78
- ```
79
- /start → describe requirement → /before-frontend-dev or /before-backend-dev → implement → /check-frontend or /check-backend → /finish-work → /record-agent-flow
80
- ```
81
-
82
- ---
83
-
84
- ### 5. Behind-the-Scenes Process Details (Claude Code)
85
-
86
- **`/start` Simple Tasks**:
87
- 1. AI executes `get-context.sh` to get current developer, branch, recent commits, and other status
88
- 2. AI reads `.trellis/workflow.md` and project guidelines under `.trellis/structure/`
89
- 3. AI implements features directly on the current branch
90
-
91
- **`/start` Complex Tasks**:
92
- 1. AI creates feature directory, calls **Research Agent** to analyze codebase and find relevant guideline files for the requirement
93
- 2. AI records guideline file paths into the feature directory and creates `prd.md` requirement document
94
- 3. AI calls **Implement Agent** to implement according to guidelines (guideline file contents recorded in previous step are automatically injected into Implement Agent's context by Hook)
95
- 4. AI calls **Check Agent** to review code and auto-fix issues
96
-
97
- **`/parallel` Multi-Agent Pipeline** (Two Modes):
98
-
99
- **Mode A: Plan Agent Auto-Planning** (Recommended for complex features with unclear requirements)
100
- 1. `plan.sh` script launches **Plan Agent** in background
101
- 2. Plan Agent evaluates requirement validity (rejects with reasons if requirement is unclear), calls **Research Agent** to analyze codebase and find relevant guideline files
102
- 3. Plan Agent records guideline file paths into feature directory and creates `prd.md` requirement document
103
-
104
- **Mode B: Manual Configuration** (For simple features with clear requirements)
105
- 1. AI creates feature directory, calls **Research Agent** to analyze codebase and find relevant guideline files
106
- 2. AI records guideline file paths into feature directory and creates `prd.md` requirement document
107
-
108
- **Subsequent Flow for Both Modes**:
109
- 1. `start.sh` creates independent Git Worktree, copies environment files per `worktree.yaml` `copy` field, runs initialization commands per `post_create` field, and launches **Dispatch Agent** in Worktree
110
- 2. Dispatch Agent reads `.trellis/.current-feature` to locate feature directory, reads `feature.json` `next_action` array, calls sub-Agents in phase order
111
- 3. **Implement Agent**: Hook (`inject-subagent-context.py`) automatically injects guideline files from `implement.jsonl` plus `prd.md` and `info.md` before Task call, then AI implements according to guidelines
112
- 4. **Check Agent**: Hook injects guideline file contents from `check.jsonl`, AI reviews code changes and auto-fixes; **Ralph Loop** (`ralph-loop.py`) intercepts Agent stop requests, runs verification commands per `worktree.yaml` `verify` field (e.g., lint, typecheck), only allows ending when all pass
113
- 5. `create-pr.sh` commits code (excluding agent-traces), pushes branch, creates Draft PR with `gh pr create`, updates `feature.json` status to `review`
114
-
115
- ---
116
-
117
- ## System Architecture
118
-
119
- After Trellis initialization, the following directory structure is created in your project:
120
-
121
- ```
122
- your-project/
123
- ├── AGENTS.md # Lightweight AI instructions (agents.md protocol compatible)
124
- ├── .trellis/ # Workflow and guidelines center
125
- │ ├── workflow.md # Development process guide (core document, read first in new sessions)
126
- │ ├── worktree.yaml # Multi-Agent pipeline configuration
127
- │ ├── .developer # Developer identity (git-ignored)
128
- │ ├── .gitignore # .trellis directory gitignore rules
129
- │ ├── structure/ # Development guidelines (core knowledge base)
130
- │ ├── agent-traces/ # Session records and Feature tracking
131
- │ ├── backlog/ # Requirements pool (bidirectional links with Features)
132
- │ └── scripts/ # Automation scripts
133
- ├── .claude/ # Claude Code specific configuration
134
- │ ├── commands/ # Slash Commands (13)
135
- │ ├── agents/ # Agent definitions (6)
136
- │ ├── hooks/ # Hook scripts (2)
137
- │ └── settings.json # Hook trigger configuration
138
- └── .cursor/ # Cursor specific configuration
139
- └── commands/ # Slash Commands (12)
140
- ```
141
-
142
- ### Entry Files
143
-
144
- **`AGENTS.md`** (~18 lines):
145
- - Lightweight instruction file following agents.md protocol
146
- - Uses `<!-- TRELLIS:START -->` and `<!-- TRELLIS:END -->` markers to protect content (`trellis update` won't overwrite)
147
- - Quick pointer to `/start` command and `.trellis/workflow.md`
148
-
149
- **`.trellis/workflow.md`** (Core Document):
150
- - **First-read document** for new AI Agent sessions
151
- - Contains: Quick Start (developer identity initialization, context acquisition), development process, session recording, best practices
152
- - Based on [Anthropic's Best Practices for Long-Running Agents](https://www.anthropic.com/engineering/effective-harnesses-for-long-running-agents)
153
-
154
- **Reading Order for New Agents**:
155
- 1. `.trellis/workflow.md` → Understand overall workflow and getting started steps
156
- 2. `.trellis/structure/{frontend|backend}/index.md` → Corresponding domain's guideline entry
157
- 3. Specific guideline files → Read on-demand based on task type
158
-
159
- ---
160
-
161
- ## I. Development Guidelines System (`.trellis/structure/`)
162
-
163
- Stores project development guidelines — the team's knowledge assets. AI references these guidelines when implementing and reviewing code.
164
-
165
- ```
166
- structure/
167
- ├── backend/ # Backend development guidelines
168
- │ ├── index.md # Backend guidelines entry
169
- │ ├── directory-structure.md # Directory structure conventions
170
- │ ├── database-guidelines.md # Database and ORM guidelines
171
- │ ├── error-handling.md # Error handling strategies
172
- │ ├── quality-guidelines.md # Code quality standards
173
- │ └── logging-guidelines.md # Logging guidelines
174
- ├── frontend/ # Frontend development guidelines
175
- │ ├── index.md # Frontend guidelines entry
176
- │ ├── directory-structure.md # Directory structure conventions
177
- │ ├── component-guidelines.md # Component design guidelines
178
- │ ├── hook-guidelines.md # Hook usage guidelines
179
- │ ├── state-management.md # State management guidelines
180
- │ ├── quality-guidelines.md # Code quality standards
181
- │ └── type-safety.md # Type safety guidelines
182
- └── guides/ # Problem thinking guides
183
- ├── index.md # Guides entry (with trigger conditions)
184
- ├── cross-layer-thinking-guide.md # Cross-layer development thinking checklist
185
- └── code-reuse-thinking-guide.md # Code reuse thinking checklist
186
- ```
187
-
188
- **Core Philosophy**:
189
- - Clearer guidelines = better AI execution results
190
- - Update guidelines whenever issues are found (bugs, omissions, inconsistencies), forming a continuous improvement loop
191
- - Thinking Guides help discover "didn't think of that" problems — most bugs come from incomplete thinking, not lack of skill
192
-
193
- **Trigger Timing** (When to use which guide):
194
- - **cross-layer-thinking-guide.md**: When feature involves 3+ layers (API, Service, Component, Database), data format changes between layers, multiple consumers need same data
195
- - **code-reuse-thinking-guide.md**: When similar code already exists, same pattern repeats 3+ times, need to add fields in multiple places, before creating new utility functions (search first!)
196
-
197
- ---
198
-
199
- ## II. Session Tracking System (`.trellis/agent-traces/`)
200
-
201
- Records all AI Agent work history, supporting multi-developer collaboration.
202
-
203
- ```
204
- agent-traces/
205
- ├── index.md # Active developers list
206
- └── {developer}/ # Each developer's directory
207
- ├── index.md # Personal session index
208
- ├── traces-N.md # Session records (max 2000 lines per file)
209
- ├── .agents/
210
- │ └── registry.json # Running Agent registry
211
- └── features/ # Feature directories
212
- ├── {day}-{name}/ # Active Feature
213
- │ ├── feature.json # Feature metadata
214
- │ ├── prd.md # Requirement document
215
- │ ├── info.md # Technical design (optional)
216
- │ ├── implement.jsonl # Implement Agent context configuration
217
- │ ├── check.jsonl # Check Agent context configuration
218
- │ └── debug.jsonl # Debug Agent context configuration
219
- └── archive/ # Archived Features
220
- └── {YYYY-MM}/
221
- ```
222
-
223
- ### Feature Directory Details
224
-
225
- Each Feature is an independent work unit containing complete context configuration:
226
-
227
- **`feature.json`** - Feature Metadata:
228
- ```json
229
- {
230
- "name": "user-auth",
231
- "status": "planning|in_progress|review|completed|rejected",
232
- "dev_type": "backend|frontend|fullstack",
233
- "branch": "feature/user-auth",
234
- "base_branch": "main",
235
- "worktree_path": "../trellis-worktrees/feature/user-auth",
236
- "current_phase": 1,
237
- "next_action": [
238
- {"phase": 1, "action": "implement"},
239
- {"phase": 2, "action": "check"},
240
- {"phase": 3, "action": "finish"},
241
- {"phase": 4, "action": "create-pr"}
242
- ],
243
- "backlog_ref": "260119-user-auth.json"
244
- }
245
- ```
246
-
247
- **`implement.jsonl` / `check.jsonl` / `debug.jsonl`** - Context Configuration:
248
- ```jsonl
249
- {"file": ".trellis/structure/backend/index.md", "reason": "Backend development guidelines"}
250
- {"file": "src/api/auth.ts", "reason": "Existing auth pattern reference"}
251
- {"file": "src/middleware/", "type": "directory", "reason": "Middleware pattern reference"}
252
- ```
253
-
254
- These jsonl files define which guideline and code files each Agent needs to read. Hooks automatically inject these file contents when calling Agents.
255
-
256
- ### Traceability
257
-
258
- **Traceability Value of jsonl Files**:
259
-
260
- Each Feature's jsonl files record which guideline files were used, which existing code was referenced, and why each file was included. When issues arise, you can trace: whether necessary guideline references were missing, whether guidelines themselves were unclear, whether it's a guideline problem or execution deviation.
261
-
262
- **Traceability Value of traces Files**:
263
-
264
- `traces-N.md` records each session's date, Feature, work summary, main changes, Git commits, test status, and next steps. Forms complete development history; new sessions can quickly review previous work.
265
-
266
- ### Backlog System
267
-
268
- Backlog is a requirements pool for managing features and tasks to be developed. Each backlog issue establishes bidirectional links with Features.
269
-
270
- ```
271
- .trellis/
272
- └── backlog/ # Requirements pool directory
273
- ├── 260119-user-auth.json # Backlog issue (ID format: YYMMDD-slug)
274
- └── 260119-payment-fix.json
275
- ```
276
-
277
- **`backlog/*.json`** - Backlog Issue Structure:
278
- ```json
279
- {
280
- "id": "260119-user-auth",
281
- "title": "Add user authentication",
282
- "description": "Implement JWT-based auth with email verification",
283
- "priority": "P1",
284
- "status": "in_progress",
285
- "assigned_to": "taosu",
286
- "created_by": "taosu",
287
- "created_at": "2026-01-19T10:30:00+08:00",
288
- "completed_at": null
289
- }
290
- ```
291
-
292
- **Bidirectional Links**:
293
- - `backlog/*.json`'s `assigned_to` points to the developer
294
- - `feature.json`'s `backlog_ref` points to the backlog filename
295
- - When archiving a Feature, the associated backlog status is automatically updated to `done`
296
-
297
- **Priority**: P0 (urgent) > P1 (high) > P2 (medium) > P3 (low)
298
-
299
- **Displayed in `get-context.sh`**:
300
- ```
301
- ## BACKLOG (Assigned to me)
302
- - [P1] Add user authentication (2026-01-19)
303
- - [P2] Fix payment display (2026-01-18)
304
-
305
- ## CREATED BY ME (Assigned to others)
306
- - [P1] Review API design (assigned to: john)
307
- ```
308
-
309
- ---
310
-
311
- ## III. Script System (`.trellis/scripts/`)
312
-
313
- Automation scripts that power the entire workflow.
314
-
315
- ```
316
- scripts/
317
- ├── get-context.sh # Get session context (developer, branch, recent commits, backlog)
318
- ├── feature.sh # Feature management (create, archive, configure)
319
- ├── add-session.sh # Record session
320
- ├── init-developer.sh # Initialize developer identity
321
- ├── common/ # Common utilities
322
- │ ├── paths.sh # Path utilities
323
- │ ├── developer.sh # Developer utilities
324
- │ ├── git-context.sh # Git context
325
- │ ├── phase.sh # Phase management
326
- │ ├── worktree.sh # Worktree utilities
327
- │ ├── backlog.sh # Backlog utilities (create, complete, list)
328
- │ ├── registry.sh # Agent registry CRUD operations
329
- │ └── feature-utils.sh # Feature common utilities (find, archive, path safety)
330
- └── multi-agent/ # Multi-Agent pipeline scripts
331
- ├── plan.sh # Launch Plan Agent
332
- ├── start.sh # Create Worktree and launch Dispatch Agent
333
- ├── status.sh # View pipeline status
334
- ├── create-pr.sh # Create PR
335
- └── cleanup.sh # Clean up Worktree
336
- ```
337
-
338
- ### Script System Design Philosophy
339
-
340
- **Why Encapsulate Operations in Scripts?**
341
-
342
- AI may "improvise" each time it executes tasks — using different commands, different parameters, different orders. This leads to:
343
- - Inconsistent workflows, difficult to track and debug
344
- - Easy to miss critical steps (like copying environment files, registering Agents)
345
- - Reinventing the wheel, having to think "how to do it" every time
346
-
347
- **Script Purpose**: Encapsulate complex operations into **deterministic, repeatable** commands. AI only needs to call scripts, doesn't need to know internal implementation details, and won't miss steps.
348
-
349
- ### Key Script Descriptions
350
-
351
- **`feature.sh`** - Feature Lifecycle Management:
352
- ```bash
353
- # Create Feature (auto-creates backlog issue with bidirectional links)
354
- feature.sh create "<title>" [--slug <name>] [--assignee <dev>] [--priority P0|P1|P2|P3]
355
- feature.sh init-context <dir> <type> # Initialize jsonl files
356
- feature.sh add-context <dir> <file> <path> <reason> # Add context entry
357
- feature.sh set-branch <dir> <branch> # Set branch
358
- feature.sh start <dir> # Set as current Feature
359
- feature.sh archive <name> # Archive Feature (also completes linked backlog)
360
- feature.sh list # List active Features
361
- feature.sh list-archive [YYYY-MM] # List archived Features
362
- ```
363
-
364
- **Create Examples**:
365
- ```bash
366
- # Basic usage (slug auto-generated from title)
367
- feature.sh create "Add user authentication"
368
-
369
- # Specify slug and priority
370
- feature.sh create "Add login page" --slug login-ui --priority P1
371
-
372
- # Specify assignee (must be existing developer)
373
- feature.sh create "Fix payment bug" --assignee john --priority P0
374
- ```
375
-
376
- **`multi-agent/plan.sh`** - Launch Plan Agent:
377
-
378
- ```bash
379
- ./plan.sh --name <feature-name> --type <dev-type> --requirement "<requirement>"
380
- ```
381
-
382
- **How It Works**:
383
- 1. Create Feature directory (calls `feature.sh create`)
384
- 2. Read `.claude/agents/plan.md`, extract Agent prompt (skip frontmatter)
385
- 3. Pass parameters to Agent via **environment variables**:
386
- ```bash
387
- export PLAN_FEATURE_NAME="user-auth"
388
- export PLAN_DEV_TYPE="backend"
389
- export PLAN_FEATURE_DIR=".trellis/agent-traces/taosu/features/19-user-auth"
390
- export PLAN_REQUIREMENT="Add JWT-based authentication"
391
- ```
392
- 4. Launch Claude Code in background: `nohup claude -p --dangerously-skip-permissions < prompt &`
393
- 5. Logs written to `<feature-dir>/.plan-log`
394
-
395
- **Why Use Environment Variables for Parameters?**
396
- - Agent prompt is a static template, environment variables make it dynamic
397
- - Agent can directly read `$PLAN_FEATURE_DIR` and other variables, knowing which directory to operate on
398
- - Avoids hardcoding paths in prompts, keeps templates generic
399
-
400
- **`multi-agent/start.sh`** - Launch Dispatch Agent:
401
-
402
- ```bash
403
- ./start.sh <feature-dir>
404
- ```
405
-
406
- **How It Works**:
407
- 1. **Validate Prerequisites**: feature.json and prd.md must exist (ensures Plan phase completed)
408
- 2. **Check Feature Status**: If `status: "rejected"`, refuse to start and show reason
409
- 3. **Create Git Worktree**:
410
- ```bash
411
- git worktree add -b feature/user-auth ../trellis-worktrees/feature/user-auth
412
- ```
413
- 4. **Copy Environment Files**: Read `worktree.yaml` `copy` field, copy each file
414
- 5. **Copy Feature Directory**: Feature directory may not be committed yet, needs manual copy to Worktree
415
- 6. **Run Initialization Commands**: Read `worktree.yaml` `post_create` field, execute in order
416
- 7. **Set Current Feature**: Write to `.trellis/.current-feature` file
417
- 8. **Prepare Agent Prompt**: Extract content from `dispatch.md`, write to `.agent-prompt`
418
- 9. **Launch Claude Code in Background**:
419
- ```bash
420
- nohup ./agent-runner.sh > .agent-log 2>&1 &
421
- ```
422
- 10. **Register to registry.json**: Record PID, Worktree path, start time for later management
423
-
424
- **Key Design**:
425
- - Scripts handle **environment preparation** (Worktree, dependencies, files), Agents only handle **task execution**
426
- - Agents know which Feature they're handling by reading `.current-feature` file
427
- - All state persisted to files (registry.json, feature.json), viewable and recoverable anytime
428
-
429
- **`multi-agent/create-pr.sh`** - Create PR:
430
- 1. `git add -A` (exclude agent-traces)
431
- 2. `git commit -m "type(scope): feature-name"`
432
- 3. `git push origin <branch>`
433
- 4. `gh pr create --draft --base <base_branch>`
434
- 5. Update `feature.json`: `status: "review"`, `pr_url: <url>`
435
-
436
- ---
437
-
438
- ## IV. Slash Commands (`.claude/commands/` and `.cursor/commands/`)
439
-
440
- Users interact with Trellis through Slash Commands. Slash Commands are **the entry point for users and the system**, calling scripts and Agents behind the scenes to do actual work.
441
-
442
- ### `/start` - Session Initialization
443
-
444
- **Purpose**: Initialize development session, read project context and guidelines.
445
-
446
- **Execution Steps**:
447
- 1. Read `.trellis/workflow.md` to understand workflow
448
- 2. Execute `get-context.sh` to get current status (developer, branch, uncommitted files, active Features)
449
- 3. Read `.trellis/structure/{frontend|backend}/index.md` guideline entry
450
- 4. Report ready status, ask user for task
451
-
452
- **Task Handling**:
453
- - **Simple tasks**: Implement directly → Remind user to run `/finish-work`
454
- - **Complex tasks** (Claude Code): Create Feature directory → Call Research Agent to analyze → Configure jsonl → Call Implement/Check Agent
455
-
456
- ### `/parallel` - Multi-Agent Pipeline (Claude Code Only)
457
-
458
- **Purpose**: Launch parallel development pipeline using Git Worktree for isolated work environments.
459
-
460
- **Differences from `/start`**:
461
-
462
- | Dimension | `/start` | `/parallel` |
463
- |-----------|----------|-------------|
464
- | Execution Location | Main repo single process | Main repo + Worktree multi-process |
465
- | Git Management | Develop directly on current branch | Create independent Worktree and branch |
466
- | Use Case | Simple tasks, quick implementation | Complex features, multi-module, needs isolation |
467
-
468
- **Two Modes**:
469
- - **Plan Agent Mode** (Recommended): `plan.sh --name <name> --type <type> --requirement "<req>"` → Plan Agent auto-analyzes requirements, configures Feature → `start.sh` launches Dispatch Agent
470
- - **Manual Configuration Mode**: Manually create Feature directory, configure jsonl, write prd.md → `start.sh` launches Dispatch Agent
471
-
472
- ### `/before-frontend-dev` and `/before-backend-dev` - Pre-Development Guidelines Reading
473
-
474
- **Purpose**: Force reading of corresponding domain's development guidelines before coding.
475
-
476
- **Execution Steps**:
477
- 1. Read `.trellis/structure/{frontend|backend}/index.md` guideline entry
478
- 2. Read specific guideline files based on task type:
479
- - **Frontend**: `component-guidelines.md`, `hook-guidelines.md`, `state-management.md`, `type-safety.md`
480
- - **Backend**: `database-guidelines.md`, `error-handling.md`, `logging-guidelines.md`, `type-safety.md`
481
- 3. Begin development after understanding coding standards
482
-
483
- ### `/check-frontend`, `/check-backend`, `/check-cross-layer` - Code Review
484
-
485
- **`/check-frontend` and `/check-backend`**:
486
- 1. `git status` to see modified files
487
- 2. Read corresponding guideline files
488
- 3. Check code against guidelines
489
- 4. Report violations and fix them
490
-
491
- **`/check-cross-layer`** (Cross-layer Check):
492
-
493
- Checks multiple dimensions to prevent "didn't think of that" bugs:
494
-
495
- | Dimension | Trigger Condition | Check Content |
496
- |-----------|-------------------|---------------|
497
- | **Cross-layer Data Flow** | Changes involve 3+ layers | Read/write flow, type propagation, error propagation, loading states |
498
- | **Code Reuse** | Modifying constants/configs | `grep` search all usage locations, whether to extract shared constants |
499
- | **New Utility Functions** | Creating utility | Search first if similar function exists |
500
- | **After Batch Modifications** | Similar changes across multiple files | Any omissions, should it be abstracted |
501
-
502
- ### `/finish-work` - Pre-Commit Checklist
503
-
504
- **Purpose**: Ensure code completeness, execute before commit.
505
-
506
- **Checklist Items**:
507
- 1. **Code Quality**: lint, type-check, test pass, no `console.log`, no `x!` (non-null assertion), no `any`
508
- 2. **Documentation Sync**: Does `.trellis/structure/` guidelines need updating
509
- 3. **API Changes**: Are schema, docs, client code in sync
510
- 4. **Database Changes**: Are migration, schema, queries updated
511
- 5. **Cross-layer Validation**: Data flow, error handling, type consistency
512
- 6. **Manual Testing**: Functionality, edge cases, error states, after refresh
513
-
514
- ### `/record-agent-flow` - Record Session Progress
515
-
516
- **Prerequisite**: User has tested and committed code (AI doesn't execute `git commit`)
517
-
518
- **Execution Steps**:
519
- 1. Execute `get-context.sh` to get current context
520
- 2. Execute `add-session.sh --title "..." --commit "hash"` to record session:
521
- - Append to `traces-N.md` (auto-creates new file when exceeding 2000 lines)
522
- - Update `index.md` (session count, last active time, history table)
523
- 3. If Feature completed, execute `feature.sh archive <name>` to archive
524
-
525
- ### Other Commands
526
-
527
- | Command | Purpose |
528
- |---------|---------|
529
- | `/break-loop` | Deep bug analysis, break out of fix loops |
530
- | `/create-command` | Create new Slash Command |
531
- | `/integrate-skill` | Extract Claude Code skill into project guidelines |
532
- | `/onboard-developer` | Landing guide for developers |
533
-
534
- ---
535
-
536
- ## V. Agent System (`.claude/agents/`)
537
-
538
- Defines 6 specialized Agents, each with specific responsibilities:
539
-
540
- | Agent | Responsibility |
541
- |-------|----------------|
542
- | **Plan** | Evaluate requirement validity, configure Feature directory |
543
- | **Research** | Search code and docs, pure research without modifications |
544
- | **Dispatch** | Pure dispatcher, calls sub-Agents by phase |
545
- | **Implement** | Implement according to guidelines, git commit forbidden |
546
- | **Check** | Review code and self-fix, controlled by Ralph Loop |
547
- | **Debug** | Deep analysis and issue fixing |
548
-
549
- ### Agent Details
550
-
551
- **Plan Agent** (`.claude/agents/plan.md`):
552
- - Can **reject** unclear, incomplete, or out-of-scope requirements
553
- - Calls Research Agent to analyze codebase
554
- - Output: Fully configured Feature directory (feature.json, prd.md, *.jsonl)
555
-
556
- **Research Agent** (`.claude/agents/research.md`):
557
- - Uses Haiku model (lightweight, fast)
558
- - **Strict boundaries**: Can only describe "what it is, where it is, how it works", forbidden from suggestions, criticism, modifications
559
-
560
- **Dispatch Agent** (`.claude/agents/dispatch.md`):
561
- - **Pure dispatcher**: Only calls sub-Agents, doesn't read guidelines (Hook auto-injects)
562
- - Reads `.trellis/.current-feature` to locate Feature directory
563
- - Reads `feature.json` `next_action` array, executes phases in order
564
-
565
- **Implement Agent** (`.claude/agents/implement.md`):
566
- - Reads Hook-injected guidelines and requirements
567
- - Implements features and runs lint/typecheck
568
- - **Forbidden**: `git commit`, `git push`, `git merge`
569
-
570
- **Check Agent** (`.claude/agents/check.md`):
571
- - `git diff` to get code changes
572
- - Check code against guidelines
573
- - **Self-fix** issues, not just report
574
- - Controlled by Ralph Loop: must output completion markers to end
575
-
576
- **Debug Agent** (`.claude/agents/debug.md`):
577
- - Not part of default flow, only called when Check Agent can't fix
578
- - Categorize issues by priority: `[P1]` must fix, `[P2]` should fix, `[P3]` optional fix
579
-
580
- ---
581
-
582
- ## VI. Automation Mechanisms
583
-
584
- Trellis implements workflow automation through Hooks and configuration files, making AI execute according to predefined processes, reducing arbitrariness.
585
-
586
- ### Staged Context Injection
587
-
588
- **Why Staged Injection?**
589
-
590
- Too much context causes AI distraction (irrelevant information interference), confusion (contradictory guidelines), and conflicts (different phase instructions overriding) — this is called **Context Rot**.
591
-
592
- **Staged Injection Strategy**:
593
- ```
594
- Plan/Research Agent analyzes requirements in advance
595
-
596
- Write relevant file paths to implement.jsonl, check.jsonl
597
-
598
- Hook injects only files needed for that phase when calling each Agent
599
-
600
- Each Agent receives precise context, focuses on current task
601
- ```
602
-
603
- | Phase | Injected Content | Excluded Content |
604
- |-------|------------------|------------------|
605
- | Implement | Requirements + implementation-related guidelines and code | Check guidelines |
606
- | Check | Check guidelines + code quality standards | Implementation details |
607
- | Finish | Commit checklist + requirements (verify satisfaction) | Full check guidelines |
608
-
609
- ### Hook Implementation (`.claude/hooks/`)
610
-
611
- Two Python scripts implement the above automation:
612
-
613
- **1. `inject-subagent-context.py` (Context Injection)**
614
-
615
- **Trigger Timing**: PreToolUse - Before Task tool call
616
-
617
- **How It Works**:
618
- ```
619
- Dispatch calls Task(subagent_type="implement", ...)
620
-
621
- Hook triggers (PreToolUse)
622
-
623
- Read .trellis/.current-feature to locate Feature directory
624
-
625
- Read corresponding jsonl file based on subagent_type
626
-
627
- Inject all file contents listed in jsonl into Agent's prompt
628
-
629
- Implement Agent starts with complete context
630
- ```
631
-
632
- **Content Injected Per Phase**:
633
-
634
- | Agent | Injected Content | Purpose |
635
- |-------|------------------|---------|
636
- | Implement | Guidelines from `implement.jsonl` + `prd.md` + `info.md` | Understand requirements, implement according to guidelines |
637
- | Check | Guidelines from `check.jsonl` + `finish-work.md` | Check if code meets guidelines |
638
- | Check ([finish] marker) | `finish-work.md` + `prd.md` (lightweight) | Final verification before commit |
639
- | Debug | Guidelines from `debug.jsonl` + error information | Deep analysis and fixing |
640
-
641
- **Design Philosophy**:
642
- - Dispatch becomes pure dispatcher, only sends simple commands
643
- - Hook handles all context injection, sub-Agents work autonomously
644
- - No manual context passing needed, behavior controlled by code not prompts
645
-
646
- ### 2. `ralph-loop.py` (Quality Control Loop)
647
-
648
- **Trigger Timing**: SubagentStop - When Check Agent attempts to stop
649
-
650
- **How It Works**:
651
- ```
652
- Check Agent attempts to stop
653
-
654
- Ralph Loop triggers (SubagentStop)
655
-
656
- Has verify config?
657
- ├─ Yes → Execute verification commands from worktree.yaml
658
- │ ├─ All pass → Allow stop
659
- │ └─ Any fail → Block stop, report failure reason, continue fixing
660
- └─ No → Check completion markers in Agent output
661
- ├─ All markers present → Allow stop
662
- └─ Missing markers → Block stop, report which markers missing
663
-
664
- Maximum 5 loops (prevent infinite loops and cost overruns)
665
- ```
666
-
667
- **Two Verification Methods**:
668
-
669
- 1. **Programmatic Verification (Recommended)**:
670
- - Configure `verify` commands in `worktree.yaml` (e.g., `pnpm lint`, `pnpm typecheck`)
671
- - Ralph Loop executes these commands to verify code
672
- - Doesn't rely on AI output, program-enforced verification, more reliable
673
-
674
- 2. **Completion Marker Verification (Fallback)**:
675
- - Generate completion markers from `check.jsonl` `reason` fields
676
- - Format: `{REASON}_FINISH` (e.g., `TYPECHECK_FINISH`, `LINT_FINISH`)
677
- - Check Agent must actually execute checks and output corresponding markers
678
- - Ralph Loop checks if all markers are in Agent output
679
-
680
- **State Management**:
681
- - State file: `.trellis/.ralph-state.json`
682
- - Tracks current iteration count and Feature
683
- - 30-minute timeout auto-reset
684
-
685
- ### Continuous Guidelines Refinement
686
-
687
- **Refinement Loop**:
688
- ```
689
- AI executes according to guidelines → Issues discovered → Update .trellis/structure/ → Better execution next time → Guidelines get better with use
690
- ```
691
-
692
- **Thinking Guides** (`.trellis/structure/guides/`) capture team's tacit knowledge:
693
- - **cross-layer-thinking-guide.md**: Thinking checklist before cross-layer development
694
- - **code-reuse-thinking-guide.md**: Search checklist before creating new code
695
-
696
- Core philosophy: **30 minutes of thinking can save 3 hours of debugging**
697
-
698
- ---
699
-
700
- ## VII. Complete Workflow Examples
701
-
702
- ### Claude Code `/parallel` Complete Flow
703
-
704
- ```
705
- User: /parallel
706
- User: Implement user registration with email verification
707
-
708
- ┌─────────────────────────────────────────────────────┐
709
- │ Plan Phase (Main Repo) │
710
- ├─────────────────────────────────────────────────────┤
711
- │ 1. plan.sh launches Plan Agent │
712
- │ 2. Plan Agent evaluates requirements (may reject │
713
- │ unclear requirements) │
714
- │ 3. Plan Agent calls Research Agent to analyze │
715
- │ codebase │
716
- │ 4. Plan Agent creates Feature directory: │
717
- │ - feature.json (metadata) │
718
- │ - prd.md (requirement document) │
719
- │ - implement.jsonl (implement phase context) │
720
- │ - check.jsonl (check phase context) │
721
- └─────────────────────────────────────────────────────┘
722
-
723
- ┌─────────────────────────────────────────────────────┐
724
- │ Worktree Creation (Main Repo → Worktree) │
725
- ├─────────────────────────────────────────────────────┤
726
- │ 1. start.sh creates Git Worktree │
727
- │ 2. Copy environment files (worktree.yaml copy) │
728
- │ 3. Run init commands (worktree.yaml post_create) │
729
- │ 4. Write .trellis/.current-feature marker │
730
- │ 5. Launch Dispatch Agent in background │
731
- │ 6. Register to registry.json │
732
- └─────────────────────────────────────────────────────┘
733
-
734
- ┌─────────────────────────────────────────────────────┐
735
- │ Implement Phase (In Worktree) │
736
- ├─────────────────────────────────────────────────────┤
737
- │ 1. Dispatch calls Task(subagent_type="implement") │
738
- │ 2. Hook triggers, injects implement.jsonl + │
739
- │ prd.md + info.md │
740
- │ 3. Implement Agent implements according to │
741
- │ guidelines │
742
- │ 4. Run lint/typecheck │
743
- │ 5. Report completion │
744
- └─────────────────────────────────────────────────────┘
745
-
746
- ┌─────────────────────────────────────────────────────┐
747
- │ Check Phase (In Worktree) │
748
- ├─────────────────────────────────────────────────────┤
749
- │ 1. Dispatch calls Task(subagent_type="check") │
750
- │ 2. Hook triggers, injects guidelines from │
751
- │ check.jsonl │
752
- │ 3. Check Agent reviews code, self-fixes issues │
753
- │ 4. Check Agent attempts to stop │
754
- │ 5. Ralph Loop triggers: │
755
- │ - Execute verify commands (pnpm lint, │
756
- │ pnpm typecheck) │
757
- │ - All pass → Allow stop │
758
- │ - Any fail → Block stop, continue fixing │
759
- │ (max 5 times) │
760
- └─────────────────────────────────────────────────────┘
761
-
762
- ┌─────────────────────────────────────────────────────┐
763
- │ Finish Phase (In Worktree) │
764
- ├─────────────────────────────────────────────────────┤
765
- │ 1. Dispatch calls Task(prompt="[finish] ...") │
766
- │ 2. Hook triggers, injects finish-work.md + │
767
- │ prd.md (lightweight) │
768
- │ 3. Check Agent executes Pre-Commit Checklist │
769
- │ 4. Skip Ralph Loop (already verified in check) │
770
- └─────────────────────────────────────────────────────┘
771
-
772
- ┌─────────────────────────────────────────────────────┐
773
- │ Create-PR Phase (In Worktree) │
774
- ├─────────────────────────────────────────────────────┤
775
- │ 1. create-pr.sh executes │
776
- │ 2. git add -A (exclude agent-traces) │
777
- │ 3. git commit -m "feat(scope): feature-name" │
778
- │ 4. git push origin <branch> │
779
- │ 5. gh pr create --draft --base <base_branch> │
780
- │ 6. Update feature.json (status: "review", pr_url) │
781
- └─────────────────────────────────────────────────────┘
782
-
783
- User: /record-agent-flow (record session)
784
- ```
785
-
786
- ### Cursor Complete Flow
787
-
788
- ```
789
- User: /start
790
-
791
- AI: Read project status, report ready
792
-
793
- User: Describe requirement
794
-
795
- User: /before-backend-dev (if backend task)
796
-
797
- AI: Read .trellis/structure/backend/ guidelines
798
-
799
- AI: Implement feature
800
-
801
- User: /check-backend
802
-
803
- AI: Review code, self-fix issues
804
-
805
- User: /finish-work
806
-
807
- AI: Execute Pre-Commit Checklist
808
-
809
- User: git commit (manual commit)
810
-
811
- User: /record-agent-flow (record session)
812
- ```
813
-
814
- ---
815
-
816
- ## Extended Reading
817
-
818
- - [Understanding Trellis Through Kubernetes Concepts](docs/use-k8s-to-know-trellis.md) - If you're familiar with Kubernetes, this article explains Trellis design using K8s concept analogies