-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathbootstrap.sh
More file actions
executable file
·5757 lines (4452 loc) · 207 KB
/
Copy pathbootstrap.sh
File metadata and controls
executable file
·5757 lines (4452 loc) · 207 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#!/usr/bin/env bash
# =============================================================================
# AI Project Kit — Bootstrap Script
# Drop this in any project root and run: bash bootstrap.sh
# =============================================================================
set -e
CYAN='\033[0;36m'
GREEN='\033[0;32m'
YELLOW='\033[1;33m'
BOLD='\033[1m'
RESET='\033[0m'
echo ""
echo -e "${CYAN}${BOLD}╔═══════════════════════════════════════════════╗${RESET}"
echo -e "${CYAN}${BOLD}║ AI Project Kit — Bootstrapping ║${RESET}"
echo -e "${CYAN}${BOLD}╚═══════════════════════════════════════════════╝${RESET}"
echo ""
# Detect if brownfield (existing code present)
FILE_COUNT=$(find . -maxdepth 2 \( -name "*.ts" -o -name "*.js" -o -name "*.py" -o -name "*.rb" -o -name "*.go" \) -not -path "./node_modules/*" -not -path "./.claude/*" 2>/dev/null | wc -l | tr -d ' ')
if [ "$FILE_COUNT" -gt "5" ]; then
echo -e "${YELLOW}⚡ Brownfield project detected ($FILE_COUNT source files found)${RESET}"
echo -e " Kit will configure for brownfield mode (spec existing system first)."
PROJECT_MODE="brownfield"
else
echo -e "${GREEN}✨ Greenfield project — full spec-first workflow will be configured.${RESET}"
PROJECT_MODE="greenfield"
fi
echo ""
# Create directory structure
echo -e "${BOLD}Creating kit structure...${RESET}"
mkdir -p .claude/commands
mkdir -p .claude/hooks
mkdir -p .claude/lib
mkdir -p .claude/skills/project-init
mkdir -p .claude/skills/project-research
mkdir -p .claude/skills/project-blueprint
mkdir -p .claude/skills/project-spec
mkdir -p .claude/skills/project-module
mkdir -p .claude/skills/project-execute
mkdir -p .claude/skills/project-review
mkdir -p .claude/skills/project-security-review
mkdir -p .claude/skills/project-status
mkdir -p .claude/skills/project-deploy
mkdir -p .claude/skills/project-test
mkdir -p .claude/parallel/locks
mkdir -p .claude/parallel/learnings
mkdir -p .kit-orchestration
mkdir -p specs/modules
mkdir -p specs/sessions
if [ ! -f ".claude/parallel/tracks.json" ]; then
cat > ".claude/parallel/tracks.json" << 'TRACKS_JSON_EOF'
{"tracks": [], "merge_order": [], "harness": null}
TRACKS_JSON_EOF
echo -e " ${GREEN}✓${RESET} .claude/parallel/tracks.json"
fi
if [ ! -f ".worktreeinclude" ]; then
cat > ".worktreeinclude" << 'WORKTREEINCLUDE_EOF'
.env
.env.local
.dev.vars
WORKTREEINCLUDE_EOF
echo -e " ${GREEN}✓${RESET} .worktreeinclude"
fi
# =============================================================================
# CLAUDE.md
# =============================================================================
cat > CLAUDE.md << 'CLAUDE_EOF'
# CLAUDE.md — Operating Model for AI Project Kit
This document defines how Claude operates within the AI Project Kit. It serves as the instruction set for every session and guides decision-making at all levels.
---
## The Prime Directive
**Every Claude session operates as a dedicated project specialist.** The goal is not to jump between tasks, but to drive ONE project forward from concept to completion in a single unbroken workflow.
A session succeeds when:
- It captures the full scope of work needed
- It executes each phase in sequence without distraction
- It captures learnings at the end for future sessions
- The project advances measurably (code written, architecture decided, tests passing, deployed)
---
## Trigger Recognition
Sessions are triggered by explicit commands that signal intent:
| Trigger | Meaning |
|---------|---------|
| `/project-init [idea]` | New project or major feature — start from zero |
| `/project-research [topic]` | Deep research mode — explore domain/tech/regulation |
| `/project-blueprint` | Architecture mode — system design or regeneration |
| `/project-spec [module]` | Specification mode — detailed module design |
| `/project-module [name]` | Implementation mode — code and tests |
| `/project-execute [module]` | Dual-harness mode: hand a fully-specced module to Codex CLI for implementation while Claude orchestrates. Live tmux pane in your most-recent attached session. |
| `/project-security-review` | Independent Agent-based security review of pending changes — UK GDPR / healthcare focus. |
| `/project-review` | Wrap-up mode — capture learnings |
| `/project-status` | Dashboard — show current state |
| `/project-deploy` | Deployment mode — deploy and verify |
| `/project-test` | Testing mode — comprehensive test pass |
These are not suggestions—they are **explicit signals** that Claude should enter a specific operational mode.
---
## Workflow
Every Claude session follows a 5-phase sequence, executed in order:
### Phase 1: Plan
- Understand the task
- Identify unknowns
- Map dependencies
- Document assumptions
- Create a todo list if multi-step
**Exit criteria:** Clear scope, no surprises ahead
### Phase 2: Research (if needed)
- Answer unknowns via Exa/Ref documentation search
- Verify current best practices for the stack
- Check competitor implementations (market context)
- Record findings for later reference
**Exit criteria:** All technical questions answered, patterns documented
### Phase 3: Execute
- Build incrementally (small, testable units)
- Verify each piece before continuing
- Keep terminal output clean
- Push incremental commits with clear messages
**Exit criteria:** Code written, feature complete, passing tests
### Phase 4: Verify
- Visually test the change (Playwright if UI)
- Check console for errors
- Verify against acceptance criteria
- Document any gaps or next steps
**Exit criteria:** Change works as intended, no breaking changes introduced
### Phase 5: Capture
- Summarize what was built
- Document unexpected learnings
- Note patterns for reuse
- Update LEARNINGS.md
- Link to relevant PRs/commits
**Exit criteria:** Learnings captured, handoff ready for next session
---
## Dual-Harness Workflow
Some tasks are big enough that you want Claude (Opus 4.7) to plan and review while Codex CLI (gpt-5.5) does the heavy implementation. The kit supports this via `/project-execute`:
- **Plan + Review**: Claude Code (this session). Reads specs, builds the dispatch prompt, reads back the scrubbed structured report + JSONL events, smoke-tests the working tree, **applies commits proposed by Codex** (orchestrator-commits pattern), summarises, runs the review skill.
- **Execute**: Codex CLI (`gpt-5.5`, medium reasoning effort), launched via `.claude/lib/dispatch.sh` with `--json --output-schema`. Runs in a live tmux pane that splits into your most-recent attached session.
Single-harness mode (`/project-module`) keeps everything in Claude. Use dual-harness when the module is large, well-specced, and you want to watch implementation happen in real time.
**Orchestrator-commits is canonical.** Codex does NOT commit. It leaves the working tree dirty and emits a structured final report (schema at `.claude/skills/project-execute/codex-report-schema.json`) listing `proposed_commits`. Claude reviews the diff, smoke-tests, and applies commits with `Co-Authored-By` attribution. This sidesteps Codex's `workspace-write` sandbox `.git` restriction and gives a verification gate that catches spec deviations and training-data bleed-through before they land in history.
**Prerequisites**:
- `npm install -g @openai/codex` (Codex CLI 0.128+ tested).
- Authenticate. Two paths with different model availability:
- `codex login` — ChatGPT auth. Required for `gpt-5.5` access without API tier requirements.
- `export OPENAI_API_KEY=…` — API-key auth. `gpt-5.5` requires Tier 1+ on your OpenAI org; if your org lacks the tier, the preflight will fail with a model-availability error.
- A tmux session with at least one attached client. dispatch.sh detects the most-recent attached client via `tmux list-clients` — Claude Code itself doesn't have to be inside tmux as long as one client is attached somewhere. Override with `KIT_TMUX_SESSION=<name>` when you have multiple sessions.
Portability: dispatch.sh works on Linux and macOS. Requires GNU coreutils (`timeout` on Linux, `gtimeout` after `brew install coreutils` on macOS). Lock is mkdir-based (no `flock` dependency).
---
## Available Slash Commands
| Command | Usage | Purpose |
|---------|-------|---------|
| `/project-init` | `/project-init [idea]` | Start a new project or major feature from scratch |
| `/project-research` | `/project-research [topic]` | Deep research on domain, technology, or regulations |
| `/project-blueprint` | `/project-blueprint` | Generate or regenerate master architecture design |
| `/project-spec` | `/project-spec [module]` | Create or update a detailed module specification |
| `/project-module` | `/project-module [name]` | Implement a specific module end-to-end |
| `/project-review` | `/project-review` | End-of-session: capture learnings and progress |
| `/project-status` | `/project-status` | Display project dashboard and current state |
| `/project-deploy` | `/project-deploy` | Deploy to staging/production and verify |
| `/project-test` | `/project-test` | Comprehensive test pass across all modules |
| `/project-execute` | `/project-execute [module]` | Dual-harness mode: hand a fully-specced module to Codex CLI for implementation while Claude orchestrates |
| `/project-security-review` | `/project-security-review` | Independent Agent-based security review of pending changes — UK GDPR / healthcare focus. |
---
## Available Tools & Integrations
Claude has access to specialized tools for research, testing, and deployment. Use these before implementing:
### Research & Documentation
- **Exa Search** (`web_search_exa`) — Web search with category filters (company, research paper, people). Use for market research, competitor analysis, and domain exploration.
- **Exa Code Context** (`get_code_context_exa`) — Find code examples from GitHub, Stack Overflow, and official docs. Use for framework patterns and implementation examples.
- **Ref Documentation** (`ref_search_documentation`) — Search framework and library documentation. Use to verify API patterns, latest versions, and best practices.
- **Ref URL Reader** (`ref_read_url`) — Read full documentation pages. Use after finding relevant docs via search.
### Testing & Verification
- **Playwright** — Browser automation for E2E testing and visual verification. Navigate pages, take screenshots, check accessibility, read console errors.
- **Chrome Automation** — Alternative browser control for testing and verification.
### Deployment
- **Vercel** — Deploy previews and production builds. Monitor build logs, check deployment status.
### Frontend Development
- **web-artifacts-builder skill** — React, Tailwind CSS, and shadcn/ui component patterns. Consult when building frontend modules.
### Hooks
- **PreCompact snapshot hook** (`.claude/hooks/pre-compact.sh`) — Writes recovery snapshots into `specs/sessions/` before conversation compaction. Configured by `.claude/settings.json`.
- **SessionStart compact backup** — On compacted-session resume, prints the latest snapshot path when one exists. Claude Code issue #13572 means PreCompact may not fire reliably for `/compact` on some versions, so treat this as best-effort recovery.
### Rule: Research Before Implementing
**Before implementing any technical pattern you're uncertain about, use Ref or Exa to look up current documentation.** Don't rely on potentially outdated training knowledge for version-specific API details. This ensures consistency with the latest tooling and avoids rework.
---
## Spec Hierarchy
Specifications follow a three-tier hierarchy from abstract to concrete:
### Tier 1: Blueprint (System Design)
- Component relationships
- Data flow
- Integration points
- Risk assessment
**Example:** "User service talks to Auth service via REST; both write to PostgreSQL"
### Tier 2: Module Spec (Detailed Design)
- Function signatures
- Input/output contracts
- Error handling
- Dependencies
**Example:** "POST /users takes { email, password }, returns { id, token } or { error }"
### Tier 3: Code (Implementation)
- Actual working code
- Tests
- Documentation
- Deployment
**Example:** Implemented function with type safety, error handling, and unit tests
Each tier is concrete enough that a developer can execute it without debate. Never skip a tier.
---
## Session Rules
1. **One session = one task.** Don't start a second task until the first is captured and ready for handoff.
2. **Plan mode first.** Before writing code, create a todo list and confirm scope.
3. **Research before building.** Use Ref or Exa to verify technical patterns before implementing.
4. **Commit early, commit often.** Push small, focused commits with clear messages. Easier to review and revert if needed.
5. **Verify as you go.** Don't leave broken code in the branch. Each phase should be testable.
6. **Capture learnings at the end.** Spend 5 minutes summarizing what you learned and what surprised you. Record in LEARNINGS.md.
7. **Link to context.** When you finish, leave breadcrumbs: commit hashes, PR links, file paths. Next session should be able to pick up immediately.
---
## Boundaries
### ✅ Always
- Use Exa/Ref to verify technical details before implementing
- Visually verify UI changes with Playwright when possible
- Commit frequently with clear messages
- Check test output before declaring success
- Ask for clarification if scope is ambiguous
- Use type safety (TypeScript, Pydantic, etc.)
- Document public APIs with examples
- Link learnings to specific code changes
### ⚠️ Ask Before
- Creating major new files or directories
- Changing system architecture
- Adding new dependencies
- Modifying existing APIs
- Deleting code or data
- Deploying to production
- Merging to main branch
### 🚫 Never
- Commit without testing
- Skip error handling
- Leave console warnings in code
- Assume API behavior—read the docs
- Deploy broken branches
- Merge without a clear reason in the commit message
- Ignore accessibility concerns in UI
---
## Stack Detection
Before starting implementation, answer these four questions to understand the project:
1. **Frontend:** React? Vue? Svelte? Plain HTML? (or N/A if backend-only)
2. **Backend:** Node.js? Python? Go? Rust? (or N/A if frontend-only)
3. **Database:** PostgreSQL? MongoDB? Firestore? (or N/A if not applicable)
4. **Deployment:** Vercel? Docker? Lambda? Self-hosted? (or N/A)
These determine which tools and patterns you'll use throughout.
---
## Quality Standards
- **Code:** Passes linting, has no console errors, uses type safety
- **Tests:** Unit tests for logic, E2E tests for user flows, passing locally before push
- **Docs:** Public functions have docstrings/comments, modules have README sections, complex logic is explained
- **UX:** Accessible (WCAG AA minimum), responsive (mobile-first), keyboard-navigable
- **Deployment:** Builds without warnings, passes CI/CD, rolls back cleanly if issues found
---
## Learnings
After every session, update `LEARNINGS.md` with:
1. **What worked well** — patterns, tools, approaches that accelerated progress
2. **What was harder than expected** — gotchas, surprises, missing documentation
3. **What to do differently next time** — concrete changes for future sessions
4. **Links to the work** — commit hashes, PRs, files touched
This creates a knowledge base that future sessions can learn from immediately.
---
## Session Checklist
At the **start** of a session:
- [ ] Read this file (you're doing it now)
- [ ] Check LEARNINGS.md for context
- [ ] Run `/project-status` if this is a continuation
- [ ] Create a todo list
- [ ] Confirm scope with the user
At the **end** of a session:
- [ ] All code tested and committed
- [ ] All todos marked done or moved to next session
- [ ] LEARNINGS.md updated
- [ ] Summary provided with links to work
- [ ] Clear handoff notes for next session
---
**This is the operating model. Follow it.**
CLAUDE_EOF
echo -e " ${GREEN}✓${RESET} CLAUDE.md"
# =============================================================================
# LEARNINGS.md
# =============================================================================
cat > LEARNINGS.md << 'LEARNINGS_EOF'
# Project Learnings
This file is updated at the end of every session. It captures mistakes, discoveries, patterns that work, and patterns that don't. Reading this at the start of an implementation session prevents repeating mistakes.
> **Maintained by:** Claude Code (auto-updated via `/project-review`)
> **Format:** Newest entries at the top.
---
## Patterns That Work
_Populated as the project progresses._
---
## Mistakes & Fixes
_Populated as the project progresses._
---
## Stack-Specific Notes
_Populated after stack is selected._
---
## Open Questions
_Architectural or product decisions still to be resolved._
LEARNINGS_EOF
echo -e " ${GREEN}✓${RESET} LEARNINGS.md"
# =============================================================================
# SKILLS AND COMMANDS
# =============================================================================
cat > .claude/skills/project-init/SKILL.md << 'SKILL_INIT_EOF'
---
name: project-init
description: "Initialise a new software project with full spec-first workflow — research, architecture, module specs, and roadmap. Use this whenever someone says 'build me a...', 'I want to create...', 'new project', 'start a project', or describes a product idea. Also use for major new feature areas within an existing project."
effort: high
---
# Project Initialization Skill
This skill guides you through a complete 7-phase spec-first project setup. Follow each phase sequentially, save outputs to the `specs/` directory, and maintain clarity throughout.
## Phase 1: Clarify the Vision
Engage with the user to deeply understand their project idea:
- **User Problem:** What pain point or opportunity does this solve?
- **Target Users:** Who are the primary users? Secondary users?
- **Success Criteria:** How will we know this project succeeded?
- **Constraints:** Budget, timeline, compliance, technical, platform constraints?
- **Out of Scope:** What explicitly will NOT be built?
Ask follow-up questions until you have a crystal-clear vision. Create a summary document: `specs/PROJECT_BRIEF.md` with sections: Overview, Problem Statement, Target Users, Success Criteria, Constraints, Out of Scope.
## Phase 2: Domain Research
Conduct structured research on the domain, market, competitors, and technical landscape. Explicitly use available research tools:
**For Market & Competitor Analysis:**
- Use `web_search_exa` with `category: "company"` to find competitor websites, products, and business models.
- Search queries like: "[product type] competitor analysis", "[industry] market landscape", "[use case] solutions".
- Document what competitors do well, weaknesses, pricing, positioning.
**For Academic & Industry Research:**
- Use `web_search_exa` with `category: "research paper"` to find peer-reviewed studies, industry reports, and technical papers relevant to your domain.
- Search queries like: "[domain] best practices", "[problem area] research", "[technology] case studies".
**For General Market Context:**
- Use `web_search_exa` (no category filter) for recent news, trends, adoption rates, and emerging patterns.
**For Technical Foundation (after tech stack decisions):**
- Use `ref_search_documentation` to find official documentation for frameworks, libraries, and APIs you're considering.
- Use `get_code_context_exa` to find production code examples and common patterns.
Record findings in `specs/RESEARCH.md` with sections: Market Landscape, Competitor Analysis, Key Trends, Regulatory Considerations, Technical Considerations, Recommendations.
## Phase 3: Module Identification
Based on the vision and research, decompose the project into logical modules. Each module should represent a cohesive business capability or feature area.
For typical web projects, consider:
- Authentication & User Management
- Core Domain Modules (e.g., Content, Products, Orders)
- Admin & Management Interfaces
- API/Backend Services
- Infrastructure & Deployment
- Observability & Analytics
Ask: "What can be built independently? What has minimal coupling? What represents distinct user workflows?"
Create a rough module list with brief descriptions and dependencies. Save as `specs/MODULES.md`.
## Phase 4: Master Blueprint
Create the comprehensive architecture blueprint by:
1. **Technology Stack Decision:** Choose your core technologies (frontend framework, backend runtime, database, infrastructure, auth, etc.). If not yet decided, answer these 4 questions:
- What frontend framework aligns with your UI complexity and team skills? (React, Vue, Svelte, etc.)
- What backend stack? (Node.js, Python, Go, etc. + framework)
- What database? (Relational, document, graph, key-value?)
- What deployment target? (Vercel, AWS, Docker, traditional servers?)
2. **Verify Latest Versions:** Use `ref_search_documentation` to check the current stable versions of chosen technologies and their recommended patterns.
3. **Find Production Examples:** Use `get_code_context_exa` with queries like "[framework] [architecture pattern] example", "[stack] production architecture" to find real-world implementations of your planned approach.
4. **Create the Blueprint:** Fill out the blueprint template with all 9 sections. Include version numbers, source URLs, and rationale for each choice.
5. **Review & Approve:** Present a summary of key decisions and architectural constraints. Ask the user for approval before saving to `specs/MASTER_BLUEPRINT.md`.
## Phase 5: Module Specifications
For each module identified in Phase 3, create a detailed module specification:
1. **Read the template:** `module-spec-template.md` (bundled here)
2. **Complete all sections:**
- Purpose: Why does this module exist?
- User Stories: Concrete workflows this module enables
- Data Model: TypeScript interfaces defining the domain
- API/Server Actions: Endpoints or functions this module exposes
- UI Screens: Key screens and user flows
- Business Logic & Rules: Validation, constraints, workflows
- Integration Points: What other modules depend on this? What does this depend on?
- Acceptance Criteria: How do we know it's complete?
- Out of Scope: What's explicitly excluded?
- Open Questions: Unknowns to resolve
3. **Save each spec:** `specs/modules/[module-name]/SPEC.md`
4. **Link specs together:** Ensure dependencies are clear and cross-module contracts are documented.
## Phase 6: Module CLAUDE.md Files
For each module, create a CLAUDE.md guide that helps future Claude instances understand module conventions and patterns:
1. **Read the template:** `claude-module-template.md` (bundled here)
2. **Document:**
- Patterns to Follow: Architectural patterns specific to this module (MVC, service layer, repository pattern, etc.)
- Conventions in This Module: Naming, file structure, error handling, logging conventions
- Module Boundaries: What this module owns, what it reads from other modules, what it must NEVER do
- Known Gotchas: Common mistakes, performance traps, threading issues, etc.
- Test Patterns: Unit test structure, mock patterns, integration test approach
3. **Save:** `specs/modules/[module-name]/CLAUDE.md`
## Phase 7: Implementation Roadmap
Create a prioritized implementation plan:
1. **Identify Phase 0 (Infrastructure):** What must be built first? Database schema, auth system, API scaffolding, deployment pipeline?
2. **Sequence Modules:** Order remaining modules by:
- User story priority (what delivers user value first?)
- Dependency graph (what unblocks other work?)
- Risk (build risky unknowns early)
- Team capacity (balance parallelizable vs. sequential work)
3. **Create Sprints/Milestones:** Break into 2–4 week chunks with clear deliverables.
4. **Define Exit Criteria:** What does "done" look like for each sprint?
5. **Save:** `specs/ROADMAP.md` with sections: Phase 0 (Infrastructure), Milestones, Sprint Details, Risk Mitigation, Success Metrics.
## Output Structure
After completing all 7 phases, you will have created:
```
specs/
├── PROJECT_BRIEF.md (Phase 1)
├── RESEARCH.md (Phase 2)
├── MODULES.md (Phase 3)
├── MASTER_BLUEPRINT.md (Phase 4)
├── ROADMAP.md (Phase 7)
└── modules/
├── [module-1]/
│ ├── SPEC.md (Phase 5)
│ └── CLAUDE.md (Phase 6)
├── [module-2]/
│ ├── SPEC.md
│ └── CLAUDE.md
└── ...
```
All specs are markdown files stored in version control, reviewed collaboratively, and updated as the project evolves.
## Execution
Start with the user's project idea from `$ARGUMENTS`. Execute each phase in order, asking clarifying questions, saving outputs, and building a comprehensive specification before implementation begins.
SKILL_INIT_EOF
echo -e " ${GREEN}✓${RESET} .claude/skills/project-init/SKILL.md"
cat > .claude/skills/project-init/blueprint-template.md << 'TEMPLATE_BLUEPRINT_EOF'
# Master Architecture Blueprint
> **Status:** {{STATUS}} (Draft / Approved / In Progress)
> **Last Updated:** {{DATE}}
> **Project:** {{PROJECT_NAME}}
> **Team:** {{TEAM_MEMBERS}}
## 1. Project Overview
**Problem Statement:** {{PROBLEM_STATEMENT}}
**Solution Overview:** {{SOLUTION_OVERVIEW}}
**Key Success Criteria:**
- {{CRITERION_1}}
- {{CRITERION_2}}
- {{CRITERION_3}}
**Scope Boundaries:** {{SCOPE_BOUNDARIES}}
---
## 2. Tech Stack
| Layer | Technology | Version | Rationale |
|-------|-----------|---------|-----------|
| Frontend Framework | {{FRONTEND_FRAMEWORK}} | {{VERSION}} | {{RATIONALE}} |
| Frontend Build & Tooling | {{FRONTEND_BUILD}} | {{VERSION}} | {{RATIONALE}} |
| Backend Runtime | {{BACKEND_RUNTIME}} | {{VERSION}} | {{RATIONALE}} |
| Backend Framework | {{BACKEND_FRAMEWORK}} | {{VERSION}} | {{RATIONALE}} |
| Database (Primary) | {{PRIMARY_DATABASE}} | {{VERSION}} | {{RATIONALE}} |
| Database (Cache/Sessions) | {{CACHE_DATABASE}} | {{VERSION}} | {{RATIONALE}} |
| Authentication | {{AUTH_SOLUTION}} | {{VERSION}} | {{RATIONALE}} |
| API Style | {{API_STYLE}} | — | {{RATIONALE}} |
| Deployment Platform | {{DEPLOYMENT_PLATFORM}} | — | {{RATIONALE}} |
| CI/CD | {{CI_CD_TOOL}} | — | {{RATIONALE}} |
| Monitoring & Logging | {{MONITORING_SOLUTION}} | — | {{RATIONALE}} |
| Testing Framework | {{TEST_FRAMEWORK}} | {{VERSION}} | {{RATIONALE}} |
**Version Strategy:** {{VERSION_STRATEGY}}
**Technology Constraints:** {{CONSTRAINTS}}
---
## 3. Data Model
### Core Entities
```typescript
// {{ENTITY_1}}
interface {{ENTITY_1}} {
id: string;
{{FIELD_1}}: {{TYPE}};
{{FIELD_2}}: {{TYPE}};
createdAt: Date;
updatedAt: Date;
}
// {{ENTITY_2}}
interface {{ENTITY_2}} {
id: string;
{{FIELD_1}}: {{TYPE}};
{{FIELD_2}}: {{TYPE}};
createdAt: Date;
updatedAt: Date;
}
```
### Relationships
{{ENTITY_RELATIONSHIP_DIAGRAM}}
**Example:** {{EXAMPLE_1}}
### Key Design Decisions
- **Primary Key Strategy:** {{PRIMARY_KEY_STRATEGY}}
- **Soft Deletes:** {{SOFT_DELETE_POLICY}}
- **Audit Trail:** {{AUDIT_POLICY}}
- **Multi-tenancy:** {{TENANCY_MODEL}} (single-tenant / multi-tenant / hybrid)
- **Scalability Considerations:** {{SCALABILITY_NOTES}}
---
## 4. API Design Patterns
### API Style
**Style:** {{API_STYLE}} (REST / GraphQL / tRPC / gRPC / Hybrid)
### Base URL & Versioning
```
Production: https://api.{{DOMAIN}}/v1
Staging: https://staging-api.{{DOMAIN}}/v1
```
### Authentication & Authorization
- **Method:** {{AUTH_METHOD}} (JWT / OAuth / Session / API Key / mTLS)
- **Token Lifetime:** {{TOKEN_LIFETIME}}
- **Scopes/Permissions Model:** {{PERMISSIONS_MODEL}}
- **Rate Limiting:** {{RATE_LIMIT_STRATEGY}}
### Naming Conventions
- **Endpoint Naming:** {{ENDPOINT_NAMING}} (e.g., `/api/v1/resources`, `/api/v1/resources/{id}/sub-resources`)
- **Field Naming:** {{FIELD_NAMING}} (camelCase / snake_case)
- **Error Field Names:** {{ERROR_NAMING}}
### Error Response Format
```json
{
"error": {
"code": "{{ERROR_CODE}}",
"message": "{{ERROR_MESSAGE}}",
"details": { "{{DETAIL_KEY}}": "{{DETAIL_VALUE}}" }
}
}
```
**Standard Error Codes:** {{ERROR_CODES}}
### Response Format
```json
{
"data": { "{{RESOURCE}}" },
"meta": { "requestId": "uuid", "timestamp": "ISO8601" }
}
```
### Pagination (if applicable)
- **Style:** {{PAGINATION_STYLE}} (offset / cursor / keyset)
- **Default Limit:** {{DEFAULT_PAGE_SIZE}}
- **Max Limit:** {{MAX_PAGE_SIZE}}
---
## 5. Shared UI Patterns
### Design System
- **Color Palette:** {{COLOR_PALETTE}}
- **Typography:** {{TYPOGRAPHY_SPECS}}
- **Component Library:** {{COMPONENT_LIBRARY}} (custom / Material UI / shadcn/ui / other)
- **Icon Library:** {{ICON_LIBRARY}}
### Layout Patterns
- **Page Structure:** {{PAGE_STRUCTURE_PATTERN}}
- **Navigation:** {{NAV_PATTERN}} (sidebar / top nav / tabbed / etc.)
- **Responsive Breakpoints:** {{RESPONSIVE_BREAKPOINTS}}
- **Mobile-first:** {{MOBILE_FIRST_APPROACH}}
### Form Patterns
- **Validation Display:** {{VALIDATION_PATTERN}} (inline / summary / field-level)
- **Error Messaging:** {{ERROR_MESSAGE_PATTERN}}
- **Field Labeling:** {{FIELD_LABEL_PATTERN}}
- **Submission Behavior:** {{SUBMISSION_BEHAVIOR}}
### Loading & Skeleton States
- **Loading Indicator:** {{LOADING_INDICATOR_STYLE}}
- **Skeleton Components:** {{SKELETON_USAGE}}
- **Progressive Enhancement:** {{PROGRESSIVE_ENHANCEMENT}}
### Navigation & Routing
- **Route Structure:** {{ROUTE_STRUCTURE}}
- **Deep Linking:** {{DEEP_LINKING_SUPPORT}}
- **Breadcrumbs:** {{BREADCRUMB_USAGE}}
- **404/Error Pages:** {{ERROR_PAGE_PATTERN}}
### Accessibility (a11y)
- **WCAG Level:** {{WCAG_LEVEL}} (A / AA / AAA)
- **Keyboard Navigation:** {{KEYBOARD_NAV_REQUIRED}}
- **Screen Reader Testing:** {{SCREEN_READER_TOOLS}}
---
## 6. Modules
| Module | Priority | Description | Depends On | Estimated Effort |
|--------|----------|-------------|-----------|------------------|
| {{MODULE_1}} | P0/P1/P2 | {{DESCRIPTION}} | {{DEPENDS}} | {{EFFORT}} |
| {{MODULE_2}} | P0/P1/P2 | {{DESCRIPTION}} | {{DEPENDS}} | {{EFFORT}} |
| {{MODULE_3}} | P0/P1/P2 | {{DESCRIPTION}} | {{DEPENDS}} | {{EFFORT}} |
| {{MODULE_N}} | P0/P1/P2 | {{DESCRIPTION}} | {{DEPENDS}} | {{EFFORT}} |
**Module Ownership:** {{MODULE_OWNERSHIP_DETAILS}}
---
## 7. Infrastructure & Deployment
### Hosting & Infrastructure
- **Deployment Platform:** {{DEPLOYMENT_PLATFORM}}
- **Infrastructure as Code:** {{IAC_TOOL}} (Terraform / CloudFormation / ARM / CDK / other)
- **Container Strategy:** {{CONTAINER_STRATEGY}} (Docker / containerless / hybrid)
- **Database Hosting:** {{DATABASE_HOSTING}}
- **CDN & Static Assets:** {{CDN_SOLUTION}}
### Environment Strategy
- **Environments:** {{ENVIRONMENTS}} (dev / staging / production / preview)
- **Environment Parity:** {{ENVIRONMENT_PARITY_APPROACH}}
- **Secrets Management:** {{SECRETS_MANAGEMENT}}
### CI/CD Pipeline
```
Trigger → Build → Test → Deploy Staging → Integration Tests → Deploy Production
```
- **Tool:** {{CI_CD_TOOL}}
- **Branch Strategy:** {{BRANCH_STRATEGY}} (main / develop / feature branches)
- **Deployment Approvals:** {{DEPLOYMENT_APPROVALS}}
- **Rollback Strategy:** {{ROLLBACK_STRATEGY}}
### Monitoring, Logging & Observability
- **Logging:** {{LOGGING_SOLUTION}}
- **Metrics & APM:** {{METRICS_SOLUTION}}
- **Error Tracking:** {{ERROR_TRACKING_SOLUTION}}
- **Uptime Monitoring:** {{UPTIME_MONITORING}}
- **Alert Thresholds:** {{ALERT_THRESHOLDS}}
### Backup & Disaster Recovery
- **Backup Frequency:** {{BACKUP_FREQUENCY}}
- **Recovery Time Objective (RTO):** {{RTO}}
- **Recovery Point Objective (RPO):** {{RPO}}
- **Disaster Recovery Plan:** {{DR_PLAN}}
---
## 8. Security & Compliance
### Authentication & Authorization
- **User Authentication:** {{AUTH_MECHANISM}}
- **MFA Support:** {{MFA_REQUIRED}}
- **Session Management:** {{SESSION_MANAGEMENT}}
- **Password Policy:** {{PASSWORD_POLICY}}
### Data Security
- **Data at Rest:** {{DATA_AT_REST_ENCRYPTION}}
- **Data in Transit:** {{DATA_IN_TRANSIT_ENCRYPTION}} (TLS 1.2+)
- **Sensitive Data Handling:** {{SENSITIVE_DATA_HANDLING}}
- **PII Protection:** {{PII_PROTECTION}}
### Network & Infrastructure Security
- **Network Isolation:** {{NETWORK_ISOLATION}}
- **VPC/Firewall:** {{FIREWALL_CONFIG}}
- **DDoS Protection:** {{DDOS_PROTECTION}}
- **API Rate Limiting:** {{RATE_LIMITING}}
### Compliance Requirements
- **Regulations:** {{REGULATIONS}} (GDPR / HIPAA / SOC2 / PCI-DSS / other)
- **Data Residency:** {{DATA_RESIDENCY}}
- **Audit Logging:** {{AUDIT_LOGGING}}
- **Compliance Certifications:** {{CERTIFICATIONS}}
### Dependency & Vulnerability Management
- **Dependency Scanning:** {{DEPENDENCY_SCANNING_TOOL}}
- **Vulnerability Response Time:** {{VULN_RESPONSE_SLA}}
- **Security Updates Cadence:** {{SECURITY_UPDATE_CADENCE}}
---
## 9. Open Architectural Questions
- **Question 1:** {{QUESTION_1}}
- Impact: {{IMPACT}}
- Resolution: {{STATUS}}
- **Question 2:** {{QUESTION_2}}
- Impact: {{IMPACT}}
- Resolution: {{STATUS}}
- **Question N:** {{QUESTION_N}}
- Impact: {{IMPACT}}
- Resolution: {{STATUS}}
---
## Approval & Signoff
- **Created By:** {{CREATOR}}
- **Approved By:** {{APPROVER}}
- **Approval Date:** {{APPROVAL_DATE}}
**Changes Since Last Approval:**
{{CHANGE_LOG}}
---
## References & Resources
- [Technology Documentation Links]
- [Architecture Decision Records (ADRs)]
- [Related Spike Documentation]
- [Competitor/Reference Implementations]
TEMPLATE_BLUEPRINT_EOF
echo -e " ${GREEN}✓${RESET} blueprint-template.md"
cat > .claude/skills/project-init/module-spec-template.md << 'TEMPLATE_SPEC_EOF'
# Module Specification: {{MODULE_NAME}}
> **Status:** {{STATUS}} (Draft / Ready for Review / In Progress / Complete)
> **Last Updated:** {{DATE}}
> **Owner:** {{MODULE_OWNER}}
> **Version:** {{VERSION}}
---
## 1. Purpose
**Why does this module exist?**
{{MODULE_PURPOSE}}
**Business Value:** {{BUSINESS_VALUE}}
**Success Criteria:**
- {{SUCCESS_CRITERION_1}}
- {{SUCCESS_CRITERION_2}}
- {{SUCCESS_CRITERION_3}}
---
## 2. User Stories
| ID | As a | I want to | So that |
|----|----|----------|---------|
| {{US_1}} | {{USER_TYPE}} | {{ACTION}} | {{BENEFIT}} |
| {{US_2}} | {{USER_TYPE}} | {{ACTION}} | {{BENEFIT}} |
| {{US_3}} | {{USER_TYPE}} | {{ACTION}} | {{BENEFIT}} |
| {{US_N}} | {{USER_TYPE}} | {{ACTION}} | {{BENEFIT}} |
**Workflow Examples:**
- **{{WORKFLOW_1}}:** {{WORKFLOW_DESCRIPTION}}
- **{{WORKFLOW_2}}:** {{WORKFLOW_DESCRIPTION}}
---
## 3. Data Model
### Core Entities & Types
```typescript
// {{ENTITY_1}} - {{ENTITY_DESCRIPTION}}
interface {{ENTITY_1}} {
id: string;
{{FIELD_1}}: {{TYPE}};
{{FIELD_2}}: {{TYPE}};
{{FIELD_3}}?: {{TYPE}}; // optional
createdAt: Date;
updatedAt: Date;
}
// {{ENTITY_2}} - {{ENTITY_DESCRIPTION}}
interface {{ENTITY_2}} {
id: string;
{{FIELD_1}}: {{TYPE}};
{{FIELD_2}}: {{TYPE}};
{{FIELD_3}}: {{TYPE}};
createdAt: Date;
updatedAt: Date;
}
// {{ENUM_TYPE}} - {{ENUM_DESCRIPTION}}
enum {{ENUM_TYPE}} {
{{VALUE_1}} = "{{VALUE_1}}",
{{VALUE_2}} = "{{VALUE_2}}",
}
// {{DTO_TYPE}} - {{DTO_DESCRIPTION}}
interface {{DTO_TYPE}} {
{{FIELD_1}}: {{TYPE}};
{{FIELD_2}}: {{TYPE}};
}
```
### Relationships & Database Schema
```sql
-- {{TABLE_1}}
CREATE TABLE {{TABLE_1}} (
id UUID PRIMARY KEY,
{{COLUMN_1}} {{TYPE}} NOT NULL,
{{COLUMN_2}} {{TYPE}},
{{FOREIGN_KEY}} UUID REFERENCES {{PARENT_TABLE}}(id),
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
);
-- {{TABLE_2}}
CREATE TABLE {{TABLE_2}} (
id UUID PRIMARY KEY,
{{COLUMN_1}} {{TYPE}} NOT NULL,
{{FOREIGN_KEY}} UUID REFERENCES {{PARENT_TABLE}}(id),
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
);
```
### Key Design Decisions
- **Soft Deletes:** {{SOFT_DELETE_YES_NO}} — {{RATIONALE}}
- **Timestamps:** {{TIMESTAMP_STRATEGY}}
- **Validation:** {{VALIDATION_LEVEL}} (client-only / server / both)
- **Data Constraints:** {{CONSTRAINTS_DESCRIPTION}}
---
## 4. API / Server Actions
### REST Endpoints (if applicable)
```http
GET /api/v1/{{resource-plural}}
→ List {{RESOURCE_NAME}} with pagination
→ Query Params: limit, offset, filter, sort
→ Response: {{ "data": [{{RESOURCE}}], "meta": { "total": number } }}
→ Status: 200 OK, 400 Bad Request
POST /api/v1/{{resource-plural}}
→ Create new {{RESOURCE_NAME}}
→ Body: {{ "field1": "value", "field2": "value" }}
→ Response: {{ "data": {{RESOURCE}} }}