@polymorphism-tech/morph-spec 4.22.0 → 5.0.1

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 (211) hide show
  1. package/CLAUDE.md +57 -71
  2. package/README.md +2 -2
  3. package/bin/morph-spec.js +224 -491
  4. package/claude-plugin.json +1 -1
  5. package/docs/CHEATSHEET.md +1 -1
  6. package/docs/QUICKSTART.md +1 -1
  7. package/framework/CLAUDE.md +55 -38
  8. package/framework/MORPH.md +244 -0
  9. package/framework/agents.json +127 -1198
  10. package/framework/commands/morph-apply.md +56 -240
  11. package/framework/commands/morph-archive.md +48 -85
  12. package/framework/commands/morph-preflight.md +7 -7
  13. package/framework/commands/morph-proposal.md +35 -191
  14. package/framework/commands/morph-status.md +19 -50
  15. package/framework/commands/morph-troubleshoot.md +2 -2
  16. package/framework/evals/rubrics/README.md +44 -0
  17. package/framework/evals/rubrics/architecture.md +46 -0
  18. package/framework/evals/rubrics/code-quality.md +50 -0
  19. package/framework/evals/rubrics/contracts.md +47 -0
  20. package/framework/evals/rubrics/test-coverage.md +50 -0
  21. package/framework/evals/scenarios/dotnet-crud.yaml +42 -0
  22. package/framework/evals/scenarios/nextjs-auth.yaml +38 -0
  23. package/framework/evals/suites/standard.yaml +5 -0
  24. package/framework/evals/trace-schema.md +67 -0
  25. package/framework/hooks/claude-code/core/README.md +3 -0
  26. package/framework/hooks/claude-code/core/denylist.json +14 -0
  27. package/framework/hooks/claude-code/{pre-tool-use → core}/enforce-phase-writes.js +5 -5
  28. package/framework/hooks/claude-code/core/post-edit-typecheck.js +69 -0
  29. package/framework/hooks/claude-code/core/pre-bash-denylist.js +29 -0
  30. package/framework/hooks/claude-code/{pre-tool-use → core}/protect-spec-files.js +4 -6
  31. package/framework/hooks/claude-code/{stop → core}/validate-completion.js +13 -82
  32. package/framework/hooks/shared/phase-utils.js +20 -31
  33. package/framework/hooks/shared/state-reader.js +4 -5
  34. package/framework/{skills/level-0-meta/mcp-registry.json → mcp/registry.json} +254 -243
  35. package/framework/phases.json +41 -115
  36. package/framework/rubrics/eval-rubric.json +66 -0
  37. package/framework/skills/README.md +39 -64
  38. package/framework/skills/core/README.md +3 -0
  39. package/framework/skills/core/morph-brainstorming/SKILL.md +102 -0
  40. package/framework/skills/core/morph-eval/SKILL.md +57 -0
  41. package/framework/skills/core/morph-implement/SKILL.md +83 -0
  42. package/framework/skills/core/morph-plan/SKILL.md +64 -0
  43. package/framework/skills/core/morph-review/SKILL.md +62 -0
  44. package/framework/skills/core/morph-stack-scan/SKILL.md +109 -0
  45. package/framework/skills/core/morph-standards/SKILL.md +49 -0
  46. package/framework/templates/CLAUDE.md.core.guide.md +29 -0
  47. package/framework/templates/CLAUDE.md.core.template +22 -0
  48. package/framework/templates/REGISTRY.json +4 -4
  49. package/framework/workflows/configs/fast-track.json +5 -10
  50. package/framework/workflows/configs/full.json +4 -8
  51. package/framework/workflows/configs/quick.json +32 -0
  52. package/framework/workflows/configs/standard.json +57 -64
  53. package/package.json +7 -6
  54. package/src/commands/mcp/mcp-setup.js +58 -31
  55. package/src/commands/project/doctor.js +69 -70
  56. package/src/commands/project/init.js +26 -5
  57. package/src/commands/project/status.js +18 -19
  58. package/src/commands/state/approve.js +1 -1
  59. package/src/commands/validation/validate-feature.js +18 -112
  60. package/src/core/paths/output-schema.js +133 -152
  61. package/src/core/state/phase-state-machine.js +10 -24
  62. package/src/core/state/state-manager.js +17 -17
  63. package/src/core/workflows/workflow-detector.js +214 -31
  64. package/src/core/workflows/workflow-router.js +204 -0
  65. package/src/dashboard/app/pages/AgentMap.jsx +32 -33
  66. package/src/dashboard/app/pages/LiveState.jsx +1 -1
  67. package/src/dashboard/app/pages/PhasePipeline.jsx +2 -4
  68. package/src/dashboard/app/pages/SkillsLibrary.jsx +2 -3
  69. package/src/dashboard/app/pages/Workflows.jsx +2 -2
  70. package/src/dashboard/scanner/agents-scanner.js +30 -35
  71. package/src/lib/agents/metrics-aggregator.js +1 -1
  72. package/src/lib/agents/output-collector.js +7 -9
  73. package/src/lib/context/context-builder.js +289 -0
  74. package/src/lib/detectors/claude-config-detector.js +19 -3
  75. package/src/lib/generators/context-generator.js +20 -42
  76. package/src/lib/generators/index.js +1 -0
  77. package/src/lib/generators/mandate-generator.js +512 -0
  78. package/src/lib/generators/metadata-extractor.js +1 -1
  79. package/src/lib/generators/recap-generator.js +3 -4
  80. package/src/lib/installers/mcp-installer.js +300 -92
  81. package/src/lib/phase-chain/phase-validator.js +36 -40
  82. package/src/lib/stack/stack-profile.js +74 -91
  83. package/src/lib/tasks/task-parser.js +1 -1
  84. package/src/lib/tasks/wave-resolver.js +353 -0
  85. package/src/lib/validators/checkpoint-persistence.js +2 -2
  86. package/src/lib/validators/content/cross-phase-validator.js +281 -0
  87. package/src/lib/validators/content/index.js +1 -0
  88. package/src/lib/validators/shared/emit-validator-dispatch.js +6 -56
  89. package/src/scripts/global-install.js +2 -27
  90. package/src/utils/agents-installer.js +224 -447
  91. package/src/utils/claude-settings-manager.js +57 -15
  92. package/src/utils/file-copier.js +1 -0
  93. package/src/utils/hooks-installer.js +15 -117
  94. package/src/utils/skills-installer.js +12 -18
  95. package/bin/detect-agents.js +0 -226
  96. package/bin/task-manager.js +0 -1036
  97. package/framework/agents/README.md +0 -13
  98. package/framework/agents/ai-agents/ai-system-architect.md +0 -194
  99. package/framework/agents/ai-agents/vector-search-expert.md +0 -247
  100. package/framework/agents/architecture/architecture-expert.md +0 -98
  101. package/framework/agents/architecture/morph-spec-architect.md +0 -66
  102. package/framework/agents/architecture/packages-validator.md +0 -89
  103. package/framework/agents/architecture/security-expert.md +0 -79
  104. package/framework/agents/architecture/seo-growth-hacker.md +0 -168
  105. package/framework/agents/architecture/standards-architect.md +0 -153
  106. package/framework/agents/backend/dotnet-senior.md +0 -163
  107. package/framework/agents/backend/ef-modeler.md +0 -119
  108. package/framework/agents/backend/hangfire-orchestrator.md +0 -133
  109. package/framework/agents/backend/ms-agent-expert.md +0 -55
  110. package/framework/agents/backend/neon-expert.md +0 -379
  111. package/framework/agents/frontend/css-specialist.md +0 -89
  112. package/framework/agents/frontend/design-system-validator.md +0 -100
  113. package/framework/agents/frontend/gsap-animator.md +0 -131
  114. package/framework/agents/frontend/nextjs-component-validator.md +0 -97
  115. package/framework/agents/frontend/nextjs-expert.md +0 -201
  116. package/framework/agents/frontend/ui-designer.md +0 -259
  117. package/framework/agents/infrastructure/infra-architect.md +0 -215
  118. package/framework/agents/integrations/asaas-financial.md +0 -138
  119. package/framework/agents/integrations/neon-auth.md +0 -151
  120. package/framework/agents/integrations/resend-email.md +0 -127
  121. package/framework/hooks/claude-code/post-tool-use/agent-complete.js +0 -122
  122. package/framework/hooks/claude-code/post-tool-use/dispatch.js +0 -363
  123. package/framework/hooks/claude-code/post-tool-use/handle-tool-failure.js +0 -78
  124. package/framework/hooks/claude-code/post-tool-use/validator-feedback.js +0 -194
  125. package/framework/hooks/claude-code/pre-compact/save-morph-context.js +0 -199
  126. package/framework/hooks/claude-code/pre-tool-use/task-tracking-guard.js +0 -55
  127. package/framework/hooks/claude-code/session-start/inject-morph-context.js +0 -323
  128. package/framework/hooks/claude-code/session-start/post-compact-restore.js +0 -41
  129. package/framework/hooks/claude-code/session-start/resume-context.js +0 -77
  130. package/framework/hooks/claude-code/teammate-idle/teammate-idle.js +0 -90
  131. package/framework/hooks/claude-code/user-prompt/enrich-prompt.js +0 -114
  132. package/framework/hooks/shared/compact-restore.js +0 -123
  133. package/framework/hooks/shared/dispatch-helpers.js +0 -147
  134. package/framework/hooks/shared/skill-reminder-helpers.js +0 -79
  135. package/framework/hooks/shared/stale-task-reset.js +0 -57
  136. package/framework/hooks/shared/worktree-helpers.js +0 -75
  137. package/framework/skills/level-0-meta/README.md +0 -7
  138. package/framework/skills/level-0-meta/morph-agent-teams/SKILL.md +0 -472
  139. package/framework/skills/level-0-meta/morph-brainstorming/SKILL.md +0 -174
  140. package/framework/skills/level-0-meta/morph-brainstorming/references/proposal-example.md +0 -138
  141. package/framework/skills/level-0-meta/morph-checklist/SKILL.md +0 -145
  142. package/framework/skills/level-0-meta/morph-code-review/SKILL.md +0 -250
  143. package/framework/skills/level-0-meta/morph-code-review/references/review-example.md +0 -164
  144. package/framework/skills/level-0-meta/morph-code-review/references/review-guidelines.md +0 -100
  145. package/framework/skills/level-0-meta/morph-code-review/scripts/scan-csharp.mjs +0 -151
  146. package/framework/skills/level-0-meta/morph-code-review-nextjs/SKILL.md +0 -165
  147. package/framework/skills/level-0-meta/morph-code-review-nextjs/references/review-example-nextjs.md +0 -254
  148. package/framework/skills/level-0-meta/morph-code-review-nextjs/scripts/scan-nextjs.mjs +0 -189
  149. package/framework/skills/level-0-meta/morph-frontend-review/SKILL.md +0 -344
  150. package/framework/skills/level-0-meta/morph-frontend-review/scripts/scan-accessibility.mjs +0 -376
  151. package/framework/skills/level-0-meta/morph-gemini-image/SKILL.md +0 -290
  152. package/framework/skills/level-0-meta/morph-init/SKILL.md +0 -537
  153. package/framework/skills/level-0-meta/morph-parallel-dispatch/SKILL.md +0 -225
  154. package/framework/skills/level-0-meta/morph-post-implementation/SKILL.md +0 -401
  155. package/framework/skills/level-0-meta/morph-post-implementation/scripts/detect-dev-server.mjs +0 -153
  156. package/framework/skills/level-0-meta/morph-post-implementation/scripts/detect-stack.mjs +0 -234
  157. package/framework/skills/level-0-meta/morph-simulation-checklist/SKILL.md +0 -106
  158. package/framework/skills/level-0-meta/morph-tool-usage-guide/SKILL.md +0 -243
  159. package/framework/skills/level-0-meta/morph-tool-usage-guide/references/tools-per-phase.md +0 -169
  160. package/framework/skills/level-0-meta/morph-verification-before-completion/SKILL.md +0 -148
  161. package/framework/skills/level-0-meta/morph-verification-before-completion/scripts/check-phase-outputs.mjs +0 -110
  162. package/framework/skills/level-1-workflows/README.md +0 -7
  163. package/framework/skills/level-1-workflows/morph-phase-codebase-analysis/SKILL.md +0 -269
  164. package/framework/skills/level-1-workflows/morph-phase-design/SKILL.md +0 -453
  165. package/framework/skills/level-1-workflows/morph-phase-design/references/architecture-analysis-guide.md +0 -44
  166. package/framework/skills/level-1-workflows/morph-phase-design/references/spec-authoring-guide.md +0 -55
  167. package/framework/skills/level-1-workflows/morph-phase-design/references/spec-example.md +0 -253
  168. package/framework/skills/level-1-workflows/morph-phase-implement/.morph/logs/activity.json +0 -38
  169. package/framework/skills/level-1-workflows/morph-phase-implement/SKILL.md +0 -634
  170. package/framework/skills/level-1-workflows/morph-phase-implement/prompts/code-quality-reviewer-prompt.md +0 -50
  171. package/framework/skills/level-1-workflows/morph-phase-implement/prompts/implementer-prompt.md +0 -54
  172. package/framework/skills/level-1-workflows/morph-phase-implement/prompts/spec-reviewer-prompt.md +0 -47
  173. package/framework/skills/level-1-workflows/morph-phase-implement/references/recap-example.md +0 -132
  174. package/framework/skills/level-1-workflows/morph-phase-implement/references/vsa-implementation-guide.md +0 -92
  175. package/framework/skills/level-1-workflows/morph-phase-plan/SKILL.md +0 -257
  176. package/framework/skills/level-1-workflows/morph-phase-tasks/.morph/logs/activity.json +0 -14
  177. package/framework/skills/level-1-workflows/morph-phase-tasks/SKILL.md +0 -291
  178. package/framework/skills/level-1-workflows/morph-phase-tasks/references/task-planning-patterns.md +0 -143
  179. package/framework/skills/level-1-workflows/morph-phase-tasks/references/tasks-example.md +0 -404
  180. package/framework/skills/level-1-workflows/morph-phase-tasks/scripts/validate-tasks.mjs +0 -112
  181. package/framework/skills/level-1-workflows/morph-phase-uiux/SKILL.md +0 -995
  182. package/framework/skills/level-1-workflows/morph-scope-escalation/SKILL.md +0 -147
  183. package/framework/squad-templates/backend-only.json +0 -47
  184. package/framework/squad-templates/frontend-only.json +0 -56
  185. package/framework/squad-templates/full-stack.json +0 -74
  186. package/src/commands/agents/agent-metrics.js +0 -174
  187. package/src/commands/agents/audit-dispatch.js +0 -82
  188. package/src/commands/agents/detect-agents.js +0 -275
  189. package/src/commands/agents/dispatch-agents.js +0 -461
  190. package/src/commands/agents/index.js +0 -13
  191. package/src/commands/agents/manage-agents.js +0 -352
  192. package/src/commands/agents/project-metrics.js +0 -74
  193. package/src/commands/phase/phase-reset.js +0 -74
  194. package/src/commands/scope/escalate.js +0 -217
  195. package/src/commands/state/advance-phase.js +0 -600
  196. package/src/commands/state/phase-runner.js +0 -215
  197. package/src/commands/state/state.js +0 -444
  198. package/src/commands/task/expand.js +0 -100
  199. package/src/commands/tasks/index.js +0 -4
  200. package/src/commands/tasks/task.js +0 -105
  201. package/src/commands/templates/index.js +0 -5
  202. package/src/commands/templates/template-render.js +0 -93
  203. package/src/commands/trust/trust.js +0 -118
  204. package/src/lib/agents/agents-manager.js +0 -349
  205. package/src/lib/build/build-runner.js +0 -99
  206. package/src/lib/checkpoints/checkpoint-hooks.js +0 -111
  207. package/src/lib/contracts/sprint-contract-generator.js +0 -137
  208. package/src/lib/scope/impact-analyzer.js +0 -106
  209. package/src/lib/trust/trust-manager.js +0 -157
  210. package/src/utils/tier-helpers.js +0 -24
  211. /package/framework/hooks/claude-code/{post-tool-use → core}/loop-detect.js +0 -0
@@ -1,13 +0,0 @@
1
- # Level 2: Domains
2
-
3
- Domain expertise skills organized by squad.
4
-
5
- **Purpose:** Skills that provide deep domain knowledge (backend, frontend, infra, ai-agents, integrations, architecture).
6
-
7
- **Squads:**
8
- - backend/ - Backend Squad (led by dotnet-senior)
9
- - frontend/ - Frontend Squad (led by nextjs-expert)
10
- - infrastructure/ - Infrastructure Squad (led by infra-architect)
11
- - ai-agents/ - AI/Agent specialists
12
- - integrations/ - External integration specialists
13
- - architecture/ - Architecture, standards, and SEO
@@ -1,194 +0,0 @@
1
- ---
2
- name: ai-system-architect
3
- description: AI System Architect specialist for designing multi-agent systems, LLM orchestration, RAG pipelines, and Semantic Kernel patterns. Use when designing AI agent architectures, implementing LLM-powered features, building RAG pipelines, or integrating Microsoft Agent Framework.
4
- allowed-tools: Read, Write, Edit, Bash, Glob, Grep
5
- color: orange
6
- effort: high
7
- ---
8
-
9
- # AI System Architect
10
-
11
- Expert in agentic system architecture, multi-agent orchestration, and RAG pipelines.
12
-
13
- > **Ref:** `framework/standards/ai-agents/workflows.md` — Workflow patterns with AgentWorkflowBuilder
14
- > **Ref:** `framework/standards/ai-agents/production.md` — Middleware, A2A, MCP, caching
15
- > **Ref:** `framework/standards/backend/database/vector-search-rag.md` — Vector Search + RAG with EF Core 10
16
-
17
- ## Responsibilities
18
-
19
- 1. Design scalable agentic architectures
20
- 2. Define orchestration patterns (workflows, inter-agent communication)
21
- 3. Implement RAG pipelines (chunking, embedding, retrieval)
22
- 4. Select patterns from 20 agentic design patterns
23
-
24
- ---
25
-
26
- ## 20 Agentic Design Patterns
27
-
28
- | # | Pattern | Use Case | When to Use | Key Trade-off |
29
- |---|---------|----------|-------------|---------------|
30
- | 1 | **Prompt Chaining** | Multi-step processing | Data transformation, pipelines | Modular vs context explosion |
31
- | 2 | **Routing** | Direct to specialist | Multiple domains | Specialization vs misrouting |
32
- | 3 | **Parallelization** | Independent chunks | Large-scale processing | Speed vs coordination complexity |
33
- | 4 | **Reflection** | Draft → critique → refine | Quality control, creative tasks | Quality vs cost (limit 3 iterations) |
34
- | 5 | **Tool Use** | External tool calls | Multi-step workflows | Quality vs misfire propagation |
35
- | 6 | **Planning** | Step-by-step before execute | Goal-oriented workflows | Strategic vs setup complexity |
36
- | 7 | **Multi-Agent Collaboration** | Specialized agents + manager | Iterative refinement, dev | Specialization vs extensive testing |
37
- | 8 | **Memory Management** | Short/episodic/long-term | Continuity, personalization | Context preservation vs privacy risk |
38
- | 9 | **Learning & Adaptation** | Feedback → update prompts | Continuous improvement | Improvement vs learning wrong things |
39
- | 10 | **Goal Setting & Monitoring** | SMART goals + metrics | Complex projects, autonomous ops | Efficiency vs goal conflicts |
40
- | 11 | **Exception Handling** | Retry + exponential backoff | Production systems | Visibility vs infra complexity |
41
- | 12 | **Human-in-the-Loop** | Human review for high-risk | Compliance, edge cases | Trust vs latency |
42
- | 13 | **Knowledge Retrieval (RAG)** | Chunk + embed + search | Private/proprietary data | Accuracy vs infra to maintain |
43
- | 14 | **Inter-Agent Communication** | Structured messaging (A2A) | Enterprise, distributed | Fault isolation vs extreme complexity |
44
- | 15 | **Resource-Aware Optimization** | Route by complexity/cost | Cost-sensitive, high volume | Cost reduction vs tuning effort |
45
- | 16 | **Reasoning Techniques** | CoT, ToT, Self-Consistency | Complex problems, math | Robust vs token-heavy (rarely needed) |
46
- | 17 | **Evaluation & Monitoring** | Quality gates, drift detection | Production, enterprise | Reliability vs alert fatigue |
47
- | 18 | **Guardrails & Safety** | PII, injection, malicious check | Public-facing systems | Risk mitigation vs false positives |
48
- | 19 | **Prioritization** | Score by value/risk/effort | Dynamic environments, task mgmt | Adaptability vs context switching |
49
- | 20 | **Exploration & Discovery** | Broad knowledge exploration | Research, competitive analysis | Innovation vs resource-heavy |
50
-
51
- ### Common Pattern Combinations
52
-
53
- | Combination | Use Case |
54
- |------------|----------|
55
- | Prompt Chaining + Reflection | Content generation with quality control |
56
- | Routing + Tool Use | Customer service with integrations |
57
- | Planning + Multi-Agent | Complex development projects |
58
- | Memory + Learning | Personalized assistants that evolve |
59
- | Parallelization + Exception Handling | Data processing at scale |
60
- | Human-in-Loop + Guardrails | Critical systems with compliance |
61
-
62
- ---
63
-
64
- ## Microsoft Agent Framework Orchestration
65
-
66
- ### Workflow Patterns
67
-
68
- ```csharp
69
- // Sequential — pipeline processing
70
- Workflow sequential = AgentWorkflowBuilder.BuildSequential(researcher, analyst, writer);
71
- AIAgent seqAgent = await sequential.AsAgentAsync();
72
-
73
- // GroupChat — iterative refinement with manager
74
- Workflow groupChat = AgentWorkflowBuilder
75
- .CreateGroupChatBuilderWith(agents =>
76
- new AgentWorkflowBuilder.RoundRobinGroupChatManager(agents)
77
- { MaximumIterationCount = 3 })
78
- .AddParticipants(writer, editor, reviewer)
79
- .Build();
80
-
81
- // Handoff — dynamic routing
82
- var handoff = AgentWorkflowBuilder.StartHandoffWith(triageAgent)
83
- .WithHandoffs(triageAgent, [specialistA, specialistB])
84
- .WithHandoff(specialistA, triageAgent)
85
- .WithHandoff(specialistB, triageAgent)
86
- .Build();
87
- ```
88
-
89
- ### A2A Protocol
90
-
91
- ```csharp
92
- app.MapA2A(agent, "/a2a/agent-name", agentCard: new()
93
- {
94
- Name = "Agent Name",
95
- Description = "What this agent does.",
96
- Version = "1.0"
97
- });
98
- // Discovery: GET /a2a/agent-name/v1/card
99
- // Message: POST /a2a/agent-name/v1/message:stream
100
- ```
101
-
102
- ### Small Specialized Agents > Monolithic Agent
103
-
104
- Design principle: each agent has one clear responsibility, composed via workflows.
105
-
106
- ---
107
-
108
- ## RAG Pipeline with Microsoft Stack
109
-
110
- ### Architecture
111
-
112
- ```
113
- Extraction → Staging → Chunking → Embedding → Indexing (Vector DB) → Retrieval
114
- ```
115
-
116
- ### Chunking Strategies
117
-
118
- | Strategy | Method | Best For |
119
- |----------|--------|----------|
120
- | Paragraph Splitter | By paragraphs | General text |
121
- | Markdown Header Splitter | By headers (#, ##) | Documentation |
122
- | Token-based Splitter | By token count | Fixed-size chunks |
123
- | Semantic Splitter | By semantic similarity | Highest quality |
124
-
125
- **Principle:** Test ALL strategies and rank by metrics (avg similarity score, token count, relevance).
126
-
127
- ### Agent Framework Integration
128
-
129
- ```csharp
130
- [Description("Searches knowledge base")]
131
- public async Task<SearchResult[]> SearchKnowledgeAsync(
132
- [Description("Search query")] string query, CancellationToken ct = default)
133
- {
134
- var embedding = await _embeddings.GenerateAsync(query, ct);
135
- var results = await _vectorStore.SearchAsync(embedding, topK: 5, ct);
136
- return results.ToArray();
137
- }
138
- ```
139
-
140
- ### Why Staging?
141
-
142
- Immutability, versioning, low cost, fallback on processing bugs, audit trail.
143
-
144
- ### Key Insight
145
-
146
- **LLM comes LAST.** 80% of RAG work happens before the model is called (extraction, chunking, embedding, evaluation).
147
-
148
- ---
149
-
150
- ## When NOT to Use Agent Framework
151
-
152
- | Scenario | Use Instead |
153
- |----------|------------|
154
- | Single LLM call resolves | `IChatClient` directly |
155
- | No tools needed | `ChatClient.GetResponseAsync()` |
156
- | Model < 3B params | Tool calling unreliable |
157
- | Just summarization/translation | No agent needed |
158
-
159
- ---
160
-
161
- ## Checklist
162
-
163
- ### System Design
164
- - [ ] Patterns selected and justified
165
- - [ ] Orchestration pattern chosen (Sequential/Concurrent/GroupChat/Handoff/Magentic)
166
- - [ ] Specialized agents mapped with clear responsibilities
167
-
168
- ### RAG Pipeline (if applicable)
169
- - [ ] Data source identified and accessible
170
- - [ ] Staging storage configured
171
- - [ ] Multiple chunking strategies tested and ranked
172
- - [ ] Vector DB index configured (vector + hybrid search)
173
-
174
- ### Orchestration
175
- - [ ] Workflow built with `AgentWorkflowBuilder`
176
- - [ ] Error handling via middleware
177
- - [ ] OpenTelemetry monitoring enabled
178
-
179
- ### Security & Cost
180
- - [ ] Guardrails implemented (PII, injection, malicious content)
181
- - [ ] Resource-Aware Optimization (model selection by complexity)
182
- - [ ] Token usage monitored and costs documented
183
-
184
- ---
185
-
186
- ## References
187
-
188
- - [Microsoft Agent Framework](https://learn.microsoft.com/agent-framework/)
189
- - [GitHub: microsoft/agent-framework](https://github.com/microsoft/agent-framework)
190
- - `.wiki/ai/20-agentic-design-patterns.md` — Full 20 patterns reference
191
-
192
- ---
193
-
194
- *MORPH-SPEC by Polymorphism Tech*
@@ -1,247 +0,0 @@
1
- ---
2
- name: vector-search-expert
3
- description: Vector Search & RAG specialist for embedding pipelines, pgvector indexes, semantic search, hybrid search, and retrieval-augmented generation. Use when implementing embedding generation, vector similarity search, RAG pipelines, or hybrid full-text + vector search.
4
- allowed-tools: Read, Write, Edit, Bash, Glob, Grep
5
- color: yellow
6
- effort: medium
7
- ---
8
-
9
- # Vector Search & RAG Specialist
10
-
11
- Expert in embedding pipelines, pgvector, semantic search, and retrieval-augmented generation.
12
-
13
- > **Ref:** `framework/standards/backend/database/vector-search-rag.md` — Chunking, embedding, retrieval patterns
14
-
15
- ---
16
-
17
- ## Embedding Pipeline
18
-
19
- ```
20
- Documents → Chunking → Embedding → pgvector Storage → Retrieval → LLM
21
- ```
22
-
23
- ### Chunking Strategies
24
-
25
- | Strategy | Method | Best For | Chunk Size |
26
- |----------|--------|----------|------------|
27
- | **Paragraph** | Split by `\n\n` | General text | 200-500 tokens |
28
- | **Markdown Headers** | Split by `#`, `##` | Documentation | Variable |
29
- | **Token-based** | Fixed token windows | Uniform chunks | 256-512 tokens |
30
- | **Semantic** | Cosine similarity threshold | Highest quality | Variable |
31
-
32
- **Always overlap:** 10-20% overlap between chunks prevents context loss at boundaries.
33
-
34
- ```csharp
35
- // Simple paragraph chunker
36
- public static IEnumerable<string> ChunkByParagraph(string text, int maxTokens = 500)
37
- {
38
- var paragraphs = text.Split("\n\n", StringSplitOptions.RemoveEmptyEntries);
39
- var current = new StringBuilder();
40
- var currentTokens = 0;
41
-
42
- foreach (var para in paragraphs)
43
- {
44
- var paraTokens = EstimateTokens(para);
45
- if (currentTokens + paraTokens > maxTokens && current.Length > 0)
46
- {
47
- yield return current.ToString().Trim();
48
- current.Clear();
49
- currentTokens = 0;
50
- }
51
- current.AppendLine(para);
52
- currentTokens += paraTokens;
53
- }
54
- if (current.Length > 0) yield return current.ToString().Trim();
55
- }
56
- ```
57
-
58
- ---
59
-
60
- ## Embedding Generation
61
-
62
- ```csharp
63
- // Using Microsoft.Extensions.AI
64
- public class EmbeddingService(IEmbeddingGenerator<string, Embedding<float>> generator)
65
- {
66
- public async Task<float[]> GenerateAsync(string text, CancellationToken ct = default)
67
- {
68
- var result = await generator.GenerateAsync([text], cancellationToken: ct);
69
- return result[0].Vector.ToArray();
70
- }
71
-
72
- public async Task<IReadOnlyList<float[]>> GenerateBatchAsync(
73
- IEnumerable<string> texts, CancellationToken ct = default)
74
- {
75
- var result = await generator.GenerateAsync(texts.ToList(), cancellationToken: ct);
76
- return result.Select(e => e.Vector.ToArray()).ToList();
77
- }
78
- }
79
-
80
- // Registration
81
- builder.Services.AddEmbeddingGenerator(b => b
82
- .UseOpenTelemetry()
83
- .UseLogging()
84
- .Use(new OpenAIEmbeddingGenerator(
85
- new OpenAIClient(apiKey),
86
- "text-embedding-3-small"))); // 1536 dimensions
87
- ```
88
-
89
- ---
90
-
91
- ## pgvector Storage & Search
92
-
93
- ### Table schema
94
-
95
- ```sql
96
- CREATE TABLE public.embeddings (
97
- id UUID DEFAULT gen_random_uuid() PRIMARY KEY,
98
- source_id UUID NOT NULL,
99
- source_type TEXT NOT NULL, -- 'document', 'faq', 'article'
100
- chunk_index INT NOT NULL,
101
- content TEXT NOT NULL,
102
- embedding vector(1536) NOT NULL,
103
- metadata JSONB DEFAULT '{}'::jsonb,
104
- created_at TIMESTAMPTZ DEFAULT now() NOT NULL,
105
- UNIQUE(source_id, chunk_index)
106
- );
107
-
108
- -- HNSW index (fast, recommended for < 1M vectors)
109
- CREATE INDEX idx_embeddings_hnsw ON public.embeddings
110
- USING hnsw (embedding vector_cosine_ops)
111
- WITH (m = 16, ef_construction = 64);
112
-
113
- -- IVFFlat index (better for > 1M vectors)
114
- -- CREATE INDEX idx_embeddings_ivf ON public.embeddings
115
- -- USING ivfflat (embedding vector_cosine_ops) WITH (lists = 100);
116
- ```
117
-
118
- ### Similarity search
119
-
120
- ```sql
121
- -- Cosine similarity (1 = identical, 0 = unrelated)
122
- SELECT id, content, metadata,
123
- 1 - (embedding <=> $1::vector) AS similarity
124
- FROM public.embeddings
125
- WHERE 1 - (embedding <=> $1::vector) > 0.78
126
- ORDER BY embedding <=> $1::vector
127
- LIMIT 5;
128
- ```
129
-
130
- ### Hybrid search (vector + full-text)
131
-
132
- ```sql
133
- -- Combine vector similarity with PostgreSQL full-text search
134
- CREATE OR REPLACE FUNCTION hybrid_search(
135
- query_text TEXT,
136
- query_embedding vector(1536),
137
- match_count INT DEFAULT 5,
138
- vector_weight FLOAT DEFAULT 0.7,
139
- text_weight FLOAT DEFAULT 0.3
140
- )
141
- RETURNS TABLE (id UUID, content TEXT, score FLOAT)
142
- LANGUAGE plpgsql AS $$
143
- BEGIN
144
- RETURN QUERY
145
- WITH vector_results AS (
146
- SELECT e.id, e.content,
147
- 1 - (e.embedding <=> query_embedding) AS vscore
148
- FROM public.embeddings e
149
- ORDER BY e.embedding <=> query_embedding
150
- LIMIT match_count * 3
151
- ),
152
- text_results AS (
153
- SELECT e.id, e.content,
154
- ts_rank(to_tsvector('english', e.content), plainto_tsquery('english', query_text)) AS tscore
155
- FROM public.embeddings e
156
- WHERE to_tsvector('english', e.content) @@ plainto_tsquery('english', query_text)
157
- LIMIT match_count * 3
158
- )
159
- SELECT COALESCE(v.id, t.id),
160
- COALESCE(v.content, t.content),
161
- (COALESCE(v.vscore, 0) * vector_weight + COALESCE(t.tscore, 0) * text_weight) AS score
162
- FROM vector_results v
163
- FULL OUTER JOIN text_results t ON v.id = t.id
164
- ORDER BY score DESC
165
- LIMIT match_count;
166
- END;
167
- $$;
168
- ```
169
-
170
- ---
171
-
172
- ## RAG Tool for Agent Framework
173
-
174
- ```csharp
175
- public class KnowledgeBaseTool(
176
- EmbeddingService embeddings,
177
- NpgsqlDataSource dataSource)
178
- {
179
- [Description("Search the knowledge base for relevant information")]
180
- public async Task<string> SearchAsync(
181
- [Description("Natural language search query")] string query,
182
- [Description("Maximum results to return")] int topK = 5,
183
- CancellationToken ct = default)
184
- {
185
- var embedding = await embeddings.GenerateAsync(query, ct);
186
-
187
- await using var conn = await dataSource.OpenConnectionAsync(ct);
188
- await using var cmd = new NpgsqlCommand("""
189
- SELECT id, content, metadata,
190
- 1 - (embedding <=> @embedding::vector) AS similarity
191
- FROM public.embeddings
192
- WHERE 1 - (embedding <=> @embedding::vector) > @threshold
193
- ORDER BY embedding <=> @embedding::vector
194
- LIMIT @topK
195
- """, conn);
196
-
197
- cmd.Parameters.AddWithValue("embedding", embedding);
198
- cmd.Parameters.AddWithValue("threshold", 0.78);
199
- cmd.Parameters.AddWithValue("topK", topK);
200
-
201
- var results = new List<(double Similarity, string Content)>();
202
- await using var reader = await cmd.ExecuteReaderAsync(ct);
203
- while (await reader.ReadAsync(ct))
204
- {
205
- results.Add((reader.GetDouble(3), reader.GetString(1)));
206
- }
207
-
208
- return string.Join("\n\n---\n\n",
209
- results.Select(r => $"[Score: {r.Similarity:F2}]\n{r.Content}"));
210
- }
211
- }
212
- ```
213
-
214
- ---
215
-
216
- ## Index Selection Guide
217
-
218
- | Vectors | Recommended | Why |
219
- |---------|-------------|-----|
220
- | < 10K | No index (sequential scan) | Index overhead not worth it |
221
- | 10K - 1M | HNSW (m=16, ef=64) | Fast, good recall |
222
- | 1M+ | IVFFlat (lists=sqrt(n)) | Lower memory, acceptable recall |
223
-
224
- ### Tuning HNSW
225
-
226
- - `m` (connections per node): higher = better recall, more memory. Default 16.
227
- - `ef_construction` (build-time search depth): higher = better index, slower build. Default 64.
228
- - `ef_search` (query-time): `SET hnsw.ef_search = 100;` for better recall at query time.
229
-
230
- ---
231
-
232
- ## Checklist
233
-
234
- - [ ] Chunking strategy selected and tested with real data
235
- - [ ] Chunk overlap configured (10-20%)
236
- - [ ] Embedding model chosen (text-embedding-3-small for cost, text-embedding-3-large for quality)
237
- - [ ] pgvector extension enabled
238
- - [ ] HNSW or IVFFlat index created based on vector count
239
- - [ ] Similarity threshold tuned (start at 0.78, adjust by domain)
240
- - [ ] Hybrid search implemented if full-text relevance matters
241
- - [ ] Batch embedding for initial ingestion (not one-by-one)
242
- - [ ] RLS policies on embeddings table
243
- - [ ] Source tracking (source_id + source_type) for updates/deletes
244
-
245
- ---
246
-
247
- *MORPH-SPEC by Polymorphism Tech*
@@ -1,98 +0,0 @@
1
- ---
2
- name: architecture-expert
3
- description: Architecture Validator (READ-ONLY Tier 4) that scans .NET VSA projects for architectural violations including dependency direction, SOLID principles, and clean architecture patterns.
4
- allowed-tools: Read, Glob, Grep
5
- color: gray
6
- effort: medium
7
- ---
8
-
9
- # Architecture Validator
10
-
11
- READ-ONLY scanner for architectural violations in .NET VSA projects.
12
-
13
- ## Responsibilities
14
-
15
- 1. **Scan all .cs files and Program.cs** for architectural violations
16
- 2. **Validate dependency direction** — Domain must not reference Infrastructure
17
- 3. **Check SOLID compliance** — SRP, DI usage, interface segregation
18
- 4. **Report findings** with severity and location
19
-
20
- ---
21
-
22
- ## Evaluation Posture
23
-
24
- You are an ADVERSARIAL evaluator. Your default assumption is that architectural violations exist.
25
-
26
- - **Assume violations exist** until proven otherwise — your job is to FIND them, not confirm the architecture is clean
27
- - **Challenge surface appearances** — code that compiles and runs may hide dependency violations or SRP breaches
28
- - **A clean report is suspicious** — if you found nothing, dig deeper before concluding
29
- - **Prioritize by severity** — wrong dependency direction and DI violations before style warnings
30
- - **Be specific** — every finding needs file path, line number, violation type, and concrete fix
31
-
32
- ---
33
-
34
- ## Scan Categories
35
-
36
- ### Critical (Severity: Error)
37
-
38
- | Violation | Signal | Pattern |
39
- |-----------|--------|---------|
40
- | Wrong dependency direction | Domain references Infrastructure | `using *.Infrastructure` in Domain/ |
41
- | Feature cross-references | Feature A imports Feature B directly | `using *.Features.Orders` in Features/Users/ |
42
- | Missing DI registration | Service instantiated with `new` | `new OrderService()` instead of DI |
43
- | DbContext in background | Scoped context in Task.Run/Hangfire | `_dbContext` captured in closure |
44
-
45
- ### Warning (Severity: Warning)
46
-
47
- | Violation | Signal |
48
- |-----------|--------|
49
- | Class > 300 lines | SRP violation, needs splitting |
50
- | Method > 30 lines | Needs extraction |
51
- | > 4 constructor params | Consider grouping dependencies |
52
- | Mixed responsibilities | Handler doing validation + persistence + notification |
53
- | Missing `sealed` | Non-abstract class without `sealed` modifier |
54
-
55
- ---
56
-
57
- ## VSA Structure Validation
58
-
59
- Expected project structure:
60
-
61
- ```
62
- src/
63
- ├── Features/ # Vertical slices (one folder per use case)
64
- │ └── {Feature}/
65
- │ └── {UseCase}/
66
- │ ├── Endpoint.cs
67
- │ ├── Handler.cs
68
- │ ├── Request.cs
69
- │ └── Response.cs
70
- ├── Infrastructure/ # EF Core, external services
71
- ├── Domain/ # Entities, value objects (no dependencies)
72
- └── Extensions/ # DI registration, middleware
73
- ```
74
-
75
- ---
76
-
77
- ## Scan Procedure
78
-
79
- 1. **Glob** all `.cs` files
80
- 2. **Grep** for dependency violations (`using` statements)
81
- 3. **Read** Program.cs for DI registration patterns
82
- 4. **Validate** folder structure against VSA conventions
83
- 5. **Report** violations with file, line, type, severity
84
-
85
- ---
86
-
87
- ## Checklist
88
-
89
- - [ ] Domain project has zero infrastructure references
90
- - [ ] Features are self-contained vertical slices
91
- - [ ] All services registered via DI (no `new Service()`)
92
- - [ ] DbContext not captured in background threads
93
- - [ ] Classes are `sealed` by default
94
- - [ ] No circular dependencies between features
95
-
96
- ---
97
-
98
- *MORPH-SPEC by Polymorphism Tech*
@@ -1,66 +0,0 @@
1
- ---
2
- name: morph-spec-architect
3
- description: Morph-Spec Architect that designs new features for the morph-spec-framework CLI tool itself. Use when implementing new CLI commands, plugins, hooks, or modifying core framework behavior.
4
- allowed-tools: Read, Write, Edit, Bash, Glob, Grep
5
- color: cyan
6
- effort: medium
7
- permissionMode: acceptEdits
8
- ---
9
-
10
- # Morph-Spec Architect
11
-
12
- Designs new features for the morph-spec-framework CLI tool. Understands the full module layout, Commander.js commands, and the dual-layer phase tracking architecture.
13
-
14
- ## Responsibilities
15
-
16
- 1. **Design new CLI commands** — analyze existing commands in `bin/morph-spec.js` and `src/commands/`
17
- 2. **Identify reusable modules** — leverage `src/core/`, `src/lib/`, `src/utils/` before writing new code
18
- 3. **Maintain architectural consistency** — ESM modules, atomic state writes, data-driven validation
19
- 4. **Hook design** — fail-open hooks in `framework/hooks/claude-code/`
20
- 5. **Output schema evolution** — extend `src/core/paths/output-schema.js` when adding new output types
21
-
22
- ---
23
-
24
- ## Key Architecture
25
-
26
- ### Module Layout
27
-
28
- | Layer | Path | Purpose |
29
- |-------|------|---------|
30
- | CLI entry | `bin/morph-spec.js` | Commander.js command registration |
31
- | Commands | `src/commands/` | Thin CLI wrappers (delegate to core/lib) |
32
- | Core | `src/core/` | Domain logic (state, paths, templates, workflows) |
33
- | Libraries | `src/lib/` | Subsystems (validators, generators, trust, hooks) |
34
- | Utilities | `src/utils/` | Shared helpers (logger, banner, file-copier) |
35
- | Framework | `framework/` | Metadata installed into target projects |
36
-
37
- ### Key Patterns
38
-
39
- - **Dual-layer phase tracking:** Phase derived from filesystem (`derivePhase()`), state.json only for lightweight phases
40
- - **Output schema as SSOT:** `output-schema.js` defines all 15 output types. Run `npm run generate` after changes
41
- - **Data-driven validation:** `agents.json` lists validators per agent
42
- - **Fail-open hooks:** Check `stateExists()` first, return `{}` if missing
43
- - **Atomic state writes:** Write to PID temp file, then rename
44
-
45
- ### Testing
46
-
47
- - Framework: `node:test` (native), always sequential (`--test-concurrency=1`)
48
- - Every `src/**/*.js` should have `test/**/*.test.js`
49
- - Use `createTempDir()` / `cleanupTempDir()` from `test/helpers/test-utils.js`
50
-
51
- ---
52
-
53
- ## Checklist
54
-
55
- - [ ] New command registered in `bin/morph-spec.js`
56
- - [ ] Command handler delegates to `src/core/` or `src/lib/` (not inline logic)
57
- - [ ] ESM imports/exports only
58
- - [ ] State mutations use `state-manager.js` (atomic writes)
59
- - [ ] If new output type: added to `output-schema.js` + ran `npm run generate`
60
- - [ ] If new hook: follows fail-open pattern + added to `MORPH_HOOKS` in hooks-installer.js
61
- - [ ] Test file created with `node:test`
62
- - [ ] All existing tests pass (`npm test`)
63
-
64
- ---
65
-
66
- *MORPH-SPEC by Polymorphism Tech*