@juicesharp/rpiv-pi 0.4.0

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.
Files changed (60) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +178 -0
  3. package/agents/codebase-analyzer.md +121 -0
  4. package/agents/codebase-locator.md +107 -0
  5. package/agents/codebase-pattern-finder.md +207 -0
  6. package/agents/integration-scanner.md +97 -0
  7. package/agents/precedent-locator.md +130 -0
  8. package/agents/test-case-locator.md +121 -0
  9. package/agents/thoughts-analyzer.md +147 -0
  10. package/agents/thoughts-locator.md +138 -0
  11. package/agents/web-search-researcher.md +107 -0
  12. package/extensions/rpiv-core/agents.ts +312 -0
  13. package/extensions/rpiv-core/git-context.ts +81 -0
  14. package/extensions/rpiv-core/guidance.ts +213 -0
  15. package/extensions/rpiv-core/index.ts +275 -0
  16. package/extensions/rpiv-core/package-checks.ts +51 -0
  17. package/package.json +36 -0
  18. package/scripts/migrate.js +242 -0
  19. package/scripts/types.js +1 -0
  20. package/skills/annotate-guidance/SKILL.md +303 -0
  21. package/skills/annotate-guidance/examples/root-dotnet-clean-arch.md +38 -0
  22. package/skills/annotate-guidance/examples/root-nodejs-monorepo.md +42 -0
  23. package/skills/annotate-guidance/examples/subfolder-database-layer.md +81 -0
  24. package/skills/annotate-guidance/examples/subfolder-dotnet-application.md +64 -0
  25. package/skills/annotate-guidance/examples/subfolder-schemas-layer.md +50 -0
  26. package/skills/annotate-guidance/templates/root-architecture.md +46 -0
  27. package/skills/annotate-guidance/templates/subfolder-architecture.md +57 -0
  28. package/skills/annotate-inline/SKILL.md +299 -0
  29. package/skills/annotate-inline/examples/root-dotnet-clean-arch.md +38 -0
  30. package/skills/annotate-inline/examples/root-nodejs-monorepo.md +42 -0
  31. package/skills/annotate-inline/examples/subfolder-database-layer.md +81 -0
  32. package/skills/annotate-inline/examples/subfolder-dotnet-application.md +64 -0
  33. package/skills/annotate-inline/examples/subfolder-schemas-layer.md +50 -0
  34. package/skills/annotate-inline/templates/root-claude-md.md +46 -0
  35. package/skills/annotate-inline/templates/subfolder-claude-md.md +57 -0
  36. package/skills/code-review/SKILL.md +184 -0
  37. package/skills/commit/SKILL.md +65 -0
  38. package/skills/create-handoff/SKILL.md +91 -0
  39. package/skills/design/SKILL.md +416 -0
  40. package/skills/discover/SKILL.md +242 -0
  41. package/skills/explore/SKILL.md +261 -0
  42. package/skills/implement/SKILL.md +74 -0
  43. package/skills/migrate-to-guidance/SKILL.md +88 -0
  44. package/skills/outline-test-cases/SKILL.md +348 -0
  45. package/skills/outline-test-cases/templates/feature-meta.md +43 -0
  46. package/skills/outline-test-cases/templates/outline-readme.md +36 -0
  47. package/skills/plan/SKILL.md +281 -0
  48. package/skills/research/SKILL.md +304 -0
  49. package/skills/resume-handoff/SKILL.md +207 -0
  50. package/skills/revise/SKILL.md +242 -0
  51. package/skills/validate/SKILL.md +175 -0
  52. package/skills/write-test-cases/SKILL.md +322 -0
  53. package/skills/write-test-cases/examples/customer-auth-flow.md +50 -0
  54. package/skills/write-test-cases/examples/order-management-suite.md +57 -0
  55. package/skills/write-test-cases/examples/order-placement-flow.md +54 -0
  56. package/skills/write-test-cases/examples/team-management-flow.md +56 -0
  57. package/skills/write-test-cases/examples/team-management-suite.md +54 -0
  58. package/skills/write-test-cases/templates/coverage-map.md +64 -0
  59. package/skills/write-test-cases/templates/regression-suite.md +63 -0
  60. package/skills/write-test-cases/templates/test-case.md +65 -0
@@ -0,0 +1,81 @@
1
+ # Database Layer Architecture
2
+
3
+ ## Responsibility
4
+ SQLite persistence with better-sqlite3, repository pattern (plain types), QueryQueue concurrency, type transformations.
5
+
6
+ ## Dependencies
7
+ - **better-sqlite3**: Native SQLite (requires rebuild for Electron)
8
+ - **@redis-ui/core**: Domain types
9
+ - **p-queue**: Query serialization
10
+
11
+ ## Consumers
12
+ - **@redis-ui/services**: Repositories via RepositoryFactory
13
+ - **Main process**: DatabaseManager initialization
14
+
15
+ ## Module Structure
16
+ ```
17
+ src/
18
+ ├── DatabaseManager.ts, QueryQueue.ts # Singleton, concurrency
19
+ ├── BaseRepository.ts, RepositoryFactory.ts
20
+ ├── schema.ts
21
+ └── repositories/ # One repo per entity
22
+ ```
23
+
24
+ ## Repository Boundary (CRITICAL: Plain Types, NOT Result<T>)
25
+
26
+ ```typescript
27
+ export class ConnectionRepository extends BaseRepository<ConnectionDB, Connection, ConnectionId> {
28
+ protected toApplication(db: ConnectionDB): Connection {
29
+ return {
30
+ id: ConnectionId.create(db.id),
31
+ host: db.host,
32
+ port: db.port,
33
+ sslEnabled: Boolean(db.ssl_enabled), // DB int → boolean
34
+ createdAt: new Date(db.created_at), // timestamp → Date
35
+ };
36
+ }
37
+
38
+ async findById(id: ConnectionId): Promise<Connection | null> {
39
+ return this.queue.enqueueRead((db) => {
40
+ const row = db.prepare('SELECT * FROM connections WHERE id = ?').get(id);
41
+ return row ? this.toApplication(row) : null;
42
+ });
43
+ }
44
+ }
45
+
46
+ // Service: Wraps repository in Result<T>
47
+ async createConnection(input: CreateInput): Promise<Result<Connection>> {
48
+ try {
49
+ const connection = await this.connectionRepo.create(input);
50
+ return Result.ok(connection);
51
+ } catch (error) {
52
+ return Result.fail(new InfrastructureError(error.message));
53
+ }
54
+ }
55
+ ```
56
+
57
+ ## QueryQueue Pattern (Write Serialization)
58
+
59
+ ```typescript
60
+ export class QueryQueue {
61
+ private writeQueue = new PQueue({ concurrency: 1 }) // Single writer
62
+ private readQueue = new PQueue({ concurrency: 5 }) // Multiple readers
63
+
64
+ async enqueueWrite<T>(op: (db: Database) => T): Promise<T> {
65
+ return this.writeQueue.add(() => op(this.db))
66
+ }
67
+ }
68
+ ```
69
+
70
+ ## Architectural Boundaries
71
+ - **NO Result<T> in repos**: Services wrap with Result
72
+ - **NO unqueued DB ops**: Always use QueryQueue
73
+ - **NO raw SQL in services**: Use repositories
74
+
75
+ <important if="you are adding a new repository to this layer">
76
+ ## Adding a New Repository
77
+ 1. Create `XRepository.ts` extending `BaseRepository<XDB, X, XId>`
78
+ 2. Implement `toApplication()` and `toDatabase()` type mappers
79
+ 3. Register in `RepositoryFactory`
80
+ 4. Add table schema in `schema.ts`
81
+ </important>
@@ -0,0 +1,64 @@
1
+ # Application Layer (CQRS + MediatR)
2
+
3
+ ## Responsibility
4
+ Command/query handlers orchestrating domain logic via MediatR pipeline. Sits between API controllers and Domain layer.
5
+
6
+ ## Dependencies
7
+ - **MediatR**: Command/query dispatch
8
+ - **FluentValidation**: Request validation via pipeline behavior
9
+ - **AutoMapper**: Domain ↔ DTO mapping
10
+
11
+ ## Consumers
12
+ - **API Controllers**: Send commands/queries via `IMediator`
13
+ - **Integration tests**: Direct handler invocation
14
+
15
+ ## Module Structure
16
+ ```
17
+ Application/
18
+ ├── Common/
19
+ │ ├── Behaviors/ # MediatR pipeline (validation, logging)
20
+ │ └── Mappings/ # AutoMapper profiles
21
+ ├── Features/ # One folder per aggregate
22
+ │ └── Orders/
23
+ │ ├── Commands/ # CreateOrder/, UpdateOrder/ (handler + validator + DTO)
24
+ │ └── Queries/ # GetOrder/, ListOrders/
25
+ └── DependencyInjection.cs # Service registration
26
+ ```
27
+
28
+ ## Handler Pattern (Command with Validation)
29
+
30
+ ```csharp
31
+ public record CreateOrderCommand(string CustomerId, List<LineItemDto> Items)
32
+ : IRequest<Result<OrderDto>>;
33
+
34
+ public class CreateOrderValidator : AbstractValidator<CreateOrderCommand> {
35
+ public CreateOrderValidator(IOrderRepository repo) {
36
+ RuleFor(x => x.CustomerId).NotEmpty();
37
+ RuleFor(x => x.Items).NotEmpty();
38
+ }
39
+ }
40
+
41
+ public class CreateOrderHandler : IRequestHandler<CreateOrderCommand, Result<OrderDto>> {
42
+ public async Task<Result<OrderDto>> Handle(
43
+ CreateOrderCommand request, CancellationToken ct) {
44
+ var order = Order.Create(request.CustomerId, request.Items); // Domain factory
45
+ await _repo.AddAsync(order, ct);
46
+ await _unitOfWork.SaveChangesAsync(ct);
47
+ return Result.Ok(_mapper.Map<OrderDto>(order));
48
+ }
49
+ }
50
+ ```
51
+
52
+ ## Architectural Boundaries
53
+ - **NO domain logic in handlers**: Handlers orchestrate, domain objects contain logic
54
+ - **NO direct DbContext access**: Use repository abstractions
55
+ - **NO cross-feature references**: Features are independent vertical slices
56
+
57
+ <important if="you are adding a new feature or command/query handler">
58
+ ## Adding a New Feature
59
+ 1. Create folder under `Features/{Aggregate}/{Commands|Queries}/`
60
+ 2. Add `Command`/`Query` record implementing `IRequest<Result<TDto>>`
61
+ 3. Add `Validator` extending `AbstractValidator<TCommand>`
62
+ 4. Add `Handler` implementing `IRequestHandler<TCommand, Result<TDto>>`
63
+ 5. Add AutoMapper profile in `Common/Mappings/` if new DTO
64
+ </important>
@@ -0,0 +1,50 @@
1
+ # Schemas Layer Architecture
2
+
3
+ ## Responsibility
4
+ Zod validation schemas for dual-layer validation (preload UX + main security), type inference via z.infer<>.
5
+
6
+ ## Dependencies
7
+ - **zod**: Runtime validation
8
+
9
+ ## Consumers
10
+ - **@redis-ui/ipc**: Main process validation (security)
11
+ - **Preload**: Fail-fast validation (UX)
12
+ - **TypeScript**: Type inference
13
+
14
+ ## Module Structure
15
+ ```
16
+ src/
17
+ ├── connection.ts, backup.ts # Domain schemas
18
+ └── __tests__/ # Validation tests
19
+ ```
20
+
21
+ ## Complete Schema Pattern (Types + Validation + Composition)
22
+
23
+ ```typescript
24
+ export const createConnectionSchema = z.object({
25
+ name: z.string().min(1).max(255),
26
+ host: z.string().min(1),
27
+ port: z.number().int().min(1).max(65535),
28
+ password: z.string().optional(),
29
+ database: z.number().int().min(0).max(15).default(0),
30
+ })
31
+
32
+ // Type inference
33
+ export type CreateConnectionInput = z.infer<typeof createConnectionSchema>
34
+
35
+ // Update schema (partial + ID required)
36
+ export const updateConnectionSchema = createConnectionSchema.partial().extend({
37
+ id: z.string().min(1)
38
+ })
39
+ ```
40
+
41
+ ## Dual-Validation Flow
42
+
43
+ ```
44
+ Renderer input → Preload (Zod parse, fail fast) → IPC → Main (Zod parse again, security)
45
+ ```
46
+
47
+ ## Architectural Boundaries
48
+ - **NO any types**: Use z.unknown()
49
+ - **NO skipping validation**: Always validate at boundaries
50
+ - **NO business logic**: Structure validation only
@@ -0,0 +1,46 @@
1
+ ```markdown
2
+ # Project Overview
3
+ [1-2 sentences: what it is, tech stack]
4
+
5
+ # Architecture
6
+ [monorepo structure tree + dependency flow diagram]
7
+ [process architecture if applicable]
8
+
9
+ # Commands
10
+ [key commands table — always bare, never wrapped in <important if>]
11
+
12
+ # Business Context
13
+ [1-2 sentences if applicable]
14
+ ```
15
+
16
+ The sections above (Overview, Architecture, Commands, Business Context) are foundational — they stay bare because they're relevant to virtually every task.
17
+
18
+ Cross-cutting patterns and domain-specific conventions go in `<important if>` blocks with narrow, action-specific conditions. Do NOT group unrelated rules under a single broad condition like "you are writing or modifying code". Instead, shard by trigger.
19
+
20
+ Root conditional blocks are for **cross-cutting conventions that don't belong to any single layer**. Layer-specific recipes (like "adding a new controller" or "adding a new repository") belong in the subfolder architecture.md, not the root.
21
+
22
+ **Deduplication rule:** If a layer has its own subfolder architecture.md, do NOT add a root conditional block summarizing that layer's conventions. The subfolder file is the authoritative guide — it provides detailed layer-specific documentation in `.rpiv/guidance/`. Root conditionals that mirror subfolder content waste attention budget and create staleness risk.
23
+
24
+ Root MAY include cross-layer vertical-slice checklists (e.g., "adding a new domain entity end-to-end") that reference multiple subfolder architecture.md files — but each step should point to the relevant subfolder for details, not inline them.
25
+
26
+ Good root conditions — things that span multiple layers:
27
+
28
+ ```markdown
29
+ <important if="you are writing or modifying tests">
30
+ - Unit: xUnit + NSubstitute / Jest + Testing Library
31
+ - Integration: WebApplicationFactory / Supertest
32
+ - Test fixtures in `__fixtures__/` or `tests/Fixtures/`
33
+ </important>
34
+
35
+ <important if="you are adding or modifying database migrations">
36
+ - Never modify existing migrations — always create new ones
37
+ - Run `dotnet ef migrations add` / `turbo db:migrate` after schema changes
38
+ </important>
39
+
40
+ <important if="you are adding or modifying environment configuration">
41
+ - All config via `IOptions<T>` pattern / environment variables
42
+ - Secrets in user-secrets locally, Key Vault in production
43
+ </important>
44
+ ```
45
+
46
+ Each block should contain only rules that share the same trigger condition. If a codebase has 3 distinct convention areas, that's 3 blocks — not 1 block with a broad condition. Layer-specific checklists (adding a controller, adding a repository) go in the subfolder architecture.md using `<important if="you are adding a new [entity] to this layer">`.
@@ -0,0 +1,57 @@
1
+ ```markdown
2
+ # [Layer/Component Name]
3
+
4
+ ## Responsibility
5
+ [1-2 sentences: what this layer does, where it sits in architecture]
6
+
7
+ ## Dependencies
8
+ [List only architectural dependencies — frameworks and libraries that shape how you write code in this layer.
9
+ Do NOT list utility libraries discoverable from package.json/imports (e.g., lodash, moment, xlsx).
10
+ A dependency is worth listing if it imposes patterns, constraints, or conventions on the code.]
11
+ - **[dep]**: Why it's used
12
+
13
+ ## Consumers
14
+ - **[consumer]**: How it uses this layer
15
+
16
+ ## Module Structure
17
+ [Compact directory tree — aim for 4-7 top-level entries, not 15.
18
+ Group related files on one line (e.g., "Service.ts, Handler.ts").
19
+ Use architectural annotations for directories (e.g., "# One repo per entity", "# Domain schemas").
20
+ DO NOT enumerate individual files inside directories — describe the convention.
21
+ When a layer has many directories (10+), group related concerns on one line
22
+ (e.g., "guards/, interceptors/, pipes/ — infrastructure plumbing") rather than listing each separately.
23
+ The structure must stay valid when non-architectural files are added.]
24
+
25
+ ## [Pattern Name] ([Key Constraint or Characterization])
26
+ [Each distinct pattern gets its own H2 section — NOT a generic "## Key Patterns" umbrella.
27
+ Include a fenced code block with an idiomatic, generalized example showing:
28
+ - Constructor / dependencies
29
+ - Key method signatures and return types
30
+ - Error handling / wrapping conventions
31
+ - Inline comments for important conventions (e.g., "// throws on error — service wraps in Result")
32
+ If a pattern spans a layer boundary, show both sides briefly.
33
+ Multiple patterns = multiple H2 sections.]
34
+
35
+ ## [Additional Pattern Name]
36
+ [Second pattern with code block if applicable]
37
+
38
+ ## Architectural Boundaries
39
+ - **NO [X]**: [Why]
40
+ - **NO [Y]**: [Why]
41
+
42
+ <important if="you are adding a new [entity type] to this layer">
43
+ ## Adding a New [Entity Type]
44
+ [Step-by-step checklist inferred from existing code:
45
+ 1. Create file following naming convention
46
+ 2. Extend/implement base class or interface
47
+ 3. Register in factory/container/index
48
+ 4. Add related artifacts (schema, test, migration)]
49
+ </important>
50
+
51
+ <important if="you are writing or modifying tests for this layer">
52
+ ## Testing Conventions
53
+ [Test patterns, helpers, fixture locations, mocking approach — if detectable from code]
54
+ </important>
55
+ ```
56
+
57
+ Conditional sections are OPTIONAL — only include them if the pattern-finder skill detects testable patterns or clear "add new entity" workflows. Conditions must be narrow and action-specific. These sections contain checklists/recipes, not code examples (those stay in the unconditional pattern sections). Conditional sections do NOT count toward the 100-line budget for unconditional content.
@@ -0,0 +1,299 @@
1
+ ---
2
+ name: annotate-inline
3
+ description: Generate CLAUDE.md files across a project by analyzing architecture and patterns in parallel. Auto-detects architecture, proposes locations, and batch-writes compact documentation. Use for onboarding or improving AI assistant context.
4
+ argument-hint: [target-directory]
5
+ allowed-tools: Agent, Read, Write, Glob, Grep
6
+ ---
7
+
8
+ # Annotate Project
9
+
10
+ You are tasked with generating CLAUDE.md files across a brownfield project. You will map the project structure, auto-detect its architecture, analyze each architectural layer, and batch-write compact CLAUDE.md files at the root and relevant subdirectories.
11
+
12
+ ## Initial Setup:
13
+
14
+ Use the current working directory as the target project by default. If the user provides a specific directory path as an argument, use that instead.
15
+
16
+ ## Steps to follow:
17
+
18
+ 1. **Read any directly mentioned files first:**
19
+ - If the user mentions specific files (existing CLAUDE.md, architecture docs, READMEs), read them FULLY first
20
+ - **IMPORTANT**: Use the Read tool WITHOUT limit/offset parameters to read entire files
21
+ - **CRITICAL**: Read these files yourself in the main context before invoking any skills
22
+ - This ensures you have full context before decomposing the work
23
+
24
+ 2. **Pass 1 — Map the project (parallel agents):**
25
+ - Spawn the following agents in parallel using the Agent tool:
26
+
27
+ **Agent A — Project tree mapping:**
28
+ - subagent_type: `codebase-locator`
29
+ - Prompt: "Map the full project tree structure for [target directory]. List all directories and their contents, respecting .gitignore. Focus on source code directories, configuration files, and build artifacts. Return a complete tree view."
30
+
31
+ **Agent B — Architecture and conventions:**
32
+ - subagent_type: `codebase-locator`
33
+ - Prompt: "Identify the architectural layers, folder roles, and framework conventions in [target directory]. Determine: What architecture pattern is used (clean architecture, MVC, monorepo, microservices, hexagonal, etc.)? What are the main layers/modules? What frameworks and languages are present? What build system is used? For each main layer/module, check if it contains internal sub-layers with distinct architectural roles. If it does, explicitly flag each sub-layer as a CLAUDE.md target candidate with: (a) path, (b) role/responsibility, (c) approximate file count, (d) how its patterns differ from siblings. Frontend frameworks (Angular, React, Vue, etc.) almost always have distinct sub-layers — components, services, shared/base classes, state management — report each separately."
34
+
35
+ - While agents run, read .gitignore yourself to understand exclusion rules
36
+
37
+ 3. **Wait for Pass 1 and determine CLAUDE.md targets:**
38
+ - IMPORTANT: Wait for ALL agents from Pass 1 to complete before proceeding
39
+ - Synthesize the tree structure and architecture findings
40
+ - Auto-detect the architecture pattern (clean architecture, MVC, monorepo, microservices, etc.)
41
+ - Determine CLAUDE.md targets using a two-pass process:
42
+
43
+ **Initial pass — identify top-level targets:**
44
+ - Apply the CLAUDE.md Depth Rules (see below) to top-level architectural layers
45
+ - This produces the initial target list (one per distinct layer/project)
46
+
47
+ **Decomposition pass — expand composite targets (ADD, never REPLACE):**
48
+ - For EACH initial target, review Agent B's sub-layer candidates
49
+ - If Agent B flagged sub-layers with distinct roles and file counts >10, ADD them as separate CLAUDE.md targets alongside the parent — the parent stays in the list as an overview, sub-layers are added beneath it
50
+ - NEVER remove the parent when promoting sub-layers — decomposition expands the target list, it does not substitute entries
51
+ - Do NOT apply a blanket "sub-folders same as parent" skip — evaluate each sub-layer Agent B flagged individually against the Depth Rules
52
+ - Common decompositions: Angular/React/Vue apps → components/, services/, shared/; monorepo packages → per-package; large shared libraries → per-concern
53
+
54
+ - Present the proposed CLAUDE.md locations to the user:
55
+ ```
56
+ ## Proposed CLAUDE.md Locations
57
+
58
+ Architecture detected: [pattern name]
59
+
60
+ ### Will create CLAUDE.md in:
61
+ - `/` (root) — Project overview (compact)
62
+ - `/src/core/` — Core domain layer
63
+ - `/src/services/` — Service layer
64
+ - [etc.]
65
+
66
+ ### Will skip:
67
+ - `/src/core/entities/` — Entity grouping, same pattern as parent
68
+ - [etc.]
69
+
70
+ Does this look right? Should I add or remove any locations?
71
+ ```
72
+ - Use the `ask_user_question` tool with the following question: "[N] CLAUDE.md targets across [M] layers. Proceed with analysis?". Options: "Proceed (Recommended)" (Analyze all proposed folders and write CLAUDE.md files); "Add folders" (I want to add more folders to the target list); "Remove folders" (Some proposed folders should be skipped).
73
+ - Adjust the target list based on user feedback
74
+
75
+ 4. **Pass 2 — Analyze each layer (parallel analyzer agents):**
76
+ - For each confirmed target folder, spawn agents in parallel:
77
+
78
+ **For each target folder, spawn TWO agents:**
79
+
80
+ **Analyzer agent:**
81
+ - subagent_type: `codebase-analyzer`
82
+ - Prompt: "Analyze [folder path] in detail. Determine: 1) What is this layer's responsibility? 2) What are its dependencies (what does it import/use)? 3) Who consumes it (what imports/uses it)? 4) What are the key architectural boundaries and constraints? 5) What is the module structure — list DIRECTORIES with their roles, base types, and naming conventions. Use architectural annotations (e.g., 'one repo per entity', 'one controller per resource') instead of listing individual filenames. The structure should remain valid when non-architectural files are added. 6) What naming conventions are used (prefixes, suffixes, base classes)?"
83
+
84
+ **Pattern finder agent:**
85
+ - subagent_type: `codebase-pattern-finder`
86
+ - Prompt: "Find all distinct code patterns used in [folder path]. For each pattern found: 1) Name the pattern with a descriptive heading (e.g., 'Repository Boundary (CRITICAL: Plain Types, NOT Result<T>)'). 2) Provide an IDIOMATIC code example — a generalized, representative version that shows the pattern's essential shape (constructor, key method signatures, return types, error handling). Do NOT copy-paste a single file verbatim; instead synthesize the typical usage across the layer. 3) Add inline comments highlighting important conventions (e.g., '// DB int → boolean', '// throws on error — service wraps in Result'). 4) If the pattern involves a boundary between layers, show both sides. 5) Identify any repeatable workflows for adding new elements to this layer — backend entities (repositories, services, controllers) AND frontend elements (components, services, pages/routes, directives). For example: creating a new repository requires extending BaseRepository + registering in factory; adding a new Angular component requires extending BaseComponent + adding to routes + creating the template. Return these as step-by-step checklists. Return patterns with full code block examples."
87
+
88
+ - Spawn 1 analyzer + 1 pattern finder per folder, all in parallel
89
+ - For the root CLAUDE.md, use findings from ALL folders to create the overview
90
+
91
+ 5. **Wait for Pass 2 and synthesize:**
92
+ - IMPORTANT: Wait for ALL agents from Pass 2 to complete before proceeding
93
+ - Compile all agent findings per folder
94
+ - **Do NOT draft CLAUDE.md content yet** — proceed to developer checkpoint first (Step 6)
95
+
96
+ 6. **Developer checkpoint — validate findings before drafting:**
97
+
98
+ Present a per-folder findings summary, then ask grounded questions. This pulls domain knowledge that agents can't discover from code alone — deprecated patterns, undocumented conventions, migration-in-progress situations, or cross-layer rules that only the developer knows.
99
+
100
+ **Findings summary** — one block per target folder, 2-3 lines each:
101
+ ```
102
+ ## Findings Summary
103
+
104
+ ### src/core/
105
+ Patterns: Repository base class, Entity base with soft-delete, Value Objects
106
+ Dependencies: Database layer (outbound), Services layer (inbound)
107
+ Workflows detected: "Add new entity" (5 steps), "Add new value object" (2 steps)
108
+
109
+ ### src/services/
110
+ Patterns: Result<T> wrapping, Transaction scope per operation
111
+ Dependencies: Core (outbound), Controllers (inbound)
112
+ Workflows detected: "Add new service" (4 steps)
113
+
114
+ [etc.]
115
+ ```
116
+
117
+ Then ask grounded questions — **one at a time**, waiting for the developer's answer before asking the next. Ask as many as the findings warrant — one per significant ambiguity or discovery gap. Use a **❓ Question:** prefix. Each question must reference real findings and pull NEW information from the developer — not confirm what you already found, and not ask about cosmetic issues (typos, formatting) or absences the developer can't add context to.
118
+
119
+ Only ask questions whose answer would change what gets written in a CLAUDE.md file. Focus on:
120
+ - Competing patterns that need a canonical vs. legacy designation (which style should new code follow?)
121
+ - Cross-layer dependencies that look like violations but might be design decisions
122
+ - Undocumented architectural constraints not visible in code (ordering, idempotency, invariants)
123
+
124
+ Example grounded questions:
125
+ - "Found two different mapping approaches in `src/services/`: manual mapping in `OrderService` and AutoMapper in `UserService`. Which is the current convention, or is there a migration in progress I should document?"
126
+ - "The analyzer found no event/message patterns in `src/core/`. Is domain event publishing handled elsewhere, or is it not used in this project?"
127
+ - "Detected 3 different error-handling styles across layers. Is there a canonical approach, or are these intentional per-layer differences?"
128
+
129
+ **CRITICAL**: Ask ONE question at a time. Wait for the answer before asking the next. Lead with your most significant finding. The developer will redirect you if needed.
130
+
131
+ **Choosing question format:**
132
+
133
+ - **`ask_user_question` tool** — when your question has 2-4 concrete options from code analysis (pattern conflicts, integration choices, scope boundaries, priority overrides). The user can always pick "Other" for free-text. Example: Use the `ask_user_question` tool with the question "Found 2 mapping approaches — which should new code follow?". Options: "Manual mapping (Recommended)" (Used in OrderService (src/services/OrderService.ts:45) — 8 occurrences); "AutoMapper" (Used in UserService (src/services/UserService.ts:12) — 2 occurrences).
134
+
135
+ - **Free-text with ❓ Question: prefix** — when the question is open-ended and options can't be predicted (discovery, "what am I missing?", corrections). Example:
136
+ "❓ Question: Integration scanner found no background job registration for this area. Is that expected, or is there async processing I'm not seeing?"
137
+
138
+ **Batching**: When you have 2-4 independent questions (answers don't depend on each other), you MAY batch them in a single `ask_user_question` call. Keep dependent questions sequential.
139
+
140
+ **Incorporate developer input:**
141
+
142
+ **Corrections** ("that pattern is deprecated", "wrong — we use X"):
143
+ - Update synthesis. If the correction reveals a pattern that needs fresh analysis, re-prompt a targeted **codebase-analyzer** or **codebase-pattern-finder** (max 2 agents).
144
+
145
+ **Missing conventions** ("you missed the soft-delete convention", "all handlers must be idempotent"):
146
+ - Add directly to synthesis for the relevant folder.
147
+
148
+ **Migration context** ("we're moving from X to Y", "old pattern in these files, new pattern in those"):
149
+ - Record both old and new approaches in synthesis — CLAUDE.md should document the canonical (new) way with a note about the legacy approach still present in specific areas.
150
+
151
+ **Scope adjustments** ("skip that layer, it's being rewritten", "add src/shared/"):
152
+ - Update target list. For new targets, run a targeted Pass 2 (analyzer + pattern-finder, max 2 agents), then fold results into synthesis.
153
+
154
+ **Confirmations** ("looks right", "yes that's correct"):
155
+ - Proceed to drafting.
156
+
157
+ After incorporating all input, proceed to Step 7.
158
+
159
+ 7. **Draft CLAUDE.md content:**
160
+ - Draft CLAUDE.md content in this order — **subfolder files first, root last**:
161
+ - Subfolder: Use the **Subfolder CLAUDE.md Template** (detailed, max 100 lines)
162
+ - Root folder (LAST): Use the **Root CLAUDE.md Template** (compact overview). Draft root only after all subfolder files are finalized — this ensures the deduplication rule can be applied and cross-layer checklists can accurately reference subfolder content
163
+ - Enforce the 100-line limit on subfolder files — code examples are essential but keep them concise
164
+ - If the pattern-finder identified repeatable "add new entity" workflows, include them as `<important if="you are adding a new [entity] to this layer">` conditional sections
165
+ - If testing patterns were detected, include them as `<important if="you are writing or modifying tests for this layer">` conditional sections
166
+ - Conditional sections are optional — only include when the pattern-finder found clear evidence of a repeatable workflow
167
+ - Conditions must be narrow and action-specific (NOT "you are writing code" — too broad)
168
+ - Do NOT include conventions enforceable by linters, formatters, or pre-commit hooks (e.g., naming conventions, import ordering, indentation) — these add noise without value
169
+ - Do NOT include patterns easily discoverable from existing code — LLMs are in-context learners and will follow patterns after a few file reads. Only document conventions that are surprising, non-obvious, or span multiple layers
170
+ - If a pattern section would contain only prose or comments with no code example, either expand it with a real idiomatic example or omit it and reference the source file (e.g., "see `BaseModalComponent` for the modal pattern")
171
+ - Before writing, verify: no root conditional block duplicates content from a subfolder CLAUDE.md. If a layer has its own subfolder file, remove its summary from root
172
+ - For cross-layer vertical-slice checklists in root, each step should reference the relevant subfolder CLAUDE.md ("see Data layer CLAUDE.md") rather than inlining the full procedure
173
+ - If an existing root CLAUDE.md was found:
174
+ - Review its content
175
+ - Redistribute any detailed layer-specific content to the appropriate subfolder CLAUDE.md files
176
+ - Rewrite the root as a compact overview
177
+
178
+ 8. **Self-review pass — verify every drafted file before writing:**
179
+ Walk through each drafted CLAUDE.md and check every item below. Fix violations in-place before proceeding to writing.
180
+
181
+ **Dependencies** — for each listed dependency, ask: "does this library impose patterns, constraints, or conventions on the code?" If the answer is no (utility libraries like lodash, moment, xlsx, FontAwesome), remove it. Only frameworks and libraries that shape how you write code survive.
182
+
183
+ **Module Structure** — count top-level entries. If more than 7, group related directories on one line (e.g., `guards/, interceptors/, pipes/ — cross-cutting plumbing`). Target 4-7 entries.
184
+
185
+ **Pattern sections** — every pattern H2 must contain a fenced code block with an idiomatic example. If a section is prose-only or comment-only, either expand it with a real code example or replace the section with a one-line file reference (e.g., "see `TradeDeskMapping.cs` for the mapping pattern").
186
+
187
+ **Root deduplication** — for each root conditional block, verify it is NOT summarizing a layer that has its own subfolder CLAUDE.md. If it is, remove the block. For cross-layer vertical-slice checklists, verify each step references the relevant subfolder file ("see X CLAUDE.md") rather than inlining the procedure.
188
+
189
+ **Frontend/UI conditional coverage** — for each frontend/UI layer, list every repeatable workflow the pattern-finder reported (components, services, pages/routes, directives, pipes, hooks, stores — whatever was detected). Then compare that list against the drafted `<important if>` conditional sections. Any workflow on the list without a matching conditional is a gap — draft and add the missing section before proceeding.
190
+
191
+ After fixing all violations, re-scan the corrected drafts to confirm every check passes. Only proceed to writing when all checks are clean. Present a brief summary of what was fixed:
192
+ ```
193
+ ## Self-review results
194
+ - [file]: removed 2 utility deps (moment, xlsx-js-style)
195
+ - [file]: grouped Module Structure from 11 → 6 entries
196
+ - [file]: added "Adding a New Service" conditional
197
+ - Root: no violations found
198
+ ```
199
+
200
+ 9. **Pass 3 — Write all CLAUDE.md files:**
201
+ - Write ALL files at once using the Write tool
202
+ - Do NOT ask for confirmation before each file — batch mode
203
+ - After writing, present a summary:
204
+ ```
205
+ ## CLAUDE.md Files Created
206
+
207
+ | File | Lines | Description |
208
+ |------|-------|-------------|
209
+ | CLAUDE.md | 45 | Root project overview |
210
+ | src/core/CLAUDE.md | 78 | Core domain layer |
211
+ | src/services/CLAUDE.md | 65 | Service layer |
212
+ | [etc.] | | |
213
+
214
+ Total: [N] files created/updated
215
+
216
+ Please review the files and let me know if you'd like any adjustments.
217
+ ```
218
+
219
+ 10. **Handle follow-up adjustments:**
220
+ - If the user requests changes to specific files, edit them directly using the Edit tool
221
+ - If the user wants additional folders annotated, run a targeted Pass 2 (analyzer + pattern finder) for those folders, then write
222
+ - If the user wants a file removed, note that they can delete it themselves
223
+
224
+ ## Root CLAUDE.md Template (compact):
225
+
226
+ Read the full template at `templates/root-claude-md.md`.
227
+
228
+ Key principles:
229
+ - Bare sections (Overview, Architecture, Commands, Business Context) are foundational — always included
230
+ - Cross-cutting patterns go in `<important if>` blocks with narrow conditions
231
+ - Deduplication rule: if a layer has a subfolder CLAUDE.md, don't summarize it in root
232
+ - Root MAY include cross-layer vertical-slice checklists referencing subfolder files
233
+
234
+ ### Root CLAUDE.md Reference Examples
235
+
236
+ See `examples/root-nodejs-monorepo.md` (Node.js monorepo) and `examples/root-dotnet-clean-arch.md` (.NET Clean Architecture) for well-formed root CLAUDE.md examples.
237
+
238
+ What makes these examples good:
239
+ - **Bare sections** (Overview, Project map, Commands) are relevant to nearly every task — no wrapper needed
240
+ - **Each `<important if>` has a narrow trigger** — "adding a new API endpoint" not "writing backend code"
241
+ - **No linter territory** — formatting rules left to tooling
242
+ - **No code snippets** — uses file path references since patterns are better shown in subfolder CLAUDE.md files
243
+ - **Same structure, different ecosystems** — the pattern works identically for Node.js and .NET
244
+
245
+ ## Subfolder CLAUDE.md Template (max 100 lines):
246
+
247
+ Read the full template at `templates/subfolder-claude-md.md`.
248
+
249
+ Key principles:
250
+ - Each distinct pattern gets its own H2 section with a fenced code block
251
+ - Module Structure: aim for 4-7 top-level entries, use architectural annotations
252
+ - Conditional sections (`<important if>`) are optional — only for detected repeatable workflows
253
+ - Conditional sections do NOT count toward the 100-line budget
254
+
255
+ ### Reference Examples
256
+
257
+ See the following for well-formed subfolder CLAUDE.md examples:
258
+ - `examples/subfolder-database-layer.md` — Database layer (~80 lines)
259
+ - `examples/subfolder-schemas-layer.md` — Schemas layer (~70 lines)
260
+ - `examples/subfolder-dotnet-application.md` — .NET Application layer (~65 lines)
261
+
262
+ ### What makes these examples good:
263
+ - **Module Structure**: Compact, uses architectural annotations, groups related files on one line
264
+ - **Patterns as H2 sections**: Each pattern has a descriptive name, NOT a generic umbrella
265
+ - **Code examples are idiomatic**: Generalized to show the pattern's shape
266
+ - **Cross-boundary patterns**: Shows both sides of layer boundaries
267
+ - **Concise**: All fit well within 100 lines
268
+ - **Conditional blocks**: Wrap scenario-specific recipes with narrow conditions
269
+
270
+ ## CLAUDE.md Depth Rules:
271
+
272
+ **CREATE CLAUDE.md when:**
273
+ - Folder represents a distinct **architectural layer** (core, services, database, redis, ipc)
274
+ - Folder contains **unique organizational logic** not captured by parent
275
+ - Subfolder has **different patterns/constraints** than parent (e.g., `database/repositories/` vs `database/`)
276
+ - Folder has **its own responsibility** (e.g., `database/migrations/`)
277
+ - Folder is a **composite application root** (e.g., SPA, monorepo package) whose children represent distinct sub-layers with different patterns — apply Depth Rules recursively to its children
278
+
279
+ **SKIP CLAUDE.md when:**
280
+ - Folder only groups entities/DTOs by domain boundary following the same pattern
281
+ - Folder content is fully described by parent CLAUDE.md
282
+ - Folder is a simple grouping without unique constraints
283
+
284
+ ## Important notes:
285
+ - Always use parallel Agent tool calls to maximize efficiency and minimize context usage
286
+ - **File reading**: Always read mentioned files FULLY (no limit/offset) before invoking skills
287
+ - **Critical ordering**: Follow the numbered steps exactly
288
+ - ALWAYS read mentioned files first before invoking skills (step 1)
289
+ - ALWAYS wait for all skills in a pass to complete before proceeding to the next step
290
+ - NEVER write CLAUDE.md files with placeholder values — all content must come from skill findings
291
+ - NEVER proceed to Pass 2 without user confirmation of target locations
292
+ - NEVER skip the developer checkpoint (step 6) — developer input is the highest-value signal for CLAUDE.md quality
293
+ - NEVER draft CLAUDE.md content before completing the developer checkpoint
294
+ - **.gitignore compliance**: Skip directories excluded by .gitignore (node_modules, dist, build, .git, vendor, etc.)
295
+ - **Batch output mode**: Write all CLAUDE.md files at once in Pass 3, do not ask for per-file confirmation
296
+ - **Existing CLAUDE.md handling**: If a CLAUDE.md already exists at any target location, replace it entirely using the Write tool
297
+ - **Line budget**: Subfolder CLAUDE.md files must not exceed 100 lines — code examples in Key Patterns are mandatory, keep them idiomatic and concise
298
+ - **No frontmatter**: CLAUDE.md files are pure markdown, no YAML frontmatter
299
+ - Keep the main agent focused on synthesis, not deep file reading — delegate analysis to sub-agents
@@ -0,0 +1,38 @@
1
+ # CLAUDE.md
2
+
3
+ ASP.NET Core 8 Web API with Clean Architecture (CQRS + MediatR).
4
+
5
+ ## Project map
6
+
7
+ - `src/Api/` - ASP.NET Core controllers, middleware, DI setup
8
+ - `src/Application/` - MediatR handlers, validators, DTOs
9
+ - `src/Domain/` - Entities, value objects, domain events
10
+ - `src/Infrastructure/` - EF Core, external services, file storage
11
+ - `tests/` - Unit and integration tests
12
+
13
+ ## Commands
14
+
15
+ | Command | What it does |
16
+ |---|---|
17
+ | `dotnet build` | Build solution |
18
+ | `dotnet test` | Run all tests |
19
+ | `dotnet run --project src/Api` | Start API locally |
20
+ | `dotnet ef migrations add <Name> -p src/Infrastructure` | Create EF migration |
21
+ | `dotnet ef database update -p src/Infrastructure` | Apply migrations |
22
+
23
+ <important if="you are adding a new API endpoint">
24
+ - Add controller in `Api/Controllers/` inheriting `BaseApiController`
25
+ - Add command/query + handler + validator in `Application/Features/`
26
+ - See `Application/Features/Orders/Commands/CreateOrder/` for the pattern
27
+ </important>
28
+
29
+ <important if="you are adding or modifying EF Core migrations or database schema">
30
+ - Entities configured via `IEntityTypeConfiguration<T>` in `Infrastructure/Persistence/Configurations/`
31
+ - Always create a migration after schema changes — never modify existing migrations
32
+ </important>
33
+
34
+ <important if="you are writing or modifying tests">
35
+ - Unit tests: xUnit + NSubstitute, one test class per handler
36
+ - Integration tests: `WebApplicationFactory<Program>` with test database
37
+ - See `tests/Application.IntegrationTests/TestBase.cs` for setup
38
+ </important>