claude-brain 0.15.2 → 0.16.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 (249) hide show
  1. package/README.md +191 -191
  2. package/VERSION +1 -1
  3. package/assets/CLAUDE-unified.md +11 -11
  4. package/assets/CLAUDE.md +29 -11
  5. package/bunfig.toml +8 -8
  6. package/package.json +82 -82
  7. package/packs/backend/node.json +173 -173
  8. package/packs/core/javascript.json +176 -176
  9. package/packs/core/typescript.json +222 -222
  10. package/packs/frontend/react.json +254 -254
  11. package/packs/meta/testing.json +172 -172
  12. package/scripts/postinstall.mjs +341 -341
  13. package/src/automation/auto-context.ts +240 -240
  14. package/src/automation/decision-detector.ts +452 -452
  15. package/src/automation/index.ts +11 -11
  16. package/src/automation/phase12-manager.ts +456 -456
  17. package/src/automation/proactive-recall.ts +373 -373
  18. package/src/automation/project-detector.ts +310 -310
  19. package/src/automation/repo-scanner.ts +205 -205
  20. package/src/cli/auto-setup.ts +82 -82
  21. package/src/cli/bin.ts +209 -202
  22. package/src/cli/commands/chroma.ts +573 -573
  23. package/src/cli/commands/git-hook.ts +189 -189
  24. package/src/cli/commands/hooks.ts +213 -213
  25. package/src/cli/commands/init.ts +122 -122
  26. package/src/cli/commands/install-mcp.ts +92 -92
  27. package/src/cli/commands/pack.ts +197 -197
  28. package/src/cli/commands/refresh.ts +323 -0
  29. package/src/cli/commands/serve.ts +167 -173
  30. package/src/cli/commands/start.ts +42 -42
  31. package/src/cli/commands/uninstall-mcp.ts +41 -41
  32. package/src/cli/commands/update.ts +124 -121
  33. package/src/cli/diagnose.ts +4 -4
  34. package/src/cli/health-check.ts +4 -4
  35. package/src/cli/migrate-chroma.ts +106 -106
  36. package/src/cli/setup.ts +4 -4
  37. package/src/cli/ui/animations.ts +80 -80
  38. package/src/cli/ui/components.ts +82 -82
  39. package/src/cli/ui/index.ts +4 -4
  40. package/src/cli/ui/logo.ts +36 -36
  41. package/src/cli/ui/theme.ts +55 -55
  42. package/src/config/defaults.ts +50 -50
  43. package/src/config/home.ts +55 -55
  44. package/src/config/index.ts +7 -7
  45. package/src/config/loader.ts +166 -166
  46. package/src/config/migration.ts +76 -76
  47. package/src/config/schema.ts +360 -360
  48. package/src/config/validator.ts +184 -184
  49. package/src/config/watcher.ts +86 -86
  50. package/src/context/assembler.ts +398 -398
  51. package/src/context/cache-manager.ts +101 -101
  52. package/src/context/formatter.ts +84 -84
  53. package/src/context/hierarchy.ts +85 -85
  54. package/src/context/index.ts +83 -83
  55. package/src/context/progress-tracker.ts +174 -174
  56. package/src/context/standards-manager.ts +287 -287
  57. package/src/context/types.ts +252 -252
  58. package/src/context/validator.ts +58 -58
  59. package/src/diagnostics/index.ts +123 -123
  60. package/src/health/index.ts +229 -229
  61. package/src/hooks/brain-hook.ts +128 -112
  62. package/src/hooks/capture.ts +168 -205
  63. package/src/hooks/deduplicator.ts +72 -72
  64. package/src/hooks/git-capture.ts +109 -109
  65. package/src/hooks/git-hook-installer.ts +207 -207
  66. package/src/hooks/index.ts +20 -20
  67. package/src/hooks/installer.ts +194 -194
  68. package/src/hooks/passive-classifier.ts +404 -723
  69. package/src/hooks/queue.ts +129 -129
  70. package/src/hooks/session-tracker.ts +312 -275
  71. package/src/hooks/types.ts +47 -47
  72. package/src/index.ts +7 -7
  73. package/src/intelligence/cross-project/affinity.ts +162 -162
  74. package/src/intelligence/cross-project/generalizer.ts +283 -283
  75. package/src/intelligence/cross-project/index.ts +13 -13
  76. package/src/intelligence/cross-project/transfer.ts +201 -201
  77. package/src/intelligence/index.ts +24 -24
  78. package/src/intelligence/optimization/index.ts +10 -10
  79. package/src/intelligence/optimization/precompute.ts +202 -202
  80. package/src/intelligence/optimization/semantic-cache.ts +207 -207
  81. package/src/intelligence/prediction/context-anticipator.ts +198 -198
  82. package/src/intelligence/prediction/decision-predictor.ts +184 -184
  83. package/src/intelligence/prediction/index.ts +13 -13
  84. package/src/intelligence/prediction/recommender.ts +268 -268
  85. package/src/intelligence/reasoning/chain-retrieval.ts +247 -247
  86. package/src/intelligence/reasoning/counterfactual.ts +248 -248
  87. package/src/intelligence/reasoning/index.ts +13 -13
  88. package/src/intelligence/reasoning/synthesizer.ts +169 -169
  89. package/src/intelligence/temporal/evolution.ts +197 -197
  90. package/src/intelligence/temporal/index.ts +16 -16
  91. package/src/intelligence/temporal/query-processor.ts +190 -190
  92. package/src/intelligence/temporal/timeline.ts +259 -259
  93. package/src/intelligence/temporal/trends.ts +263 -263
  94. package/src/knowledge/entity-extractor.ts +416 -416
  95. package/src/knowledge/graph/builder.ts +185 -185
  96. package/src/knowledge/graph/linker.ts +201 -201
  97. package/src/knowledge/graph/memory-graph.ts +359 -359
  98. package/src/knowledge/graph/schema.ts +99 -99
  99. package/src/knowledge/graph/search.ts +168 -168
  100. package/src/knowledge/relationship-extractor.ts +108 -108
  101. package/src/memory/chroma/client.ts +174 -174
  102. package/src/memory/chroma/collection-manager.ts +94 -94
  103. package/src/memory/chroma/config.ts +57 -57
  104. package/src/memory/chroma/embeddings.ts +155 -155
  105. package/src/memory/chroma/index.ts +82 -82
  106. package/src/memory/chroma/migration.ts +270 -270
  107. package/src/memory/chroma/schemas.ts +69 -69
  108. package/src/memory/chroma/search.ts +315 -315
  109. package/src/memory/chroma/store.ts +741 -741
  110. package/src/memory/consolidation/archiver.ts +164 -164
  111. package/src/memory/consolidation/merger.ts +186 -186
  112. package/src/memory/consolidation/scorer.ts +138 -138
  113. package/src/memory/context-builder.ts +236 -236
  114. package/src/memory/database.ts +169 -169
  115. package/src/memory/embedding-utils.ts +156 -156
  116. package/src/memory/embeddings.ts +226 -226
  117. package/src/memory/episodic/detector.ts +108 -108
  118. package/src/memory/episodic/manager.ts +351 -351
  119. package/src/memory/episodic/summarizer.ts +179 -179
  120. package/src/memory/episodic/types.ts +52 -52
  121. package/src/memory/index.ts +582 -582
  122. package/src/memory/knowledge-extractor.ts +455 -455
  123. package/src/memory/learning.ts +378 -378
  124. package/src/memory/patterns.ts +396 -396
  125. package/src/memory/schema.ts +88 -88
  126. package/src/memory/search.ts +309 -309
  127. package/src/memory/store.ts +787 -787
  128. package/src/memory/types.ts +121 -121
  129. package/src/orchestrator/coordinator.ts +272 -272
  130. package/src/orchestrator/decision-logger.ts +228 -228
  131. package/src/orchestrator/event-emitter.ts +198 -198
  132. package/src/orchestrator/event-queue.ts +184 -184
  133. package/src/orchestrator/handlers/base-handler.ts +70 -70
  134. package/src/orchestrator/handlers/context-handler.ts +73 -73
  135. package/src/orchestrator/handlers/decision-handler.ts +204 -204
  136. package/src/orchestrator/handlers/index.ts +10 -10
  137. package/src/orchestrator/handlers/status-handler.ts +131 -131
  138. package/src/orchestrator/handlers/task-handler.ts +171 -171
  139. package/src/orchestrator/index.ts +275 -275
  140. package/src/orchestrator/task-parser.ts +284 -284
  141. package/src/orchestrator/types.ts +98 -98
  142. package/src/packs/index.ts +9 -9
  143. package/src/packs/loader.ts +134 -134
  144. package/src/packs/manager.ts +204 -204
  145. package/src/packs/ranker.ts +78 -78
  146. package/src/packs/types.ts +81 -81
  147. package/src/phase12/index.ts +5 -5
  148. package/src/retrieval/bm25/index.ts +300 -300
  149. package/src/retrieval/bm25/tokenizer.ts +184 -184
  150. package/src/retrieval/feedback/adaptive.ts +223 -223
  151. package/src/retrieval/feedback/index.ts +16 -16
  152. package/src/retrieval/feedback/metrics.ts +223 -223
  153. package/src/retrieval/feedback/store.ts +283 -283
  154. package/src/retrieval/fusion/index.ts +194 -194
  155. package/src/retrieval/fusion/rrf.ts +163 -163
  156. package/src/retrieval/index.ts +12 -12
  157. package/src/retrieval/pipeline.ts +375 -375
  158. package/src/retrieval/query/expander.ts +198 -198
  159. package/src/retrieval/query/index.ts +27 -27
  160. package/src/retrieval/query/intent-classifier.ts +236 -236
  161. package/src/retrieval/query/temporal-parser.ts +295 -295
  162. package/src/retrieval/reranker/index.ts +188 -188
  163. package/src/retrieval/reranker/model.ts +95 -95
  164. package/src/retrieval/service.ts +125 -125
  165. package/src/retrieval/types.ts +162 -162
  166. package/src/routing/entity-extractor.ts +428 -428
  167. package/src/routing/intent-classifier.ts +450 -436
  168. package/src/routing/response-filter.ts +261 -258
  169. package/src/routing/router.ts +1441 -1322
  170. package/src/routing/search-engine.ts +515 -475
  171. package/src/routing/types.ts +94 -94
  172. package/src/scripts/health-check.ts +118 -118
  173. package/src/scripts/setup.ts +122 -122
  174. package/src/server/handlers/call-tool.ts +156 -156
  175. package/src/server/handlers/index.ts +9 -9
  176. package/src/server/handlers/list-tools.ts +35 -35
  177. package/src/server/handlers/tools/analyze-decision-evolution.ts +151 -151
  178. package/src/server/handlers/tools/auto-remember.ts +200 -200
  179. package/src/server/handlers/tools/brain.ts +85 -85
  180. package/src/server/handlers/tools/create-project.ts +135 -135
  181. package/src/server/handlers/tools/detect-trends.ts +144 -144
  182. package/src/server/handlers/tools/find-cross-project-patterns.ts +168 -168
  183. package/src/server/handlers/tools/get-activity-log.ts +194 -194
  184. package/src/server/handlers/tools/get-code-standards.ts +124 -124
  185. package/src/server/handlers/tools/get-corrections.ts +154 -154
  186. package/src/server/handlers/tools/get-decision-timeline.ts +172 -172
  187. package/src/server/handlers/tools/get-episode.ts +103 -103
  188. package/src/server/handlers/tools/get-patterns.ts +158 -158
  189. package/src/server/handlers/tools/get-phase12-status.ts +63 -63
  190. package/src/server/handlers/tools/get-project-context.ts +75 -75
  191. package/src/server/handlers/tools/get-recommendations.ts +145 -145
  192. package/src/server/handlers/tools/index.ts +31 -31
  193. package/src/server/handlers/tools/init-project.ts +757 -757
  194. package/src/server/handlers/tools/list-episodes.ts +90 -90
  195. package/src/server/handlers/tools/list-projects.ts +125 -125
  196. package/src/server/handlers/tools/rate-memory.ts +101 -101
  197. package/src/server/handlers/tools/recall-similar.ts +87 -87
  198. package/src/server/handlers/tools/recognize-pattern.ts +126 -126
  199. package/src/server/handlers/tools/record-correction.ts +125 -125
  200. package/src/server/handlers/tools/remember-decision.ts +153 -153
  201. package/src/server/handlers/tools/schemas.ts +253 -253
  202. package/src/server/handlers/tools/search-knowledge-graph.ts +102 -102
  203. package/src/server/handlers/tools/smart-context.ts +146 -146
  204. package/src/server/handlers/tools/update-progress.ts +131 -131
  205. package/src/server/handlers/tools/what-if-analysis.ts +135 -135
  206. package/src/server/http-api.ts +693 -693
  207. package/src/server/index.ts +40 -40
  208. package/src/server/mcp-server.ts +283 -283
  209. package/src/server/providers/index.ts +7 -7
  210. package/src/server/providers/prompts.ts +327 -327
  211. package/src/server/providers/resources.ts +622 -622
  212. package/src/server/services.ts +468 -468
  213. package/src/server/types.ts +39 -39
  214. package/src/server/utils/error-handler.ts +155 -155
  215. package/src/server/utils/index.ts +13 -13
  216. package/src/server/utils/memory-indicator.ts +83 -83
  217. package/src/server/utils/request-context.ts +122 -122
  218. package/src/server/utils/response-formatter.ts +129 -129
  219. package/src/server/utils/validators.ts +210 -210
  220. package/src/setup/index.ts +48 -48
  221. package/src/setup/wizard.ts +461 -461
  222. package/src/tools/index.ts +24 -24
  223. package/src/tools/registry.ts +115 -115
  224. package/src/tools/schemas.test.ts +30 -30
  225. package/src/tools/schemas.ts +617 -617
  226. package/src/tools/types.ts +412 -412
  227. package/src/utils/circuit-breaker.ts +130 -130
  228. package/src/utils/cleanup.ts +34 -34
  229. package/src/utils/error-handler.ts +132 -132
  230. package/src/utils/error-messages.ts +60 -60
  231. package/src/utils/fallback.ts +45 -45
  232. package/src/utils/index.ts +54 -54
  233. package/src/utils/logger-utils.ts +80 -80
  234. package/src/utils/logger.ts +88 -88
  235. package/src/utils/phase12-helper.ts +56 -56
  236. package/src/utils/retry.ts +94 -94
  237. package/src/utils/timing.ts +47 -47
  238. package/src/utils/transaction.ts +63 -63
  239. package/src/vault/frontmatter.ts +264 -264
  240. package/src/vault/index.ts +318 -318
  241. package/src/vault/paths.ts +106 -106
  242. package/src/vault/query.ts +422 -422
  243. package/src/vault/reader.ts +264 -264
  244. package/src/vault/templates.ts +186 -186
  245. package/src/vault/types.ts +73 -73
  246. package/src/vault/watcher.ts +277 -277
  247. package/src/vault/writer.ts +413 -413
  248. package/tsconfig.json +30 -30
  249. package/src/cli/auto-update.ts +0 -157
@@ -1,757 +1,757 @@
1
- /**
2
- * Init Project Handler
3
- * Analyzes an existing codebase and creates project in vault
4
- * Similar to `claude init` - reads files to extract project info
5
- */
6
-
7
- import type { Logger } from 'pino'
8
- import type { ToolResponse } from '@/tools/types'
9
- import { getVaultService, getMemoryService, isServicesInitialized } from '@/server/services'
10
- import { ToolValidator } from '@/server/utils/validators'
11
- import { ResponseFormatter } from '@/server/utils/response-formatter'
12
- import { ErrorHandler } from '@/server/utils/error-handler'
13
- import { McpError, ErrorCode } from '@modelcontextprotocol/sdk/types.js'
14
- import { PackManager, PackLoader, type PackLoadResult } from '@/packs/index'
15
- import fs from 'fs/promises'
16
- import path from 'path'
17
- import { fileURLToPath } from 'node:url'
18
- import { dirname, resolve } from 'node:path'
19
-
20
- interface InitProjectInput {
21
- project_path?: string
22
- project_name?: string
23
- save_to_memory?: boolean
24
- }
25
-
26
- interface ProjectAnalysis {
27
- name: string
28
- description: string
29
- techStack: string[]
30
- frameworks: string[]
31
- languages: string[]
32
- packageManager: string | null
33
- structure: string[]
34
- keyFiles: string[]
35
- scripts: Record<string, string>
36
- dependencies: string[]
37
- devDependencies: string[]
38
- hasTests: boolean
39
- hasTypeScript: boolean
40
- hasLinting: boolean
41
- hasFormatting: boolean
42
- gitIgnorePatterns: string[]
43
- conventions: string[]
44
- }
45
-
46
- export async function handleInitProject(
47
- args: unknown,
48
- logger: Logger
49
- ): Promise<ToolResponse> {
50
- try {
51
- const input = args as InitProjectInput
52
- const {
53
- project_path = process.cwd(),
54
- project_name,
55
- save_to_memory = true
56
- } = input
57
-
58
- logger.info({ project_path, project_name }, 'Initializing project analysis')
59
-
60
- if (!isServicesInitialized()) {
61
- throw new McpError(
62
- ErrorCode.InternalError,
63
- 'Services not initialized'
64
- )
65
- }
66
-
67
- // Verify path exists
68
- try {
69
- const stats = await fs.stat(project_path)
70
- if (!stats.isDirectory()) {
71
- throw new McpError(
72
- ErrorCode.InvalidParams,
73
- `Path is not a directory: ${project_path}`
74
- )
75
- }
76
- } catch (error) {
77
- if ((error as NodeJS.ErrnoException).code === 'ENOENT') {
78
- throw new McpError(
79
- ErrorCode.InvalidParams,
80
- `Directory not found: ${project_path}`
81
- )
82
- }
83
- throw error
84
- }
85
-
86
- // Analyze the project
87
- const analysis = await analyzeProject(project_path, logger)
88
-
89
- // Use provided name or detected name
90
- const finalName = project_name || analysis.name
91
- const normalizedName = finalName
92
- .toLowerCase()
93
- .replace(/\s+/g, '-')
94
- .replace(/[^a-z0-9-]/g, '')
95
-
96
- if (!normalizedName || normalizedName.length < 2) {
97
- throw new McpError(
98
- ErrorCode.InvalidParams,
99
- 'Could not determine project name. Please provide project_name parameter.'
100
- )
101
- }
102
-
103
- const vault = getVaultService()
104
-
105
- // Check if project already exists
106
- const existingProjects = await vault.listProjects()
107
- const projectExists = existingProjects.includes(normalizedName)
108
-
109
- if (!projectExists) {
110
- // Create new project
111
- await vault.createProject(normalizedName)
112
- }
113
-
114
- // Update project files with analysis
115
- const projectPaths = vault.getProjectPaths(normalizedName)
116
-
117
- // Update context.md
118
- const contextContent = generateContextContent(analysis)
119
- await vault.writer.writeMarkdownFile(
120
- projectPaths.context,
121
- {
122
- type: 'project-context',
123
- project: normalizedName,
124
- status: 'active',
125
- created: new Date().toISOString().split('T')[0],
126
- updated: new Date().toISOString().split('T')[0],
127
- tech_stack: analysis.techStack,
128
- languages: analysis.languages,
129
- frameworks: analysis.frameworks,
130
- tags: detectTags(analysis),
131
- description: analysis.description,
132
- analyzed_from: project_path
133
- },
134
- contextContent,
135
- { createBackup: projectExists }
136
- )
137
-
138
- // Update standards.md
139
- const standardsContent = generateStandardsContent(analysis)
140
- await vault.writer.writeMarkdownFile(
141
- projectPaths.standards,
142
- {
143
- type: 'coding-standards',
144
- project: normalizedName,
145
- languages: analysis.languages,
146
- frameworks: analysis.frameworks,
147
- last_updated: new Date().toISOString().split('T')[0]
148
- },
149
- standardsContent,
150
- { createBackup: projectExists }
151
- )
152
-
153
- // Save to memory for semantic search
154
- if (save_to_memory) {
155
- const memory = getMemoryService()
156
-
157
- // Store project overview as a decision/context
158
- const projectSummary = `
159
- Project: ${normalizedName}
160
- Description: ${analysis.description}
161
- Tech Stack: ${analysis.techStack.join(', ')}
162
- Languages: ${analysis.languages.join(', ')}
163
- Frameworks: ${analysis.frameworks.join(', ')}
164
- Key Files: ${analysis.keyFiles.join(', ')}
165
- Has Tests: ${analysis.hasTests}
166
- Has TypeScript: ${analysis.hasTypeScript}
167
- `.trim()
168
-
169
- await memory.rememberDecision(
170
- normalizedName,
171
- 'Project initialization and setup',
172
- `Initialized ${normalizedName} with Claude Brain`,
173
- projectSummary,
174
- {
175
- tags: ['project-init', 'setup', ...analysis.languages, ...analysis.frameworks]
176
- }
177
- )
178
-
179
- logger.info({ normalizedName }, 'Project saved to memory')
180
- }
181
-
182
- // Phase 18: Load knowledge packs based on detected tech stack
183
- let packResult: PackLoadResult | null = null
184
- try {
185
- const initFile = fileURLToPath(import.meta.url)
186
- const initDir = dirname(initFile)
187
- const PACKAGE_ROOT = resolve(initDir, '..', '..', '..', '..')
188
- const dataDir = path.join(process.env.CLAUDE_BRAIN_HOME || path.join(process.env.HOME || '~', '.claude-brain'), 'data')
189
-
190
- // Default packs config
191
- const packsConfig = {
192
- enabled: true,
193
- packsDir: 'packs',
194
- alwaysLoadCore: true,
195
- alwaysLoadMeta: true,
196
- communityConfidenceMultiplier: 0.8,
197
- personalBoost: 1.2,
198
- projectBoost: 1.15
199
- }
200
-
201
- if (packsConfig.enabled) {
202
- const memory = getMemoryService()
203
- const packManager = new PackManager(logger, packsConfig, PACKAGE_ROOT, dataDir)
204
- const packLoader = new PackLoader(logger, memory, packManager, packsConfig)
205
- packResult = await packLoader.loadPacksForProject(normalizedName, analysis.techStack)
206
- logger.info({ packResult }, 'Knowledge packs loaded')
207
- }
208
- } catch (packError) {
209
- logger.warn({ error: packError }, 'Pack loading failed (non-blocking)')
210
- }
211
-
212
- // Build response
213
- const parts: string[] = []
214
- parts.push(`## ${projectExists ? '🔄 Project Updated' : '✅ Project Initialized'}: ${normalizedName}\n`)
215
-
216
- parts.push(`### Analysis Results\n`)
217
- parts.push(`**Source:** \`${project_path}\`\n`)
218
-
219
- if (analysis.description) {
220
- parts.push(`**Description:** ${analysis.description}\n`)
221
- }
222
-
223
- parts.push(`\n### Tech Stack`)
224
- parts.push(`- **Languages:** ${analysis.languages.join(', ') || 'Not detected'}`)
225
- parts.push(`- **Frameworks:** ${analysis.frameworks.join(', ') || 'Not detected'}`)
226
- parts.push(`- **Package Manager:** ${analysis.packageManager || 'Not detected'}`)
227
-
228
- parts.push(`\n### Project Features`)
229
- parts.push(`- TypeScript: ${analysis.hasTypeScript ? '✅' : '❌'}`)
230
- parts.push(`- Tests: ${analysis.hasTests ? '✅' : '❌'}`)
231
- parts.push(`- Linting: ${analysis.hasLinting ? '✅' : '❌'}`)
232
- parts.push(`- Formatting: ${analysis.hasFormatting ? '✅' : '❌'}`)
233
-
234
- if (analysis.keyFiles.length > 0) {
235
- parts.push(`\n### Key Files Detected`)
236
- analysis.keyFiles.slice(0, 10).forEach(f => parts.push(`- \`${f}\``))
237
- }
238
-
239
- if (Object.keys(analysis.scripts).length > 0) {
240
- parts.push(`\n### Available Scripts`)
241
- Object.entries(analysis.scripts).slice(0, 8).forEach(([name, cmd]) => {
242
- parts.push(`- \`${name}\`: ${cmd.slice(0, 50)}${cmd.length > 50 ? '...' : ''}`)
243
- })
244
- }
245
-
246
- if (analysis.conventions.length > 0) {
247
- parts.push(`\n### Detected Conventions`)
248
- analysis.conventions.forEach(c => parts.push(`- ${c}`))
249
- }
250
-
251
- parts.push(`\n### Files Created/Updated`)
252
- parts.push(`- \`${normalizedName}/context.md\` - Project overview`)
253
- parts.push(`- \`${normalizedName}/standards.md\` - Coding standards`)
254
- parts.push(`- \`${normalizedName}/progress.md\` - Progress tracking`)
255
- parts.push(`- \`${normalizedName}/decisions.md\` - Decision log`)
256
-
257
- if (save_to_memory) {
258
- parts.push(`\n### Memory`)
259
- parts.push(`Project context saved to semantic memory for future recall.`)
260
- }
261
-
262
- if (packResult && packResult.packsLoaded > 0) {
263
- parts.push(`\n### Knowledge Packs`)
264
- parts.push(`Loaded **${packResult.packsLoaded}** pack(s) with **${packResult.entriesLoaded}** entries:`)
265
- for (const detail of packResult.packDetails) {
266
- parts.push(`- **${detail.name}** (${detail.entriesLoaded} entries)`)
267
- }
268
- if (packResult.skipped.length > 0) {
269
- parts.push(`\nSkipped: ${packResult.skipped.map(s => `${s.packId} (${s.reason})`).join(', ')}`)
270
- }
271
- } else if (packResult && packResult.skipped.length > 0) {
272
- parts.push(`\n### Knowledge Packs`)
273
- parts.push(`All packs already loaded (${packResult.skipped.length} skipped).`)
274
- }
275
-
276
- parts.push(`\n### Next Steps`)
277
- parts.push(`1. Use \`get_project_context("${normalizedName}")\` to view full context`)
278
- parts.push(`2. Use \`remember_decision\` to save architectural decisions`)
279
- parts.push(`3. Use \`recall_similar\` to search past decisions`)
280
-
281
- logger.info({
282
- project: normalizedName,
283
- techStack: analysis.techStack,
284
- isNew: !projectExists
285
- }, 'Project initialized successfully')
286
-
287
- return ResponseFormatter.text(parts.join('\n'))
288
-
289
- } catch (error) {
290
- ErrorHandler.logError(logger, error, { tool: 'init_project', args })
291
-
292
- if (error instanceof McpError) {
293
- throw error
294
- }
295
-
296
- // Provide detailed error message
297
- if (error instanceof Error) {
298
- let errorMsg = `Failed to initialize project: ${error.message}\n\n`
299
-
300
- // Add specific troubleshooting steps based on error type
301
- if (error.message.includes('EACCES') || error.message.includes('permission')) {
302
- errorMsg += `**Permission Error**\n` +
303
- `- Check that you have read/write permissions for the project directory\n` +
304
- `- Ensure the Obsidian vault path is writable\n`
305
- } else if (error.message.includes('ENOENT')) {
306
- errorMsg += `**File Not Found**\n` +
307
- `- Verify the project_path exists\n` +
308
- `- Check that the path is absolute, not relative\n`
309
- } else if (error.message.includes('parse') || error.message.includes('JSON')) {
310
- errorMsg += `**Parse Error**\n` +
311
- `- package.json or other config files may be malformed\n` +
312
- `- Check for syntax errors in configuration files\n`
313
- } else {
314
- errorMsg += `**Troubleshooting:**\n` +
315
- `- Ensure the directory exists and is accessible\n` +
316
- `- Check file permissions in both project and vault directories\n` +
317
- `- Verify config files (package.json, etc.) are valid\n`
318
- }
319
-
320
- errorMsg += `\n**Error details:** ${error.stack || error.message}`
321
-
322
- throw new McpError(ErrorCode.InternalError, errorMsg)
323
- }
324
-
325
- throw new McpError(
326
- ErrorCode.InternalError,
327
- `Failed to initialize project: Unknown error occurred`
328
- )
329
- }
330
- }
331
-
332
- /**
333
- * Analyze project directory
334
- */
335
- async function analyzeProject(projectPath: string, logger: Logger): Promise<ProjectAnalysis> {
336
- const analysis: ProjectAnalysis = {
337
- name: path.basename(projectPath),
338
- description: '',
339
- techStack: [],
340
- frameworks: [],
341
- languages: [],
342
- packageManager: null,
343
- structure: [],
344
- keyFiles: [],
345
- scripts: {},
346
- dependencies: [],
347
- devDependencies: [],
348
- hasTests: false,
349
- hasTypeScript: false,
350
- hasLinting: false,
351
- hasFormatting: false,
352
- gitIgnorePatterns: [],
353
- conventions: []
354
- }
355
-
356
- // Read directory structure (top level + 1 deep)
357
- try {
358
- const entries = await fs.readdir(projectPath, { withFileTypes: true })
359
-
360
- for (const entry of entries) {
361
- if (entry.name.startsWith('.') && entry.name !== '.eslintrc.json' && entry.name !== '.prettierrc') {
362
- continue
363
- }
364
-
365
- if (entry.isDirectory()) {
366
- analysis.structure.push(`${entry.name}/`)
367
- } else {
368
- analysis.structure.push(entry.name)
369
- }
370
- }
371
- } catch (error) {
372
- logger.warn({ error }, 'Failed to read directory structure')
373
- }
374
-
375
- // Check for package.json (Node.js/JavaScript projects)
376
- await analyzePackageJson(projectPath, analysis, logger)
377
-
378
- // Check for other config files
379
- await analyzeConfigFiles(projectPath, analysis, logger)
380
-
381
- // Check for Python projects
382
- await analyzePythonProject(projectPath, analysis, logger)
383
-
384
- // Check for Go projects
385
- await analyzeGoProject(projectPath, analysis, logger)
386
-
387
- // Check for Rust projects
388
- await analyzeRustProject(projectPath, analysis, logger)
389
-
390
- // Detect test directories
391
- await detectTests(projectPath, analysis, logger)
392
-
393
- // Read README for description
394
- await readReadme(projectPath, analysis, logger)
395
-
396
- // Read .gitignore
397
- await readGitignore(projectPath, analysis, logger)
398
-
399
- // Detect conventions from structure
400
- detectConventions(analysis)
401
-
402
- // Build final tech stack
403
- analysis.techStack = [...new Set([...analysis.languages, ...analysis.frameworks])]
404
-
405
- return analysis
406
- }
407
-
408
- async function analyzePackageJson(projectPath: string, analysis: ProjectAnalysis, logger: Logger) {
409
- try {
410
- const pkgPath = path.join(projectPath, 'package.json')
411
- const content = await fs.readFile(pkgPath, 'utf-8')
412
- const pkg = JSON.parse(content)
413
-
414
- analysis.name = pkg.name || analysis.name
415
- analysis.description = pkg.description || ''
416
- analysis.scripts = pkg.scripts || {}
417
-
418
- // Detect package manager
419
- if (await fileExists(path.join(projectPath, 'bun.lockb'))) {
420
- analysis.packageManager = 'bun'
421
- } else if (await fileExists(path.join(projectPath, 'pnpm-lock.yaml'))) {
422
- analysis.packageManager = 'pnpm'
423
- } else if (await fileExists(path.join(projectPath, 'yarn.lock'))) {
424
- analysis.packageManager = 'yarn'
425
- } else if (await fileExists(path.join(projectPath, 'package-lock.json'))) {
426
- analysis.packageManager = 'npm'
427
- }
428
-
429
- // Languages
430
- analysis.languages.push('javascript')
431
-
432
- // Analyze dependencies
433
- const allDeps = {
434
- ...pkg.dependencies,
435
- ...pkg.devDependencies
436
- }
437
-
438
- analysis.dependencies = Object.keys(pkg.dependencies || {})
439
- analysis.devDependencies = Object.keys(pkg.devDependencies || {})
440
-
441
- // Detect frameworks
442
- if (allDeps['react']) {
443
- analysis.frameworks.push('react')
444
- if (allDeps['next']) analysis.frameworks.push('next.js')
445
- if (allDeps['gatsby']) analysis.frameworks.push('gatsby')
446
- if (allDeps['remix']) analysis.frameworks.push('remix')
447
- }
448
- if (allDeps['vue']) analysis.frameworks.push('vue')
449
- if (allDeps['@angular/core']) analysis.frameworks.push('angular')
450
- if (allDeps['svelte']) analysis.frameworks.push('svelte')
451
- if (allDeps['express']) analysis.frameworks.push('express')
452
- if (allDeps['fastify']) analysis.frameworks.push('fastify')
453
- if (allDeps['hono']) analysis.frameworks.push('hono')
454
- if (allDeps['elysia']) analysis.frameworks.push('elysia')
455
- if (allDeps['nestjs'] || allDeps['@nestjs/core']) analysis.frameworks.push('nestjs')
456
- if (allDeps['electron']) analysis.frameworks.push('electron')
457
- if (allDeps['tauri']) analysis.frameworks.push('tauri')
458
-
459
- // Detect TypeScript
460
- if (allDeps['typescript'] || await fileExists(path.join(projectPath, 'tsconfig.json'))) {
461
- analysis.hasTypeScript = true
462
- analysis.languages.push('typescript')
463
- }
464
-
465
- // Detect testing
466
- if (allDeps['jest'] || allDeps['vitest'] || allDeps['mocha'] || allDeps['ava']) {
467
- analysis.hasTests = true
468
- }
469
-
470
- // Detect linting
471
- if (allDeps['eslint'] || allDeps['biome'] || allDeps['@biomejs/biome']) {
472
- analysis.hasLinting = true
473
- }
474
-
475
- // Detect formatting
476
- if (allDeps['prettier'] || allDeps['biome'] || allDeps['@biomejs/biome']) {
477
- analysis.hasFormatting = true
478
- }
479
-
480
- // Key files
481
- analysis.keyFiles.push('package.json')
482
-
483
- } catch (error) {
484
- // Not a Node.js project
485
- }
486
- }
487
-
488
- async function analyzeConfigFiles(projectPath: string, analysis: ProjectAnalysis, logger: Logger) {
489
- const configFiles = [
490
- 'tsconfig.json',
491
- '.eslintrc.json',
492
- '.eslintrc.js',
493
- '.prettierrc',
494
- 'prettier.config.js',
495
- 'vite.config.ts',
496
- 'vite.config.js',
497
- 'webpack.config.js',
498
- 'rollup.config.js',
499
- 'tailwind.config.js',
500
- 'tailwind.config.ts',
501
- 'postcss.config.js',
502
- 'next.config.js',
503
- 'next.config.ts',
504
- 'nuxt.config.ts',
505
- 'astro.config.mjs',
506
- 'svelte.config.js',
507
- 'biome.json'
508
- ]
509
-
510
- for (const file of configFiles) {
511
- if (await fileExists(path.join(projectPath, file))) {
512
- analysis.keyFiles.push(file)
513
-
514
- // Detect specific tools
515
- if (file.includes('tailwind')) analysis.frameworks.push('tailwindcss')
516
- if (file.includes('vite')) analysis.frameworks.push('vite')
517
- if (file.includes('webpack')) analysis.frameworks.push('webpack')
518
- if (file.includes('astro')) analysis.frameworks.push('astro')
519
- }
520
- }
521
- }
522
-
523
- async function analyzePythonProject(projectPath: string, analysis: ProjectAnalysis, logger: Logger) {
524
- // Check for Python files
525
- if (await fileExists(path.join(projectPath, 'requirements.txt')) ||
526
- await fileExists(path.join(projectPath, 'pyproject.toml')) ||
527
- await fileExists(path.join(projectPath, 'setup.py'))) {
528
-
529
- analysis.languages.push('python')
530
-
531
- if (await fileExists(path.join(projectPath, 'requirements.txt'))) {
532
- analysis.keyFiles.push('requirements.txt')
533
- analysis.packageManager = 'pip'
534
- }
535
-
536
- if (await fileExists(path.join(projectPath, 'pyproject.toml'))) {
537
- analysis.keyFiles.push('pyproject.toml')
538
- analysis.packageManager = 'poetry'
539
- }
540
-
541
- // Check for frameworks
542
- try {
543
- const reqPath = path.join(projectPath, 'requirements.txt')
544
- if (await fileExists(reqPath)) {
545
- const content = await fs.readFile(reqPath, 'utf-8')
546
- if (content.includes('django')) analysis.frameworks.push('django')
547
- if (content.includes('flask')) analysis.frameworks.push('flask')
548
- if (content.includes('fastapi')) analysis.frameworks.push('fastapi')
549
- if (content.includes('pytest')) analysis.hasTests = true
550
- }
551
- } catch {}
552
- }
553
- }
554
-
555
- async function analyzeGoProject(projectPath: string, analysis: ProjectAnalysis, logger: Logger) {
556
- if (await fileExists(path.join(projectPath, 'go.mod'))) {
557
- analysis.languages.push('go')
558
- analysis.keyFiles.push('go.mod')
559
- analysis.packageManager = 'go modules'
560
- }
561
- }
562
-
563
- async function analyzeRustProject(projectPath: string, analysis: ProjectAnalysis, logger: Logger) {
564
- if (await fileExists(path.join(projectPath, 'Cargo.toml'))) {
565
- analysis.languages.push('rust')
566
- analysis.keyFiles.push('Cargo.toml')
567
- analysis.packageManager = 'cargo'
568
- }
569
- }
570
-
571
- async function detectTests(projectPath: string, analysis: ProjectAnalysis, logger: Logger) {
572
- const testDirs = ['test', 'tests', '__tests__', 'spec', 'specs']
573
-
574
- for (const dir of testDirs) {
575
- if (await fileExists(path.join(projectPath, dir))) {
576
- analysis.hasTests = true
577
- analysis.keyFiles.push(`${dir}/`)
578
- break
579
- }
580
- }
581
- }
582
-
583
- async function readReadme(projectPath: string, analysis: ProjectAnalysis, logger: Logger) {
584
- const readmeFiles = ['README.md', 'readme.md', 'Readme.md', 'README.txt', 'README']
585
-
586
- for (const file of readmeFiles) {
587
- try {
588
- const content = await fs.readFile(path.join(projectPath, file), 'utf-8')
589
- analysis.keyFiles.push(file)
590
-
591
- // Extract first paragraph as description if not set
592
- if (!analysis.description) {
593
- const lines = content.split('\n')
594
- for (const line of lines) {
595
- const trimmed = line.trim()
596
- // Skip headers and empty lines
597
- if (trimmed && !trimmed.startsWith('#') && !trimmed.startsWith('!') && trimmed.length > 20) {
598
- analysis.description = trimmed.slice(0, 200)
599
- break
600
- }
601
- }
602
- }
603
- break
604
- } catch {}
605
- }
606
- }
607
-
608
- async function readGitignore(projectPath: string, analysis: ProjectAnalysis, logger: Logger) {
609
- try {
610
- const content = await fs.readFile(path.join(projectPath, '.gitignore'), 'utf-8')
611
- analysis.gitIgnorePatterns = content
612
- .split('\n')
613
- .filter(line => line.trim() && !line.startsWith('#'))
614
- .slice(0, 20)
615
- } catch {}
616
- }
617
-
618
- function detectConventions(analysis: ProjectAnalysis) {
619
- // Detect conventions based on structure and config
620
-
621
- if (analysis.structure.includes('src/')) {
622
- analysis.conventions.push('Source code in src/ directory')
623
- }
624
-
625
- if (analysis.structure.includes('lib/')) {
626
- analysis.conventions.push('Library code in lib/ directory')
627
- }
628
-
629
- if (analysis.structure.includes('components/') || analysis.structure.some(s => s.includes('components'))) {
630
- analysis.conventions.push('Component-based architecture')
631
- }
632
-
633
- if (analysis.hasTypeScript) {
634
- analysis.conventions.push('TypeScript for type safety')
635
- }
636
-
637
- if (analysis.hasLinting) {
638
- analysis.conventions.push('Code linting enforced')
639
- }
640
-
641
- if (analysis.hasFormatting) {
642
- analysis.conventions.push('Code formatting enforced')
643
- }
644
-
645
- if (analysis.hasTests) {
646
- analysis.conventions.push('Test coverage expected')
647
- }
648
-
649
- if (analysis.frameworks.includes('tailwindcss')) {
650
- analysis.conventions.push('Tailwind CSS for styling')
651
- }
652
- }
653
-
654
- function detectTags(analysis: ProjectAnalysis): string[] {
655
- const tags: string[] = []
656
-
657
- if (analysis.frameworks.some(f => ['react', 'vue', 'angular', 'svelte'].includes(f))) {
658
- tags.push('frontend')
659
- }
660
-
661
- if (analysis.frameworks.some(f => ['express', 'fastify', 'nestjs', 'hono', 'elysia'].includes(f))) {
662
- tags.push('backend')
663
- }
664
-
665
- if (analysis.frameworks.some(f => ['next.js', 'nuxt', 'remix'].includes(f))) {
666
- tags.push('fullstack')
667
- }
668
-
669
- if (analysis.frameworks.includes('electron') || analysis.frameworks.includes('tauri')) {
670
- tags.push('desktop')
671
- }
672
-
673
- return tags
674
- }
675
-
676
- function generateContextContent(analysis: ProjectAnalysis): string {
677
- const parts: string[] = []
678
-
679
- parts.push(`# ${analysis.name}\n`)
680
-
681
- parts.push(`## Overview`)
682
- parts.push(analysis.description || '*Add project description here*')
683
- parts.push('')
684
-
685
- parts.push(`## Tech Stack`)
686
- if (analysis.languages.length > 0) {
687
- parts.push(`**Languages:** ${analysis.languages.join(', ')}`)
688
- }
689
- if (analysis.frameworks.length > 0) {
690
- parts.push(`**Frameworks:** ${analysis.frameworks.join(', ')}`)
691
- }
692
- if (analysis.packageManager) {
693
- parts.push(`**Package Manager:** ${analysis.packageManager}`)
694
- }
695
- parts.push('')
696
-
697
- parts.push(`## Architecture`)
698
- parts.push(`### Project Structure`)
699
- parts.push('```')
700
- analysis.structure.slice(0, 15).forEach(s => parts.push(s))
701
- parts.push('```')
702
- parts.push('')
703
-
704
- if (analysis.keyFiles.length > 0) {
705
- parts.push(`### Key Files`)
706
- analysis.keyFiles.forEach(f => parts.push(`- \`${f}\``))
707
- parts.push('')
708
- }
709
-
710
- parts.push(`## Key Decisions`)
711
- parts.push(`*Use \`remember_decision\` to add architectural decisions here*`)
712
-
713
- return parts.join('\n')
714
- }
715
-
716
- function generateStandardsContent(analysis: ProjectAnalysis): string {
717
- const parts: string[] = []
718
-
719
- parts.push(`# Coding Standards: ${analysis.name}\n`)
720
-
721
- parts.push(`## General Principles`)
722
- analysis.conventions.forEach(c => parts.push(`- ${c}`))
723
- if (analysis.conventions.length === 0) {
724
- parts.push('*Add general coding principles*')
725
- }
726
- parts.push('')
727
-
728
- parts.push(`## Language-Specific Standards`)
729
- for (const lang of analysis.languages) {
730
- parts.push(`### ${lang.charAt(0).toUpperCase() + lang.slice(1)}`)
731
- parts.push(`*Add ${lang}-specific standards*`)
732
- parts.push('')
733
- }
734
-
735
- if (analysis.frameworks.length > 0) {
736
- parts.push(`## Framework-Specific Patterns`)
737
- for (const fw of analysis.frameworks) {
738
- parts.push(`### ${fw}`)
739
- parts.push(`*Add ${fw}-specific patterns and conventions*`)
740
- parts.push('')
741
- }
742
- }
743
-
744
- parts.push(`## Common Anti-Patterns to Avoid`)
745
- parts.push(`*Document patterns to avoid*`)
746
-
747
- return parts.join('\n')
748
- }
749
-
750
- async function fileExists(filePath: string): Promise<boolean> {
751
- try {
752
- await fs.access(filePath)
753
- return true
754
- } catch {
755
- return false
756
- }
757
- }
1
+ /**
2
+ * Init Project Handler
3
+ * Analyzes an existing codebase and creates project in vault
4
+ * Similar to `claude init` - reads files to extract project info
5
+ */
6
+
7
+ import type { Logger } from 'pino'
8
+ import type { ToolResponse } from '@/tools/types'
9
+ import { getVaultService, getMemoryService, isServicesInitialized } from '@/server/services'
10
+ import { ToolValidator } from '@/server/utils/validators'
11
+ import { ResponseFormatter } from '@/server/utils/response-formatter'
12
+ import { ErrorHandler } from '@/server/utils/error-handler'
13
+ import { McpError, ErrorCode } from '@modelcontextprotocol/sdk/types.js'
14
+ import { PackManager, PackLoader, type PackLoadResult } from '@/packs/index'
15
+ import fs from 'fs/promises'
16
+ import path from 'path'
17
+ import { fileURLToPath } from 'node:url'
18
+ import { dirname, resolve } from 'node:path'
19
+
20
+ interface InitProjectInput {
21
+ project_path?: string
22
+ project_name?: string
23
+ save_to_memory?: boolean
24
+ }
25
+
26
+ interface ProjectAnalysis {
27
+ name: string
28
+ description: string
29
+ techStack: string[]
30
+ frameworks: string[]
31
+ languages: string[]
32
+ packageManager: string | null
33
+ structure: string[]
34
+ keyFiles: string[]
35
+ scripts: Record<string, string>
36
+ dependencies: string[]
37
+ devDependencies: string[]
38
+ hasTests: boolean
39
+ hasTypeScript: boolean
40
+ hasLinting: boolean
41
+ hasFormatting: boolean
42
+ gitIgnorePatterns: string[]
43
+ conventions: string[]
44
+ }
45
+
46
+ export async function handleInitProject(
47
+ args: unknown,
48
+ logger: Logger
49
+ ): Promise<ToolResponse> {
50
+ try {
51
+ const input = args as InitProjectInput
52
+ const {
53
+ project_path = process.cwd(),
54
+ project_name,
55
+ save_to_memory = true
56
+ } = input
57
+
58
+ logger.info({ project_path, project_name }, 'Initializing project analysis')
59
+
60
+ if (!isServicesInitialized()) {
61
+ throw new McpError(
62
+ ErrorCode.InternalError,
63
+ 'Services not initialized'
64
+ )
65
+ }
66
+
67
+ // Verify path exists
68
+ try {
69
+ const stats = await fs.stat(project_path)
70
+ if (!stats.isDirectory()) {
71
+ throw new McpError(
72
+ ErrorCode.InvalidParams,
73
+ `Path is not a directory: ${project_path}`
74
+ )
75
+ }
76
+ } catch (error) {
77
+ if ((error as NodeJS.ErrnoException).code === 'ENOENT') {
78
+ throw new McpError(
79
+ ErrorCode.InvalidParams,
80
+ `Directory not found: ${project_path}`
81
+ )
82
+ }
83
+ throw error
84
+ }
85
+
86
+ // Analyze the project
87
+ const analysis = await analyzeProject(project_path, logger)
88
+
89
+ // Use provided name or detected name
90
+ const finalName = project_name || analysis.name
91
+ const normalizedName = finalName
92
+ .toLowerCase()
93
+ .replace(/\s+/g, '-')
94
+ .replace(/[^a-z0-9-]/g, '')
95
+
96
+ if (!normalizedName || normalizedName.length < 2) {
97
+ throw new McpError(
98
+ ErrorCode.InvalidParams,
99
+ 'Could not determine project name. Please provide project_name parameter.'
100
+ )
101
+ }
102
+
103
+ const vault = getVaultService()
104
+
105
+ // Check if project already exists
106
+ const existingProjects = await vault.listProjects()
107
+ const projectExists = existingProjects.includes(normalizedName)
108
+
109
+ if (!projectExists) {
110
+ // Create new project
111
+ await vault.createProject(normalizedName)
112
+ }
113
+
114
+ // Update project files with analysis
115
+ const projectPaths = vault.getProjectPaths(normalizedName)
116
+
117
+ // Update context.md
118
+ const contextContent = generateContextContent(analysis)
119
+ await vault.writer.writeMarkdownFile(
120
+ projectPaths.context,
121
+ {
122
+ type: 'project-context',
123
+ project: normalizedName,
124
+ status: 'active',
125
+ created: new Date().toISOString().split('T')[0],
126
+ updated: new Date().toISOString().split('T')[0],
127
+ tech_stack: analysis.techStack,
128
+ languages: analysis.languages,
129
+ frameworks: analysis.frameworks,
130
+ tags: detectTags(analysis),
131
+ description: analysis.description,
132
+ analyzed_from: project_path
133
+ },
134
+ contextContent,
135
+ { createBackup: projectExists }
136
+ )
137
+
138
+ // Update standards.md
139
+ const standardsContent = generateStandardsContent(analysis)
140
+ await vault.writer.writeMarkdownFile(
141
+ projectPaths.standards,
142
+ {
143
+ type: 'coding-standards',
144
+ project: normalizedName,
145
+ languages: analysis.languages,
146
+ frameworks: analysis.frameworks,
147
+ last_updated: new Date().toISOString().split('T')[0]
148
+ },
149
+ standardsContent,
150
+ { createBackup: projectExists }
151
+ )
152
+
153
+ // Save to memory for semantic search
154
+ if (save_to_memory) {
155
+ const memory = getMemoryService()
156
+
157
+ // Store project overview as a decision/context
158
+ const projectSummary = `
159
+ Project: ${normalizedName}
160
+ Description: ${analysis.description}
161
+ Tech Stack: ${analysis.techStack.join(', ')}
162
+ Languages: ${analysis.languages.join(', ')}
163
+ Frameworks: ${analysis.frameworks.join(', ')}
164
+ Key Files: ${analysis.keyFiles.join(', ')}
165
+ Has Tests: ${analysis.hasTests}
166
+ Has TypeScript: ${analysis.hasTypeScript}
167
+ `.trim()
168
+
169
+ await memory.rememberDecision(
170
+ normalizedName,
171
+ 'Project initialization and setup',
172
+ `Initialized ${normalizedName} with Claude Brain`,
173
+ projectSummary,
174
+ {
175
+ tags: ['project-init', 'setup', ...analysis.languages, ...analysis.frameworks]
176
+ }
177
+ )
178
+
179
+ logger.info({ normalizedName }, 'Project saved to memory')
180
+ }
181
+
182
+ // Phase 18: Load knowledge packs based on detected tech stack
183
+ let packResult: PackLoadResult | null = null
184
+ try {
185
+ const initFile = fileURLToPath(import.meta.url)
186
+ const initDir = dirname(initFile)
187
+ const PACKAGE_ROOT = resolve(initDir, '..', '..', '..', '..')
188
+ const dataDir = path.join(process.env.CLAUDE_BRAIN_HOME || path.join(process.env.HOME || '~', '.claude-brain'), 'data')
189
+
190
+ // Default packs config
191
+ const packsConfig = {
192
+ enabled: true,
193
+ packsDir: 'packs',
194
+ alwaysLoadCore: true,
195
+ alwaysLoadMeta: true,
196
+ communityConfidenceMultiplier: 0.8,
197
+ personalBoost: 1.2,
198
+ projectBoost: 1.15
199
+ }
200
+
201
+ if (packsConfig.enabled) {
202
+ const memory = getMemoryService()
203
+ const packManager = new PackManager(logger, packsConfig, PACKAGE_ROOT, dataDir)
204
+ const packLoader = new PackLoader(logger, memory, packManager, packsConfig)
205
+ packResult = await packLoader.loadPacksForProject(normalizedName, analysis.techStack)
206
+ logger.info({ packResult }, 'Knowledge packs loaded')
207
+ }
208
+ } catch (packError) {
209
+ logger.warn({ error: packError }, 'Pack loading failed (non-blocking)')
210
+ }
211
+
212
+ // Build response
213
+ const parts: string[] = []
214
+ parts.push(`## ${projectExists ? '🔄 Project Updated' : '✅ Project Initialized'}: ${normalizedName}\n`)
215
+
216
+ parts.push(`### Analysis Results\n`)
217
+ parts.push(`**Source:** \`${project_path}\`\n`)
218
+
219
+ if (analysis.description) {
220
+ parts.push(`**Description:** ${analysis.description}\n`)
221
+ }
222
+
223
+ parts.push(`\n### Tech Stack`)
224
+ parts.push(`- **Languages:** ${analysis.languages.join(', ') || 'Not detected'}`)
225
+ parts.push(`- **Frameworks:** ${analysis.frameworks.join(', ') || 'Not detected'}`)
226
+ parts.push(`- **Package Manager:** ${analysis.packageManager || 'Not detected'}`)
227
+
228
+ parts.push(`\n### Project Features`)
229
+ parts.push(`- TypeScript: ${analysis.hasTypeScript ? '✅' : '❌'}`)
230
+ parts.push(`- Tests: ${analysis.hasTests ? '✅' : '❌'}`)
231
+ parts.push(`- Linting: ${analysis.hasLinting ? '✅' : '❌'}`)
232
+ parts.push(`- Formatting: ${analysis.hasFormatting ? '✅' : '❌'}`)
233
+
234
+ if (analysis.keyFiles.length > 0) {
235
+ parts.push(`\n### Key Files Detected`)
236
+ analysis.keyFiles.slice(0, 10).forEach(f => parts.push(`- \`${f}\``))
237
+ }
238
+
239
+ if (Object.keys(analysis.scripts).length > 0) {
240
+ parts.push(`\n### Available Scripts`)
241
+ Object.entries(analysis.scripts).slice(0, 8).forEach(([name, cmd]) => {
242
+ parts.push(`- \`${name}\`: ${cmd.slice(0, 50)}${cmd.length > 50 ? '...' : ''}`)
243
+ })
244
+ }
245
+
246
+ if (analysis.conventions.length > 0) {
247
+ parts.push(`\n### Detected Conventions`)
248
+ analysis.conventions.forEach(c => parts.push(`- ${c}`))
249
+ }
250
+
251
+ parts.push(`\n### Files Created/Updated`)
252
+ parts.push(`- \`${normalizedName}/context.md\` - Project overview`)
253
+ parts.push(`- \`${normalizedName}/standards.md\` - Coding standards`)
254
+ parts.push(`- \`${normalizedName}/progress.md\` - Progress tracking`)
255
+ parts.push(`- \`${normalizedName}/decisions.md\` - Decision log`)
256
+
257
+ if (save_to_memory) {
258
+ parts.push(`\n### Memory`)
259
+ parts.push(`Project context saved to semantic memory for future recall.`)
260
+ }
261
+
262
+ if (packResult && packResult.packsLoaded > 0) {
263
+ parts.push(`\n### Knowledge Packs`)
264
+ parts.push(`Loaded **${packResult.packsLoaded}** pack(s) with **${packResult.entriesLoaded}** entries:`)
265
+ for (const detail of packResult.packDetails) {
266
+ parts.push(`- **${detail.name}** (${detail.entriesLoaded} entries)`)
267
+ }
268
+ if (packResult.skipped.length > 0) {
269
+ parts.push(`\nSkipped: ${packResult.skipped.map(s => `${s.packId} (${s.reason})`).join(', ')}`)
270
+ }
271
+ } else if (packResult && packResult.skipped.length > 0) {
272
+ parts.push(`\n### Knowledge Packs`)
273
+ parts.push(`All packs already loaded (${packResult.skipped.length} skipped).`)
274
+ }
275
+
276
+ parts.push(`\n### Next Steps`)
277
+ parts.push(`1. Use \`get_project_context("${normalizedName}")\` to view full context`)
278
+ parts.push(`2. Use \`remember_decision\` to save architectural decisions`)
279
+ parts.push(`3. Use \`recall_similar\` to search past decisions`)
280
+
281
+ logger.info({
282
+ project: normalizedName,
283
+ techStack: analysis.techStack,
284
+ isNew: !projectExists
285
+ }, 'Project initialized successfully')
286
+
287
+ return ResponseFormatter.text(parts.join('\n'))
288
+
289
+ } catch (error) {
290
+ ErrorHandler.logError(logger, error, { tool: 'init_project', args })
291
+
292
+ if (error instanceof McpError) {
293
+ throw error
294
+ }
295
+
296
+ // Provide detailed error message
297
+ if (error instanceof Error) {
298
+ let errorMsg = `Failed to initialize project: ${error.message}\n\n`
299
+
300
+ // Add specific troubleshooting steps based on error type
301
+ if (error.message.includes('EACCES') || error.message.includes('permission')) {
302
+ errorMsg += `**Permission Error**\n` +
303
+ `- Check that you have read/write permissions for the project directory\n` +
304
+ `- Ensure the Obsidian vault path is writable\n`
305
+ } else if (error.message.includes('ENOENT')) {
306
+ errorMsg += `**File Not Found**\n` +
307
+ `- Verify the project_path exists\n` +
308
+ `- Check that the path is absolute, not relative\n`
309
+ } else if (error.message.includes('parse') || error.message.includes('JSON')) {
310
+ errorMsg += `**Parse Error**\n` +
311
+ `- package.json or other config files may be malformed\n` +
312
+ `- Check for syntax errors in configuration files\n`
313
+ } else {
314
+ errorMsg += `**Troubleshooting:**\n` +
315
+ `- Ensure the directory exists and is accessible\n` +
316
+ `- Check file permissions in both project and vault directories\n` +
317
+ `- Verify config files (package.json, etc.) are valid\n`
318
+ }
319
+
320
+ errorMsg += `\n**Error details:** ${error.stack || error.message}`
321
+
322
+ throw new McpError(ErrorCode.InternalError, errorMsg)
323
+ }
324
+
325
+ throw new McpError(
326
+ ErrorCode.InternalError,
327
+ `Failed to initialize project: Unknown error occurred`
328
+ )
329
+ }
330
+ }
331
+
332
+ /**
333
+ * Analyze project directory
334
+ */
335
+ async function analyzeProject(projectPath: string, logger: Logger): Promise<ProjectAnalysis> {
336
+ const analysis: ProjectAnalysis = {
337
+ name: path.basename(projectPath),
338
+ description: '',
339
+ techStack: [],
340
+ frameworks: [],
341
+ languages: [],
342
+ packageManager: null,
343
+ structure: [],
344
+ keyFiles: [],
345
+ scripts: {},
346
+ dependencies: [],
347
+ devDependencies: [],
348
+ hasTests: false,
349
+ hasTypeScript: false,
350
+ hasLinting: false,
351
+ hasFormatting: false,
352
+ gitIgnorePatterns: [],
353
+ conventions: []
354
+ }
355
+
356
+ // Read directory structure (top level + 1 deep)
357
+ try {
358
+ const entries = await fs.readdir(projectPath, { withFileTypes: true })
359
+
360
+ for (const entry of entries) {
361
+ if (entry.name.startsWith('.') && entry.name !== '.eslintrc.json' && entry.name !== '.prettierrc') {
362
+ continue
363
+ }
364
+
365
+ if (entry.isDirectory()) {
366
+ analysis.structure.push(`${entry.name}/`)
367
+ } else {
368
+ analysis.structure.push(entry.name)
369
+ }
370
+ }
371
+ } catch (error) {
372
+ logger.warn({ error }, 'Failed to read directory structure')
373
+ }
374
+
375
+ // Check for package.json (Node.js/JavaScript projects)
376
+ await analyzePackageJson(projectPath, analysis, logger)
377
+
378
+ // Check for other config files
379
+ await analyzeConfigFiles(projectPath, analysis, logger)
380
+
381
+ // Check for Python projects
382
+ await analyzePythonProject(projectPath, analysis, logger)
383
+
384
+ // Check for Go projects
385
+ await analyzeGoProject(projectPath, analysis, logger)
386
+
387
+ // Check for Rust projects
388
+ await analyzeRustProject(projectPath, analysis, logger)
389
+
390
+ // Detect test directories
391
+ await detectTests(projectPath, analysis, logger)
392
+
393
+ // Read README for description
394
+ await readReadme(projectPath, analysis, logger)
395
+
396
+ // Read .gitignore
397
+ await readGitignore(projectPath, analysis, logger)
398
+
399
+ // Detect conventions from structure
400
+ detectConventions(analysis)
401
+
402
+ // Build final tech stack
403
+ analysis.techStack = [...new Set([...analysis.languages, ...analysis.frameworks])]
404
+
405
+ return analysis
406
+ }
407
+
408
+ async function analyzePackageJson(projectPath: string, analysis: ProjectAnalysis, logger: Logger) {
409
+ try {
410
+ const pkgPath = path.join(projectPath, 'package.json')
411
+ const content = await fs.readFile(pkgPath, 'utf-8')
412
+ const pkg = JSON.parse(content)
413
+
414
+ analysis.name = pkg.name || analysis.name
415
+ analysis.description = pkg.description || ''
416
+ analysis.scripts = pkg.scripts || {}
417
+
418
+ // Detect package manager
419
+ if (await fileExists(path.join(projectPath, 'bun.lockb'))) {
420
+ analysis.packageManager = 'bun'
421
+ } else if (await fileExists(path.join(projectPath, 'pnpm-lock.yaml'))) {
422
+ analysis.packageManager = 'pnpm'
423
+ } else if (await fileExists(path.join(projectPath, 'yarn.lock'))) {
424
+ analysis.packageManager = 'yarn'
425
+ } else if (await fileExists(path.join(projectPath, 'package-lock.json'))) {
426
+ analysis.packageManager = 'npm'
427
+ }
428
+
429
+ // Languages
430
+ analysis.languages.push('javascript')
431
+
432
+ // Analyze dependencies
433
+ const allDeps = {
434
+ ...pkg.dependencies,
435
+ ...pkg.devDependencies
436
+ }
437
+
438
+ analysis.dependencies = Object.keys(pkg.dependencies || {})
439
+ analysis.devDependencies = Object.keys(pkg.devDependencies || {})
440
+
441
+ // Detect frameworks
442
+ if (allDeps['react']) {
443
+ analysis.frameworks.push('react')
444
+ if (allDeps['next']) analysis.frameworks.push('next.js')
445
+ if (allDeps['gatsby']) analysis.frameworks.push('gatsby')
446
+ if (allDeps['remix']) analysis.frameworks.push('remix')
447
+ }
448
+ if (allDeps['vue']) analysis.frameworks.push('vue')
449
+ if (allDeps['@angular/core']) analysis.frameworks.push('angular')
450
+ if (allDeps['svelte']) analysis.frameworks.push('svelte')
451
+ if (allDeps['express']) analysis.frameworks.push('express')
452
+ if (allDeps['fastify']) analysis.frameworks.push('fastify')
453
+ if (allDeps['hono']) analysis.frameworks.push('hono')
454
+ if (allDeps['elysia']) analysis.frameworks.push('elysia')
455
+ if (allDeps['nestjs'] || allDeps['@nestjs/core']) analysis.frameworks.push('nestjs')
456
+ if (allDeps['electron']) analysis.frameworks.push('electron')
457
+ if (allDeps['tauri']) analysis.frameworks.push('tauri')
458
+
459
+ // Detect TypeScript
460
+ if (allDeps['typescript'] || await fileExists(path.join(projectPath, 'tsconfig.json'))) {
461
+ analysis.hasTypeScript = true
462
+ analysis.languages.push('typescript')
463
+ }
464
+
465
+ // Detect testing
466
+ if (allDeps['jest'] || allDeps['vitest'] || allDeps['mocha'] || allDeps['ava']) {
467
+ analysis.hasTests = true
468
+ }
469
+
470
+ // Detect linting
471
+ if (allDeps['eslint'] || allDeps['biome'] || allDeps['@biomejs/biome']) {
472
+ analysis.hasLinting = true
473
+ }
474
+
475
+ // Detect formatting
476
+ if (allDeps['prettier'] || allDeps['biome'] || allDeps['@biomejs/biome']) {
477
+ analysis.hasFormatting = true
478
+ }
479
+
480
+ // Key files
481
+ analysis.keyFiles.push('package.json')
482
+
483
+ } catch (error) {
484
+ // Not a Node.js project
485
+ }
486
+ }
487
+
488
+ async function analyzeConfigFiles(projectPath: string, analysis: ProjectAnalysis, logger: Logger) {
489
+ const configFiles = [
490
+ 'tsconfig.json',
491
+ '.eslintrc.json',
492
+ '.eslintrc.js',
493
+ '.prettierrc',
494
+ 'prettier.config.js',
495
+ 'vite.config.ts',
496
+ 'vite.config.js',
497
+ 'webpack.config.js',
498
+ 'rollup.config.js',
499
+ 'tailwind.config.js',
500
+ 'tailwind.config.ts',
501
+ 'postcss.config.js',
502
+ 'next.config.js',
503
+ 'next.config.ts',
504
+ 'nuxt.config.ts',
505
+ 'astro.config.mjs',
506
+ 'svelte.config.js',
507
+ 'biome.json'
508
+ ]
509
+
510
+ for (const file of configFiles) {
511
+ if (await fileExists(path.join(projectPath, file))) {
512
+ analysis.keyFiles.push(file)
513
+
514
+ // Detect specific tools
515
+ if (file.includes('tailwind')) analysis.frameworks.push('tailwindcss')
516
+ if (file.includes('vite')) analysis.frameworks.push('vite')
517
+ if (file.includes('webpack')) analysis.frameworks.push('webpack')
518
+ if (file.includes('astro')) analysis.frameworks.push('astro')
519
+ }
520
+ }
521
+ }
522
+
523
+ async function analyzePythonProject(projectPath: string, analysis: ProjectAnalysis, logger: Logger) {
524
+ // Check for Python files
525
+ if (await fileExists(path.join(projectPath, 'requirements.txt')) ||
526
+ await fileExists(path.join(projectPath, 'pyproject.toml')) ||
527
+ await fileExists(path.join(projectPath, 'setup.py'))) {
528
+
529
+ analysis.languages.push('python')
530
+
531
+ if (await fileExists(path.join(projectPath, 'requirements.txt'))) {
532
+ analysis.keyFiles.push('requirements.txt')
533
+ analysis.packageManager = 'pip'
534
+ }
535
+
536
+ if (await fileExists(path.join(projectPath, 'pyproject.toml'))) {
537
+ analysis.keyFiles.push('pyproject.toml')
538
+ analysis.packageManager = 'poetry'
539
+ }
540
+
541
+ // Check for frameworks
542
+ try {
543
+ const reqPath = path.join(projectPath, 'requirements.txt')
544
+ if (await fileExists(reqPath)) {
545
+ const content = await fs.readFile(reqPath, 'utf-8')
546
+ if (content.includes('django')) analysis.frameworks.push('django')
547
+ if (content.includes('flask')) analysis.frameworks.push('flask')
548
+ if (content.includes('fastapi')) analysis.frameworks.push('fastapi')
549
+ if (content.includes('pytest')) analysis.hasTests = true
550
+ }
551
+ } catch {}
552
+ }
553
+ }
554
+
555
+ async function analyzeGoProject(projectPath: string, analysis: ProjectAnalysis, logger: Logger) {
556
+ if (await fileExists(path.join(projectPath, 'go.mod'))) {
557
+ analysis.languages.push('go')
558
+ analysis.keyFiles.push('go.mod')
559
+ analysis.packageManager = 'go modules'
560
+ }
561
+ }
562
+
563
+ async function analyzeRustProject(projectPath: string, analysis: ProjectAnalysis, logger: Logger) {
564
+ if (await fileExists(path.join(projectPath, 'Cargo.toml'))) {
565
+ analysis.languages.push('rust')
566
+ analysis.keyFiles.push('Cargo.toml')
567
+ analysis.packageManager = 'cargo'
568
+ }
569
+ }
570
+
571
+ async function detectTests(projectPath: string, analysis: ProjectAnalysis, logger: Logger) {
572
+ const testDirs = ['test', 'tests', '__tests__', 'spec', 'specs']
573
+
574
+ for (const dir of testDirs) {
575
+ if (await fileExists(path.join(projectPath, dir))) {
576
+ analysis.hasTests = true
577
+ analysis.keyFiles.push(`${dir}/`)
578
+ break
579
+ }
580
+ }
581
+ }
582
+
583
+ async function readReadme(projectPath: string, analysis: ProjectAnalysis, logger: Logger) {
584
+ const readmeFiles = ['README.md', 'readme.md', 'Readme.md', 'README.txt', 'README']
585
+
586
+ for (const file of readmeFiles) {
587
+ try {
588
+ const content = await fs.readFile(path.join(projectPath, file), 'utf-8')
589
+ analysis.keyFiles.push(file)
590
+
591
+ // Extract first paragraph as description if not set
592
+ if (!analysis.description) {
593
+ const lines = content.split('\n')
594
+ for (const line of lines) {
595
+ const trimmed = line.trim()
596
+ // Skip headers and empty lines
597
+ if (trimmed && !trimmed.startsWith('#') && !trimmed.startsWith('!') && trimmed.length > 20) {
598
+ analysis.description = trimmed.slice(0, 200)
599
+ break
600
+ }
601
+ }
602
+ }
603
+ break
604
+ } catch {}
605
+ }
606
+ }
607
+
608
+ async function readGitignore(projectPath: string, analysis: ProjectAnalysis, logger: Logger) {
609
+ try {
610
+ const content = await fs.readFile(path.join(projectPath, '.gitignore'), 'utf-8')
611
+ analysis.gitIgnorePatterns = content
612
+ .split('\n')
613
+ .filter(line => line.trim() && !line.startsWith('#'))
614
+ .slice(0, 20)
615
+ } catch {}
616
+ }
617
+
618
+ function detectConventions(analysis: ProjectAnalysis) {
619
+ // Detect conventions based on structure and config
620
+
621
+ if (analysis.structure.includes('src/')) {
622
+ analysis.conventions.push('Source code in src/ directory')
623
+ }
624
+
625
+ if (analysis.structure.includes('lib/')) {
626
+ analysis.conventions.push('Library code in lib/ directory')
627
+ }
628
+
629
+ if (analysis.structure.includes('components/') || analysis.structure.some(s => s.includes('components'))) {
630
+ analysis.conventions.push('Component-based architecture')
631
+ }
632
+
633
+ if (analysis.hasTypeScript) {
634
+ analysis.conventions.push('TypeScript for type safety')
635
+ }
636
+
637
+ if (analysis.hasLinting) {
638
+ analysis.conventions.push('Code linting enforced')
639
+ }
640
+
641
+ if (analysis.hasFormatting) {
642
+ analysis.conventions.push('Code formatting enforced')
643
+ }
644
+
645
+ if (analysis.hasTests) {
646
+ analysis.conventions.push('Test coverage expected')
647
+ }
648
+
649
+ if (analysis.frameworks.includes('tailwindcss')) {
650
+ analysis.conventions.push('Tailwind CSS for styling')
651
+ }
652
+ }
653
+
654
+ function detectTags(analysis: ProjectAnalysis): string[] {
655
+ const tags: string[] = []
656
+
657
+ if (analysis.frameworks.some(f => ['react', 'vue', 'angular', 'svelte'].includes(f))) {
658
+ tags.push('frontend')
659
+ }
660
+
661
+ if (analysis.frameworks.some(f => ['express', 'fastify', 'nestjs', 'hono', 'elysia'].includes(f))) {
662
+ tags.push('backend')
663
+ }
664
+
665
+ if (analysis.frameworks.some(f => ['next.js', 'nuxt', 'remix'].includes(f))) {
666
+ tags.push('fullstack')
667
+ }
668
+
669
+ if (analysis.frameworks.includes('electron') || analysis.frameworks.includes('tauri')) {
670
+ tags.push('desktop')
671
+ }
672
+
673
+ return tags
674
+ }
675
+
676
+ function generateContextContent(analysis: ProjectAnalysis): string {
677
+ const parts: string[] = []
678
+
679
+ parts.push(`# ${analysis.name}\n`)
680
+
681
+ parts.push(`## Overview`)
682
+ parts.push(analysis.description || '*Add project description here*')
683
+ parts.push('')
684
+
685
+ parts.push(`## Tech Stack`)
686
+ if (analysis.languages.length > 0) {
687
+ parts.push(`**Languages:** ${analysis.languages.join(', ')}`)
688
+ }
689
+ if (analysis.frameworks.length > 0) {
690
+ parts.push(`**Frameworks:** ${analysis.frameworks.join(', ')}`)
691
+ }
692
+ if (analysis.packageManager) {
693
+ parts.push(`**Package Manager:** ${analysis.packageManager}`)
694
+ }
695
+ parts.push('')
696
+
697
+ parts.push(`## Architecture`)
698
+ parts.push(`### Project Structure`)
699
+ parts.push('```')
700
+ analysis.structure.slice(0, 15).forEach(s => parts.push(s))
701
+ parts.push('```')
702
+ parts.push('')
703
+
704
+ if (analysis.keyFiles.length > 0) {
705
+ parts.push(`### Key Files`)
706
+ analysis.keyFiles.forEach(f => parts.push(`- \`${f}\``))
707
+ parts.push('')
708
+ }
709
+
710
+ parts.push(`## Key Decisions`)
711
+ parts.push(`*Use \`remember_decision\` to add architectural decisions here*`)
712
+
713
+ return parts.join('\n')
714
+ }
715
+
716
+ function generateStandardsContent(analysis: ProjectAnalysis): string {
717
+ const parts: string[] = []
718
+
719
+ parts.push(`# Coding Standards: ${analysis.name}\n`)
720
+
721
+ parts.push(`## General Principles`)
722
+ analysis.conventions.forEach(c => parts.push(`- ${c}`))
723
+ if (analysis.conventions.length === 0) {
724
+ parts.push('*Add general coding principles*')
725
+ }
726
+ parts.push('')
727
+
728
+ parts.push(`## Language-Specific Standards`)
729
+ for (const lang of analysis.languages) {
730
+ parts.push(`### ${lang.charAt(0).toUpperCase() + lang.slice(1)}`)
731
+ parts.push(`*Add ${lang}-specific standards*`)
732
+ parts.push('')
733
+ }
734
+
735
+ if (analysis.frameworks.length > 0) {
736
+ parts.push(`## Framework-Specific Patterns`)
737
+ for (const fw of analysis.frameworks) {
738
+ parts.push(`### ${fw}`)
739
+ parts.push(`*Add ${fw}-specific patterns and conventions*`)
740
+ parts.push('')
741
+ }
742
+ }
743
+
744
+ parts.push(`## Common Anti-Patterns to Avoid`)
745
+ parts.push(`*Document patterns to avoid*`)
746
+
747
+ return parts.join('\n')
748
+ }
749
+
750
+ async function fileExists(filePath: string): Promise<boolean> {
751
+ try {
752
+ await fs.access(filePath)
753
+ return true
754
+ } catch {
755
+ return false
756
+ }
757
+ }