@polymorphism-tech/morph-spec 2.3.0 → 3.0.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 (166) hide show
  1. package/CLAUDE.md +446 -1730
  2. package/README.md +515 -516
  3. package/bin/morph-spec.js +366 -294
  4. package/bin/task-manager.js +429 -368
  5. package/bin/validate.js +369 -268
  6. package/content/.claude/commands/morph-apply.md +221 -158
  7. package/content/.claude/commands/morph-deploy.md +529 -0
  8. package/content/.claude/commands/morph-preflight.md +227 -0
  9. package/content/.claude/commands/morph-proposal.md +122 -101
  10. package/content/.claude/commands/morph-status.md +86 -86
  11. package/content/.claude/commands/morph-troubleshoot.md +122 -0
  12. package/content/.claude/skills/infra/azure-deploy-specialist.md +699 -0
  13. package/content/.claude/skills/level-0-meta/README.md +7 -0
  14. package/content/.claude/skills/level-0-meta/code-review.md +226 -0
  15. package/content/.claude/skills/level-0-meta/morph-checklist.md +117 -0
  16. package/content/.claude/skills/level-0-meta/simulation-checklist.md +77 -0
  17. package/content/.claude/skills/level-1-workflows/README.md +7 -0
  18. package/content/.claude/skills/level-1-workflows/morph-replicate.md +213 -0
  19. package/content/.claude/{commands/morph-clarify.md → skills/level-1-workflows/phase-clarify.md} +131 -184
  20. package/content/.claude/{commands/morph-design.md → skills/level-1-workflows/phase-design.md} +213 -275
  21. package/content/.claude/skills/level-1-workflows/phase-setup.md +106 -0
  22. package/content/.claude/skills/level-1-workflows/phase-tasks.md +164 -0
  23. package/content/.claude/{commands/morph-uiux.md → skills/level-1-workflows/phase-uiux.md} +169 -211
  24. package/content/.claude/skills/level-2-domains/README.md +14 -0
  25. package/content/.claude/skills/level-2-domains/ai-agents/ai-system-architect.md +192 -0
  26. package/content/.claude/skills/{specialists → level-2-domains/architecture}/po-pm-advisor.md +197 -197
  27. package/content/.claude/skills/level-2-domains/architecture/standards-architect.md +156 -0
  28. package/content/.claude/skills/level-2-domains/backend/dotnet-senior.md +287 -0
  29. package/content/.claude/skills/level-2-domains/backend/ef-modeler.md +113 -0
  30. package/content/.claude/skills/level-2-domains/backend/hangfire-orchestrator.md +126 -0
  31. package/content/.claude/skills/level-2-domains/backend/ms-agent-expert.md +109 -0
  32. package/content/.claude/skills/level-2-domains/frontend/blazor-builder.md +210 -0
  33. package/content/.claude/skills/level-2-domains/frontend/nextjs-expert.md +154 -0
  34. package/content/.claude/skills/level-2-domains/frontend/ui-ux-designer.md +191 -0
  35. package/content/.claude/skills/{specialists → level-2-domains/infrastructure}/azure-architect.md +142 -142
  36. package/content/.claude/skills/level-2-domains/infrastructure/bicep-architect.md +126 -0
  37. package/content/.claude/skills/level-2-domains/infrastructure/container-specialist.md +131 -0
  38. package/content/.claude/skills/level-2-domains/infrastructure/devops-engineer.md +119 -0
  39. package/content/.claude/skills/level-2-domains/integrations/asaas-financial.md +130 -0
  40. package/content/.claude/skills/level-2-domains/integrations/azure-identity.md +142 -0
  41. package/content/.claude/skills/level-2-domains/integrations/clerk-auth.md +108 -0
  42. package/content/.claude/skills/level-2-domains/integrations/resend-email.md +119 -0
  43. package/content/.claude/skills/level-2-domains/quality/code-analyzer.md +235 -0
  44. package/content/.claude/skills/level-2-domains/quality/testing-specialist.md +126 -0
  45. package/content/.claude/skills/level-3-technologies/README.md +7 -0
  46. package/content/.claude/skills/level-4-patterns/README.md +7 -0
  47. package/content/.claude/skills/specialists/prompt-engineer.md +189 -0
  48. package/content/.claude/skills/specialists/seo-growth-hacker.md +320 -0
  49. package/content/.morph/config/agents.json +762 -242
  50. package/content/.morph/config/config.template.json +122 -108
  51. package/content/.morph/docs/workflows/design-impl.md +37 -0
  52. package/content/.morph/docs/workflows/enforcement-pipeline.md +668 -0
  53. package/content/.morph/docs/workflows/fast-track.md +29 -0
  54. package/content/.morph/docs/workflows/full-morph.md +76 -0
  55. package/content/.morph/docs/workflows/standard.md +44 -0
  56. package/content/.morph/docs/workflows/ui-refresh.md +39 -0
  57. package/content/.morph/examples/scheduled-reports/decisions.md +158 -0
  58. package/content/.morph/examples/scheduled-reports/proposal.md +95 -0
  59. package/content/.morph/examples/scheduled-reports/spec.md +267 -0
  60. package/content/.morph/hooks/README.md +348 -239
  61. package/content/.morph/hooks/pre-commit-agents.sh +24 -24
  62. package/content/.morph/hooks/task-completed.js +73 -0
  63. package/content/.morph/hooks/teammate-idle.js +68 -0
  64. package/content/.morph/schemas/tasks.schema.json +220 -0
  65. package/content/.morph/standards/agent-framework-blazor-ui.md +359 -0
  66. package/content/.morph/standards/agent-framework-production.md +410 -0
  67. package/content/.morph/standards/agent-framework-setup.md +413 -453
  68. package/content/.morph/standards/agent-framework-workflows.md +349 -0
  69. package/content/.morph/standards/agent-teams-workflow.md +474 -0
  70. package/content/.morph/standards/architecture.md +325 -325
  71. package/content/.morph/standards/azure.md +605 -379
  72. package/content/.morph/standards/dotnet10-migration.md +520 -494
  73. package/content/.morph/templates/CONTEXT-FEATURE.md +276 -0
  74. package/content/.morph/templates/CONTEXT.md +170 -0
  75. package/content/.morph/templates/agent.cs +163 -172
  76. package/content/.morph/templates/clarify-questions.md +159 -0
  77. package/content/.morph/templates/contracts/Commands.cs +74 -0
  78. package/content/.morph/templates/contracts/Entities.cs +25 -0
  79. package/content/.morph/templates/contracts/Queries.cs +74 -0
  80. package/content/.morph/templates/contracts/README.md +74 -0
  81. package/content/.morph/templates/decisions.md +123 -106
  82. package/content/.morph/templates/infra/azure-pipelines-deploy.yml +480 -0
  83. package/content/.morph/templates/infra/deploy-checklist.md +426 -0
  84. package/content/.morph/templates/proposal.md +141 -155
  85. package/content/.morph/templates/recap.md +94 -105
  86. package/content/.morph/templates/simulation.md +353 -0
  87. package/content/.morph/templates/spec.md +149 -148
  88. package/content/.morph/templates/state.template.json +222 -222
  89. package/content/.morph/templates/tasks.md +257 -235
  90. package/content/.morph/templates/ui-components.md +362 -276
  91. package/content/CLAUDE.md +150 -442
  92. package/detectors/structure-detector.js +245 -250
  93. package/docs/README.md +144 -149
  94. package/docs/getting-started.md +301 -302
  95. package/docs/installation.md +361 -361
  96. package/docs/validation-checklist.md +265 -266
  97. package/package.json +80 -80
  98. package/src/commands/advance-phase.js +266 -0
  99. package/src/commands/analyze-blazor-concurrency.js +193 -0
  100. package/src/commands/deploy.js +780 -0
  101. package/src/commands/detect-agents.js +167 -0
  102. package/src/commands/doctor.js +356 -280
  103. package/src/commands/generate-context.js +40 -0
  104. package/src/commands/init.js +258 -245
  105. package/src/commands/lint-fluent.js +352 -0
  106. package/src/commands/rollback-phase.js +185 -0
  107. package/src/commands/session-summary.js +291 -0
  108. package/src/commands/task.js +78 -75
  109. package/src/commands/troubleshoot.js +222 -0
  110. package/src/commands/update.js +192 -159
  111. package/src/commands/validate-blazor-state.js +210 -0
  112. package/src/commands/validate-blazor.js +156 -0
  113. package/src/commands/validate-css.js +84 -0
  114. package/src/commands/validate-phase.js +221 -0
  115. package/src/lib/blazor-concurrency-analyzer.js +288 -0
  116. package/src/lib/blazor-state-validator.js +291 -0
  117. package/src/lib/blazor-validator.js +374 -0
  118. package/src/lib/complexity-analyzer.js +441 -292
  119. package/src/lib/context-generator.js +513 -0
  120. package/src/lib/continuous-validator.js +421 -440
  121. package/src/lib/css-validator.js +352 -0
  122. package/src/lib/decision-constraint-loader.js +109 -0
  123. package/src/lib/design-system-detector.js +187 -0
  124. package/src/lib/design-system-scaffolder.js +299 -0
  125. package/src/lib/hook-executor.js +256 -0
  126. package/src/lib/recap-generator.js +205 -0
  127. package/src/lib/spec-validator.js +258 -0
  128. package/src/lib/standards-context-injector.js +287 -0
  129. package/src/lib/state-manager.js +397 -340
  130. package/src/lib/team-orchestrator.js +322 -0
  131. package/src/lib/troubleshoot-grep.js +194 -0
  132. package/src/lib/troubleshoot-index.js +144 -0
  133. package/src/lib/validation-runner.js +283 -0
  134. package/src/lib/validators/contract-compliance-validator.js +273 -0
  135. package/src/lib/validators/design-system-validator.js +231 -0
  136. package/src/utils/file-copier.js +187 -139
  137. package/content/.claude/commands/morph-costs.md +0 -206
  138. package/content/.claude/commands/morph-setup.md +0 -100
  139. package/content/.claude/commands/morph-tasks.md +0 -319
  140. package/content/.claude/skills/infra/bicep-architect.md +0 -419
  141. package/content/.claude/skills/infra/container-specialist.md +0 -437
  142. package/content/.claude/skills/infra/devops-engineer.md +0 -405
  143. package/content/.claude/skills/integrations/asaas-financial.md +0 -333
  144. package/content/.claude/skills/integrations/azure-identity.md +0 -309
  145. package/content/.claude/skills/integrations/clerk-auth.md +0 -290
  146. package/content/.claude/skills/specialists/ai-system-architect.md +0 -604
  147. package/content/.claude/skills/specialists/cost-guardian.md +0 -110
  148. package/content/.claude/skills/specialists/ef-modeler.md +0 -211
  149. package/content/.claude/skills/specialists/hangfire-orchestrator.md +0 -255
  150. package/content/.claude/skills/specialists/ms-agent-expert.md +0 -263
  151. package/content/.claude/skills/specialists/standards-architect.md +0 -78
  152. package/content/.claude/skills/specialists/ui-ux-designer.md +0 -1100
  153. package/content/.claude/skills/stacks/dotnet-blazor.md +0 -606
  154. package/content/.claude/skills/stacks/dotnet-nextjs.md +0 -402
  155. package/content/.claude/skills/stacks/shopify.md +0 -445
  156. package/content/.morph/config/azure-pricing.json +0 -70
  157. package/content/.morph/config/azure-pricing.schema.json +0 -50
  158. package/content/.morph/hooks/pre-commit-costs.sh +0 -91
  159. package/docs/api/cost-calculator.js.html +0 -513
  160. package/docs/api/design-system-generator.js.html +0 -382
  161. package/docs/api/global.html +0 -5263
  162. package/docs/api/index.html +0 -96
  163. package/docs/api/state-manager.js.html +0 -423
  164. package/src/commands/cost.js +0 -181
  165. package/src/commands/update-pricing.js +0 -206
  166. package/src/lib/cost-calculator.js +0 -429
@@ -0,0 +1,322 @@
1
+ /**
2
+ * @fileoverview Hierarchical Agent Teams Orchestrator
3
+ *
4
+ * Builds Agent Teams using 4-tier hierarchy:
5
+ * - Tier 1: Orchestrators (Team Lead in delegate mode)
6
+ * - Tier 2: Domain Leaders (Squad Leaders)
7
+ * - Tier 3: Specialists (Domain experts)
8
+ * - Tier 4: Validators (Run in hooks, not teammates)
9
+ *
10
+ * @module team-orchestrator
11
+ */
12
+
13
+ import fs from 'fs/promises';
14
+ import path from 'path';
15
+ import { fileURLToPath } from 'url';
16
+
17
+ const __filename = fileURLToPath(import.meta.url);
18
+ const __dirname = path.dirname(__filename);
19
+
20
+ /**
21
+ * Load agents.json with hierarchical structure
22
+ * @param {string} projectPath - Root path of the project
23
+ * @returns {Promise<Object>} Parsed agents configuration
24
+ */
25
+ async function loadAgentsConfig(projectPath) {
26
+ const agentsPath = path.join(projectPath, 'content/.morph/config/agents.json');
27
+ const content = await fs.readFile(agentsPath, 'utf8');
28
+ return JSON.parse(content);
29
+ }
30
+
31
+ /**
32
+ * Detect if Agent Teams should be spawned based on complexity
33
+ * @param {Object} options
34
+ * @param {string[]} options.activeAgents - Agent IDs detected for feature
35
+ * @param {string} options.complexity - Complexity level (trivial|low|medium|high|critical)
36
+ * @param {number} options.estimatedFiles - Estimated files to modify
37
+ * @param {boolean} options.multiDomain - Does feature span multiple domains?
38
+ * @returns {Object} { shouldSpawn: boolean, reason: string, recommendedMode: string }
39
+ */
40
+ export function shouldSpawnAgentTeam(options) {
41
+ const { activeAgents = [], complexity, estimatedFiles = 0, multiDomain = false } = options;
42
+
43
+ // Never spawn for trivial/low complexity
44
+ if (complexity === 'trivial' || complexity === 'low') {
45
+ return {
46
+ shouldSpawn: false,
47
+ reason: 'Complexity too low - single session sufficient',
48
+ recommendedMode: 'single'
49
+ };
50
+ }
51
+
52
+ // Always spawn for critical complexity
53
+ if (complexity === 'critical') {
54
+ return {
55
+ shouldSpawn: true,
56
+ reason: 'Critical complexity - parallel coordination essential',
57
+ recommendedMode: 'tmux'
58
+ };
59
+ }
60
+
61
+ // Spawn if multi-domain (backend + frontend + infra)
62
+ if (multiDomain) {
63
+ return {
64
+ shouldSpawn: true,
65
+ reason: 'Multi-domain feature - benefits from parallel squads',
66
+ recommendedMode: 'auto'
67
+ };
68
+ }
69
+
70
+ // Spawn if 3+ independent modules (high file count)
71
+ if (estimatedFiles >= 15) {
72
+ return {
73
+ shouldSpawn: true,
74
+ reason: 'High file count - parallel implementation recommended',
75
+ recommendedMode: 'auto'
76
+ };
77
+ }
78
+
79
+ // Spawn if 5+ specialists active (indicates complex coordination)
80
+ if (activeAgents.length >= 5) {
81
+ return {
82
+ shouldSpawn: true,
83
+ reason: '5+ specialists active - team coordination beneficial',
84
+ recommendedMode: 'auto'
85
+ };
86
+ }
87
+
88
+ // Default: single session for medium complexity
89
+ return {
90
+ shouldSpawn: false,
91
+ reason: 'Medium complexity - single session with subagents OK',
92
+ recommendedMode: 'single'
93
+ };
94
+ }
95
+
96
+ /**
97
+ * Build hierarchical team structure from active agents
98
+ * @param {string[]} activeAgentIds - Agent IDs to include in team
99
+ * @param {Object} agentsConfig - Loaded agents.json
100
+ * @returns {Object} Team structure with lead, domain leaders, specialists
101
+ */
102
+ export function buildTeamHierarchy(activeAgentIds, agentsConfig) {
103
+ const agents = agentsConfig.agents;
104
+ const activeAgents = activeAgentIds
105
+ .filter(id => !id.startsWith('_comment') && agents[id])
106
+ .map(id => ({ id, ...agents[id] }));
107
+
108
+ // Tier 1: Orchestrator (Team Lead)
109
+ const orchestrators = activeAgents.filter(a => a.tier === 1 && a.role === 'orchestrator');
110
+ const teamLead = orchestrators.find(a => a.id === 'standards-architect') || orchestrators[0];
111
+
112
+ // Tier 2: Domain Leaders
113
+ const domainLeaders = activeAgents.filter(a => a.tier === 2 && a.role === 'domain-leader');
114
+
115
+ // Tier 3: Specialists (group by domain)
116
+ const specialists = activeAgents.filter(a => a.tier === 3 && a.role === 'specialist');
117
+
118
+ // Tier 4: Validators (run in hooks, NOT teammates)
119
+ const validators = activeAgents.filter(a => a.tier === 4 && a.role === 'validator');
120
+
121
+ // Group specialists under their Domain Leaders
122
+ const squads = {};
123
+ domainLeaders.forEach(leader => {
124
+ const squadMembers = specialists.filter(specialist => {
125
+ // Check if specialist reports to this leader
126
+ return specialist.relationships?.reports_to === leader.id;
127
+ });
128
+
129
+ if (squadMembers.length > 0) {
130
+ squads[leader.id] = {
131
+ leader,
132
+ members: squadMembers
133
+ };
134
+ }
135
+ });
136
+
137
+ return {
138
+ teamLead,
139
+ squads,
140
+ validators, // Not in teammates, run as hooks
141
+ totalTeammates: 1 + domainLeaders.length + specialists.length // Lead + Leaders + Specialists
142
+ };
143
+ }
144
+
145
+ /**
146
+ * Generate teammate spawn instructions for Agent Teams
147
+ * @param {Object} teamHierarchy - Output from buildTeamHierarchy
148
+ * @param {string} featureName - Feature name
149
+ * @param {string} phase - Current MORPH phase
150
+ * @returns {Object[]} Array of teammate configs for Agent Teams
151
+ */
152
+ export function generateTeammateConfigs(teamHierarchy, featureName, phase) {
153
+ const teammates = [];
154
+ const { teamLead, squads } = teamHierarchy;
155
+
156
+ // Add Team Lead (standards-architect in delegate mode)
157
+ if (teamLead && teamLead.teammate) {
158
+ teammates.push({
159
+ id: teamLead.id,
160
+ tier: teamLead.tier,
161
+ role: teamLead.teammate.role,
162
+ icon: teamLead.teammate.icon,
163
+ spawnPrompt: `${teamLead.teammate.spawn_prompt}
164
+
165
+ Feature: ${featureName}
166
+ Phase: ${phase}
167
+
168
+ Your Domain Leaders:
169
+ ${Object.values(squads).map(s => `- ${s.leader.title} (${s.leader.id})`).join('\n')}
170
+
171
+ DO NOT implement code yourself. Coordinate Domain Leaders, resolve conflicts, synthesize results.`
172
+ });
173
+ }
174
+
175
+ // Add Domain Leaders + their squad members
176
+ Object.entries(squads).forEach(([leaderId, squad]) => {
177
+ const leader = squad.leader;
178
+
179
+ // Add Domain Leader
180
+ if (leader.teammate) {
181
+ teammates.push({
182
+ id: leader.id,
183
+ tier: leader.tier,
184
+ role: leader.teammate.role,
185
+ icon: leader.teammate.icon,
186
+ spawnPrompt: `${leader.teammate.spawn_prompt}
187
+
188
+ Feature: ${featureName}
189
+ Phase: ${phase}
190
+
191
+ Your Squad (${squad.members.length} specialists):
192
+ ${squad.members.map(m => `- ${m.title} (${m.id})`).join('\n')}
193
+
194
+ Coordinate your specialists. Escalate conflicts to ${leader.relationships.escalates_to}.`
195
+ });
196
+ }
197
+
198
+ // Add Specialists in this squad
199
+ squad.members.forEach(specialist => {
200
+ if (specialist.teammate) {
201
+ teammates.push({
202
+ id: specialist.id,
203
+ tier: specialist.tier,
204
+ role: specialist.teammate.role,
205
+ icon: specialist.teammate.icon,
206
+ spawnPrompt: `${specialist.teammate.spawn_prompt}
207
+
208
+ Feature: ${featureName}
209
+ Phase: ${phase}
210
+
211
+ Reports to: ${specialist.relationships.reports_to}
212
+ Escalate to: ${specialist.relationships.escalates_to}
213
+
214
+ ${specialist.relationships.collaborates_with ?
215
+ `Collaborate with: ${specialist.relationships.collaborates_with.join(', ')}` : ''}`
216
+ });
217
+ }
218
+ });
219
+ });
220
+
221
+ return teammates;
222
+ }
223
+
224
+ /**
225
+ * Generate Agent Teams command for spawning
226
+ * @param {Object[]} teammates - Output from generateTeammateConfigs
227
+ * @param {string} displayMode - 'auto' | 'in-process' | 'tmux'
228
+ * @returns {string} Command to spawn Agent Teams
229
+ */
230
+ export function generateSpawnCommand(teammates, displayMode = 'auto') {
231
+ // Agent Teams are spawned via Claude Code's Task tool with subagent_type="general-purpose"
232
+ // and special teammate configs. This is a conceptual representation.
233
+
234
+ const command = {
235
+ tool: 'Task',
236
+ subagent_type: 'general-purpose',
237
+ agent_teams_enabled: true,
238
+ display_mode: displayMode,
239
+ teammates: teammates.map(t => ({
240
+ id: t.id,
241
+ role: t.role,
242
+ icon: t.icon,
243
+ prompt: t.spawnPrompt
244
+ }))
245
+ };
246
+
247
+ return JSON.stringify(command, null, 2);
248
+ }
249
+
250
+ /**
251
+ * Main orchestration function - decides if/when to spawn Agent Teams
252
+ * @param {Object} options
253
+ * @param {string} options.projectPath - Project root path
254
+ * @param {string} options.featureName - Feature name
255
+ * @param {string} options.phase - MORPH phase
256
+ * @param {string[]} options.activeAgents - Active agent IDs
257
+ * @param {string} options.complexity - Complexity level
258
+ * @param {number} options.estimatedFiles - Estimated file count
259
+ * @param {boolean} options.multiDomain - Multi-domain feature?
260
+ * @returns {Promise<Object>} Team orchestration result
261
+ */
262
+ export async function orchestrateTeam(options) {
263
+ const {
264
+ projectPath,
265
+ featureName,
266
+ phase,
267
+ activeAgents = [],
268
+ complexity,
269
+ estimatedFiles = 0,
270
+ multiDomain = false
271
+ } = options;
272
+
273
+ // Step 1: Decide if Agent Teams should spawn
274
+ const spawnDecision = shouldSpawnAgentTeam({
275
+ activeAgents,
276
+ complexity,
277
+ estimatedFiles,
278
+ multiDomain
279
+ });
280
+
281
+ if (!spawnDecision.shouldSpawn) {
282
+ return {
283
+ useAgentTeams: false,
284
+ reason: spawnDecision.reason,
285
+ recommendation: 'Use single session with Task tool for subagents'
286
+ };
287
+ }
288
+
289
+ // Step 2: Load agents config and build hierarchy
290
+ const agentsConfig = await loadAgentsConfig(projectPath);
291
+ const teamHierarchy = buildTeamHierarchy(activeAgents, agentsConfig);
292
+
293
+ // Step 3: Generate teammate configs
294
+ const teammates = generateTeammateConfigs(teamHierarchy, featureName, phase);
295
+
296
+ // Step 4: Generate spawn command
297
+ const spawnCommand = generateSpawnCommand(teammates, spawnDecision.recommendedMode);
298
+
299
+ return {
300
+ useAgentTeams: true,
301
+ reason: spawnDecision.reason,
302
+ displayMode: spawnDecision.recommendedMode,
303
+ teamHierarchy: {
304
+ teamLead: teamHierarchy.teamLead?.id,
305
+ squads: Object.keys(teamHierarchy.squads),
306
+ totalTeammates: teamHierarchy.totalTeammates,
307
+ validators: teamHierarchy.validators.map(v => v.id)
308
+ },
309
+ teammates,
310
+ spawnCommand,
311
+ recommendation: `Spawn ${teamHierarchy.totalTeammates} teammates in ${spawnDecision.recommendedMode} mode`
312
+ };
313
+ }
314
+
315
+ /**
316
+ * Get agent squad assignments (for informational purposes)
317
+ * @param {Object} agentsConfig - Loaded agents.json
318
+ * @returns {Object} Squad information
319
+ */
320
+ export function getSquadInfo(agentsConfig) {
321
+ return agentsConfig.squads || {};
322
+ }
@@ -0,0 +1,194 @@
1
+ /**
2
+ * Troubleshoot Grep Fallback
3
+ * Searches markdown files for matching content when index doesn't find results
4
+ */
5
+
6
+ import { readFileSync, readdirSync, existsSync } from 'fs';
7
+ import { join, dirname, basename } from 'path';
8
+ import { fileURLToPath } from 'url';
9
+
10
+ const __filename = fileURLToPath(import.meta.url);
11
+ const __dirname = dirname(__filename);
12
+
13
+ // Directories to search
14
+ const SEARCH_PATHS = [
15
+ 'framework/standards',
16
+ 'content/.morph/standards',
17
+ '.wiki'
18
+ ];
19
+
20
+ /**
21
+ * Get all markdown files from search paths
22
+ * @param {string} basePath - Base path of the project
23
+ * @returns {string[]} Array of file paths
24
+ */
25
+ function getMarkdownFiles(basePath) {
26
+ const files = [];
27
+
28
+ for (const searchPath of SEARCH_PATHS) {
29
+ const fullPath = join(basePath, searchPath);
30
+
31
+ if (!existsSync(fullPath)) {
32
+ continue;
33
+ }
34
+
35
+ try {
36
+ const entries = readdirSync(fullPath, { withFileTypes: true });
37
+
38
+ for (const entry of entries) {
39
+ if (entry.isFile() && entry.name.endsWith('.md')) {
40
+ files.push(join(fullPath, entry.name));
41
+ }
42
+ }
43
+ } catch (error) {
44
+ // Skip directories we can't read
45
+ }
46
+ }
47
+
48
+ return files;
49
+ }
50
+
51
+ /**
52
+ * Extract section containing the match
53
+ * @param {string} content - File content
54
+ * @param {number} matchIndex - Index of the match
55
+ * @returns {Object} Section object with title and content
56
+ */
57
+ function extractSection(content, matchIndex) {
58
+ const lines = content.split('\n');
59
+ let charCount = 0;
60
+ let matchLineIndex = 0;
61
+
62
+ // Find the line containing the match
63
+ for (let i = 0; i < lines.length; i++) {
64
+ charCount += lines[i].length + 1; // +1 for newline
65
+ if (charCount > matchIndex) {
66
+ matchLineIndex = i;
67
+ break;
68
+ }
69
+ }
70
+
71
+ // Find the section header (## heading) above the match
72
+ let sectionTitle = 'Unknown Section';
73
+ let sectionStart = 0;
74
+
75
+ for (let i = matchLineIndex; i >= 0; i--) {
76
+ if (lines[i].startsWith('## ')) {
77
+ sectionTitle = lines[i].replace('## ', '').trim();
78
+ sectionStart = i;
79
+ break;
80
+ }
81
+ }
82
+
83
+ // Find the end of the section (next ## or end of file)
84
+ let sectionEnd = lines.length;
85
+ for (let i = sectionStart + 1; i < lines.length; i++) {
86
+ if (lines[i].startsWith('## ')) {
87
+ sectionEnd = i;
88
+ break;
89
+ }
90
+ }
91
+
92
+ // Extract section content (limit to ~20 lines around match)
93
+ const contextStart = Math.max(sectionStart, matchLineIndex - 10);
94
+ const contextEnd = Math.min(sectionEnd, matchLineIndex + 10);
95
+ const sectionContent = lines.slice(contextStart, contextEnd).join('\n');
96
+
97
+ return {
98
+ title: sectionTitle,
99
+ content: sectionContent,
100
+ lineNumber: matchLineIndex + 1
101
+ };
102
+ }
103
+
104
+ /**
105
+ * Search a file for keywords
106
+ * @param {string} filePath - Path to the file
107
+ * @param {string[]} keywords - Keywords to search for
108
+ * @returns {Object[]} Array of matches
109
+ */
110
+ function searchFile(filePath, keywords) {
111
+ const matches = [];
112
+
113
+ try {
114
+ const content = readFileSync(filePath, 'utf-8');
115
+ const contentLower = content.toLowerCase();
116
+
117
+ for (const keyword of keywords) {
118
+ const keywordLower = keyword.toLowerCase();
119
+ let index = contentLower.indexOf(keywordLower);
120
+
121
+ while (index !== -1) {
122
+ const section = extractSection(content, index);
123
+
124
+ // Check if we already have a match for this section
125
+ const existingMatch = matches.find(m => m.section === section.title);
126
+
127
+ if (existingMatch) {
128
+ existingMatch.matchCount++;
129
+ existingMatch.keywords.add(keyword);
130
+ } else {
131
+ matches.push({
132
+ file: filePath,
133
+ fileName: basename(filePath),
134
+ section: section.title,
135
+ content: section.content,
136
+ lineNumber: section.lineNumber,
137
+ matchCount: 1,
138
+ keywords: new Set([keyword])
139
+ });
140
+ }
141
+
142
+ index = contentLower.indexOf(keywordLower, index + 1);
143
+ }
144
+ }
145
+ } catch (error) {
146
+ // Skip files we can't read
147
+ }
148
+
149
+ return matches;
150
+ }
151
+
152
+ /**
153
+ * Search all markdown files for keywords
154
+ * @param {string[]} keywords - Keywords to search for
155
+ * @param {Object} options - Search options
156
+ * @returns {Object[]} Array of matches sorted by relevance
157
+ */
158
+ export function searchGrep(keywords, options = {}) {
159
+ // Determine base path
160
+ const basePath = options.basePath || join(__dirname, '../..');
161
+
162
+ const files = getMarkdownFiles(basePath);
163
+ let allMatches = [];
164
+
165
+ for (const file of files) {
166
+ const matches = searchFile(file, keywords);
167
+ allMatches = allMatches.concat(matches);
168
+ }
169
+
170
+ // Convert keywords Set to Array and calculate score
171
+ const results = allMatches.map(match => ({
172
+ ...match,
173
+ keywords: Array.from(match.keywords),
174
+ score: match.matchCount * 5 + match.keywords.size * 3,
175
+ source: 'grep'
176
+ }));
177
+
178
+ // Sort by score (higher is better) and deduplicate
179
+ const seen = new Set();
180
+ const uniqueResults = results
181
+ .sort((a, b) => b.score - a.score)
182
+ .filter(r => {
183
+ const key = `${r.file}:${r.section}`;
184
+ if (seen.has(key)) return false;
185
+ seen.add(key);
186
+ return true;
187
+ });
188
+
189
+ return uniqueResults.slice(0, 10); // Limit to top 10
190
+ }
191
+
192
+ export default {
193
+ searchGrep
194
+ };
@@ -0,0 +1,144 @@
1
+ /**
2
+ * Troubleshoot Index Search
3
+ * Searches the troubleshooting-index.json for matching problems
4
+ */
5
+
6
+ import { readFileSync, existsSync } from 'fs';
7
+ import { join, dirname } from 'path';
8
+ import { fileURLToPath } from 'url';
9
+
10
+ const __filename = fileURLToPath(import.meta.url);
11
+ const __dirname = dirname(__filename);
12
+
13
+ /**
14
+ * Load the troubleshooting index
15
+ * @returns {Object} The index object or null if not found
16
+ */
17
+ export function loadIndex() {
18
+ const indexPath = join(__dirname, '../../framework/index/troubleshooting-index.json');
19
+
20
+ if (!existsSync(indexPath)) {
21
+ return null;
22
+ }
23
+
24
+ try {
25
+ const content = readFileSync(indexPath, 'utf-8');
26
+ return JSON.parse(content);
27
+ } catch (error) {
28
+ console.error('Error loading troubleshooting index:', error.message);
29
+ return null;
30
+ }
31
+ }
32
+
33
+ /**
34
+ * Calculate relevance score for a problem based on keywords
35
+ * @param {Object} problem - The problem object from index
36
+ * @param {string[]} searchTerms - Search terms from user
37
+ * @returns {number} Relevance score (higher is better)
38
+ */
39
+ function calculateScore(problem, searchTerms) {
40
+ let score = 0;
41
+ const searchLower = searchTerms.map(t => t.toLowerCase());
42
+
43
+ // Check keywords
44
+ for (const keyword of problem.keywords) {
45
+ const keywordLower = keyword.toLowerCase();
46
+ for (const term of searchLower) {
47
+ if (keywordLower.includes(term) || term.includes(keywordLower)) {
48
+ score += 10;
49
+ }
50
+ }
51
+ }
52
+
53
+ // Check title
54
+ const titleLower = problem.title.toLowerCase();
55
+ for (const term of searchLower) {
56
+ if (titleLower.includes(term)) {
57
+ score += 5;
58
+ }
59
+ }
60
+
61
+ // Check error pattern (regex match on search string)
62
+ if (problem.errorPattern) {
63
+ try {
64
+ const regex = new RegExp(problem.errorPattern, 'i');
65
+ const searchString = searchTerms.join(' ');
66
+ if (regex.test(searchString)) {
67
+ score += 20; // High score for error pattern match
68
+ }
69
+ } catch (e) {
70
+ // Invalid regex, skip
71
+ }
72
+ }
73
+
74
+ // Boost critical severity
75
+ if (problem.severity === 'critical') {
76
+ score *= 1.2;
77
+ }
78
+
79
+ return score;
80
+ }
81
+
82
+ /**
83
+ * Search the index for problems matching the keywords
84
+ * @param {string[]} keywords - Search keywords
85
+ * @param {Object} options - Search options
86
+ * @param {string} options.category - Filter by category
87
+ * @returns {Object[]} Array of matching problems with scores
88
+ */
89
+ export function searchIndex(keywords, options = {}) {
90
+ const index = loadIndex();
91
+
92
+ if (!index || !index.problems) {
93
+ return [];
94
+ }
95
+
96
+ let problems = index.problems;
97
+
98
+ // Filter by category if specified
99
+ if (options.category) {
100
+ problems = problems.filter(p => p.category === options.category);
101
+ }
102
+
103
+ // Score and filter problems
104
+ const results = problems
105
+ .map(problem => ({
106
+ ...problem,
107
+ score: calculateScore(problem, keywords)
108
+ }))
109
+ .filter(p => p.score > 0)
110
+ .sort((a, b) => b.score - a.score);
111
+
112
+ return results;
113
+ }
114
+
115
+ /**
116
+ * Get all categories from the index
117
+ * @returns {Object} Categories object
118
+ */
119
+ export function getCategories() {
120
+ const index = loadIndex();
121
+ return index?.categories || {};
122
+ }
123
+
124
+ /**
125
+ * Get a specific problem by ID
126
+ * @param {string} id - Problem ID
127
+ * @returns {Object|null} Problem object or null
128
+ */
129
+ export function getProblemById(id) {
130
+ const index = loadIndex();
131
+
132
+ if (!index || !index.problems) {
133
+ return null;
134
+ }
135
+
136
+ return index.problems.find(p => p.id === id) || null;
137
+ }
138
+
139
+ export default {
140
+ loadIndex,
141
+ searchIndex,
142
+ getCategories,
143
+ getProblemById
144
+ };