@dzhechkov/p-replicator 1.2.0 → 1.3.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.
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "@dzhechkov/p-replicator",
3
- "version": "1.2.0",
4
- "description": "P-Replicator — Claude Code toolkit for AI-assisted product development (Vibe Coding). Full /replicate pipeline, 10 modular skills (165K+ chars), /harvest knowledge extraction, swarm agents, quality gates, cross-project learning.",
3
+ "version": "1.3.0",
4
+ "description": "P-Replicator — Claude Code toolkit for AI-assisted product development (Vibe Coding). Full /replicate pipeline, 10 modular skills (194K+ chars), /harvest knowledge extraction, swarm agents, quality gates, security patterns, cross-project learning.",
5
5
  "main": "src/cli.js",
6
6
  "bin": {
7
7
  "p-replicator": "bin/cli.js"
@@ -35,6 +35,8 @@
35
35
  "bdd",
36
36
  "invest",
37
37
  "smart",
38
+ "security",
39
+ "owasp",
38
40
  "documentation",
39
41
  "skill-pack",
40
42
  "modular-skills",
@@ -20,7 +20,7 @@ When executing skills during the pipeline:
20
20
  3. When a skill references `/mnt/user-data/uploads/` — read from `docs/` instead
21
21
  4. When a skill outputs to `/output/` — write to `docs/` or project root instead
22
22
  5. `goap-research` skill name maps to `goap-research-ed25519` in this repo
23
- 6. When a skill has `modules/` directory — read the module file referenced by the phase
23
+ 6. **CRITICAL:** When a skill has `modules/` directory — you MUST read the FULL module file for EVERY phase before executing it. SKILL.md is the orchestrator only — it contains summaries, NOT the actual generation logic. NEVER generate artifacts from SKILL.md summaries. In a real project, skipping `modules/04-generate-p1.md` caused 10+ artifacts to be silently omitted.
24
24
  7. See `.claude/rules/skill-interface-protocol.md` for full interface specification
25
25
 
26
26
  ## Modular Skills
@@ -28,6 +28,10 @@ When executing skills during the pipeline:
28
28
  Skills with `modules/` directories delegate phases to self-contained module files.
29
29
  Each module follows: INPUT → PROCESS → OUTPUT → QUALITY GATE interface.
30
30
 
31
+ **MANDATORY:** Before executing any modular skill phase, read the corresponding module file in full.
32
+ Module files contain the actual generation instructions, templates, and quality gates.
33
+ SKILL.md contains only summaries and orchestration logic — it is NOT sufficient for generation.
34
+
31
35
  Currently modularized skills:
32
36
  - `cc-toolkit-generator-enhanced` — 9 modules (6 core pipeline + 3 extensions)
33
37
  - `knowledge-extractor` — 4 modules (agent review → classify → decontextualize → integrate)
@@ -136,6 +136,49 @@ higher quality. They don't."
136
136
 
137
137
  ---
138
138
 
139
+ ## Security Review Checklist (Linus Mode — CRITICAL)
140
+
141
+ When reviewing code that handles authentication, authorization, data storage,
142
+ or external integrations, apply this checklist in addition to standard code quality:
143
+
144
+ ### OWASP Top 10 Quick Checks
145
+
146
+ | # | Vulnerability | What to Look For | Severity |
147
+ |---|--------------|-------------------|----------|
148
+ | A01 | Broken Access Control | Missing auth middleware, RLS bypass (pool.query vs dbClient), cross-tenant entity access without ownership check | CRITICAL |
149
+ | A02 | Cryptographic Failures | Weak JWT secrets with fallback defaults, hardcoded secrets, missing HMAC on webhooks | CRITICAL |
150
+ | A03 | Injection | SQL via string interpolation (SET LOCAL), template literals in queries, unsanitized user input in commands | CRITICAL |
151
+ | A04 | Insecure Design | Per-request stateful services (circuit breakers never trigger), missing rate limiting | HIGH |
152
+ | A05 | Security Misconfiguration | Same CORS policy across environments, verbose errors in production, missing security headers | HIGH |
153
+ | A07 | Auth Failures | No account lockout, weak password policy, session fixation | HIGH |
154
+ | A08 | Data Integrity | Unsigned webhook payloads, missing CSRF tokens, unvalidated redirects | HIGH |
155
+ | A09 | Logging Failures | No audit trail for auth events, PII in logs, missing failed-attempt logging | MEDIUM |
156
+
157
+ ### Multi-Tenant Security (if applicable)
158
+
159
+ - [ ] All DB queries use tenant-scoped connection, NOT shared pool
160
+ - [ ] SET LOCAL uses parameterized set_config(), NOT string interpolation
161
+ - [ ] Cross-entity references verify tenant ownership before operation
162
+ - [ ] Tenant isolation tested with cross-tenant attack scenarios
163
+
164
+ ### Secret Management
165
+
166
+ - [ ] All secrets validated at startup — missing = process.exit(1)
167
+ - [ ] No fallback defaults for security-critical secrets
168
+ - [ ] Secrets never appear in logs, error messages, or stack traces
169
+ - [ ] Environment-specific security posture (dev/staging/prod)
170
+
171
+ ### Webhook Security
172
+
173
+ - [ ] Every webhook endpoint verifies request signature/HMAC
174
+ - [ ] Unsigned payloads are rejected and logged
175
+ - [ ] Webhook secrets stored in environment variables
176
+
177
+ **Calibration:** Security violations ALWAYS trigger Level 3 (Brutal).
178
+ Security bugs are not "style issues" — they are negligence.
179
+
180
+ ---
181
+
139
182
  ## Assessment Rubrics
140
183
 
141
184
  ### Code Quality (Linus Mode)
@@ -18,6 +18,14 @@ description: >
18
18
  Three modes: AUTO, HYBRID (default), MANUAL.
19
19
  ---
20
20
 
21
+ > **CRITICAL MODULE LOADING REQUIREMENT:**
22
+ > This skill has 9 modules in `modules/`. SKILL.md is the orchestrator ONLY.
23
+ > You MUST read EVERY module file referenced in the Module Execution Protocol below
24
+ > before executing its phase. Skipping module files causes entire artifact categories
25
+ > to be silently omitted. In one real project, skipping `modules/04-generate-p1.md`
26
+ > caused 10+ P1 artifacts (agents, skills, commands) to be completely missing.
27
+ > NEVER generate artifacts from SKILL.md summaries alone — always read the full module.
28
+
21
29
  # CC-Toolkit-Generator Enhanced
22
30
 
23
31
  Generate production-ready Claude Code instruments from **SPARC or idea2prd-manual documentation**.
@@ -27,6 +27,12 @@ From the Instrument Map this module uses:
27
27
 
28
28
  ## Process
29
29
 
30
+ > **ANTI-COMPRESSION DIRECTIVE:** When generating files from templates in this module,
31
+ > COPY the FULL text of each template. Do NOT summarize, compress, or "interpret" templates.
32
+ > Every section, every placeholder, every comment must be preserved verbatim.
33
+ > AI systems routinely compress 211-line templates to 60 lines — this is a CRITICAL defect.
34
+ > Validate: generated file line count must be >= 80% of template line count.
35
+
30
36
  ### P0 Mandatory Items (always generated)
31
37
 
32
38
  The following 16 items are generated for every project, regardless of pipeline
@@ -37,6 +43,7 @@ type or user mode.
37
43
  #### Item 1: CLAUDE.md
38
44
 
39
45
  **Template:** `view() references/claude-md-strategy.md`
46
+ > CRITICAL: COPY the full template. Do NOT compress or summarize.
40
47
 
41
48
  The project's root context file. Generation strategy differs by pipeline:
42
49
 
@@ -154,6 +161,39 @@ Generate `.claude/rules/coding-style.md` containing:
154
161
  - Code organization patterns
155
162
  - IF idea2prd: DDD tactical patterns (aggregate rules, entity identity, VO immutability)
156
163
 
164
+ **Known Gotchas section (always include):**
165
+
166
+ Add a `## Known Gotchas` section to coding-style.md with language/framework-specific
167
+ pitfalls extracted from harvest insights. Include at minimum:
168
+
169
+ ```markdown
170
+ ## Known Gotchas
171
+
172
+ ### TypeScript / JavaScript
173
+ - `\w` in regex does NOT match Cyrillic or other non-Latin characters.
174
+ Use `\p{L}` with `/u` flag or explicit character classes for Unicode text.
175
+ - Direct type casting `req as CustomType` fails with TS2352. Use double-cast
176
+ via `unknown`: `(req as unknown as CustomType)`. Better: use generic route handlers.
177
+ - Jest `coverageThreshold` (singular) silently fails if spelled `coverageThresholds` (plural).
178
+ Per-directory thresholds require a `global` key. ts-jest needs `ts-node` as peer dependency.
179
+ - `jest.fn(async () => value)` doesn't satisfy `jest.Mocked<T>` in strict mode.
180
+ Use `jest.fn().mockResolvedValue(value)` or `jest.fn().mockImplementation(...)`.
181
+ - Opossum `CircuitBreaker.fire()` returns `Promise<unknown>`, requires explicit cast.
182
+ Both `@types/opossum` and `opossum` packages are needed.
183
+ - Socket.io `Server` has no `.toRoom()` method. Wrap it:
184
+ `{ toRoom: (room) => io.to(room) }` for hexagonal architecture ports.
185
+
186
+ ### Infrastructure
187
+ - Services with circuit breakers/rate limiters MUST be singletons.
188
+ Per-request instances bypass protection (breaker never accumulates failures).
189
+ - `SET LOCAL` in PostgreSQL only affects the current transaction on the current connection.
190
+ Use parameterized `set_config()` instead of string interpolation.
191
+ ```
192
+
193
+ Adapt gotchas to the specific tech stack detected in IPM. Remove irrelevant entries
194
+ (e.g., no TypeScript gotchas for Python projects). Add stack-specific gotchas from
195
+ `view() references/security-patterns-library.md` if applicable.
196
+
157
197
  **Output path:** `.claude/rules/coding-style.md`
158
198
 
159
199
  ---
@@ -161,6 +201,7 @@ Generate `.claude/rules/coding-style.md` containing:
161
201
  #### Item 4: /start command
162
202
 
163
203
  **Template:** `view() references/templates/start-command.md`
204
+ > CRITICAL: COPY the full template. Do NOT compress or summarize.
164
205
 
165
206
  Generate `.claude/commands/start.md` -- the full project bootstrap command.
166
207
 
@@ -189,6 +230,7 @@ code from memory. Every Phase 2 Task includes explicit doc references.
189
230
  #### Item 5: /myinsights command
190
231
 
191
232
  **Template:** `view() references/templates/insights-system.md` (Section 1)
233
+ > CRITICAL: COPY the full template. Do NOT compress or summarize.
192
234
 
193
235
  Generate `.claude/commands/myinsights.md` -- the insight capture and management
194
236
  command with:
@@ -207,6 +249,7 @@ command with:
207
249
  #### Item 6: /feature command
208
250
 
209
251
  **Template:** `view() references/templates/feature-lifecycle.md` (Section 2)
252
+ > CRITICAL: COPY the full template. Do NOT compress or summarize.
210
253
 
211
254
  Generate `.claude/commands/feature.md` -- the 4-phase feature lifecycle command:
212
255
 
@@ -278,6 +321,7 @@ type(scope): description
278
321
  #### Item 8: insights-capture.md rule
279
322
 
280
323
  **Template:** `view() references/templates/insights-system.md` (Section 2)
324
+ > CRITICAL: COPY the full template. Do NOT compress or summarize.
281
325
 
282
326
  Generate `.claude/rules/insights-capture.md` with:
283
327
  - Error-First Lookup protocol (grep index BEFORE debugging)
@@ -293,6 +337,7 @@ Generate `.claude/rules/insights-capture.md` with:
293
337
  #### Item 9: feature-lifecycle.md rule
294
338
 
295
339
  **Template:** `view() references/templates/feature-lifecycle.md` (Section 3)
340
+ > CRITICAL: COPY the full template. Do NOT compress or summarize.
296
341
 
297
342
  Generate `.claude/rules/feature-lifecycle.md` with:
298
343
  - Protocol definition (4-phase lifecycle)
@@ -310,6 +355,7 @@ Generate `.claude/rules/feature-lifecycle.md` with:
310
355
  #### Item 10: settings.json hooks
311
356
 
312
357
  **Template:** `view() references/templates/insights-system.md` (Section 3 -- Stop hook)
358
+ > CRITICAL: COPY the full template. Do NOT compress or summarize.
313
359
 
314
360
  Generate `.claude/settings.json` with hook configuration:
315
361
 
@@ -19,6 +19,12 @@ engine and conditionally included based on project characteristics and document
19
19
 
20
20
  ## Process
21
21
 
22
+ > **ANTI-COMPRESSION DIRECTIVE:** When generating files from templates in this module,
23
+ > COPY the FULL text of each template. Do NOT summarize, compress, or "interpret" templates.
24
+ > Every section, every placeholder, every comment must be preserved verbatim.
25
+ > AI systems routinely compress 211-line templates to 60 lines — this is a CRITICAL defect.
26
+ > Validate: generated file line count must be >= 80% of template line count.
27
+
22
28
  ### Step 1: Filter P1 Candidates
23
29
 
24
30
  Select all instruments assigned tier P1 from the Instrument Map (score >= 12 after tier boosts).
@@ -208,6 +214,7 @@ Generate .claude/rules/testing.md:
208
214
  **Trigger:** `IPM.has_ddd == true`
209
215
 
210
216
  Read complete template: `view("references/templates/feature-lifecycle-ent.md")`
217
+ > CRITICAL: COPY the full template. Do NOT compress or summarize.
211
218
 
212
219
  ```
213
220
  IF has_ddd:
@@ -254,6 +261,7 @@ IF has_ddd:
254
261
  **Trigger:** Always generated for P1 (enhances developer workflow regardless of pipeline).
255
262
 
256
263
  Read complete template: `view("references/templates/feature-suggestions.md")`
264
+ > CRITICAL: COPY the full template. Do NOT compress or summarize.
257
265
 
258
266
  ```
259
267
  7a. Generate .claude/feature-roadmap.json
@@ -305,6 +313,7 @@ Read complete template: `view("references/templates/feature-suggestions.md")`
305
313
  **Trigger:** Always generated for P1 (provides autonomous execution capabilities).
306
314
 
307
315
  Read complete template: `view("references/templates/automation-commands.md")`
316
+ > CRITICAL: COPY the full template. Do NOT compress or summarize.
308
317
 
309
318
  ```
310
319
  8a. Generate .claude/commands/go.md
@@ -22,6 +22,12 @@ when DDD documentation is detected.
22
22
 
23
23
  ## Process
24
24
 
25
+ > **ANTI-COMPRESSION DIRECTIVE:** When generating files from templates in this module,
26
+ > COPY the FULL text of each template. Do NOT summarize, compress, or "interpret" templates.
27
+ > Every section, every placeholder, every comment must be preserved verbatim.
28
+ > AI systems routinely compress 211-line templates to 60 lines — this is a CRITICAL defect.
29
+ > Validate: generated file line count must be >= 80% of template line count.
30
+
25
31
  ### Tier Overview
26
32
 
27
33
  ```
@@ -41,6 +47,7 @@ P3 — External Integrations:
41
47
  Source: Pseudocode (SPARC/idea2prd) + Gherkin tests (idea2prd) + Fitness Functions (idea2prd)
42
48
 
43
49
  Read template: `view("references/templates/ddd-agents.md")` section "tdd-guide.md Agent (Enhanced)"
50
+ > CRITICAL: COPY the full template. Do NOT compress or summarize.
44
51
 
45
52
  ```
46
53
  Generate .claude/agents/tdd-guide.md:
@@ -156,6 +163,7 @@ skip this entire step.
156
163
  Source: DDD Tactical (aggregates) + Fitness Functions
157
164
 
158
165
  Read template: `view("references/templates/ddd-agents.md")` section "ddd-validator.md Agent"
166
+ > CRITICAL: COPY the full template. Do NOT compress or summarize.
159
167
 
160
168
  ```
161
169
  IF has_ddd:
@@ -191,6 +199,7 @@ IF has_ddd:
191
199
  Source: DDD Tactical (aggregates, entities, value-objects)
192
200
 
193
201
  Read template: `view("references/templates/ddd-skills.md")` section "aggregate-patterns/ Skill"
202
+ > CRITICAL: COPY the full template. Do NOT compress or summarize.
194
203
 
195
204
  ```
196
205
  IF has_ddd:
@@ -213,6 +222,7 @@ IF has_ddd:
213
222
  Source: DDD Tactical (events)
214
223
 
215
224
  Read template: `view("references/templates/ddd-skills.md")` section "event-handlers/ Skill"
225
+ > CRITICAL: COPY the full template. Do NOT compress or summarize.
216
226
 
217
227
  ```
218
228
  IF has_ddd:
@@ -284,6 +294,7 @@ IF has_ddd AND has_fitness:
284
294
  ### Step 3: Generate P3 Items — MCP Configuration
285
295
 
286
296
  Read complete template: `view("references/templates/mcp.md")`
297
+ > CRITICAL: COPY the full template. Do NOT compress or summarize.
287
298
 
288
299
  ```
289
300
  Generate .mcp.json in project root:
@@ -216,6 +216,52 @@ CHECK 20: P3 MCP (IF external integrations detected)
216
216
  [ ] INSTALL.md documents all required env vars from .mcp.json
217
217
  ```
218
218
 
219
+ ### Step 1.5: Automated File-Existence Validation
220
+
221
+ Before proceeding to placeholder scanning, run an automated file-existence check
222
+ against the expected output manifest. This catches the most common generation failure:
223
+ files that should exist but were silently omitted (often due to skipping module files).
224
+
225
+ ```
226
+ AUTOMATED FILE CHECK PROTOCOL:
227
+
228
+ Step 1: Build expected file list from Instrument Map tiers:
229
+ - P0 mandatory: 16 items (always expected)
230
+ - P0 conditional: check IPM flags before expecting
231
+ - P1 core: 10 items (if P1 was executed)
232
+ - P1 conditional: check IPM flags
233
+ - P2/P3: check flags and execution status
234
+
235
+ Step 2: For each expected file, run existence check:
236
+ for file in expected_files:
237
+ if not exists(file.path):
238
+ log CRITICAL: "Missing file: {file.path} (expected from {file.phase})"
239
+ missing_count++
240
+
241
+ Step 3: For each expected directory, verify SKILL.md exists inside:
242
+ for skill_dir in expected_skill_directories:
243
+ if not exists(skill_dir + "/SKILL.md"):
244
+ log CRITICAL: "Missing SKILL.md in {skill_dir}"
245
+ missing_count++
246
+
247
+ Step 4: Verify file sizes (anti-compression check):
248
+ for file in generated_files:
249
+ if file.size_bytes < 100:
250
+ log WARNING: "Suspiciously small file: {file.path} ({file.size_bytes} bytes)"
251
+ log WARNING: "Possible template compression — verify content completeness"
252
+
253
+ Step 5: Report
254
+ if missing_count > 0:
255
+ CRITICAL FAILURE: {missing_count} expected files are missing.
256
+ List each missing file with its expected source phase/module.
257
+ Attempt auto-fix by re-reading the relevant module and regenerating.
258
+ else:
259
+ PASS: All {total_count} expected files exist.
260
+ ```
261
+
262
+ This step was added based on a real-project insight where skipping `modules/04-generate-p1.md`
263
+ caused 10+ P1 artifacts to be silently omitted without any error in the final report.
264
+
219
265
  ### Step 2: Verify Placeholder Substitution
220
266
 
221
267
  Scan ALL generated files for unsubstituted placeholders:
@@ -0,0 +1,196 @@
1
+ # Security Patterns Library
2
+
3
+ Reference library of security patterns extracted from real-project harvest insights.
4
+ Used by toolkit generator modules (03, 04, 05) when generating security.md rules,
5
+ secrets-management.md, security-patterns/ skill, and code-reviewer agent.
6
+
7
+ ## Critical Patterns (Must-Have for Multi-Tenant Systems)
8
+
9
+ ### S-01: RLS Bypass Prevention — Pool vs Client Query
10
+
11
+ **Problem:** Tenant middleware sets `app.tenant_id` via `SET LOCAL` on a dedicated
12
+ PoolClient (`req.dbClient`), but repositories use `pool.query()` (shared pool).
13
+ The query runs on a different connection without tenant context — RLS is bypassed.
14
+
15
+ **Pattern:**
16
+ ```
17
+ RULE: NEVER use pool.query() in multi-tenant systems with RLS.
18
+ ALWAYS pass the tenant-scoped dbClient from middleware through service layer to repository.
19
+ Every database query MUST use the same connection where SET LOCAL was executed.
20
+ ```
21
+
22
+ **Detection:** Search for `pool.query()` in repository files when RLS is enabled.
23
+
24
+ **Generated Rule (security.md):**
25
+ ```markdown
26
+ - Multi-tenant RLS: All database queries MUST use tenant-scoped connection (req.dbClient),
27
+ NEVER the shared pool. Verify by grepping for pool.query() — any hit is a security bug.
28
+ ```
29
+
30
+ ---
31
+
32
+ ### S-02: SQL Injection via SET LOCAL
33
+
34
+ **Problem:** String interpolation in `SET LOCAL app.tenant_id = '${tenantId}'`
35
+ is an SQL injection vector even with UUID validation.
36
+
37
+ **Pattern:**
38
+ ```
39
+ RULE: NEVER use string interpolation for SET LOCAL.
40
+ ALWAYS use parameterized set_config():
41
+ SELECT set_config('app.tenant_id', $1, true)
42
+ ```
43
+
44
+ **Detection:** Search for `SET LOCAL` with template literals or string concatenation.
45
+
46
+ **Generated Rule (security.md):**
47
+ ```markdown
48
+ - Parameterized config: Use `set_config('key', $1, true)` instead of
49
+ `SET LOCAL key = '${value}'`. Applies to all session-level config.
50
+ ```
51
+
52
+ ---
53
+
54
+ ### S-03: Fail-Fast Secret Validation at Startup
55
+
56
+ **Problem:** Service A falls back to `'dev-secret-change-me'` when JWT_SECRET is
57
+ missing, while Service B uses `process.env.JWT_SECRET!`. Creates split-brain:
58
+ signing uses weak fallback, verification uses undefined.
59
+
60
+ **Pattern:**
61
+ ```
62
+ RULE: NEVER provide fallback values for security-critical secrets.
63
+ ALWAYS validate at startup and exit with process.exit(1) if missing or too short.
64
+
65
+ Required checks:
66
+ - JWT_SECRET: exists AND length >= 32 characters
67
+ - DATABASE_URL: exists AND not localhost in production
68
+ - API keys: exist AND not placeholder values
69
+ ```
70
+
71
+ **Generated Rule (security.md):**
72
+ ```markdown
73
+ - Startup secret guard: All security secrets (JWT_SECRET, API keys, encryption keys)
74
+ MUST be validated at application startup. Missing or weak secrets MUST cause
75
+ immediate process.exit(1). NEVER use fallback defaults for secrets.
76
+ ```
77
+
78
+ ---
79
+
80
+ ### S-04: Cross-Tenant Entity Ownership
81
+
82
+ **Problem:** API endpoint accepts an entity ID (e.g., operatorId) without
83
+ verifying that the entity belongs to the requesting tenant. RLS on the target
84
+ table may not cover this cross-reference.
85
+
86
+ **Pattern:**
87
+ ```
88
+ RULE: Before using any entity ID from request params in a cross-table operation,
89
+ verify the entity belongs to the same tenant:
90
+ 1. Load entity by ID
91
+ 2. Check entity.tenantId === request.tenantId
92
+ 3. Return 403 if mismatch
93
+ ```
94
+
95
+ **Generated Rule (security.md):**
96
+ ```markdown
97
+ - Cross-tenant ownership: When an API accepts entity IDs (operatorId, userId, etc.),
98
+ ALWAYS verify entity.tenantId matches the requesting tenant before any operation.
99
+ RLS alone may not protect cross-table references.
100
+ ```
101
+
102
+ ---
103
+
104
+ ### S-05: Webhook Signature Verification
105
+
106
+ **Problem:** Webhook endpoints accept any POST without HMAC/signature verification.
107
+ Attackers can inject fake messages if webhook URLs are discovered.
108
+
109
+ **Pattern:**
110
+ ```
111
+ RULE: Every webhook endpoint MUST verify the request signature:
112
+ - Telegram: verify X-Telegram-Bot-Api-Secret-Token header
113
+ - Stripe: verify Stripe-Signature header with webhook secret
114
+ - GitHub: verify X-Hub-Signature-256 header
115
+ - Generic: verify HMAC-SHA256 of body with shared secret
116
+ ```
117
+
118
+ **Generated Rule (security.md):**
119
+ ```markdown
120
+ - Webhook HMAC: Every webhook endpoint MUST verify request signature/HMAC.
121
+ NEVER accept unsigned webhook requests. Log and reject unsigned payloads.
122
+ ```
123
+
124
+ ---
125
+
126
+ ## High-Priority Patterns
127
+
128
+ ### S-06: Singleton Service Instances
129
+
130
+ **Problem:** Creating service instances per-request (e.g., `Service.fromEnv()` in
131
+ route handler) means stateful components like circuit breakers never accumulate
132
+ failure state and never trigger protection.
133
+
134
+ **Pattern:**
135
+ ```
136
+ RULE: Services with stateful protection mechanisms (circuit breakers, rate limiters,
137
+ connection pools) MUST be created as singletons at application startup.
138
+ NEVER create per-request instances of stateful services.
139
+ ```
140
+
141
+ **Impact on Generated Code:**
142
+ - In architect.md agent: include singleton pattern for infrastructure services
143
+ - In coding-style.md rule: "stateful services are singletons, injected at startup"
144
+
145
+ ---
146
+
147
+ ### S-07: Environment-Specific Security Posture
148
+
149
+ **Pattern:**
150
+ ```
151
+ RULE: Security posture MUST match environment:
152
+ - Development: relaxed CORS, verbose errors, debug logging
153
+ - Staging: production-like security, sanitized test data
154
+ - Production: strict CORS, generic errors, structured logging only
155
+
156
+ NEVER: same security config across all environments
157
+ NEVER: expose stack traces in production error responses
158
+ ```
159
+
160
+ ---
161
+
162
+ ## Integration Patterns for Generated Toolkit
163
+
164
+ ### How Patterns Map to Generated Files
165
+
166
+ | Pattern | security.md | secrets-management.md | code-reviewer.md | architect.md |
167
+ |---------|------------|----------------------|-------------------|--------------|
168
+ | S-01 RLS Bypass | Rule | — | Check | Architecture note |
169
+ | S-02 SQL Injection | Rule | — | Check | — |
170
+ | S-03 Secret Validation | Rule | Primary content | Check | Startup validation |
171
+ | S-04 Cross-Tenant | Rule | — | Check | — |
172
+ | S-05 Webhook HMAC | Rule | Secret storage | Check | — |
173
+ | S-06 Singleton | — | — | Check | Architecture pattern |
174
+ | S-07 Env Security | Rule | Env-specific rules | — | Environment guide |
175
+
176
+ ### Usage in Module 03 (Generate P0)
177
+
178
+ When generating `security.md` rule (Item 2), include applicable patterns:
179
+ - IF multi-tenant detected: S-01, S-02, S-04
180
+ - IF has_external_apis: S-03, S-05
181
+ - IF has_database: S-01, S-02
182
+ - ALWAYS: S-03, S-07
183
+
184
+ ### Usage in Module 04 (Generate P1)
185
+
186
+ When generating `code-reviewer.md` agent (Step 2b), add security review checklist
187
+ from applicable patterns to the agent's review criteria.
188
+
189
+ When generating `architect.md` agent (Step 2c), include S-06 singleton pattern
190
+ and S-07 environment posture in architecture guidelines.
191
+
192
+ ### Usage in brutal-honesty-review
193
+
194
+ When reviewing code in Linus Mode, check for violations of all S-01 through S-07
195
+ patterns as CRITICAL findings. Security violations should always trigger
196
+ Level 3 (Brutal) calibration.
@@ -27,6 +27,13 @@ description: Intelligent feature implementation pipeline. Analyzes complexity an
27
27
  One-command feature implementation that automatically selects the right pipeline
28
28
  based on feature complexity, then executes it without manual confirmations.
29
29
 
30
+ > **PROCESS COMPLIANCE — BLOCKING RULES:**
31
+ > - MUST use /plan, /feature, or /feature-ent commands — NEVER launch raw Agent tools directly
32
+ > - MUST follow the skill chain: /next -> /go -> /plan|/feature|/feature-ent
33
+ > - FORBIDDEN: Bypassing the skill chain by spawning parallel agents without commands
34
+ > - FORBIDDEN: Batching multiple features into a single commit wave
35
+ > - CRITICAL: Each feature MUST get its own plan, validation, and commit sequence
36
+
30
37
  ## Step 1: Determine Target Feature
31
38
 
32
39
  IF $ARGUMENTS is provided:
@@ -186,6 +193,14 @@ description: Autonomous project build loop. Bootstraps project and implements fe
186
193
  End-to-end autonomous project build: bootstrap → implement features in loop → done.
187
194
  Combines `/start`, `/next`, and `/go` into a single continuous pipeline.
188
195
 
196
+ > **AUTONOMOUS EXECUTION — BLOCKING RULES:**
197
+ > - MUST execute features ONE AT A TIME through the full /go pipeline
198
+ > - MUST create 1 plan per feature, 1 validation per feature, 1 commit per feature
199
+ > - NEVER batch features into parallel waves without individual plans
200
+ > - NEVER skip the /next -> /go pipeline by launching raw implementation agents
201
+ > - CRITICAL: If a feature fails 3 times, skip it and log — NEVER retry indefinitely
202
+ > - MUST push state after each feature completion (independent commits)
203
+
189
204
  ## Step 0: Parse Scope
190
205
 
191
206
  ```
@@ -194,6 +194,44 @@ Proposed
194
194
  [What was rejected and why?]
195
195
  ```
196
196
 
197
+ ## Architecture Patterns
198
+
199
+ ### Singleton Services (Infrastructure)
200
+
201
+ Services with stateful protection mechanisms MUST be created as singletons at
202
+ application startup. NEVER create per-request instances of stateful services.
203
+
204
+ **Why:** Per-request instances of circuit breakers, rate limiters, or connection pools
205
+ bypass protection — the breaker never accumulates failure state and never opens.
206
+
207
+ **Pattern:**
208
+ ```
209
+ CORRECT:
210
+ const mcpService = MCPService.fromEnv() // at startup, once
211
+ app.use((req, res, next) => {
212
+ req.mcpService = mcpService // inject singleton
213
+ next()
214
+ })
215
+
216
+ WRONG:
217
+ app.get('/api', (req, res) => {
218
+ const mcpService = MCPService.fromEnv() // new instance per request!
219
+ // circuit breaker resets every request — never trips
220
+ })
221
+ ```
222
+
223
+ **Applies to:** circuit breakers, rate limiters, connection pools, MCP clients,
224
+ external service adapters, cache managers.
225
+
226
+ ### Security-by-Environment
227
+
228
+ Security posture MUST match environment:
229
+ - **Development:** relaxed CORS, verbose errors, debug logging
230
+ - **Staging:** production-like security, sanitized test data
231
+ - **Production:** strict CORS, generic errors, structured logging only
232
+
233
+ NEVER use the same security configuration across all environments.
234
+
197
235
  ## Fitness Functions
198
236
 
199
237
  {{ARCHITECTURE_FITNESS_FUNCTIONS}}
@@ -206,6 +244,7 @@ For architecture questions:
206
244
  - Explain bounded context impact
207
245
  - List trade-offs explicitly
208
246
  - Suggest ADR if recording needed
247
+ - Check singleton pattern for infrastructure services
209
248
  ```
210
249
 
211
250
  ---
@@ -65,6 +65,14 @@ description: Full feature lifecycle — from idea to reviewed implementation.
65
65
  Four-phase feature development lifecycle with quality gates between each phase.
66
66
  All documentation goes to `docs/features/<feature-name>/sparc/`.
67
67
 
68
+ > **SKILL CHAIN — BLOCKING RULES:**
69
+ > - MUST execute Phase 0 (pre-flight check) before ANY generation
70
+ > - MUST use sparc-prd-mini skill for planning — NEVER generate SPARC docs from memory
71
+ > - MUST use requirements-validator for validation — NEVER skip validation phase
72
+ > - MUST use brutal-honesty-review for review — NEVER self-review
73
+ > - FORBIDDEN: Skipping any phase without explicit user permission
74
+ > - CRITICAL: Each phase MUST complete and commit before the next phase starts
75
+
68
76
  ## Phase 0: PRE-FLIGHT CHECK
69
77
 
70
78
  Before starting, verify all required skills exist:
@@ -103,13 +103,37 @@ Always flag these terms and suggest specific replacements:
103
103
  - Add AC: "Given X, when Y, then Z within 200ms"
104
104
  ```
105
105
 
106
+ ### Security Acceptance Criteria (10% bonus weight)
107
+
108
+ When requirements involve authentication, data storage, external APIs, or multi-tenancy,
109
+ apply additional security validation:
110
+
111
+ | Criterion | Check | Red Flags |
112
+ |-----------|-------|-----------|
113
+ | Input Validation | All user inputs sanitized? | No validation mentioned, "trust client" |
114
+ | Authentication | Auth mechanism specified? | "users can access", no auth context |
115
+ | Authorization | Access control defined? | No role/permission model |
116
+ | Data Protection | Sensitive data handling specified? | PII without encryption rules |
117
+ | Multi-Tenant Isolation | Tenant boundary enforced? | Shared queries, no tenant context |
118
+ | Secret Management | Secrets externalized? | Hardcoded keys, fallback defaults |
119
+ | Webhook Security | Signature verification? | "Accept POST", no HMAC |
120
+
121
+ **Scoring Bonus:** +5 points if security criteria present and specific, +0 if not applicable,
122
+ -10 if security-relevant requirement lacks any security criteria (BLOCKED if score drops below 50).
123
+
124
+ **Security BDD Scenarios:** For security-relevant requirements, ALWAYS generate:
125
+ - Auth bypass attempt scenario
126
+ - Input injection scenario (SQL, XSS, command)
127
+ - Cross-tenant access attempt (if multi-tenant)
128
+ - Rate limiting / brute force scenario (if auth endpoint)
129
+
106
130
  ### BDD Scenario Generation
107
131
 
108
132
  For each requirement, generate scenarios covering:
109
133
  1. **Happy path** (1-2 scenarios) — Primary success flow
110
134
  2. **Error handling** (2-3 scenarios) — Validation, network, server errors
111
135
  3. **Edge cases** (1-2 scenarios) — Boundaries, concurrent access
112
- 4. **Security** (if applicable) — Auth, injection, rate limiting
136
+ 4. **Security** (1-3 scenarios) — Auth bypass, injection, cross-tenant, rate limiting
113
137
 
114
138
  See `references/bdd-patterns.md` for Gherkin templates and examples.
115
139