@dzhechkov/keysarium 1.3.0 → 1.5.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 (105) hide show
  1. package/README.md +70 -10
  2. package/bin/cli.js +0 -0
  3. package/package.json +5 -3
  4. package/src/utils.js +1 -1
  5. package/templates/.claude/commands/analyst-manual.md +38 -0
  6. package/templates/.claude/commands/brain-export.md +2 -0
  7. package/templates/.claude/commands/bto-benchmark.md +302 -0
  8. package/templates/.claude/commands/casarium.md +55 -4
  9. package/templates/.claude/commands/feature-adr.md +8 -0
  10. package/templates/.claude/commands/harvest.md +28 -46
  11. package/templates/.claude/rules/trust-tiers.md +6 -0
  12. package/templates/.claude/shards/feature-adr.shard.md +64 -10
  13. package/templates/.claude/shards/phase-ai-factory.shard.md +109 -0
  14. package/templates/.claude/skills/ai-factory-mapper/README.md +90 -0
  15. package/templates/.claude/skills/ai-factory-mapper/SKILL.md +309 -0
  16. package/templates/.claude/skills/ai-factory-mapper/assets/report-template.md +123 -0
  17. package/templates/.claude/skills/ai-factory-mapper/references/catalog.md +230 -0
  18. package/templates/.claude/skills/ai-factory-mapper/references/coverage-formula.md +219 -0
  19. package/templates/.claude/skills/ai-factory-mapper/references/decomposition-checklist.md +183 -0
  20. package/templates/.claude/skills/ai-factory-mapper/references/pattern-library.md +312 -0
  21. package/templates/.claude/skills/ai-factory-mapper/scripts/build_docx_report.js +423 -0
  22. package/templates/.claude/skills/analyst-manual-full/SKILL.md +286 -0
  23. package/templates/.claude/skills/edu-site-generator/SKILL.md +254 -0
  24. package/templates/.claude/skills/edu-site-generator/examples/sample-course-structure.md +116 -0
  25. package/templates/.claude/skills/edu-site-generator/modules/00-content-analysis.md +84 -0
  26. package/templates/.claude/skills/edu-site-generator/modules/01-course-structure.md +75 -0
  27. package/templates/.claude/skills/edu-site-generator/modules/02-data-generation.md +186 -0
  28. package/templates/.claude/skills/edu-site-generator/modules/03-scaffold.md +249 -0
  29. package/templates/.claude/skills/edu-site-generator/modules/04-components.md +130 -0
  30. package/templates/.claude/skills/edu-site-generator/modules/05-gamification.md +163 -0
  31. package/templates/.claude/skills/edu-site-generator/modules/06-deploy.md +88 -0
  32. package/templates/.claude/skills/edu-site-generator/modules/07-verification.md +97 -0
  33. package/templates/.claude/skills/edu-site-generator/references/component-templates.md +436 -0
  34. package/templates/.claude/skills/edu-site-generator/references/data-schemas.md +164 -0
  35. package/templates/.claude/skills/edu-site-generator/references/exercise-catalog.md +110 -0
  36. package/templates/.claude/skills/edu-site-generator/references/tech-stack.md +69 -0
  37. package/templates/.claude/skills/feature-adr/SKILL.md +245 -59
  38. package/templates/.claude/skills/feature-adr/modules/03-adr.md +43 -0
  39. package/templates/.claude/skills/feature-adr/modules/03.5-ideation-swarm.md +180 -0
  40. package/templates/.claude/skills/feature-adr/modules/06-implementation-plan.md +56 -7
  41. package/templates/.claude/skills/feature-adr/modules/08-qe.md +87 -23
  42. package/templates/.claude/skills/feature-adr/modules/09-fleet-qe.md +305 -0
  43. package/templates/.claude/skills/feature-adr/references/agentic-qe/README.md +143 -0
  44. package/templates/.claude/skills/feature-adr/references/agentic-qe/brutal-honesty-review.md +240 -0
  45. package/templates/.claude/skills/feature-adr/references/agentic-qe/chaos-engineering-resilience.md +163 -0
  46. package/templates/.claude/skills/feature-adr/references/agentic-qe/code-goal-planner.md +446 -0
  47. package/templates/.claude/skills/feature-adr/references/agentic-qe/enterprise-integration-testing.md +111 -0
  48. package/templates/.claude/skills/feature-adr/references/agentic-qe/mutation-testing.md +236 -0
  49. package/templates/.claude/skills/feature-adr/references/agentic-qe/performance-testing.md +315 -0
  50. package/templates/.claude/skills/feature-adr/references/agentic-qe/qcsd-ideation-swarm.md +126 -0
  51. package/templates/.claude/skills/feature-adr/references/agentic-qe/qcsd-production-swarm.md +108 -0
  52. package/templates/.claude/skills/feature-adr/references/agentic-qe/qe-coverage-analysis.md +193 -0
  53. package/templates/.claude/skills/feature-adr/references/agentic-qe/qe-requirements-validation.md +254 -0
  54. package/templates/.claude/skills/feature-adr/references/agentic-qe/regression-testing.md +233 -0
  55. package/templates/.claude/skills/feature-adr/references/agentic-qe/risk-based-testing.md +212 -0
  56. package/templates/.claude/skills/feature-adr/references/agentic-qe/security-testing.md +311 -0
  57. package/templates/.claude/skills/feature-adr/references/agentic-qe/shift-left-testing.md +231 -0
  58. package/templates/.claude/skills/feature-adr/references/agentic-qe/tdd-london-chicago.md +249 -0
  59. package/templates/.claude/skills/knowledge-extractor/SKILL.md +254 -0
  60. package/templates/.claude/skills/knowledge-extractor/modules/01-extract.md +188 -0
  61. package/templates/.claude/skills/knowledge-extractor/modules/02-classify.md +99 -0
  62. package/templates/.claude/skills/knowledge-extractor/modules/03-gate.md +150 -0
  63. package/templates/.claude/skills/knowledge-extractor/modules/04-integrate.md +159 -0
  64. package/templates/.claude/skills/knowledge-extractor/references/artifact-categories.md +100 -0
  65. package/templates/.claude/skills/knowledge-extractor/references/maturity-model.md +94 -0
  66. package/templates/.claude/skills/knowledge-extractor/references/quality-gates.md +98 -0
  67. package/templates/.claude/skills/knowledge-extractor/templates/artifact-card.md +63 -0
  68. package/templates/.claude/skills/knowledge-extractor/templates/harvest-report.md +102 -0
  69. package/templates/.claude/skills/transcript-site-generator/SKILL.md +287 -0
  70. package/templates/.claude/skills/transcript-site-generator/examples/sample-text-only-site.md +123 -0
  71. package/templates/.claude/skills/transcript-site-generator/examples/sample-transcript-site.md +134 -0
  72. package/templates/.claude/skills/transcript-site-generator/modules/00-input-analysis.md +132 -0
  73. package/templates/.claude/skills/transcript-site-generator/modules/01-content-parsing.md +117 -0
  74. package/templates/.claude/skills/transcript-site-generator/modules/02-site-generation.md +293 -0
  75. package/templates/.claude/skills/transcript-site-generator/modules/03-interactivity.md +406 -0
  76. package/templates/.claude/skills/transcript-site-generator/modules/04-deploy.md +130 -0
  77. package/templates/.claude/skills/transcript-site-generator/modules/05-verification.md +155 -0
  78. package/templates/.claude/skills/transcript-site-generator/references/component-catalog.md +86 -0
  79. package/templates/.claude/skills/transcript-site-generator/references/data-schemas.md +123 -0
  80. package/templates/.claude/skills/transcript-site-generator/references/tech-stack.md +132 -0
  81. package/templates/CLAUDE.md +30 -9
  82. package/templates/docs/continuous-learning-guide.md +622 -0
  83. package/templates/docs/edu-site-generator/01-deployment-guide.md +911 -0
  84. package/templates/docs/edu-site-generator/02-admin-guide.md +901 -0
  85. package/templates/docs/edu-site-generator/03-user-guide.md +1008 -0
  86. package/templates/docs/edu-site-generator/04-infrastructure-requirements.md +489 -0
  87. package/templates/docs/edu-site-generator/05-architecture.md +902 -0
  88. package/templates/docs/edu-site-generator/06-user-flows.md +759 -0
  89. package/templates/docs/improvement-directions.md +8 -4
  90. package/templates/docs/keysarium-core/02-functionality.md +3 -1
  91. package/templates/docs/skills-bto/01-deployment-guide.md +1 -1
  92. package/templates/docs/skills-bto/02-admin-guide.md +4 -1
  93. package/templates/docs/skills-bto/03-user-guide.md +4 -3
  94. package/templates/docs/skills-bto/04-infrastructure-requirements.md +2 -1
  95. package/templates/docs/skills-bto/05-architecture.md +11 -11
  96. package/templates/docs/skills-bto/06-user-flows.md +2 -1
  97. package/templates/docs/transcript-site-generator/01-deployment-guide.md +1042 -0
  98. package/templates/docs/transcript-site-generator/02-admin-guide.md +918 -0
  99. package/templates/docs/transcript-site-generator/03-user-guide.md +925 -0
  100. package/templates/docs/transcript-site-generator/04-infrastructure-requirements.md +482 -0
  101. package/templates/docs/transcript-site-generator/05-architecture.md +1068 -0
  102. package/templates/docs/transcript-site-generator/06-user-flows.md +855 -0
  103. package/templates/lib/dream-engine.md +1 -1
  104. package/templates/lib/memory-protocol.md +6 -2
  105. package/templates/lib/reward-tracker.md +6 -3
@@ -0,0 +1,249 @@
1
+ ---
2
+ name: tdd-london-chicago
3
+ description: "Apply London (mock-based) and Chicago (state-based) TDD schools. Use when practicing test-driven development or choosing testing style for your context."
4
+ category: development-practices
5
+ priority: high
6
+ tokenEstimate: 1100
7
+ agents: [qe-test-generator, qe-test-implementer, qe-test-refactorer]
8
+ implementation_status: optimized
9
+ optimization_version: 1.0
10
+ last_optimized: 2025-12-02
11
+ dependencies: []
12
+ quick_reference_card: true
13
+ tags: [tdd, testing, london-school, chicago-school, red-green-refactor, mocks]
14
+ trust_tier: 2
15
+ validation:
16
+ schema_path: schemas/output.json
17
+ validator_path: scripts/validate-config.json
18
+
19
+ ---
20
+
21
+ # Test-Driven Development: London & Chicago Schools
22
+
23
+ <default_to_action>
24
+ When implementing TDD or choosing testing style:
25
+ 1. IDENTIFY code type: domain logic → Chicago, external deps → London
26
+ 2. WRITE failing test first (Red phase)
27
+ 3. IMPLEMENT minimal code to pass (Green phase)
28
+ 4. REFACTOR while keeping tests green (Refactor phase)
29
+ 5. REPEAT cycle for next functionality
30
+
31
+ **Quick Style Selection:**
32
+ - Pure functions/calculations → Chicago (real objects, state verification)
33
+ - Controllers/services with deps → London (mocks, interaction verification)
34
+ - Value objects → Chicago (test final state)
35
+ - API integrations → London (mock external services)
36
+ - Mix both in practice (London for controllers, Chicago for domain)
37
+
38
+ **Critical Success Factors:**
39
+ - Tests drive design, not just verify it
40
+ - Make tests fail first to ensure they test something
41
+ - Write minimal code - no features beyond what's tested
42
+ </default_to_action>
43
+
44
+ ## Quick Reference Card
45
+
46
+ ### When to Use
47
+ - Starting new feature with test-first approach
48
+ - Refactoring legacy code with test coverage
49
+ - Teaching TDD practices to team
50
+ - Choosing between mocking vs real objects
51
+
52
+ ### TDD Cycle
53
+ | Phase | Action | Discipline |
54
+ |-------|--------|------------|
55
+ | **Red** | Write failing test | Verify it fails, check message is clear |
56
+ | **Green** | Minimal code to pass | No extra features, don't refactor |
57
+ | **Refactor** | Improve structure | Keep tests passing, no new functionality |
58
+
59
+ ### School Comparison
60
+ | Aspect | Chicago (Classicist) | London (Mockist) |
61
+ |--------|---------------------|------------------|
62
+ | Collaborators | Real objects | Mocks/stubs |
63
+ | Verification | State (assert outcomes) | Interaction (assert calls) |
64
+ | Isolation | Lower (integrated) | Higher (unit only) |
65
+ | Refactoring | Easier | Harder (mocks break) |
66
+ | Design feedback | Emerges from use | Explicit from start |
67
+
68
+ ### Agent Coordination
69
+ - `qe-test-generator`: Generate tests in both schools
70
+ - `qe-test-implementer`: Implement minimal code (Green)
71
+ - `qe-test-refactorer`: Safe refactoring (Refactor)
72
+
73
+ ---
74
+
75
+ ## Chicago School (State-Based)
76
+
77
+ **Philosophy:** Test observable behavior through public API. Keep tests close to consumer usage.
78
+
79
+ ```javascript
80
+ // State verification - test final outcome
81
+ describe('Order', () => {
82
+ it('calculates total with tax', () => {
83
+ const order = new Order();
84
+ order.addItem(new Product('Widget', 10.00), 2);
85
+ order.addItem(new Product('Gadget', 15.00), 1);
86
+
87
+ expect(order.totalWithTax(0.10)).toBe(38.50);
88
+ });
89
+ });
90
+ ```
91
+
92
+ **When Chicago Shines:**
93
+ - Domain logic with clear state
94
+ - Algorithms and calculations
95
+ - Value objects (`Money`, `Email`)
96
+ - Simple collaborations
97
+ - Learning new domain
98
+
99
+ ---
100
+
101
+ ## London School (Mock-Based)
102
+
103
+ **Philosophy:** Test each unit in isolation. Focus on how objects collaborate.
104
+
105
+ ```javascript
106
+ // Interaction verification - test method calls
107
+ describe('Order', () => {
108
+ it('delegates tax calculation', () => {
109
+ const taxCalculator = {
110
+ calculateTax: jest.fn().mockReturnValue(3.50)
111
+ };
112
+ const order = new Order(taxCalculator);
113
+ order.addItem({ price: 10 }, 2);
114
+
115
+ order.totalWithTax();
116
+
117
+ expect(taxCalculator.calculateTax).toHaveBeenCalledWith(20.00);
118
+ });
119
+ });
120
+ ```
121
+
122
+ **When London Shines:**
123
+ - External integrations (DB, APIs)
124
+ - Command patterns with side effects
125
+ - Complex workflows
126
+ - Slow operations (network, I/O)
127
+
128
+ ---
129
+
130
+ ## Mixed Approach (Recommended)
131
+
132
+ ```javascript
133
+ // London for controller (external deps)
134
+ describe('OrderController', () => {
135
+ it('creates order and sends confirmation', async () => {
136
+ const orderService = { create: jest.fn().mockResolvedValue({ id: 123 }) };
137
+ const emailService = { send: jest.fn() };
138
+
139
+ const controller = new OrderController(orderService, emailService);
140
+ await controller.placeOrder(orderData);
141
+
142
+ expect(orderService.create).toHaveBeenCalledWith(orderData);
143
+ expect(emailService.send).toHaveBeenCalled();
144
+ });
145
+ });
146
+
147
+ // Chicago for domain logic
148
+ describe('OrderService', () => {
149
+ it('applies discount when threshold met', () => {
150
+ const service = new OrderService();
151
+ const order = service.create({ items: [...], total: 150 });
152
+
153
+ expect(order.discount).toBe(15); // 10% off > $100
154
+ });
155
+ });
156
+ ```
157
+
158
+ ---
159
+
160
+ ## Common Pitfalls
161
+
162
+ ### ❌ Over-Mocking (London)
163
+ ```javascript
164
+ // BAD - mocking everything
165
+ const product = { getName: jest.fn(), getPrice: jest.fn() };
166
+ ```
167
+ **Better:** Only mock external dependencies.
168
+
169
+ ### ❌ Mocking Internals
170
+ ```javascript
171
+ // BAD - testing private methods
172
+ expect(order._calculateSubtotal).toHaveBeenCalled();
173
+ ```
174
+ **Better:** Test public behavior only.
175
+
176
+ ### ❌ Test Pain = Design Pain
177
+ - Need many mocks? → Too many dependencies
178
+ - Hard to set up? → Constructor does too much
179
+ - Can't test without database? → Coupling issue
180
+
181
+ ---
182
+
183
+ ## Agent-Assisted TDD
184
+
185
+ ```typescript
186
+ // Agent generates tests in both schools
187
+ await Task("Generate Tests", {
188
+ style: 'chicago', // or 'london'
189
+ target: 'src/domain/Order.ts',
190
+ focus: 'state-verification' // or 'collaboration-patterns'
191
+ }, "qe-test-generator");
192
+
193
+ // Agent-human ping-pong TDD
194
+ // Human writes test concept
195
+ const testIdea = "Order applies 10% discount when total > $100";
196
+
197
+ // Agent generates formal failing test (Red)
198
+ await Task("Create Failing Test", testIdea, "qe-test-generator");
199
+
200
+ // Human writes minimal code (Green)
201
+
202
+ // Agent suggests refactorings
203
+ await Task("Suggest Refactorings", { preserveTests: true }, "qe-test-refactorer");
204
+ ```
205
+
206
+ ---
207
+
208
+ ## Agent Coordination Hints
209
+
210
+ ### Memory Namespace
211
+ ```
212
+ aqe/tdd/
213
+ ├── test-plan/* - TDD session plans
214
+ ├── red-phase/* - Failing tests generated
215
+ ├── green-phase/* - Implementation code
216
+ └── refactor-phase/* - Refactoring suggestions
217
+ ```
218
+
219
+ ### Fleet Coordination
220
+ ```typescript
221
+ const tddFleet = await FleetManager.coordinate({
222
+ workflow: 'red-green-refactor',
223
+ agents: {
224
+ testGenerator: 'qe-test-generator',
225
+ testExecutor: 'qe-test-executor',
226
+ qualityAnalyzer: 'qe-quality-analyzer'
227
+ },
228
+ mode: 'sequential'
229
+ });
230
+ ```
231
+
232
+ ---
233
+
234
+ ## Related Skills
235
+ - [agentic-quality-engineering](../agentic-quality-engineering/) - TDD with agent coordination
236
+ - [refactoring-patterns](../refactoring-patterns/) - Refactor phase techniques
237
+ - [api-testing-patterns](../api-testing-patterns/) - London school for API testing
238
+
239
+ ---
240
+
241
+ ## Remember
242
+
243
+ **Chicago:** Test state, use real objects, refactor freely
244
+ **London:** Test interactions, mock dependencies, design interfaces first
245
+ **Both:** Write the test first, make it pass, refactor
246
+
247
+ Neither is "right." Choose based on context. Mix as needed. Goal: well-designed, tested code.
248
+
249
+ **With Agents:** Agents excel at generating tests, validating green phase, and suggesting refactorings. Use agents to maintain TDD discipline while humans focus on design decisions.
@@ -0,0 +1,254 @@
1
+ ---
2
+ name: knowledge-extractor
3
+ description: >
4
+ Multi-agent knowledge harvesting system that extracts reusable patterns, commands,
5
+ rules, templates, and snippets from any project directory. Uses 5 parallel extractor
6
+ agents, 7-category classification, 8 blocking quality gates, and auto-placement.
7
+ Triggers on "harvest", "extract knowledge", "извлеки знания", "/harvest".
8
+ trust_tier: 2
9
+ trust_tier_label: "Validated"
10
+ bto_score: 7.5
11
+ bto_date: "2026-03-03"
12
+ trust_tier_path: "Run /bto-test, score >= 8.5 + eval tests for Tier 3"
13
+ ---
14
+
15
+ # Knowledge Extractor
16
+
17
+ > Domain-agnostic multi-agent system for extracting, classifying, gating, and placing
18
+ > reusable knowledge from completed projects into the toolkit.
19
+
20
+ ## When To Activate
21
+
22
+ Trigger on:
23
+ - `/harvest [path]` or `/harvest all`
24
+ - "extract knowledge from [path]"
25
+ - "извлеки знания из [path]"
26
+ - "harvest patterns from [project]"
27
+ - "что можно переиспользовать из [project]"
28
+
29
+ ## What You Get
30
+
31
+ After a successful harvest session:
32
+ - **Findings JSON** — structured extraction results at `.keysarium/harvest/findings-{SESSION_ID}.json`
33
+ - **Placed artifacts** — skills, commands, and rules placed in `.claude/skills/`, `.claude/commands/`, `.claude/rules/`
34
+ - **TOOLKIT_HARVEST.md** — updated with new patterns, templates, snippets, and hooks
35
+ - **Harvest report** — session summary with metrics (extracted → approved → placed counts, gate pass rates)
36
+ - **Memory record** — reward data stored via `memory_store()` for future session optimization
37
+
38
+ ## Architecture
39
+
40
+ ```
41
+ .claude/skills/knowledge-extractor/
42
+ ├── SKILL.md ← This file (orchestrator)
43
+ ├── modules/
44
+ │ ├── 01-extract.md ← 5 parallel extractor agents
45
+ │ ├── 02-classify.md ← 7-category classification + dedup
46
+ │ ├── 03-gate.md ← 8 quality gates (2-pass)
47
+ │ └── 04-integrate.md ← Auto-placement + harvest report
48
+ ├── references/
49
+ │ ├── quality-gates.md ← Gate definitions (G1-G8)
50
+ │ ├── artifact-categories.md ← 7 categories with destinations
51
+ │ └── maturity-model.md ← Alpha → Beta → Stable
52
+ └── templates/
53
+ ├── artifact-card.md ← Per-finding output template
54
+ └── harvest-report.md ← Session summary template
55
+ ```
56
+
57
+ ## Modules
58
+
59
+ | Module | Purpose | Agents | Model |
60
+ |--------|---------|--------|-------|
61
+ | 01-extract | Scan project via 5 focused lenses | 5 parallel | sonnet |
62
+ | 02-classify | Assign categories, deduplicate, cross-ref | 0 (inline) | — |
63
+ | 03-gate | Evaluate 8 quality gates in 2 passes | 1 (semantic) | haiku |
64
+ | 04-integrate | Place artifacts, generate report | 0 (inline) | — |
65
+
66
+ ## Pipeline Protocol
67
+
68
+ ### Step 0: Initialize Session
69
+
70
+ 1. Parse arguments: `{TARGET_PATH}` (directory or "all"), `{SCOPE_FILTER}` (optional `only X,Y`)
71
+ 2. **Resolve target path:**
72
+ - If `{TARGET_PATH}` is a specific directory → validate it exists, set `{slug}` = directory basename
73
+ - If `{TARGET_PATH}` is `"all"` → list all subdirectories in `researches/`. For each directory, run a separate harvest session (each gets its own findings JSON, session ID, and pipeline run). Merge reports at the end.
74
+ - If `{TARGET_PATH}` does not exist → report error and stop
75
+ 3. **Resolve domain:** If running inside a `/casarium` pipeline, inherit `{domain}` from Phase 0 discovery. If standalone, detect domain from file content keywords (banking/retail/enterprise/healthcare). If unable to detect, set `{domain}` = `"unknown"`.
76
+ 4. Generate session ID: `{slug}-{YYYYMMDDHHmmss}`
77
+ 5. If `TOOLKIT_HARVEST.md` does not exist at repo root → create it with a standard skeleton (title + empty section headers for each category).
78
+ 6. Call `memory_query({phase: "harvest", domain, slug, skill: "knowledge-extractor"})`
79
+ 7. Log loaded patterns count
80
+
81
+ ### Step 1: Extract (Module 01)
82
+
83
+ ```
84
+ Read: modules/01-extract.md
85
+ ```
86
+
87
+ Spawn 5 parallel extractor agents (sonnet), each with a focused lens:
88
+
89
+ | Agent | Lens | Seeks |
90
+ |-------|------|-------|
91
+ | extractor-patterns | patterns | Architecture patterns, design patterns, agent topologies |
92
+ | extractor-commands | commands | Scripts, CLI workflows, pipeline stages, automation |
93
+ | extractor-rules | rules | Constraints, anti-patterns, lessons learned, domain rules |
94
+ | extractor-templates | templates | Document structures, config templates, diagram templates |
95
+ | extractor-snippets | snippets | Reusable code fragments, hooks, utility functions |
96
+
97
+ Each agent returns numbered findings with reusability confidence (0.0-1.0).
98
+ Orchestrator merges all findings into a single numbered list and writes to JSON:
99
+ `.keysarium/harvest/findings-{SESSION_ID}.json`
100
+
101
+ **Scope filtering:** If `{SCOPE_FILTER}` is set, only spawn matching agents. See mapping in `references/artifact-categories.md`.
102
+
103
+ ### Step 2: Classify (Module 02)
104
+
105
+ ```
106
+ Read: modules/02-classify.md
107
+ Read: references/artifact-categories.md
108
+ ```
109
+
110
+ 1. Read findings from JSON file
111
+ 2. Assign each finding to one of 7 categories
112
+ 3. Deduplicate: check content similarity across findings and against TOOLKIT_HARVEST.md
113
+ 4. Cross-reference: link findings that reference existing skills/commands
114
+ 5. Write classified findings back to JSON
115
+
116
+ ### Step 3: User Checkpoint (Interactive)
117
+
118
+ Display all findings grouped by category as a numbered list:
119
+
120
+ ```
121
+ ═══════════════════════════════════════════════════════
122
+ 📋 HARVEST FINDINGS: {N} items extracted
123
+
124
+ ## patterns (K items)
125
+ #1 [0.85] Agent Swarm Topology — parallel agents with merge pattern
126
+ #4 [0.72] Event-Driven Pipeline — phase-to-phase data flow via files
127
+
128
+ ## rules (M items)
129
+ #2 [0.91] Domain Detection Rule — auto-detect domain from keywords
130
+ #7 [0.65] Regulatory Constraint — ФЗ-152 data isolation requirement
131
+
132
+ ## snippets (P items)
133
+ #3 [0.78] CJM Renderer — universal React component for CJM display
134
+ ...
135
+
136
+ Commands:
137
+ • "убери #N" — remove finding
138
+ • "переклассифицируй #N в X" — reclassify to category X
139
+ • "доработай #N" — expand/improve finding
140
+ • "объедини #N и #M" — merge two findings
141
+ • "покажи только X" — filter by category
142
+ • "ок" — proceed to quality gates
143
+ ═══════════════════════════════════════════════════════
144
+ ```
145
+
146
+ Apply user mutations to JSON file. Numbers are stable (removed items leave gaps).
147
+ Loop until user says "ок".
148
+
149
+ ### Step 4: Gate (Module 03)
150
+
151
+ ```
152
+ Read: modules/03-gate.md
153
+ Read: references/quality-gates.md
154
+ ```
155
+
156
+ Evaluate each active finding against 8 quality gates in 2 passes:
157
+
158
+ **Pass 1 — Deterministic (zero LLM cost):**
159
+ - G1: Has "When to use" section
160
+ - G2: Has "When NOT to use" section
161
+ - G5: Reusability confidence >= 0.5
162
+ - G6: Not a duplicate of existing toolkit entry
163
+ - G7: Has maturity label (alpha/beta/stable)
164
+
165
+ **Pass 2 — Semantic (haiku agent):**
166
+ - G3: Properly decontextualized (no project-specific refs)
167
+ - G4: Has at least one concrete example
168
+ - G8: Passes brutal-honesty review (self-critical assessment)
169
+
170
+ Findings passing all gates → status `approved`.
171
+ Findings failing any gate → status `blocked` with gate IDs.
172
+
173
+ Display blocked findings and allow overrides:
174
+ ```
175
+ ⚠️ BLOCKED: #7 — failed G3 (project-specific references remain)
176
+ • "пропусти G3 для #7" — override gate
177
+ • "ок" — accept blocks, proceed with approved only
178
+ ```
179
+
180
+ ### Step 5: Integrate (Module 04)
181
+
182
+ ```
183
+ Read: modules/04-integrate.md
184
+ Read: templates/artifact-card.md
185
+ Read: templates/harvest-report.md
186
+ ```
187
+
188
+ 1. Render artifact cards for each approved finding
189
+ 2. Auto-place by category:
190
+ - `skills` → create `.claude/skills/<name>/SKILL.md` (skeleton)
191
+ - `commands` → create `.claude/commands/<name>.md`
192
+ - `hooks` → document in TOOLKIT_HARVEST.md (hooks section)
193
+ - `rules` → create `.claude/rules/<name>.md`
194
+ - `templates` → document in TOOLKIT_HARVEST.md (templates section)
195
+ - `patterns` → document in TOOLKIT_HARVEST.md (patterns section)
196
+ - `snippets` → document in TOOLKIT_HARVEST.md (snippets section)
197
+ 3. Update TOOLKIT_HARVEST.md "Обработанные проекты" table
198
+ 4. Generate harvest report
199
+ 5. Call `memory_store()` with harvest results and user reward
200
+ 6. Update `.keysarium/insights/trigger-state.json` (case_completion event)
201
+ 7. Clean up findings JSON file
202
+
203
+ ## Scope Filtering
204
+
205
+ The `only` keyword filters which extractor agents are spawned:
206
+
207
+ ```
208
+ /harvest path/ → all 5 agents
209
+ /harvest path/ only patterns → extractor-patterns only
210
+ /harvest path/ only rules,templates → extractor-rules + extractor-templates
211
+ /harvest all only snippets → extractor-snippets for each directory
212
+ ```
213
+
214
+ Category-to-agent mapping (see `references/artifact-categories.md`):
215
+ - patterns → extractor-patterns
216
+ - commands → extractor-commands
217
+ - hooks → extractor-commands (shared lens)
218
+ - rules → extractor-rules
219
+ - templates → extractor-templates
220
+ - snippets → extractor-snippets
221
+ - skills → all agents (skills are cross-cutting)
222
+
223
+ ## Integration Points
224
+
225
+ | System | When | Operation |
226
+ |--------|------|-----------|
227
+ | memory_query() | Pipeline start | Load historical harvest patterns |
228
+ | memory_store() | After user checkpoint | Store harvest reward data |
229
+ | brain-export | N/A (passive) | Findings JSON is brain-compatible schema |
230
+ | BTO | Post-harvest | Placed skills can be evaluated via `/bto-test` |
231
+ | dream cycles | Pipeline end | Update trigger-state.json |
232
+ | /harvest command | Entry point | Thin wrapper loads this skill |
233
+
234
+ ## Anti-Patterns
235
+
236
+ | Anti-Pattern | Detection | Fix |
237
+ |-------------|-----------|-----|
238
+ | Extracting project-specific details | Finding contains project names, slugs, dates | Decontextualize: replace specifics with generic placeholders |
239
+ | Duplicate extraction | content_hash matches existing TOOLKIT_HARVEST.md entry | Skip or merge; gate G6 blocks duplicates |
240
+ | Extracting from incomplete phases | Artifact lacks promise tag or checkpoint | Only harvest from completed projects |
241
+ | Over-classifying snippets as patterns | Single-use code without abstraction | Require reuse evidence before promoting to pattern |
242
+ | Under-specifying maturity | All findings marked "stable" on first run | First extraction is always "alpha" or "beta" |
243
+ | Skipping user checkpoint | Proceeding to gates without user review | BLOCK — user checkpoint is mandatory |
244
+ | Running all agents when scope is filtered | `only patterns` but 5 agents spawned | Check SCOPE_FILTER before spawning |
245
+
246
+ ## Dependencies
247
+
248
+ | Resource | Path | Purpose |
249
+ |----------|------|---------|
250
+ | quality-gates.md | references/quality-gates.md | Gate definitions for Module 03 |
251
+ | artifact-categories.md | references/artifact-categories.md | 7-category taxonomy |
252
+ | maturity-model.md | references/maturity-model.md | Alpha/Beta/Stable criteria |
253
+ | artifact-card.md | templates/artifact-card.md | Per-finding output format |
254
+ | harvest-report.md | templates/harvest-report.md | Session report format |
@@ -0,0 +1,188 @@
1
+ # Extract Module — Parallel Knowledge Extraction
2
+
3
+ ## Purpose
4
+
5
+ Spawn 5 focused extractor agents to scan a project directory through different lenses, collecting reusable knowledge findings with confidence scores.
6
+
7
+ ## Input
8
+
9
+ - `{TARGET_PATH}` — directory to scan (e.g., `researches/bank-kc-automation/`)
10
+ - `{SCOPE_FILTER}` — optional list of lenses to activate (null = all 5)
11
+ - `{MEMORY_PATTERNS}` — historical patterns from memory_query() (may be empty)
12
+ - `{SESSION_ID}` — harvest session identifier
13
+
14
+ ## Protocol
15
+
16
+ ### Step 1: Inventory Target Directory
17
+
18
+ List all files in `{TARGET_PATH}`. Build a file manifest with paths and sizes.
19
+ Skip binary files, images, and files > 100KB.
20
+
21
+ ### Step 2: Determine Active Agents
22
+
23
+ If `{SCOPE_FILTER}` is set, map categories to lenses:
24
+
25
+ | Requested Category | Agent Lens to Spawn |
26
+ |-------------------|---------------------|
27
+ | patterns | extractor-patterns |
28
+ | commands | extractor-commands |
29
+ | hooks | extractor-commands (shared) |
30
+ | rules | extractor-rules |
31
+ | templates | extractor-templates |
32
+ | snippets | extractor-snippets |
33
+ | skills | ALL agents (cross-cutting) |
34
+
35
+ If `{SCOPE_FILTER}` is null, spawn all 5 agents.
36
+
37
+ ### Step 3: Spawn Extractor Agents
38
+
39
+ Spawn selected agents in parallel using the Agent tool:
40
+
41
+ ```
42
+ Agent(
43
+ subagent_type="general-purpose",
44
+ model="sonnet",
45
+ description="Harvest Extractor — {LENS_NAME}",
46
+ prompt="""
47
+ You are a knowledge extraction agent with a focused lens: {LENS_DESCRIPTION}.
48
+
49
+ ## Your Task
50
+ Scan the following project files and extract reusable knowledge through your lens.
51
+ For each finding, provide:
52
+ 1. A short descriptive title (3-8 words)
53
+ 2. Content: the reusable knowledge (decontextualized where possible)
54
+ 3. "When to use" guidance (1-2 sentences)
55
+ 4. "When NOT to use" guidance (1-2 sentences)
56
+ 5. A concrete example of usage
57
+ 6. Reusability confidence (0.0 to 1.0):
58
+ - 0.9-1.0: Universal, works in any project
59
+ - 0.7-0.89: Works in most similar projects
60
+ - 0.5-0.69: Works in some contexts
61
+ - < 0.5: Probably too project-specific
62
+ 7. Suggested maturity: alpha (first time seen) or beta (if evidence of reuse)
63
+
64
+ ## Project Files
65
+ Read the following directory: {TARGET_PATH}
66
+
67
+ ## Historical Patterns (from previous harvests)
68
+ {MEMORY_PATTERNS_OR_NONE}
69
+
70
+ Avoid extracting findings that overlap with these historical patterns.
71
+
72
+ ## Extraction Rules
73
+ - Extract ONLY genuinely reusable knowledge
74
+ - DO NOT extract project-specific implementation details
75
+ - DO NOT extract trivial or obvious patterns
76
+ - Each finding must be independently useful outside this project
77
+ - Prefer actionable knowledge over abstract observations
78
+ - If in doubt about reusability, include it with a lower confidence score
79
+
80
+ ## Output Format
81
+ Return a numbered list of findings in this exact format:
82
+
83
+ ### Finding 1
84
+ **Title:** [short title]
85
+ **Confidence:** [0.0-1.0]
86
+ **Maturity:** [alpha|beta]
87
+ **Content:** [the reusable knowledge]
88
+ **When to use:** [guidance]
89
+ **When NOT to use:** [anti-guidance]
90
+ **Example:** [concrete example]
91
+
92
+ ### Finding 2
93
+ ...
94
+ """
95
+ )
96
+ ```
97
+
98
+ ### Step 4: Handle Agent Failures
99
+
100
+ If any extractor agent fails, times out, or returns malformed output:
101
+
102
+ 1. **Partial success:** Proceed with results from successful agents. Do NOT block the entire pipeline.
103
+ 2. **Log failures:** Record which lenses failed and why:
104
+ ```
105
+ ⚠️ Extractor agent failed: extractor-snippets (timeout after 120s)
106
+ Proceeding with 4/5 lenses. Snippets will not be harvested.
107
+ ```
108
+ 3. **Surface in report:** Add failed lenses to the harvest report's "Coverage Gaps" section.
109
+ 4. **Retry option:** Offer the user: `"повтори snippets"` — retry the failed lens only.
110
+ 5. **Malformed output:** If an agent returns output that cannot be parsed into the Finding format, discard that agent's results and log: `"Extractor {lens} returned unparseable output — discarded."`
111
+ 6. **Zero findings:** If an agent returns no findings, this is normal (not all lenses find relevant content). Log: `"Extractor {lens}: 0 findings (no relevant content detected)."`
112
+
113
+ ### Step 5: Report Skipped Files
114
+
115
+ Before merging, surface any files that were skipped during inventory:
116
+
117
+ ```
118
+ 📋 File inventory: {total_files} files scanned, {skipped_count} skipped
119
+ Skipped: {file1} (112KB, exceeds 100KB limit), {file2} (binary)
120
+ ```
121
+
122
+ Include this in the harvest report under "Coverage Gaps" so the user knows what was NOT examined.
123
+
124
+ ### Step 6: Merge Results
125
+
126
+ After all agents complete (or after handling failures):
127
+
128
+ 1. Collect all findings from all agents
129
+ 2. Assign sequential numbers starting from 1 (global numbering across all agents)
130
+ 3. Tag each finding with its source lens
131
+ 4. Set initial status to `raw`
132
+ 5. Write to findings JSON file at `.keysarium/harvest/findings-{SESSION_ID}.json`
133
+
134
+ ### 5 Agent Lens Descriptions
135
+
136
+ | Agent | Lens Description |
137
+ |-------|-----------------|
138
+ | extractor-patterns | Architecture patterns, design patterns, agent topologies, data flow patterns, orchestration strategies, parallelism approaches. Look for structural solutions that could be applied to other systems. |
139
+ | extractor-commands | CLI commands, scripts, pipeline stages, automation workflows, slash commands, build processes. Look for reusable command patterns and workflow automations. |
140
+ | extractor-rules | Constraints, quality gates, anti-patterns, domain rules, naming conventions, regulatory requirements, lessons learned. Look for guardrails and restrictions that prevent mistakes. |
141
+ | extractor-templates | Document structures, config file formats, diagram templates, report formats, checklist templates. Look for reusable document and configuration scaffolding. |
142
+ | extractor-snippets | Reusable code fragments, utility functions, React components, bash one-liners, prompt templates, hook implementations. Look for copy-paste-ready code blocks. |
143
+
144
+ ## Output Format
145
+
146
+ The findings JSON file structure:
147
+
148
+ ```json
149
+ {
150
+ "session_id": "{SESSION_ID}",
151
+ "status": "extracting",
152
+ "target_paths": ["{TARGET_PATH}"],
153
+ "scope_filter": null,
154
+ "created_at": "ISO-8601",
155
+ "next_number": 16,
156
+ "extractors_spawned": ["patterns", "commands", "rules", "templates", "snippets"],
157
+ "findings": {
158
+ "1": {
159
+ "number": 1,
160
+ "title": "Agent Swarm Topology",
161
+ "content": "...",
162
+ "when_to_use": "...",
163
+ "when_not_to_use": "...",
164
+ "example": "...",
165
+ "confidence": 0.85,
166
+ "maturity": "alpha",
167
+ "source_lens": "patterns",
168
+ "category": null,
169
+ "status": "raw",
170
+ "gate_results": {},
171
+ "gate_overrides": [],
172
+ "merged_from": null
173
+ }
174
+ }
175
+ }
176
+ ```
177
+
178
+ ## Anti-Patterns
179
+
180
+ | Anti-Pattern | Detection | Fix |
181
+ |-------------|-----------|-----|
182
+ | Agent extracts trivial findings | Findings like "use git for version control" | Prompt emphasizes non-obvious, actionable knowledge |
183
+ | Agent reads files outside target | File paths outside {TARGET_PATH} | Prompt constrains to target directory only |
184
+ | Duplicate findings across agents | Two agents extract the same pattern | Handled by Module 02 (dedup), not here |
185
+ | Agent returns unstructured text | Missing required fields in output | Strict output format in prompt; orchestrator validates |
186
+ | All findings have confidence 0.9+ | Agent is not being self-critical | Prompt calibration: explain the confidence scale |
187
+ | Agent timeout with no fallback | Pipeline stalls waiting for failed agent | Use Step 4 failure protocol: proceed with partial results |
188
+ | Large files silently skipped | User unaware of coverage gaps | Step 5 surfaces skipped files; harvest report includes coverage gaps |