claude-code-workflow 6.1.4 → 6.2.2

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 (437) hide show
  1. package/.claude/CLAUDE.md +10 -0
  2. package/.claude/agents/action-planning-agent.md +857 -778
  3. package/.claude/agents/cli-execution-agent.md +266 -269
  4. package/.claude/agents/cli-explore-agent.md +2 -2
  5. package/.claude/agents/cli-lite-planning-agent.md +142 -92
  6. package/.claude/agents/cli-planning-agent.md +4 -4
  7. package/.claude/agents/code-developer.md +7 -6
  8. package/.claude/agents/conceptual-planning-agent.md +2 -2
  9. package/.claude/agents/context-search-agent.md +31 -32
  10. package/.claude/agents/doc-generator.md +4 -4
  11. package/.claude/agents/memory-bridge.md +93 -93
  12. package/.claude/agents/test-context-search-agent.md +8 -7
  13. package/.claude/agents/test-fix-agent.md +7 -6
  14. package/.claude/commands/clean.md +516 -0
  15. package/.claude/commands/memory/compact.md +383 -0
  16. package/.claude/commands/memory/docs-full-cli.md +471 -471
  17. package/.claude/commands/memory/docs-related-cli.md +386 -386
  18. package/.claude/commands/memory/docs.md +615 -615
  19. package/.claude/commands/memory/load.md +5 -5
  20. package/.claude/commands/memory/tech-research-rules.md +310 -0
  21. package/.claude/commands/memory/update-full.md +332 -332
  22. package/.claude/commands/memory/workflow-skill-memory.md +4 -4
  23. package/.claude/commands/task/create.md +151 -151
  24. package/.claude/commands/version.md +254 -254
  25. package/.claude/commands/workflow/brainstorm/api-designer.md +587 -585
  26. package/.claude/commands/workflow/brainstorm/artifacts.md +1 -0
  27. package/.claude/commands/workflow/brainstorm/auto-parallel.md +443 -443
  28. package/.claude/commands/workflow/brainstorm/data-architect.md +220 -220
  29. package/.claude/commands/workflow/brainstorm/product-manager.md +200 -200
  30. package/.claude/commands/workflow/brainstorm/product-owner.md +200 -200
  31. package/.claude/commands/workflow/brainstorm/scrum-master.md +200 -200
  32. package/.claude/commands/workflow/brainstorm/subject-matter-expert.md +200 -200
  33. package/.claude/commands/workflow/brainstorm/system-architect.md +389 -387
  34. package/.claude/commands/workflow/brainstorm/ui-designer.md +221 -221
  35. package/.claude/commands/workflow/brainstorm/ux-expert.md +221 -221
  36. package/.claude/commands/workflow/debug.md +321 -0
  37. package/.claude/commands/workflow/execute.md +13 -0
  38. package/.claude/commands/workflow/init.md +165 -164
  39. package/.claude/commands/workflow/lite-execute.md +119 -13
  40. package/.claude/commands/workflow/lite-fix.md +623 -621
  41. package/.claude/commands/workflow/lite-plan.md +610 -592
  42. package/.claude/commands/workflow/plan.md +5 -5
  43. package/.claude/commands/workflow/review-module-cycle.md +2 -0
  44. package/.claude/commands/workflow/review-session-cycle.md +2 -0
  45. package/.claude/commands/workflow/review.md +297 -291
  46. package/.claude/commands/workflow/session/complete.md +153 -500
  47. package/.claude/commands/workflow/session/list.md +95 -95
  48. package/.claude/commands/workflow/session/resume.md +60 -60
  49. package/.claude/commands/workflow/session/start.md +199 -199
  50. package/.claude/commands/workflow/tdd-plan.md +3 -3
  51. package/.claude/commands/workflow/tdd-verify.md +23 -9
  52. package/.claude/commands/workflow/test-cycle-execute.md +2 -0
  53. package/.claude/commands/workflow/test-fix-gen.md +699 -699
  54. package/.claude/commands/workflow/tools/conflict-resolution.md +104 -18
  55. package/.claude/commands/workflow/tools/context-gather.md +436 -434
  56. package/.claude/commands/workflow/tools/task-generate-agent.md +490 -291
  57. package/.claude/commands/workflow/tools/task-generate-tdd.md +18 -10
  58. package/.claude/commands/workflow/tools/test-concept-enhanced.md +2 -1
  59. package/.claude/commands/workflow/tools/test-context-gather.md +1 -0
  60. package/.claude/commands/workflow/tools/test-task-generate.md +1 -0
  61. package/.claude/commands/workflow/ui-design/import-from-code.md +9 -6
  62. package/.claude/skills/command-guide/SKILL.md +5 -5
  63. package/.claude/skills/command-guide/index/all-commands.json +1 -1
  64. package/.claude/skills/command-guide/index/by-category.json +1 -1
  65. package/.claude/skills/command-guide/index/by-use-case.json +1 -1
  66. package/.claude/skills/command-guide/reference/agents/action-planning-agent.md +857 -778
  67. package/.claude/skills/command-guide/reference/agents/cli-execution-agent.md +266 -269
  68. package/.claude/skills/command-guide/reference/agents/cli-explore-agent.md +2 -2
  69. package/.claude/skills/command-guide/reference/agents/cli-lite-planning-agent.md +142 -92
  70. package/.claude/skills/command-guide/reference/agents/cli-planning-agent.md +4 -4
  71. package/.claude/skills/command-guide/reference/agents/code-developer.md +7 -6
  72. package/.claude/skills/command-guide/reference/agents/conceptual-planning-agent.md +2 -2
  73. package/.claude/skills/command-guide/reference/agents/context-search-agent.md +31 -32
  74. package/.claude/skills/command-guide/reference/agents/doc-generator.md +4 -4
  75. package/.claude/skills/command-guide/reference/agents/memory-bridge.md +93 -93
  76. package/.claude/skills/command-guide/reference/agents/test-context-search-agent.md +8 -7
  77. package/.claude/skills/command-guide/reference/agents/test-fix-agent.md +7 -6
  78. package/.claude/skills/command-guide/reference/commands/memory/docs-full-cli.md +471 -471
  79. package/.claude/skills/command-guide/reference/commands/memory/docs-related-cli.md +386 -386
  80. package/.claude/skills/command-guide/reference/commands/memory/docs.md +17 -16
  81. package/.claude/skills/command-guide/reference/commands/memory/load.md +5 -5
  82. package/.claude/skills/command-guide/reference/commands/memory/tech-research.md +194 -357
  83. package/.claude/skills/command-guide/reference/commands/memory/update-full.md +332 -332
  84. package/.claude/skills/command-guide/reference/commands/memory/workflow-skill-memory.md +4 -4
  85. package/.claude/skills/command-guide/reference/commands/task/create.md +151 -151
  86. package/.claude/skills/command-guide/reference/commands/version.md +254 -254
  87. package/.claude/skills/command-guide/reference/commands/workflow/brainstorm/api-designer.md +585 -585
  88. package/.claude/skills/command-guide/reference/commands/workflow/brainstorm/auto-parallel.md +443 -443
  89. package/.claude/skills/command-guide/reference/commands/workflow/brainstorm/data-architect.md +220 -220
  90. package/.claude/skills/command-guide/reference/commands/workflow/brainstorm/product-manager.md +200 -200
  91. package/.claude/skills/command-guide/reference/commands/workflow/brainstorm/product-owner.md +200 -200
  92. package/.claude/skills/command-guide/reference/commands/workflow/brainstorm/scrum-master.md +200 -200
  93. package/.claude/skills/command-guide/reference/commands/workflow/brainstorm/subject-matter-expert.md +200 -200
  94. package/.claude/skills/command-guide/reference/commands/workflow/brainstorm/system-architect.md +387 -387
  95. package/.claude/skills/command-guide/reference/commands/workflow/brainstorm/ui-designer.md +221 -221
  96. package/.claude/skills/command-guide/reference/commands/workflow/brainstorm/ux-expert.md +221 -221
  97. package/.claude/skills/command-guide/reference/commands/workflow/execute.md +25 -20
  98. package/.claude/skills/command-guide/reference/commands/workflow/init.md +164 -164
  99. package/.claude/skills/command-guide/reference/commands/workflow/lite-execute.md +748 -686
  100. package/.claude/skills/command-guide/reference/commands/workflow/lite-fix.md +664 -621
  101. package/.claude/skills/command-guide/reference/commands/workflow/lite-plan.md +645 -592
  102. package/.claude/skills/command-guide/reference/commands/workflow/plan.md +5 -5
  103. package/.claude/skills/command-guide/reference/commands/workflow/review.md +25 -18
  104. package/.claude/skills/command-guide/reference/commands/workflow/session/complete.md +547 -500
  105. package/.claude/skills/command-guide/reference/commands/workflow/session/list.md +45 -27
  106. package/.claude/skills/command-guide/reference/commands/workflow/session/resume.md +35 -19
  107. package/.claude/skills/command-guide/reference/commands/workflow/session/start.md +90 -33
  108. package/.claude/skills/command-guide/reference/commands/workflow/tdd-plan.md +3 -3
  109. package/.claude/skills/command-guide/reference/commands/workflow/tdd-verify.md +23 -9
  110. package/.claude/skills/command-guide/reference/commands/workflow/test-fix-gen.md +699 -699
  111. package/.claude/skills/command-guide/reference/commands/workflow/tools/conflict-resolution.md +103 -17
  112. package/.claude/skills/command-guide/reference/commands/workflow/tools/context-gather.md +434 -434
  113. package/.claude/skills/command-guide/reference/commands/workflow/tools/task-generate-agent.md +487 -291
  114. package/.claude/skills/command-guide/reference/commands/workflow/tools/task-generate-tdd.md +17 -10
  115. package/.claude/skills/command-guide/reference/commands/workflow/tools/test-concept-enhanced.md +1 -1
  116. package/.claude/skills/command-guide/reference/commands/workflow/ui-design/import-from-code.md +6 -6
  117. package/.claude/workflows/chinese-response.md +38 -0
  118. package/.claude/workflows/cli-templates/prompts/rules/rule-api.txt +122 -0
  119. package/.claude/workflows/cli-templates/prompts/rules/rule-components.txt +122 -0
  120. package/.claude/workflows/cli-templates/prompts/rules/rule-config.txt +89 -0
  121. package/.claude/workflows/cli-templates/prompts/rules/rule-core.txt +60 -0
  122. package/.claude/workflows/cli-templates/prompts/rules/rule-patterns.txt +70 -0
  123. package/.claude/workflows/cli-templates/prompts/rules/rule-testing.txt +81 -0
  124. package/.claude/workflows/cli-templates/prompts/rules/tech-rules-agent-prompt.txt +89 -0
  125. package/.claude/workflows/cli-templates/prompts/workflow/gemini-solution-design.txt +131 -131
  126. package/.claude/workflows/cli-templates/prompts/workflow/skill-conflict-patterns.txt +5 -9
  127. package/.claude/workflows/cli-templates/prompts/workflow/skill-lessons-learned.txt +5 -9
  128. package/.claude/workflows/cli-templates/protocols/analysis-protocol.md +112 -0
  129. package/.claude/workflows/cli-templates/protocols/write-protocol.md +201 -0
  130. package/.claude/workflows/cli-templates/schemas/conflict-resolution-schema.json +137 -0
  131. package/.claude/workflows/cli-templates/schemas/debug-log-json-schema.json +127 -0
  132. package/.claude/workflows/cli-templates/schemas/fix-plan-json-schema.json +25 -0
  133. package/.claude/workflows/cli-templates/schemas/plan-json-schema.json +25 -0
  134. package/.claude/workflows/cli-tools-usage.md +526 -0
  135. package/{CLAUDE.md → .claude/workflows/coding-philosophy.md} +24 -45
  136. package/.claude/workflows/context-tools.md +84 -0
  137. package/.claude/workflows/file-modification.md +64 -0
  138. package/.claude/workflows/tool-strategy.md +216 -79
  139. package/.claude/workflows/windows-platform.md +16 -0
  140. package/.claude/workflows/workflow-architecture.md +942 -942
  141. package/.codex/AGENTS.md +63 -330
  142. package/.codex/prompts/debug.md +318 -0
  143. package/.codex/prompts/execute.md +273 -0
  144. package/.codex/prompts/lite-execute.md +164 -0
  145. package/.codex/prompts/lite-plan.md +469 -0
  146. package/.codex/prompts.zip +0 -0
  147. package/.gemini/GEMINI.md +25 -164
  148. package/.qwen/QWEN.md +0 -139
  149. package/README.md +29 -9
  150. package/ccw/README.md +30 -6
  151. package/ccw/bin/ccw-mcp.js +7 -0
  152. package/ccw/bin/ccw.js +9 -9
  153. package/ccw/package.json +65 -47
  154. package/ccw/src/.workflow/.cli-history/history.db +0 -0
  155. package/ccw/src/.workflow/.cli-history/history.db-shm +0 -0
  156. package/ccw/src/.workflow/.cli-history/history.db-wal +0 -0
  157. package/ccw/src/cli.ts +244 -0
  158. package/ccw/src/commands/cli.ts +740 -0
  159. package/ccw/src/commands/core-memory.ts +770 -0
  160. package/ccw/src/commands/hook.ts +315 -0
  161. package/ccw/src/commands/install.ts +519 -0
  162. package/ccw/src/commands/{list.js → list.ts} +1 -1
  163. package/ccw/src/commands/memory.ts +1090 -0
  164. package/ccw/src/commands/{serve.js → serve.ts} +14 -5
  165. package/ccw/src/commands/session-path-resolver.ts +372 -0
  166. package/ccw/src/commands/session.ts +1141 -0
  167. package/ccw/src/commands/{stop.js → stop.ts} +16 -6
  168. package/ccw/src/commands/tool.ts +201 -0
  169. package/ccw/src/commands/{uninstall.js → uninstall.ts} +89 -40
  170. package/ccw/src/commands/{upgrade.js → upgrade.ts} +68 -23
  171. package/ccw/src/commands/{view.js → view.ts} +22 -8
  172. package/ccw/src/config/storage-paths.ts +670 -0
  173. package/ccw/src/core/cache-manager.ts +294 -0
  174. package/ccw/src/core/claude-freshness.ts +319 -0
  175. package/ccw/src/core/core-memory-store.ts +1528 -0
  176. package/ccw/src/core/{dashboard-generator-patch.js → dashboard-generator-patch.ts} +18 -0
  177. package/ccw/src/core/{dashboard-generator.js → dashboard-generator.ts} +69 -12
  178. package/ccw/src/core/data-aggregator.ts +584 -0
  179. package/ccw/src/core/history-importer.ts +625 -0
  180. package/ccw/src/core/{lite-scanner.js → lite-scanner-complete.ts} +162 -66
  181. package/ccw/src/core/lite-scanner.ts +469 -0
  182. package/ccw/src/core/{manifest.js → manifest.ts} +104 -34
  183. package/ccw/src/core/memory-embedder-bridge.ts +262 -0
  184. package/ccw/src/core/memory-store.ts +978 -0
  185. package/ccw/src/core/routes/ccw-routes.ts +96 -0
  186. package/ccw/src/core/routes/claude-routes.ts +1183 -0
  187. package/ccw/src/core/routes/cli-routes.ts +561 -0
  188. package/ccw/src/core/routes/codexlens-routes.ts +806 -0
  189. package/ccw/src/core/routes/core-memory-routes.ts +605 -0
  190. package/ccw/src/core/routes/files-routes.ts +428 -0
  191. package/ccw/src/core/routes/graph-routes.md +164 -0
  192. package/ccw/src/core/routes/graph-routes.ts +626 -0
  193. package/ccw/src/core/routes/help-routes.ts +308 -0
  194. package/ccw/src/core/routes/hooks-routes.ts +405 -0
  195. package/ccw/src/core/routes/mcp-routes.ts +1271 -0
  196. package/ccw/src/core/routes/mcp-routes.ts.backup +550 -0
  197. package/ccw/src/core/routes/mcp-templates-db.ts +268 -0
  198. package/ccw/src/core/routes/memory-routes.ts +1206 -0
  199. package/ccw/src/core/routes/rules-routes.ts +526 -0
  200. package/ccw/src/core/routes/session-routes.ts +467 -0
  201. package/ccw/src/core/routes/skills-routes.ts +599 -0
  202. package/ccw/src/core/routes/status-routes.ts +57 -0
  203. package/ccw/src/core/routes/system-routes.ts +427 -0
  204. package/ccw/src/core/server.ts +431 -0
  205. package/ccw/src/core/session-clustering-service.ts +1258 -0
  206. package/ccw/src/core/session-scanner.ts +283 -0
  207. package/ccw/src/core/websocket.ts +190 -0
  208. package/ccw/src/{index.js → index.ts} +1 -0
  209. package/ccw/src/mcp-server/index.ts +186 -0
  210. package/ccw/src/templates/assets/css/github-dark.min.css +10 -0
  211. package/ccw/src/templates/assets/css/github.min.css +10 -0
  212. package/ccw/src/templates/assets/js/cytoscape.min.js +32 -0
  213. package/ccw/src/templates/assets/js/d3.min.js +2 -0
  214. package/ccw/src/templates/assets/js/highlight.min.js +1244 -0
  215. package/ccw/src/templates/assets/js/lucide.min.js +12 -0
  216. package/ccw/src/templates/assets/js/marked.min.js +69 -0
  217. package/ccw/src/templates/assets/js/tailwind.js +83 -0
  218. package/ccw/src/templates/dashboard-css/01-base.css +11 -0
  219. package/ccw/src/templates/dashboard-css/02-session.css +22 -0
  220. package/ccw/src/templates/dashboard-css/04-lite-tasks.css +10 -0
  221. package/ccw/src/templates/dashboard-css/06-cards.css +10 -4
  222. package/ccw/src/templates/dashboard-css/07-managers.css +1178 -7
  223. package/ccw/src/templates/dashboard-css/09-explorer.css +23 -12
  224. package/ccw/src/templates/dashboard-css/10-cli-status.css +337 -0
  225. package/ccw/src/templates/dashboard-css/11-cli-history.css +271 -0
  226. package/ccw/src/templates/dashboard-css/12-cli-legacy.css +796 -0
  227. package/ccw/src/templates/dashboard-css/13-cli-ccw.css +199 -0
  228. package/ccw/src/templates/dashboard-css/14-cli-modals.css +258 -0
  229. package/ccw/src/templates/dashboard-css/15-cli-endpoints.css +305 -0
  230. package/ccw/src/templates/dashboard-css/16-cli-session.css +241 -0
  231. package/ccw/src/templates/dashboard-css/17-cli-conversation.css +283 -0
  232. package/ccw/src/templates/dashboard-css/18-cli-settings.css +160 -0
  233. package/ccw/src/templates/dashboard-css/19-cli-native-session.css +496 -0
  234. package/ccw/src/templates/dashboard-css/20-cli-taskqueue.css +188 -0
  235. package/ccw/src/templates/dashboard-css/21-cli-toolmgmt.css +310 -0
  236. package/ccw/src/templates/dashboard-css/22-cli-semantic.css +240 -0
  237. package/ccw/src/templates/dashboard-css/23-memory.css +2390 -0
  238. package/ccw/src/templates/dashboard-css/24-prompt-history.css +1089 -0
  239. package/ccw/src/templates/dashboard-css/25-skills-rules.css +326 -0
  240. package/ccw/src/templates/dashboard-css/26-claude-manager.css +908 -0
  241. package/ccw/src/templates/dashboard-css/27-graph-explorer.css +1678 -0
  242. package/ccw/src/templates/dashboard-css/28-mcp-manager.css +748 -0
  243. package/ccw/src/templates/dashboard-css/29-help.css +264 -0
  244. package/ccw/src/templates/dashboard-css/30-core-memory.css +1700 -0
  245. package/ccw/src/templates/dashboard-js/api.js +162 -142
  246. package/ccw/src/templates/dashboard-js/components/carousel.js +4 -4
  247. package/ccw/src/templates/dashboard-js/components/cli-history.js +876 -0
  248. package/ccw/src/templates/dashboard-js/components/cli-status.js +978 -0
  249. package/ccw/src/templates/dashboard-js/components/global-notifications.js +508 -219
  250. package/ccw/src/templates/dashboard-js/components/hook-manager.js +1277 -282
  251. package/ccw/src/templates/dashboard-js/components/index-manager.js +302 -0
  252. package/ccw/src/templates/dashboard-js/components/mcp-manager.js +718 -27
  253. package/ccw/src/templates/dashboard-js/components/modals.js +66 -0
  254. package/ccw/src/templates/dashboard-js/components/navigation.js +80 -12
  255. package/ccw/src/templates/dashboard-js/components/notifications.js +758 -194
  256. package/ccw/src/templates/dashboard-js/components/storage-manager.js +478 -0
  257. package/ccw/src/templates/dashboard-js/components/tabs-other.js +157 -6
  258. package/ccw/src/templates/dashboard-js/components/task-queue-sidebar.js +716 -0
  259. package/ccw/src/templates/dashboard-js/help-i18n.js +272 -0
  260. package/ccw/src/templates/dashboard-js/i18n.js +2807 -0
  261. package/ccw/src/templates/dashboard-js/main.js +15 -0
  262. package/ccw/src/templates/dashboard-js/state.js +243 -42
  263. package/ccw/src/templates/dashboard-js/utils.js +47 -1
  264. package/ccw/src/templates/dashboard-js/views/claude-manager.js +912 -0
  265. package/ccw/src/templates/dashboard-js/views/cli-manager.js +2272 -0
  266. package/ccw/src/templates/dashboard-js/views/codexlens-manager.js +964 -0
  267. package/ccw/src/templates/dashboard-js/views/core-memory-clusters.js +503 -0
  268. package/ccw/src/templates/dashboard-js/views/core-memory.js +782 -0
  269. package/ccw/src/templates/dashboard-js/views/explorer.js +888 -852
  270. package/ccw/src/templates/dashboard-js/views/graph-explorer.js +1157 -0
  271. package/ccw/src/templates/dashboard-js/views/help.js +856 -0
  272. package/ccw/src/templates/dashboard-js/views/history.js +337 -0
  273. package/ccw/src/templates/dashboard-js/views/home.js +61 -15
  274. package/ccw/src/templates/dashboard-js/views/hook-manager.js +311 -43
  275. package/ccw/src/templates/dashboard-js/views/lite-tasks.js +204 -28
  276. package/ccw/src/templates/dashboard-js/views/mcp-manager.js +2187 -411
  277. package/ccw/src/templates/dashboard-js/views/mcp-manager.js.backup +1729 -0
  278. package/ccw/src/templates/dashboard-js/views/mcp-manager.js.new +928 -0
  279. package/ccw/src/templates/dashboard-js/views/memory.js +1221 -0
  280. package/ccw/src/templates/dashboard-js/views/prompt-history.js +713 -0
  281. package/ccw/src/templates/dashboard-js/views/rules-manager.js +828 -0
  282. package/ccw/src/templates/dashboard-js/views/session-detail.js +54 -53
  283. package/ccw/src/templates/dashboard-js/views/skills-manager.js +819 -0
  284. package/ccw/src/templates/dashboard.html +185 -85
  285. package/ccw/src/templates/hooks-config-example.json +60 -0
  286. package/ccw/src/tools/classify-folders.ts +245 -0
  287. package/ccw/src/tools/cli-config-manager.ts +268 -0
  288. package/ccw/src/tools/cli-executor.ts +2014 -0
  289. package/ccw/src/tools/cli-history-store.ts +1195 -0
  290. package/ccw/src/tools/codex-lens.ts +1141 -0
  291. package/ccw/src/tools/{convert-tokens-to-css.js → convert-tokens-to-css.ts} +73 -23
  292. package/ccw/src/tools/core-memory.ts +444 -0
  293. package/ccw/src/tools/detect-changed-modules.ts +325 -0
  294. package/ccw/src/tools/{discover-design-files.js → discover-design-files.ts} +74 -24
  295. package/ccw/src/tools/edit-file.ts +568 -0
  296. package/ccw/src/tools/{generate-module-docs.js → generate-module-docs.ts} +207 -185
  297. package/ccw/src/tools/{get-modules-by-depth.js → get-modules-by-depth.ts} +120 -79
  298. package/ccw/src/tools/index.ts +370 -0
  299. package/ccw/src/tools/native-session-discovery.ts +795 -0
  300. package/ccw/src/tools/notifier.ts +129 -0
  301. package/ccw/src/tools/read-file.ts +410 -0
  302. package/ccw/src/tools/resume-strategy.ts +345 -0
  303. package/ccw/src/tools/session-content-parser.ts +619 -0
  304. package/ccw/src/tools/session-manager.ts +1026 -0
  305. package/ccw/src/tools/smart-context.ts +228 -0
  306. package/ccw/src/tools/smart-search.ts +2065 -0
  307. package/ccw/src/tools/smart-search.ts.backup +1233 -0
  308. package/ccw/src/tools/storage-manager.ts +455 -0
  309. package/ccw/src/tools/write-file.ts +222 -0
  310. package/ccw/src/types/config.ts +11 -0
  311. package/ccw/src/types/index.ts +3 -0
  312. package/ccw/src/types/session.ts +25 -0
  313. package/ccw/src/types/tool.ts +41 -0
  314. package/ccw/src/utils/{browser-launcher.js → browser-launcher.ts} +10 -8
  315. package/ccw/src/utils/file-utils.ts +48 -0
  316. package/ccw/src/utils/{path-resolver.js → path-resolver.ts} +114 -78
  317. package/ccw/src/utils/path-validator.ts +153 -0
  318. package/ccw/src/utils/{ui.js → ui.ts} +32 -25
  319. package/codex-lens/pyproject.toml +48 -0
  320. package/codex-lens/src/codexlens/.workflow/.cli-history/history.db +0 -0
  321. package/codex-lens/src/codexlens/__init__.py +28 -0
  322. package/codex-lens/src/codexlens/__main__.py +14 -0
  323. package/codex-lens/src/codexlens/__pycache__/__init__.cpython-313.pyc +0 -0
  324. package/codex-lens/src/codexlens/__pycache__/__main__.cpython-313.pyc +0 -0
  325. package/codex-lens/src/codexlens/__pycache__/config.cpython-313.pyc +0 -0
  326. package/codex-lens/src/codexlens/__pycache__/entities.cpython-313.pyc +0 -0
  327. package/codex-lens/src/codexlens/__pycache__/errors.cpython-313.pyc +0 -0
  328. package/codex-lens/src/codexlens/cli/__init__.py +27 -0
  329. package/codex-lens/src/codexlens/cli/__pycache__/__init__.cpython-313.pyc +0 -0
  330. package/codex-lens/src/codexlens/cli/__pycache__/commands.cpython-313.pyc +0 -0
  331. package/codex-lens/src/codexlens/cli/__pycache__/embedding_manager.cpython-313.pyc +0 -0
  332. package/codex-lens/src/codexlens/cli/__pycache__/model_manager.cpython-313.pyc +0 -0
  333. package/codex-lens/src/codexlens/cli/__pycache__/output.cpython-313.pyc +0 -0
  334. package/codex-lens/src/codexlens/cli/commands.py +1931 -0
  335. package/codex-lens/src/codexlens/cli/embedding_manager.py +620 -0
  336. package/codex-lens/src/codexlens/cli/model_manager.py +289 -0
  337. package/codex-lens/src/codexlens/cli/output.py +124 -0
  338. package/codex-lens/src/codexlens/config.py +201 -0
  339. package/codex-lens/src/codexlens/entities.py +121 -0
  340. package/codex-lens/src/codexlens/errors.py +55 -0
  341. package/codex-lens/src/codexlens/indexing/README.md +77 -0
  342. package/codex-lens/src/codexlens/indexing/__init__.py +4 -0
  343. package/codex-lens/src/codexlens/indexing/__pycache__/__init__.cpython-313.pyc +0 -0
  344. package/codex-lens/src/codexlens/indexing/__pycache__/symbol_extractor.cpython-313.pyc +0 -0
  345. package/codex-lens/src/codexlens/indexing/symbol_extractor.py +243 -0
  346. package/codex-lens/src/codexlens/parsers/__init__.py +8 -0
  347. package/codex-lens/src/codexlens/parsers/__pycache__/__init__.cpython-313.pyc +0 -0
  348. package/codex-lens/src/codexlens/parsers/__pycache__/encoding.cpython-313.pyc +0 -0
  349. package/codex-lens/src/codexlens/parsers/__pycache__/factory.cpython-313.pyc +0 -0
  350. package/codex-lens/src/codexlens/parsers/__pycache__/tokenizer.cpython-313.pyc +0 -0
  351. package/codex-lens/src/codexlens/parsers/__pycache__/treesitter_parser.cpython-313.pyc +0 -0
  352. package/codex-lens/src/codexlens/parsers/encoding.py +202 -0
  353. package/codex-lens/src/codexlens/parsers/factory.py +256 -0
  354. package/codex-lens/src/codexlens/parsers/tokenizer.py +98 -0
  355. package/codex-lens/src/codexlens/parsers/treesitter_parser.py +335 -0
  356. package/codex-lens/src/codexlens/search/__init__.py +15 -0
  357. package/codex-lens/src/codexlens/search/__pycache__/__init__.cpython-313.pyc +0 -0
  358. package/codex-lens/src/codexlens/search/__pycache__/chain_search.cpython-313.pyc +0 -0
  359. package/codex-lens/src/codexlens/search/__pycache__/enrichment.cpython-313.pyc +0 -0
  360. package/codex-lens/src/codexlens/search/__pycache__/hybrid_search.cpython-313.pyc +0 -0
  361. package/codex-lens/src/codexlens/search/__pycache__/query_parser.cpython-313.pyc +0 -0
  362. package/codex-lens/src/codexlens/search/__pycache__/ranking.cpython-313.pyc +0 -0
  363. package/codex-lens/src/codexlens/search/chain_search.py +647 -0
  364. package/codex-lens/src/codexlens/search/enrichment.py +150 -0
  365. package/codex-lens/src/codexlens/search/hybrid_search.py +313 -0
  366. package/codex-lens/src/codexlens/search/query_parser.py +242 -0
  367. package/codex-lens/src/codexlens/search/ranking.py +274 -0
  368. package/codex-lens/src/codexlens/semantic/__init__.py +39 -0
  369. package/codex-lens/src/codexlens/semantic/__pycache__/__init__.cpython-313.pyc +0 -0
  370. package/codex-lens/src/codexlens/semantic/__pycache__/ann_index.cpython-313.pyc +0 -0
  371. package/codex-lens/src/codexlens/semantic/__pycache__/chunker.cpython-313.pyc +0 -0
  372. package/codex-lens/src/codexlens/semantic/__pycache__/code_extractor.cpython-313.pyc +0 -0
  373. package/codex-lens/src/codexlens/semantic/__pycache__/embedder.cpython-313.pyc +0 -0
  374. package/codex-lens/src/codexlens/semantic/__pycache__/graph_analyzer.cpython-313.pyc +0 -0
  375. package/codex-lens/src/codexlens/semantic/__pycache__/llm_enhancer.cpython-313.pyc +0 -0
  376. package/codex-lens/src/codexlens/semantic/__pycache__/vector_store.cpython-313.pyc +0 -0
  377. package/codex-lens/src/codexlens/semantic/ann_index.py +414 -0
  378. package/codex-lens/src/codexlens/semantic/chunker.py +448 -0
  379. package/codex-lens/src/codexlens/semantic/code_extractor.py +274 -0
  380. package/codex-lens/src/codexlens/semantic/embedder.py +185 -0
  381. package/codex-lens/src/codexlens/semantic/vector_store.py +955 -0
  382. package/codex-lens/src/codexlens/storage/__init__.py +29 -0
  383. package/codex-lens/src/codexlens/storage/__pycache__/__init__.cpython-313.pyc +0 -0
  384. package/codex-lens/src/codexlens/storage/__pycache__/dir_index.cpython-313.pyc +0 -0
  385. package/codex-lens/src/codexlens/storage/__pycache__/file_cache.cpython-313.pyc +0 -0
  386. package/codex-lens/src/codexlens/storage/__pycache__/index_tree.cpython-313.pyc +0 -0
  387. package/codex-lens/src/codexlens/storage/__pycache__/migration_manager.cpython-313.pyc +0 -0
  388. package/codex-lens/src/codexlens/storage/__pycache__/path_mapper.cpython-313.pyc +0 -0
  389. package/codex-lens/src/codexlens/storage/__pycache__/registry.cpython-313.pyc +0 -0
  390. package/codex-lens/src/codexlens/storage/__pycache__/sqlite_store.cpython-313.pyc +0 -0
  391. package/codex-lens/src/codexlens/storage/__pycache__/sqlite_utils.cpython-313.pyc +0 -0
  392. package/codex-lens/src/codexlens/storage/dir_index.py +1850 -0
  393. package/codex-lens/src/codexlens/storage/file_cache.py +32 -0
  394. package/codex-lens/src/codexlens/storage/index_tree.py +776 -0
  395. package/codex-lens/src/codexlens/storage/migration_manager.py +154 -0
  396. package/codex-lens/src/codexlens/storage/migrations/__init__.py +1 -0
  397. package/codex-lens/src/codexlens/storage/migrations/__pycache__/__init__.cpython-313.pyc +0 -0
  398. package/codex-lens/src/codexlens/storage/migrations/__pycache__/migration_001_normalize_keywords.cpython-313.pyc +0 -0
  399. package/codex-lens/src/codexlens/storage/migrations/__pycache__/migration_002_add_token_metadata.cpython-313.pyc +0 -0
  400. package/codex-lens/src/codexlens/storage/migrations/__pycache__/migration_003_code_relationships.cpython-313.pyc +0 -0
  401. package/codex-lens/src/codexlens/storage/migrations/__pycache__/migration_004_dual_fts.cpython-313.pyc +0 -0
  402. package/codex-lens/src/codexlens/storage/migrations/__pycache__/migration_005_cleanup_unused_fields.cpython-313.pyc +0 -0
  403. package/codex-lens/src/codexlens/storage/migrations/migration_001_normalize_keywords.py +123 -0
  404. package/codex-lens/src/codexlens/storage/migrations/migration_002_add_token_metadata.py +48 -0
  405. package/codex-lens/src/codexlens/storage/migrations/migration_004_dual_fts.py +232 -0
  406. package/codex-lens/src/codexlens/storage/migrations/migration_005_cleanup_unused_fields.py +196 -0
  407. package/codex-lens/src/codexlens/storage/path_mapper.py +274 -0
  408. package/codex-lens/src/codexlens/storage/registry.py +670 -0
  409. package/codex-lens/src/codexlens/storage/sqlite_store.py +576 -0
  410. package/codex-lens/src/codexlens/storage/sqlite_utils.py +64 -0
  411. package/package.json +4 -1
  412. package/.claude/commands/memory/tech-research.md +0 -477
  413. package/.claude/scripts/classify-folders.sh +0 -39
  414. package/.claude/scripts/convert_tokens_to_css.sh +0 -229
  415. package/.claude/scripts/detect_changed_modules.sh +0 -161
  416. package/.claude/scripts/discover-design-files.sh +0 -87
  417. package/.claude/scripts/extract-animations.js +0 -243
  418. package/.claude/scripts/extract-computed-styles.js +0 -118
  419. package/.claude/scripts/extract-layout-structure.js +0 -411
  420. package/.claude/scripts/generate_module_docs.sh +0 -717
  421. package/.claude/scripts/get_modules_by_depth.sh +0 -170
  422. package/.claude/scripts/ui-generate-preview.sh +0 -395
  423. package/.claude/scripts/ui-instantiate-prototypes.sh +0 -815
  424. package/.claude/scripts/update_module_claude.sh +0 -337
  425. package/.claude/workflows/context-search-strategy.md +0 -77
  426. package/.claude/workflows/intelligent-tools-strategy.md +0 -662
  427. package/ccw/src/cli.js +0 -119
  428. package/ccw/src/commands/install.js +0 -324
  429. package/ccw/src/commands/tool.js +0 -138
  430. package/ccw/src/core/data-aggregator.js +0 -409
  431. package/ccw/src/core/server.js +0 -2063
  432. package/ccw/src/core/session-scanner.js +0 -235
  433. package/ccw/src/tools/classify-folders.js +0 -204
  434. package/ccw/src/tools/detect-changed-modules.js +0 -288
  435. package/ccw/src/tools/edit-file.js +0 -266
  436. package/ccw/src/tools/index.js +0 -176
  437. package/ccw/src/utils/file-utils.js +0 -48
@@ -0,0 +1,1206 @@
1
+ import http from 'http';
2
+ import { URL } from 'url';
3
+ import { readFileSync, writeFileSync, existsSync, mkdirSync, statSync, unlinkSync } from 'fs';
4
+ import { join, isAbsolute, extname } from 'path';
5
+ import { homedir } from 'os';
6
+ import { getMemoryStore } from '../memory-store.js';
7
+ import { executeCliTool } from '../../tools/cli-executor.js';
8
+
9
+ /**
10
+ * Route context interface
11
+ */
12
+ interface RouteContext {
13
+ pathname: string;
14
+ url: URL;
15
+ req: http.IncomingMessage;
16
+ res: http.ServerResponse;
17
+ initialPath: string;
18
+ handlePostRequest: (req: http.IncomingMessage, res: http.ServerResponse, handler: (body: any) => Promise<any>) => void;
19
+ broadcastToClients: (data: any) => void;
20
+ }
21
+
22
+ /**
23
+ * Derive prompt intent from text
24
+ */
25
+ function derivePromptIntent(text: string): string {
26
+ const lower = text.toLowerCase();
27
+
28
+ // Implementation/coding patterns
29
+ if (/实现|implement|create|add|build|write|develop|make/.test(lower)) return 'implement';
30
+ if (/修复|fix|bug|error|issue|problem|解决/.test(lower)) return 'fix';
31
+ if (/重构|refactor|optimize|improve|clean/.test(lower)) return 'refactor';
32
+ if (/测试|test|spec|coverage/.test(lower)) return 'test';
33
+
34
+ // Analysis patterns
35
+ if (/分析|analyze|review|check|examine|audit/.test(lower)) return 'analyze';
36
+ if (/解释|explain|what|how|why|understand/.test(lower)) return 'explain';
37
+ if (/搜索|search|find|look|where|locate/.test(lower)) return 'search';
38
+
39
+ // Documentation patterns
40
+ if (/文档|document|readme|comment|注释/.test(lower)) return 'document';
41
+
42
+ // Planning patterns
43
+ if (/计划|plan|design|architect|strategy/.test(lower)) return 'plan';
44
+
45
+ // Configuration patterns
46
+ if (/配置|config|setup|install|设置/.test(lower)) return 'configure';
47
+
48
+ // Default
49
+ return 'general';
50
+ }
51
+
52
+ /**
53
+ * Calculate prompt quality score (0-100)
54
+ */
55
+ function calculateQualityScore(text: string): number {
56
+ let score = 50; // Base score
57
+
58
+ // Length factors
59
+ const length = text.length;
60
+ if (length > 50 && length < 500) score += 15;
61
+ else if (length >= 500 && length < 1000) score += 10;
62
+ else if (length < 20) score -= 20;
63
+
64
+ // Specificity indicators
65
+ if (/file|path|function|class|method|variable/i.test(text)) score += 10;
66
+ if (/src\/|\.ts|\.js|\.py|\.go/i.test(text)) score += 10;
67
+
68
+ // Context indicators
69
+ if (/when|after|before|because|since/i.test(text)) score += 5;
70
+
71
+ // Action clarity
72
+ if (/please|要|请|帮|help/i.test(text)) score += 5;
73
+
74
+ // Structure indicators
75
+ if (/\d+\.|•|-\s/.test(text)) score += 10; // Lists
76
+
77
+ // Cap at 100
78
+ return Math.min(100, Math.max(0, score));
79
+ }
80
+
81
+ /**
82
+ * Handle Memory API routes
83
+ * @returns true if route was handled, false otherwise
84
+ */
85
+ export async function handleMemoryRoutes(ctx: RouteContext): Promise<boolean> {
86
+ const { pathname, url, req, res, initialPath, handlePostRequest, broadcastToClients } = ctx;
87
+
88
+ // API: Memory Module - Track entity access
89
+ if (pathname === '/api/memory/track' && req.method === 'POST') {
90
+ handlePostRequest(req, res, async (body) => {
91
+ const { type, action, value, sessionId, metadata, path: projectPath } = body;
92
+
93
+ if (!type || !action || !value) {
94
+ return { error: 'type, action, and value are required', status: 400 };
95
+ }
96
+
97
+ const basePath = projectPath || initialPath;
98
+
99
+ try {
100
+ const memoryStore = getMemoryStore(basePath);
101
+ const now = new Date().toISOString();
102
+
103
+ // Normalize the value
104
+ const normalizedValue = value.toLowerCase().trim();
105
+
106
+ // Upsert entity
107
+ const entityId = memoryStore.upsertEntity({
108
+ type,
109
+ value,
110
+ normalized_value: normalizedValue,
111
+ first_seen_at: now,
112
+ last_seen_at: now,
113
+ metadata: metadata ? JSON.stringify(metadata) : undefined
114
+ });
115
+
116
+ // Log access
117
+ memoryStore.logAccess({
118
+ entity_id: entityId,
119
+ action,
120
+ session_id: sessionId,
121
+ timestamp: now,
122
+ context_summary: metadata?.context
123
+ });
124
+
125
+ // Update stats
126
+ memoryStore.updateStats(entityId, action);
127
+
128
+ // Calculate new heat score
129
+ const heatScore = memoryStore.calculateHeatScore(entityId);
130
+ const stats = memoryStore.getStats(entityId);
131
+
132
+ // Broadcast MEMORY_UPDATED event via WebSocket
133
+ broadcastToClients({
134
+ type: 'MEMORY_UPDATED',
135
+ payload: {
136
+ entity: { id: entityId, type, value },
137
+ stats: {
138
+ read_count: stats?.read_count || 0,
139
+ write_count: stats?.write_count || 0,
140
+ mention_count: stats?.mention_count || 0,
141
+ heat_score: heatScore
142
+ },
143
+ timestamp: now
144
+ }
145
+ });
146
+
147
+ return {
148
+ success: true,
149
+ entity_id: entityId,
150
+ heat_score: heatScore
151
+ };
152
+ } catch (error: unknown) {
153
+ return { error: (error as Error).message, status: 500 };
154
+ }
155
+ });
156
+ return true;
157
+ }
158
+
159
+ // API: Memory Module - Get native Claude history from ~/.claude/history.jsonl
160
+ if (pathname === '/api/memory/native-history') {
161
+ const projectPath = url.searchParams.get('path') || initialPath;
162
+ const limit = parseInt(url.searchParams.get('limit') || '100', 10);
163
+ const historyFile = join(homedir(), '.claude', 'history.jsonl');
164
+
165
+ try {
166
+ if (!existsSync(historyFile)) {
167
+ res.writeHead(200, { 'Content-Type': 'application/json' });
168
+ res.end(JSON.stringify({ prompts: [], total: 0, message: 'No history file found' }));
169
+ return true;
170
+ }
171
+
172
+ const content = readFileSync(historyFile, 'utf8');
173
+ const lines = content.trim().split('\n').filter(line => line.trim());
174
+ const allPrompts = [];
175
+
176
+ for (const line of lines) {
177
+ try {
178
+ const entry = JSON.parse(line);
179
+ // Filter by project if specified
180
+ if (projectPath && entry.project) {
181
+ const normalizedProject = entry.project.replace(/\\/g, '/').toLowerCase();
182
+ const normalizedPath = projectPath.replace(/\\/g, '/').toLowerCase();
183
+ if (!normalizedProject.includes(normalizedPath) && !normalizedPath.includes(normalizedProject)) {
184
+ continue;
185
+ }
186
+ }
187
+
188
+ allPrompts.push({
189
+ id: `${entry.sessionId}-${entry.timestamp}`,
190
+ text: entry.display || '',
191
+ timestamp: new Date(entry.timestamp).toISOString(),
192
+ project: entry.project || '',
193
+ session_id: entry.sessionId || '',
194
+ pasted_contents: entry.pastedContents || {},
195
+ // Derive intent from content keywords
196
+ intent: derivePromptIntent(entry.display || ''),
197
+ quality_score: calculateQualityScore(entry.display || '')
198
+ });
199
+ } catch (parseError) {
200
+ // Skip malformed lines
201
+ }
202
+ }
203
+
204
+ // Sort by timestamp descending
205
+ allPrompts.sort((a, b) => new Date(b.timestamp).getTime() - new Date(a.timestamp).getTime());
206
+
207
+ // Apply limit
208
+ const prompts = allPrompts.slice(0, limit);
209
+
210
+ res.writeHead(200, { 'Content-Type': 'application/json' });
211
+ res.end(JSON.stringify({ prompts, total: allPrompts.length }));
212
+ } catch (error: unknown) {
213
+ res.writeHead(500, { 'Content-Type': 'application/json' });
214
+ res.end(JSON.stringify({ error: (error as Error).message }));
215
+ }
216
+ return true;
217
+ }
218
+
219
+ // API: Memory Module - Get prompt history
220
+ if (pathname === '/api/memory/prompts') {
221
+ const projectPath = url.searchParams.get('path') || initialPath;
222
+ const limit = parseInt(url.searchParams.get('limit') || '50', 10);
223
+ const search = url.searchParams.get('search') || null;
224
+ const recursive = url.searchParams.get('recursive') !== 'false';
225
+
226
+ try {
227
+ let prompts;
228
+
229
+ // Recursive mode: aggregate prompts from parent and child projects
230
+ if (recursive && !search) {
231
+ const { getAggregatedPrompts } = await import('../memory-store.js');
232
+ prompts = await getAggregatedPrompts(projectPath, limit);
233
+ } else {
234
+ // Non-recursive mode or search mode: query only current project
235
+ const memoryStore = getMemoryStore(projectPath);
236
+
237
+ if (search) {
238
+ prompts = memoryStore.searchPrompts(search, limit);
239
+ } else {
240
+ // Get all recent prompts (we'll need to add this method to MemoryStore)
241
+ const stmt = memoryStore['db'].prepare(`
242
+ SELECT * FROM prompt_history
243
+ ORDER BY timestamp DESC
244
+ LIMIT ?
245
+ `);
246
+ prompts = stmt.all(limit);
247
+ }
248
+ }
249
+
250
+ res.writeHead(200, { 'Content-Type': 'application/json' });
251
+ res.end(JSON.stringify({ prompts }));
252
+ } catch (error: unknown) {
253
+ res.writeHead(500, { 'Content-Type': 'application/json' });
254
+ res.end(JSON.stringify({ error: (error as Error).message }));
255
+ }
256
+ return true;
257
+ }
258
+
259
+ // API: Memory Module - Get insights (from prompt_patterns)
260
+ if (pathname === '/api/memory/insights' && req.method === 'GET') {
261
+ const projectPath = url.searchParams.get('path') || initialPath;
262
+ const limitParam = url.searchParams.get('limit');
263
+ const tool = url.searchParams.get('tool') || undefined;
264
+
265
+ // Check if this is a request for insights history (has limit or tool param)
266
+ if (limitParam || tool) {
267
+ const limit = parseInt(limitParam || '20', 10);
268
+ try {
269
+ const storeModule = await import('../../tools/cli-history-store.js');
270
+ const store = storeModule.getHistoryStore(projectPath);
271
+ const insights = store.getInsights({ limit, tool });
272
+
273
+ res.writeHead(200, { 'Content-Type': 'application/json' });
274
+ res.end(JSON.stringify({ success: true, insights }));
275
+ } catch (error: unknown) {
276
+ res.writeHead(500, { 'Content-Type': 'application/json' });
277
+ res.end(JSON.stringify({ error: (error as Error).message }));
278
+ }
279
+ return true;
280
+ }
281
+
282
+ // Default: Get prompt pattern insights
283
+ try {
284
+ const memoryStore = getMemoryStore(projectPath);
285
+
286
+ // Get total prompt count
287
+ const countStmt = memoryStore['db'].prepare(`SELECT COUNT(*) as count FROM prompt_history`);
288
+ const { count: totalPrompts } = countStmt.get() as { count: number };
289
+
290
+ // Get top intent
291
+ const topIntentStmt = memoryStore['db'].prepare(`
292
+ SELECT intent_label, COUNT(*) as count
293
+ FROM prompt_history
294
+ WHERE intent_label IS NOT NULL
295
+ GROUP BY intent_label
296
+ ORDER BY count DESC
297
+ LIMIT 1
298
+ `);
299
+ const topIntentRow = topIntentStmt.get() as { intent_label: string; count: number } | undefined;
300
+
301
+ // Get average prompt length
302
+ const avgLengthStmt = memoryStore['db'].prepare(`
303
+ SELECT AVG(LENGTH(prompt_text)) as avg_length
304
+ FROM prompt_history
305
+ WHERE prompt_text IS NOT NULL
306
+ `);
307
+ const { avg_length: avgLength } = avgLengthStmt.get() as { avg_length: number };
308
+
309
+ // Get prompt patterns
310
+ const patternsStmt = memoryStore['db'].prepare(`
311
+ SELECT * FROM prompt_patterns
312
+ ORDER BY frequency DESC
313
+ LIMIT 10
314
+ `);
315
+ const patterns = patternsStmt.all();
316
+
317
+ res.writeHead(200, { 'Content-Type': 'application/json' });
318
+ res.end(JSON.stringify({
319
+ stats: {
320
+ totalPrompts,
321
+ topIntent: topIntentRow?.intent_label || 'unknown',
322
+ avgLength: Math.round(avgLength || 0)
323
+ },
324
+ patterns: patterns.map((p: any) => ({
325
+ type: p.pattern_type,
326
+ description: `Pattern detected in prompts`,
327
+ occurrences: p.frequency,
328
+ suggestion: `Consider using more specific prompts for ${p.pattern_type}`
329
+ }))
330
+ }));
331
+ } catch (error: unknown) {
332
+ res.writeHead(500, { 'Content-Type': 'application/json' });
333
+ res.end(JSON.stringify({ error: (error as Error).message }));
334
+ }
335
+ return true;
336
+ }
337
+
338
+ // API: Memory Module - Trigger async CLI-based insights analysis
339
+ if (pathname === '/api/memory/insights/analyze' && req.method === 'POST') {
340
+ handlePostRequest(req, res, async (body: any) => {
341
+ const projectPath = body.path || initialPath;
342
+ const tool = body.tool || 'gemini'; // gemini, qwen, codex, claude
343
+ const prompts = body.prompts || [];
344
+ const lang = body.lang || 'en'; // Language preference
345
+
346
+ if (prompts.length === 0) {
347
+ return { error: 'No prompts provided for analysis', status: 400 };
348
+ }
349
+
350
+ // Prepare prompt summary for CLI analysis
351
+ const promptSummary = prompts.slice(0, 20).map((p: any, i: number) => {
352
+ return `${i + 1}. [${p.intent || 'unknown'}] ${(p.text || '').substring(0, 100)}...`;
353
+ }).join('\n');
354
+
355
+ const langInstruction = lang === 'zh'
356
+ ? '请用中文回复。所有 description、suggestion、title 字段必须使用中文。'
357
+ : 'Respond in English. All description, suggestion, title fields must be in English.';
358
+
359
+ const analysisPrompt = `
360
+ PURPOSE: Analyze prompt patterns and provide optimization suggestions
361
+ TASK:
362
+ • Review the following prompt history summary
363
+ • Identify common patterns (vague requests, repetitive queries, incomplete context)
364
+ • Suggest specific improvements for prompt quality
365
+ • Detect areas where prompts could be more effective
366
+ MODE: analysis
367
+ CONTEXT: ${prompts.length} prompts from project: ${projectPath}
368
+ EXPECTED: JSON with patterns array and suggestions array
369
+ LANGUAGE: ${langInstruction}
370
+
371
+ PROMPT HISTORY:
372
+ ${promptSummary}
373
+
374
+ Return ONLY valid JSON in this exact format (no markdown, no code blocks, just pure JSON):
375
+ {
376
+ "patterns": [
377
+ {"type": "pattern_type", "description": "description", "occurrences": count, "severity": "low|medium|high", "suggestion": "how to improve"}
378
+ ],
379
+ "suggestions": [
380
+ {"title": "title", "description": "description", "example": "example prompt"}
381
+ ]
382
+ }`;
383
+
384
+ try {
385
+ // Queue CLI execution
386
+ const result = await executeCliTool({
387
+ tool,
388
+ prompt: analysisPrompt,
389
+ mode: 'analysis',
390
+ timeout: 120000,
391
+ cd: projectPath,
392
+ category: 'insight'
393
+ });
394
+
395
+ // Try to parse JSON from response
396
+ let insights: { patterns: any[]; suggestions: any[] } = { patterns: [], suggestions: [] };
397
+ if (result.stdout) {
398
+ let outputText = result.stdout;
399
+
400
+ // Strip markdown code blocks if present
401
+ const codeBlockMatch = outputText.match(/```(?:json)?\s*([\s\S]*?)```/);
402
+ if (codeBlockMatch) {
403
+ outputText = codeBlockMatch[1].trim();
404
+ }
405
+
406
+ // Find JSON object in the response
407
+ const jsonMatch = outputText.match(/\{[\s\S]*\}/);
408
+ if (jsonMatch) {
409
+ try {
410
+ insights = JSON.parse(jsonMatch[0]);
411
+ // Ensure arrays exist
412
+ if (!Array.isArray(insights.patterns)) insights.patterns = [];
413
+ if (!Array.isArray(insights.suggestions)) insights.suggestions = [];
414
+ } catch (e) {
415
+ console.error('[insights/analyze] JSON parse error:', e);
416
+ // Return raw output if JSON parse fails
417
+ insights = {
418
+ patterns: [{ type: 'raw_analysis', description: result.stdout.substring(0, 500), occurrences: 1, severity: 'low', suggestion: '' }],
419
+ suggestions: []
420
+ };
421
+ }
422
+ } else {
423
+ // No JSON found, wrap raw output
424
+ insights = {
425
+ patterns: [{ type: 'raw_analysis', description: result.stdout.substring(0, 500), occurrences: 1, severity: 'low', suggestion: '' }],
426
+ suggestions: []
427
+ };
428
+ }
429
+ }
430
+
431
+ // Save insight to database
432
+ try {
433
+ const storeModule = await import('../../tools/cli-history-store.js');
434
+ const store = storeModule.getHistoryStore(projectPath);
435
+ const insightId = `insight-${Date.now()}`;
436
+ store.saveInsight({
437
+ id: insightId,
438
+ tool,
439
+ promptCount: prompts.length,
440
+ patterns: insights.patterns,
441
+ suggestions: insights.suggestions,
442
+ rawOutput: result.stdout || '',
443
+ executionId: result.execution?.id,
444
+ lang
445
+ });
446
+ console.log('[Insights] Saved insight:', insightId);
447
+ } catch (saveErr) {
448
+ console.warn('[Insights] Failed to save insight:', (saveErr as Error).message);
449
+ }
450
+
451
+ return {
452
+ success: true,
453
+ insights,
454
+ tool,
455
+ executionId: result.execution.id
456
+ };
457
+ } catch (error: unknown) {
458
+ return { error: (error as Error).message, status: 500 };
459
+ }
460
+ });
461
+ return true;
462
+ }
463
+
464
+ // API: Get single insight detail
465
+ if (pathname.startsWith('/api/memory/insights/') && req.method === 'GET') {
466
+ const insightId = pathname.replace('/api/memory/insights/', '');
467
+ const projectPath = url.searchParams.get('path') || initialPath;
468
+
469
+ if (!insightId || insightId === 'analyze') {
470
+ // Skip - handled by other routes
471
+ return false;
472
+ }
473
+
474
+ try {
475
+ const storeModule = await import('../../tools/cli-history-store.js');
476
+ const store = storeModule.getHistoryStore(projectPath);
477
+ const insight = store.getInsight(insightId);
478
+
479
+ if (insight) {
480
+ res.writeHead(200, { 'Content-Type': 'application/json' });
481
+ res.end(JSON.stringify({ success: true, insight }));
482
+ } else {
483
+ res.writeHead(404, { 'Content-Type': 'application/json' });
484
+ res.end(JSON.stringify({ error: 'Insight not found' }));
485
+ }
486
+ } catch (error: unknown) {
487
+ res.writeHead(500, { 'Content-Type': 'application/json' });
488
+ res.end(JSON.stringify({ error: (error as Error).message }));
489
+ }
490
+ return true;
491
+ }
492
+
493
+ // API: Delete insight
494
+ if (pathname.startsWith('/api/memory/insights/') && req.method === 'DELETE') {
495
+ const insightId = pathname.replace('/api/memory/insights/', '');
496
+ const projectPath = url.searchParams.get('path') || initialPath;
497
+
498
+ try {
499
+ const storeModule = await import('../../tools/cli-history-store.js');
500
+ const store = storeModule.getHistoryStore(projectPath);
501
+ const deleted = store.deleteInsight(insightId);
502
+
503
+ res.writeHead(200, { 'Content-Type': 'application/json' });
504
+ res.end(JSON.stringify({ success: deleted }));
505
+ } catch (error: unknown) {
506
+ res.writeHead(500, { 'Content-Type': 'application/json' });
507
+ res.end(JSON.stringify({ error: (error as Error).message }));
508
+ }
509
+ return true;
510
+ }
511
+
512
+ // API: Memory Module - Get hotspot statistics
513
+ if (pathname === '/api/memory/stats') {
514
+ const projectPath = url.searchParams.get('path') || initialPath;
515
+ const filter = url.searchParams.get('filter') || 'all'; // today, week, all
516
+ const limit = parseInt(url.searchParams.get('limit') || '10', 10);
517
+ const recursive = url.searchParams.get('recursive') !== 'false';
518
+
519
+ try {
520
+ // If requesting aggregated stats, use the aggregated function
521
+ if (url.searchParams.has('aggregated') || recursive) {
522
+ const { getAggregatedStats } = await import('../memory-store.js');
523
+ const aggregatedStats = await getAggregatedStats(projectPath);
524
+
525
+ res.writeHead(200, { 'Content-Type': 'application/json' });
526
+ res.end(JSON.stringify({
527
+ stats: aggregatedStats,
528
+ aggregated: true
529
+ }));
530
+ return true;
531
+ }
532
+
533
+ // Original hotspot statistics (non-recursive)
534
+ const memoryStore = getMemoryStore(projectPath);
535
+ const hotEntities = memoryStore.getHotEntities(limit * 4);
536
+
537
+ // Filter by time if needed
538
+ let filtered = hotEntities;
539
+ if (filter === 'today') {
540
+ const today = new Date();
541
+ today.setHours(0, 0, 0, 0);
542
+ filtered = hotEntities.filter((e: any) => new Date(e.last_seen_at) >= today);
543
+ } else if (filter === 'week') {
544
+ const weekAgo = new Date();
545
+ weekAgo.setDate(weekAgo.getDate() - 7);
546
+ filtered = hotEntities.filter((e: any) => new Date(e.last_seen_at) >= weekAgo);
547
+ }
548
+
549
+ // Separate into mostRead, mostEdited, and mostMentioned
550
+ const fileEntities = filtered.filter((e: any) => e.type === 'file');
551
+ const topicEntities = filtered.filter((e: any) => e.type === 'topic');
552
+
553
+ const mostRead = fileEntities
554
+ .filter((e: any) => e.stats.read_count > 0)
555
+ .sort((a: any, b: any) => b.stats.read_count - a.stats.read_count)
556
+ .slice(0, limit)
557
+ .map((e: any) => ({
558
+ path: e.value,
559
+ file: e.value.split(/[/\\]/).pop(),
560
+ heat: e.stats.read_count,
561
+ count: e.stats.read_count,
562
+ lastSeen: e.last_seen_at
563
+ }));
564
+
565
+ const mostEdited = fileEntities
566
+ .filter((e: any) => e.stats.write_count > 0)
567
+ .sort((a: any, b: any) => b.stats.write_count - a.stats.write_count)
568
+ .slice(0, limit)
569
+ .map((e: any) => ({
570
+ path: e.value,
571
+ file: e.value.split(/[/\\]/).pop(),
572
+ heat: e.stats.write_count,
573
+ count: e.stats.write_count,
574
+ lastSeen: e.last_seen_at
575
+ }));
576
+
577
+ const mostMentioned = topicEntities
578
+ .filter((e: any) => e.stats.mention_count > 0)
579
+ .sort((a: any, b: any) => b.stats.mention_count - a.stats.mention_count)
580
+ .slice(0, limit)
581
+ .map((e: any) => ({
582
+ topic: e.value,
583
+ preview: e.value.substring(0, 100) + (e.value.length > 100 ? '...' : ''),
584
+ heat: e.stats.mention_count,
585
+ count: e.stats.mention_count,
586
+ lastSeen: e.last_seen_at
587
+ }));
588
+
589
+ res.writeHead(200, { 'Content-Type': 'application/json' });
590
+ res.end(JSON.stringify({ stats: { mostRead, mostEdited, mostMentioned } }));
591
+ } catch (error: unknown) {
592
+ res.writeHead(200, { 'Content-Type': 'application/json' });
593
+ res.end(JSON.stringify({ stats: { mostRead: [], mostEdited: [], mostMentioned: [] } }));
594
+ }
595
+ return true;
596
+ }
597
+
598
+ // API: Memory Module - Get memory graph (file associations with modules and components)
599
+ if (pathname === '/api/memory/graph') {
600
+ const projectPath = url.searchParams.get('path') || initialPath;
601
+
602
+ try {
603
+ const memoryStore = getMemoryStore(projectPath);
604
+ const hotEntities = memoryStore.getHotEntities(100);
605
+
606
+ // Build file nodes from entities
607
+ const fileEntities = hotEntities.filter((e: any) => e.type === 'file');
608
+ const fileNodes = fileEntities.map((e: any) => {
609
+ const fileName = e.value.split(/[/\\]/).pop() || '';
610
+ // Detect component type based on file name patterns
611
+ const isComponent = /\.(tsx|jsx|vue|svelte)$/.test(fileName) ||
612
+ /^[A-Z][a-zA-Z]+\.(ts|js)$/.test(fileName) ||
613
+ fileName.includes('.component.') ||
614
+ fileName.includes('.controller.');
615
+
616
+ return {
617
+ id: e.value,
618
+ name: fileName,
619
+ path: e.value,
620
+ type: isComponent ? 'component' : 'file',
621
+ heat: Math.min(25, 8 + e.stats.heat_score / 10)
622
+ };
623
+ });
624
+
625
+ // Extract unique modules (directories) from file paths
626
+ const moduleMap = new Map<string, { heat: number; files: string[] }>();
627
+ for (const file of fileEntities) {
628
+ const parts = file.value.split(/[/\\]/);
629
+ // Get parent directory as module (skip if root level)
630
+ if (parts.length > 1) {
631
+ const modulePath = parts.slice(0, -1).join('/');
632
+ const moduleName = parts[parts.length - 2] || modulePath;
633
+ // Skip common non-module directories
634
+ if (['node_modules', '.git', 'dist', 'build', '.next', '.nuxt'].includes(moduleName)) continue;
635
+
636
+ if (!moduleMap.has(modulePath)) {
637
+ moduleMap.set(modulePath, { heat: 0, files: [] });
638
+ }
639
+ const mod = moduleMap.get(modulePath)!;
640
+ mod.heat += file.stats.heat_score / 20;
641
+ mod.files.push(file.value);
642
+ }
643
+ }
644
+
645
+ // Create module nodes (limit to top modules by heat)
646
+ const moduleNodes = Array.from(moduleMap.entries())
647
+ .sort((a, b) => b[1].heat - a[1].heat)
648
+ .slice(0, 15)
649
+ .map(([modulePath, data]) => ({
650
+ id: modulePath,
651
+ name: modulePath.split(/[/\\]/).pop() || modulePath,
652
+ path: modulePath,
653
+ type: 'module',
654
+ heat: Math.min(20, 12 + data.heat / 5),
655
+ fileCount: data.files.length
656
+ }));
657
+
658
+ // Combine all nodes
659
+ const nodes = [...fileNodes, ...moduleNodes];
660
+ const nodeIds = new Set(nodes.map(n => n.id));
661
+
662
+ // Build edges from associations
663
+ const edges: any[] = [];
664
+ const edgeSet = new Set<string>(); // Prevent duplicate edges
665
+
666
+ // Add file-to-file associations
667
+ for (const entity of hotEntities) {
668
+ if (!entity.id || entity.type !== 'file') continue;
669
+ const associations = memoryStore.getAssociations(entity.id, 10);
670
+ for (const assoc of associations) {
671
+ if (assoc.target && nodeIds.has(assoc.target.value)) {
672
+ const edgeKey = [entity.value, assoc.target.value].sort().join('|');
673
+ if (!edgeSet.has(edgeKey)) {
674
+ edgeSet.add(edgeKey);
675
+ edges.push({
676
+ source: entity.value,
677
+ target: assoc.target.value,
678
+ weight: assoc.weight
679
+ });
680
+ }
681
+ }
682
+ }
683
+ }
684
+
685
+ // Add file-to-module edges (files belong to their parent modules)
686
+ for (const [modulePath, data] of moduleMap.entries()) {
687
+ if (!nodeIds.has(modulePath)) continue;
688
+ for (const filePath of data.files) {
689
+ if (nodeIds.has(filePath)) {
690
+ const edgeKey = [modulePath, filePath].sort().join('|');
691
+ if (!edgeSet.has(edgeKey)) {
692
+ edgeSet.add(edgeKey);
693
+ edges.push({
694
+ source: modulePath,
695
+ target: filePath,
696
+ weight: 2 // Lower weight for structural relationships
697
+ });
698
+ }
699
+ }
700
+ }
701
+ }
702
+
703
+ res.writeHead(200, { 'Content-Type': 'application/json' });
704
+ res.end(JSON.stringify({ graph: { nodes, edges } }));
705
+ } catch (error: unknown) {
706
+ res.writeHead(200, { 'Content-Type': 'application/json' });
707
+ res.end(JSON.stringify({ graph: { nodes: [], edges: [] } }));
708
+ }
709
+ return true;
710
+ }
711
+
712
+ // API: Memory Module - Get recent context activities
713
+ if (pathname === '/api/memory/recent') {
714
+ const projectPath = url.searchParams.get('path') || initialPath;
715
+ const limit = parseInt(url.searchParams.get('limit') || '20', 10);
716
+
717
+ try {
718
+ const memoryStore = getMemoryStore(projectPath);
719
+
720
+ // Get recent access logs with entity info - filter to file type only
721
+ const db = (memoryStore as any).db;
722
+ const recentLogs = db.prepare(`
723
+ SELECT a.*, e.type, e.value
724
+ FROM access_logs a
725
+ JOIN entities e ON a.entity_id = e.id
726
+ WHERE e.type = 'file'
727
+ ORDER BY a.timestamp DESC
728
+ LIMIT ?
729
+ `).all(limit * 2) as any[]; // Fetch more to account for filtering
730
+
731
+ // Filter out invalid entries (JSON strings, error messages, etc.)
732
+ const validLogs = recentLogs.filter((log: any) => {
733
+ const value = log.value || '';
734
+ // Skip if value looks like JSON or contains error-like patterns
735
+ if (value.includes('"status"') || value.includes('"content"') ||
736
+ value.includes('"activeForm"') || value.startsWith('{') ||
737
+ value.startsWith('[') || value.includes('graph 400')) {
738
+ return false;
739
+ }
740
+ // Must have a file extension or look like a valid path
741
+ const hasExtension = /\.[a-zA-Z0-9]{1,10}$/.test(value);
742
+ const looksLikePath = value.includes('/') || value.includes('\\');
743
+ return hasExtension || looksLikePath;
744
+ }).slice(0, limit);
745
+
746
+ const recent = validLogs.map((log: any) => ({
747
+ type: log.action, // read, write, mention
748
+ timestamp: log.timestamp,
749
+ prompt: log.context_summary || '',
750
+ files: [log.value],
751
+ description: `${log.action}: ${log.value.split(/[/\\]/).pop()}`
752
+ }));
753
+
754
+ res.writeHead(200, { 'Content-Type': 'application/json' });
755
+ res.end(JSON.stringify({ recent }));
756
+ } catch (error: unknown) {
757
+ res.writeHead(200, { 'Content-Type': 'application/json' });
758
+ res.end(JSON.stringify({ recent: [] }));
759
+ }
760
+ return true;
761
+ }
762
+
763
+ // API: Active Memory - Get status
764
+ if (pathname === '/api/memory/active/status') {
765
+ const projectPath = url.searchParams.get('path') || initialPath;
766
+
767
+ if (!projectPath) {
768
+ res.writeHead(200, { 'Content-Type': 'application/json' });
769
+ res.end(JSON.stringify({ enabled: false, status: null, config: { interval: 'manual', tool: 'gemini' } }));
770
+ return true;
771
+ }
772
+
773
+ try {
774
+ const rulesDir = join(projectPath, '.claude', 'rules');
775
+ const configPath = join(rulesDir, 'active_memory.md');
776
+ const configJsonPath = join(projectPath, '.claude', 'active_memory_config.json');
777
+ const enabled = existsSync(configPath);
778
+ let lastSync: string | null = null;
779
+ let fileCount = 0;
780
+ let config = { interval: 'manual', tool: 'gemini' };
781
+
782
+ if (enabled) {
783
+ const stats = statSync(configPath);
784
+ lastSync = stats.mtime.toISOString();
785
+ const content = readFileSync(configPath, 'utf-8');
786
+ // Count file sections
787
+ fileCount = (content.match(/^## /gm) || []).length;
788
+ }
789
+
790
+ // Load config if exists
791
+ if (existsSync(configJsonPath)) {
792
+ try {
793
+ config = JSON.parse(readFileSync(configJsonPath, 'utf-8'));
794
+ } catch (e) { /* ignore parse errors */ }
795
+ }
796
+
797
+ res.writeHead(200, { 'Content-Type': 'application/json' });
798
+ res.end(JSON.stringify({
799
+ enabled,
800
+ status: enabled ? { lastSync, fileCount } : null,
801
+ config
802
+ }));
803
+ } catch (error: unknown) {
804
+ console.error('Active Memory status error:', error);
805
+ res.writeHead(200, { 'Content-Type': 'application/json' });
806
+ res.end(JSON.stringify({ enabled: false, status: null, config: { interval: 'manual', tool: 'gemini' } }));
807
+ }
808
+ return true;
809
+ }
810
+
811
+ // API: Active Memory - Toggle
812
+ if (pathname === '/api/memory/active/toggle' && req.method === 'POST') {
813
+ let body = '';
814
+ req.on('data', (chunk: Buffer) => { body += chunk.toString(); });
815
+ req.on('end', async () => {
816
+ try {
817
+ const { enabled, config } = JSON.parse(body || '{}');
818
+ const projectPath = initialPath;
819
+
820
+ if (!projectPath) {
821
+ res.writeHead(400, { 'Content-Type': 'application/json' });
822
+ res.end(JSON.stringify({ error: 'No project path configured' }));
823
+ return;
824
+ }
825
+
826
+ const claudeDir = join(projectPath, '.claude');
827
+ const rulesDir = join(claudeDir, 'rules');
828
+ const configPath = join(rulesDir, 'active_memory.md');
829
+ const configJsonPath = join(claudeDir, 'active_memory_config.json');
830
+
831
+ if (enabled) {
832
+ // Enable: Create directories and initial file
833
+ if (!existsSync(claudeDir)) {
834
+ mkdirSync(claudeDir, { recursive: true });
835
+ }
836
+ if (!existsSync(rulesDir)) {
837
+ mkdirSync(rulesDir, { recursive: true });
838
+ }
839
+
840
+ // Save config
841
+ if (config) {
842
+ writeFileSync(configJsonPath, JSON.stringify(config, null, 2), 'utf-8');
843
+ }
844
+
845
+ // Create initial active_memory.md with header
846
+ const initialContent = `# Active Memory - Project Context
847
+
848
+ > Auto-generated understanding of frequently accessed files.
849
+ > Last updated: ${new Date().toISOString()}
850
+
851
+ ---
852
+
853
+ *No files analyzed yet. Click "Sync Now" to analyze hot files.*
854
+ `;
855
+ writeFileSync(configPath, initialContent, 'utf-8');
856
+
857
+ res.writeHead(200, { 'Content-Type': 'application/json' });
858
+ res.end(JSON.stringify({ enabled: true, message: 'Active Memory enabled' }));
859
+ } else {
860
+ // Disable: Remove the files
861
+ if (existsSync(configPath)) {
862
+ unlinkSync(configPath);
863
+ }
864
+ if (existsSync(configJsonPath)) {
865
+ unlinkSync(configJsonPath);
866
+ }
867
+
868
+ res.writeHead(200, { 'Content-Type': 'application/json' });
869
+ res.end(JSON.stringify({ enabled: false, message: 'Active Memory disabled' }));
870
+ }
871
+ } catch (error: unknown) {
872
+ console.error('Active Memory toggle error:', error);
873
+ if (!res.headersSent) {
874
+ res.writeHead(500, { 'Content-Type': 'application/json' });
875
+ res.end(JSON.stringify({ error: (error as Error).message }));
876
+ }
877
+ }
878
+ });
879
+ return true;
880
+ }
881
+
882
+ // API: Active Memory - Update Config
883
+ if (pathname === '/api/memory/active/config' && req.method === 'POST') {
884
+ let body = '';
885
+ req.on('data', (chunk: Buffer) => { body += chunk.toString(); });
886
+ req.on('end', async () => {
887
+ try {
888
+ const { config } = JSON.parse(body || '{}');
889
+ const projectPath = initialPath;
890
+ const claudeDir = join(projectPath, '.claude');
891
+ const configJsonPath = join(claudeDir, 'active_memory_config.json');
892
+
893
+ if (!existsSync(claudeDir)) {
894
+ mkdirSync(claudeDir, { recursive: true });
895
+ }
896
+
897
+ writeFileSync(configJsonPath, JSON.stringify(config, null, 2), 'utf-8');
898
+
899
+ res.writeHead(200, { 'Content-Type': 'application/json' });
900
+ res.end(JSON.stringify({ success: true, config }));
901
+ } catch (error: unknown) {
902
+ res.writeHead(500, { 'Content-Type': 'application/json' });
903
+ res.end(JSON.stringify({ error: (error as Error).message }));
904
+ }
905
+ });
906
+ return true;
907
+ }
908
+
909
+ // API: Active Memory - Sync (analyze hot files using CLI and update active_memory.md)
910
+ if (pathname === '/api/memory/active/sync' && req.method === 'POST') {
911
+ let body = '';
912
+ req.on('data', (chunk: Buffer) => { body += chunk.toString(); });
913
+ req.on('end', async () => {
914
+ try {
915
+ const { tool = 'gemini' } = JSON.parse(body || '{}');
916
+ const projectPath = initialPath;
917
+
918
+ if (!projectPath) {
919
+ res.writeHead(400, { 'Content-Type': 'application/json' });
920
+ res.end(JSON.stringify({ error: 'No project path configured' }));
921
+ return;
922
+ }
923
+
924
+ const claudeDir = join(projectPath, '.claude');
925
+ const rulesDir = join(claudeDir, 'rules');
926
+ const configPath = join(rulesDir, 'active_memory.md');
927
+
928
+ // Get hot files from memory store - with fallback
929
+ let hotFiles: any[] = [];
930
+ try {
931
+ const memoryStore = getMemoryStore(projectPath);
932
+ const hotEntities = memoryStore.getHotEntities(20);
933
+ hotFiles = hotEntities
934
+ .filter((e: any) => e.type === 'file')
935
+ .slice(0, 10);
936
+ } catch (memErr) {
937
+ console.warn('[Active Memory] Memory store error, using empty list:', (memErr as Error).message);
938
+ }
939
+
940
+ // Build file list for CLI analysis
941
+ const filePaths = hotFiles.map((f: any) => {
942
+ const filePath = f.value;
943
+ return isAbsolute(filePath) ? filePath : join(projectPath, filePath);
944
+ }).filter((p: string) => existsSync(p));
945
+
946
+ // Build the active_memory.md content header
947
+ let content = `# Active Memory - Project Context
948
+
949
+ > Auto-generated understanding of frequently accessed files using ${tool.toUpperCase()}.
950
+ > Last updated: ${new Date().toISOString()}
951
+ > Files analyzed: ${hotFiles.length}
952
+ > CLI Tool: ${tool}
953
+
954
+ ---
955
+
956
+ `;
957
+
958
+ // Use CCW CLI tool to analyze files
959
+ let cliOutput = '';
960
+
961
+ // Build CLI prompt
962
+ const cliPrompt = `PURPOSE: Analyze the following hot files and provide a concise understanding of each.
963
+ TASK: For each file, describe its purpose, key exports, dependencies, and how it relates to other files.
964
+ MODE: analysis
965
+ CONTEXT: ${filePaths.map((p: string) => '@' + p).join(' ')}
966
+ EXPECTED: Markdown format with ## headings for each file, bullet points for key information.
967
+ RULES: Be concise. Focus on practical understanding. Include function signatures for key exports.`;
968
+
969
+ // Try to execute CLI using CCW's built-in executor
970
+ try {
971
+ const syncId = `active-memory-${Date.now()}`;
972
+ const result = await executeCliTool({
973
+ tool: tool === 'qwen' ? 'qwen' : 'gemini',
974
+ prompt: cliPrompt,
975
+ mode: 'analysis',
976
+ format: 'plain',
977
+ cd: projectPath,
978
+ timeout: 120000,
979
+ stream: false,
980
+ category: 'internal',
981
+ id: syncId
982
+ });
983
+
984
+ if (result.success && result.execution?.output) {
985
+ // Extract stdout from output object with proper serialization
986
+ const output = result.execution.output;
987
+ if (typeof output === 'string') {
988
+ cliOutput = output;
989
+ } else if (output && typeof output === 'object') {
990
+ // Handle object output - extract stdout or serialize the object
991
+ if (output.stdout && typeof output.stdout === 'string') {
992
+ cliOutput = output.stdout;
993
+ } else if (output.stderr && typeof output.stderr === 'string') {
994
+ cliOutput = output.stderr;
995
+ } else {
996
+ // Last resort: serialize the entire object as JSON
997
+ cliOutput = JSON.stringify(output, null, 2);
998
+ }
999
+ } else {
1000
+ cliOutput = '';
1001
+ }
1002
+ }
1003
+
1004
+ // Add CLI output to content (only if not empty)
1005
+ if (cliOutput && cliOutput.trim()) {
1006
+ content += cliOutput + '\n\n---\n\n';
1007
+ }
1008
+
1009
+ } catch (cliErr) {
1010
+ // Fallback to basic analysis if CLI fails
1011
+ console.warn('[Active Memory] CLI analysis failed, using basic analysis:', (cliErr as Error).message);
1012
+
1013
+ // Basic analysis fallback
1014
+ for (const file of hotFiles) {
1015
+ const fileName = file.value.split(/[/\\]/).pop() || file.value;
1016
+ const filePath = file.value;
1017
+ const heat = file.stats?.heat_score || 0;
1018
+ const readCount = file.stats?.read_count || 0;
1019
+ const writeCount = file.stats?.write_count || 0;
1020
+
1021
+ content += `## ${fileName}
1022
+
1023
+ - **Path**: \`${filePath}\`
1024
+ - **Heat Score**: ${heat}
1025
+ - **Access**: ${readCount} reads, ${writeCount} writes
1026
+ - **Last Seen**: ${file.last_seen_at || 'Unknown'}
1027
+
1028
+ `;
1029
+
1030
+ // Try to read file and generate summary
1031
+ try {
1032
+ const fullPath = isAbsolute(filePath) ? filePath : join(projectPath, filePath);
1033
+
1034
+ if (existsSync(fullPath)) {
1035
+ const stat = statSync(fullPath);
1036
+ const ext = extname(fullPath).toLowerCase();
1037
+
1038
+ content += `- **Size**: ${(stat.size / 1024).toFixed(1)} KB\n`;
1039
+ content += `- **Type**: ${ext || 'unknown'}\n`;
1040
+
1041
+ const textExts = ['.ts', '.js', '.tsx', '.jsx', '.md', '.json', '.css', '.html', '.vue', '.svelte', '.py', '.go', '.rs'];
1042
+ if (textExts.includes(ext) && stat.size < 100000) {
1043
+ const fileContent = readFileSync(fullPath, 'utf-8');
1044
+ const lines = fileContent.split('\n').slice(0, 30);
1045
+
1046
+ const exports = lines.filter(l =>
1047
+ l.includes('export ') || l.includes('function ') ||
1048
+ l.includes('class ') || l.includes('interface ')
1049
+ ).slice(0, 8);
1050
+
1051
+ if (exports.length > 0) {
1052
+ content += `\n**Key Exports**:\n\`\`\`\n${exports.join('\n')}\n\`\`\`\n`;
1053
+ }
1054
+ }
1055
+ }
1056
+ } catch (fileErr) {
1057
+ // Skip file analysis errors
1058
+ }
1059
+
1060
+ content += '\n---\n\n';
1061
+ }
1062
+ }
1063
+
1064
+ // Ensure directories exist
1065
+ if (!existsSync(claudeDir)) {
1066
+ mkdirSync(claudeDir, { recursive: true });
1067
+ }
1068
+ if (!existsSync(rulesDir)) {
1069
+ mkdirSync(rulesDir, { recursive: true });
1070
+ }
1071
+
1072
+ // Write the file
1073
+ writeFileSync(configPath, content, 'utf-8');
1074
+
1075
+ // Broadcast Active Memory sync completion event
1076
+ broadcastToClients({
1077
+ type: 'ACTIVE_MEMORY_SYNCED',
1078
+ payload: {
1079
+ filesAnalyzed: hotFiles.length,
1080
+ path: configPath,
1081
+ tool,
1082
+ usedCli: cliOutput.length > 0,
1083
+ timestamp: new Date().toISOString()
1084
+ }
1085
+ });
1086
+
1087
+ res.writeHead(200, { 'Content-Type': 'application/json' });
1088
+ res.end(JSON.stringify({
1089
+ success: true,
1090
+ filesAnalyzed: hotFiles.length,
1091
+ path: configPath,
1092
+ usedCli: cliOutput.length > 0
1093
+ }));
1094
+ } catch (error: unknown) {
1095
+ console.error('[Active Memory] Sync error:', error);
1096
+ if (!res.headersSent) {
1097
+ res.writeHead(500, { 'Content-Type': 'application/json' });
1098
+ res.end(JSON.stringify({ error: (error as Error).message }));
1099
+ }
1100
+ }
1101
+ });
1102
+ return true;
1103
+ }
1104
+
1105
+ // API: Memory Module - Get conversations index
1106
+ if (pathname === '/api/memory/conversations') {
1107
+ const projectPath = url.searchParams.get('path') || initialPath;
1108
+ const project = url.searchParams.get('project') || null;
1109
+ const limit = parseInt(url.searchParams.get('limit') || '20', 10);
1110
+
1111
+ try {
1112
+ const memoryStore = getMemoryStore(projectPath);
1113
+
1114
+ let conversations;
1115
+ if (project) {
1116
+ const stmt = memoryStore['db'].prepare(`
1117
+ SELECT * FROM conversations
1118
+ WHERE project_name = ?
1119
+ ORDER BY updated_at DESC
1120
+ LIMIT ?
1121
+ `);
1122
+ conversations = stmt.all(project, limit);
1123
+ } else {
1124
+ conversations = memoryStore.getConversations(limit);
1125
+ }
1126
+
1127
+ res.writeHead(200, { 'Content-Type': 'application/json' });
1128
+ res.end(JSON.stringify({ conversations }));
1129
+ } catch (error: unknown) {
1130
+ res.writeHead(500, { 'Content-Type': 'application/json' });
1131
+ res.end(JSON.stringify({ error: (error as Error).message }));
1132
+ }
1133
+ return true;
1134
+ }
1135
+
1136
+ // API: Memory Module - Replay conversation
1137
+ if (pathname.startsWith('/api/memory/replay/')) {
1138
+ const conversationId = pathname.replace('/api/memory/replay/', '');
1139
+ const projectPath = url.searchParams.get('path') || initialPath;
1140
+
1141
+ if (!conversationId) {
1142
+ res.writeHead(400, { 'Content-Type': 'application/json' });
1143
+ res.end(JSON.stringify({ error: 'Conversation ID is required' }));
1144
+ return true;
1145
+ }
1146
+
1147
+ try {
1148
+ const memoryStore = getMemoryStore(projectPath);
1149
+ const conversation = memoryStore.getConversation(conversationId);
1150
+
1151
+ if (!conversation) {
1152
+ res.writeHead(404, { 'Content-Type': 'application/json' });
1153
+ res.end(JSON.stringify({ error: 'Conversation not found' }));
1154
+ return true;
1155
+ }
1156
+
1157
+ const messages = memoryStore.getMessages(conversationId);
1158
+
1159
+ // Enhance messages with tool calls
1160
+ const messagesWithTools = [];
1161
+ for (const message of messages) {
1162
+ const toolCalls = message.id ? memoryStore.getToolCalls(message.id) : [];
1163
+ messagesWithTools.push({
1164
+ ...message,
1165
+ tool_calls: toolCalls
1166
+ });
1167
+ }
1168
+
1169
+ res.writeHead(200, { 'Content-Type': 'application/json' });
1170
+ res.end(JSON.stringify({
1171
+ conversation,
1172
+ messages: messagesWithTools
1173
+ }));
1174
+ } catch (error: unknown) {
1175
+ res.writeHead(500, { 'Content-Type': 'application/json' });
1176
+ res.end(JSON.stringify({ error: (error as Error).message }));
1177
+ }
1178
+ return true;
1179
+ }
1180
+
1181
+ // API: Memory Module - Import history (async task)
1182
+ if (pathname === '/api/memory/import' && req.method === 'POST') {
1183
+ handlePostRequest(req, res, async (body) => {
1184
+ const { source = 'all', project, path: projectPath } = body;
1185
+ const basePath = projectPath || initialPath;
1186
+
1187
+ // Generate task ID for async operation
1188
+ const taskId = `import-${Date.now()}`;
1189
+
1190
+ // TODO: Implement actual history import using HistoryImporter
1191
+ // For now, return a placeholder response
1192
+ console.log(`[Memory] Import task ${taskId} started: source=${source}, project=${project}`);
1193
+
1194
+ return {
1195
+ success: true,
1196
+ taskId,
1197
+ message: 'Import task started (not yet implemented)',
1198
+ source,
1199
+ project
1200
+ };
1201
+ });
1202
+ return true;
1203
+ }
1204
+
1205
+ return false;
1206
+ }