toolnet-memory 0.2.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 (329) hide show
  1. package/.env.example +28 -0
  2. package/README.md +147 -0
  3. package/bin/toolnet-memory +415 -0
  4. package/dist/packages/cli/commands.js +1 -0
  5. package/dist/packages/cli/index.js +1 -0
  6. package/dist/packages/sdk/client.js +78 -0
  7. package/dist/packages/sdk/index.js +1 -0
  8. package/dist/packages/sdk/types.js +1 -0
  9. package/dist/src/api/index.js +1 -0
  10. package/dist/src/api/routes/health.js +1 -0
  11. package/dist/src/api/routes/index.js +1 -0
  12. package/dist/src/api/routes/memory.js +1 -0
  13. package/dist/src/api/routes/projects.js +1 -0
  14. package/dist/src/api/routes/search.js +1 -0
  15. package/dist/src/api/server.js +1 -0
  16. package/dist/src/capture/activity-capture.js +21 -0
  17. package/dist/src/capture/command-capture.js +12 -0
  18. package/dist/src/capture/error-capture.js +14 -0
  19. package/dist/src/capture/event-deduplicator.js +28 -0
  20. package/dist/src/capture/event-queue.js +20 -0
  21. package/dist/src/capture/file-capture.js +23 -0
  22. package/dist/src/capture/index.js +8 -0
  23. package/dist/src/capture/session-capture.js +18 -0
  24. package/dist/src/capture/tool-capture.js +13 -0
  25. package/dist/src/code-intelligence/analysis/analysis-engine.js +26 -0
  26. package/dist/src/code-intelligence/analysis/dead-code-analyzer.js +127 -0
  27. package/dist/src/code-intelligence/analysis/dependency-analyzer.js +66 -0
  28. package/dist/src/code-intelligence/analysis/index.js +4 -0
  29. package/dist/src/code-intelligence/analysis/types.js +1 -0
  30. package/dist/src/code-intelligence/architecture/architecture-engine.js +48 -0
  31. package/dist/src/code-intelligence/architecture/clusters.js +322 -0
  32. package/dist/src/code-intelligence/architecture/entry-points.js +150 -0
  33. package/dist/src/code-intelligence/architecture/hotspots.js +136 -0
  34. package/dist/src/code-intelligence/architecture/index.js +6 -0
  35. package/dist/src/code-intelligence/architecture/layers.js +197 -0
  36. package/dist/src/code-intelligence/architecture/types.js +1 -0
  37. package/dist/src/code-intelligence/chunks/index.js +2 -0
  38. package/dist/src/code-intelligence/chunks/smart-chunker.js +125 -0
  39. package/dist/src/code-intelligence/chunks/types.js +1 -0
  40. package/dist/src/code-intelligence/git/git-diff.js +109 -0
  41. package/dist/src/code-intelligence/git/index.js +1 -0
  42. package/dist/src/code-intelligence/graph/architecture.js +26 -0
  43. package/dist/src/code-intelligence/graph/graph-builder.js +213 -0
  44. package/dist/src/code-intelligence/graph/graph-store.js +57 -0
  45. package/dist/src/code-intelligence/graph/index.js +1 -0
  46. package/dist/src/code-intelligence/graph/relationships.js +1 -0
  47. package/dist/src/code-intelligence/graph/trace.js +65 -0
  48. package/dist/src/code-intelligence/impact/blast-radius.js +160 -0
  49. package/dist/src/code-intelligence/impact/change-mapper.js +69 -0
  50. package/dist/src/code-intelligence/impact/edit-tool-detector.js +92 -0
  51. package/dist/src/code-intelligence/impact/impact-analyzer.js +60 -0
  52. package/dist/src/code-intelligence/impact/impact-guard.js +33 -0
  53. package/dist/src/code-intelligence/impact/index.js +5 -0
  54. package/dist/src/code-intelligence/incremental/file-hash.js +8 -0
  55. package/dist/src/code-intelligence/incremental/incremental-indexer.js +106 -0
  56. package/dist/src/code-intelligence/incremental/manifest-builder.js +19 -0
  57. package/dist/src/code-intelligence/incremental/manifest.js +31 -0
  58. package/dist/src/code-intelligence/index.js +23 -0
  59. package/dist/src/code-intelligence/indexer/file-watcher.js +1 -0
  60. package/dist/src/code-intelligence/indexer/incremental-indexer.js +1 -0
  61. package/dist/src/code-intelligence/indexer/index.js +1 -0
  62. package/dist/src/code-intelligence/indexer/repository-indexer.js +31 -0
  63. package/dist/src/code-intelligence/indexer/repository-scanner.js +50 -0
  64. package/dist/src/code-intelligence/parsers/index.js +1 -0
  65. package/dist/src/code-intelligence/parsers/tree-sitter/index.js +1 -0
  66. package/dist/src/code-intelligence/parsers/tree-sitter/languages.js +1 -0
  67. package/dist/src/code-intelligence/parsers/tree-sitter/parser.js +1 -0
  68. package/dist/src/code-intelligence/parsers/typescript-parser.js +190 -0
  69. package/dist/src/code-intelligence/query/graph-query-engine.js +275 -0
  70. package/dist/src/code-intelligence/query/index.js +2 -0
  71. package/dist/src/code-intelligence/query/types.js +1 -0
  72. package/dist/src/code-intelligence/resolution/index.js +2 -0
  73. package/dist/src/code-intelligence/resolution/types.js +1 -0
  74. package/dist/src/code-intelligence/resolution/typescript-resolver.js +316 -0
  75. package/dist/src/code-intelligence/rich/index.js +1 -0
  76. package/dist/src/code-intelligence/rich/rich-graph-enricher.js +463 -0
  77. package/dist/src/code-intelligence/semantic/index.js +2 -0
  78. package/dist/src/code-intelligence/semantic/semantic-code-engine.js +213 -0
  79. package/dist/src/code-intelligence/semantic/source-priority.js +22 -0
  80. package/dist/src/code-intelligence/symbols/index.js +1 -0
  81. package/dist/src/code-intelligence/symbols/reference-resolver.js +21 -0
  82. package/dist/src/code-intelligence/symbols/symbol-extractor.js +1 -0
  83. package/dist/src/code-intelligence/test-analysis.js +72 -0
  84. package/dist/src/code-intelligence/test-architecture.js +67 -0
  85. package/dist/src/code-intelligence/test-impact.js +47 -0
  86. package/dist/src/code-intelligence/test-incremental.js +24 -0
  87. package/dist/src/code-intelligence/test-index.js +39 -0
  88. package/dist/src/code-intelligence/test-resolution.js +54 -0
  89. package/dist/src/code-intelligence/test-rich-graph.js +48 -0
  90. package/dist/src/code-intelligence/test-semantic.js +57 -0
  91. package/dist/src/code-intelligence/test-visualization.js +36 -0
  92. package/dist/src/code-intelligence/types.js +1 -0
  93. package/dist/src/code-intelligence/visualization/index.js +2 -0
  94. package/dist/src/code-intelligence/visualization/types.js +1 -0
  95. package/dist/src/code-intelligence/visualization/visualization-builder.js +104 -0
  96. package/dist/src/core/config.js +66 -0
  97. package/dist/src/core/global-env.js +70 -0
  98. package/dist/src/core/importance.js +30 -0
  99. package/dist/src/core/index.js +5 -0
  100. package/dist/src/core/memory-engine.js +183 -0
  101. package/dist/src/core/project-manager.js +243 -0
  102. package/dist/src/core/types.js +1 -0
  103. package/dist/src/embeddings/batch-embedder.js +1 -0
  104. package/dist/src/embeddings/cache.js +1 -0
  105. package/dist/src/embeddings/embedder.js +51 -0
  106. package/dist/src/embeddings/index.js +4 -0
  107. package/dist/src/embeddings/local.js +37 -0
  108. package/dist/src/embeddings/provider.js +1 -0
  109. package/dist/src/embeddings/remote.js +76 -0
  110. package/dist/src/embeddings/test-connection.js +16 -0
  111. package/dist/src/hooks/after-edit.js +3 -0
  112. package/dist/src/hooks/after-tool.js +3 -0
  113. package/dist/src/hooks/auto-context.js +68 -0
  114. package/dist/src/hooks/auto-impact-guard.js +94 -0
  115. package/dist/src/hooks/auto-retrieval.js +27 -0
  116. package/dist/src/hooks/before-agent.js +18 -0
  117. package/dist/src/hooks/before-compact.js +3 -0
  118. package/dist/src/hooks/before-edit.js +20 -0
  119. package/dist/src/hooks/index.js +11 -0
  120. package/dist/src/hooks/runtime.js +110 -0
  121. package/dist/src/hooks/session-end.js +3 -0
  122. package/dist/src/hooks/session-start.js +3 -0
  123. package/dist/src/index.js +22 -0
  124. package/dist/src/mcp/bootstrap.js +68 -0
  125. package/dist/src/mcp/context.js +1 -0
  126. package/dist/src/mcp/index.js +3 -0
  127. package/dist/src/mcp/server.js +45 -0
  128. package/dist/src/mcp/tools/analyze-impact.js +41 -0
  129. package/dist/src/mcp/tools/dead-code.js +55 -0
  130. package/dist/src/mcp/tools/find-callers.js +24 -0
  131. package/dist/src/mcp/tools/find-dependencies.js +57 -0
  132. package/dist/src/mcp/tools/find-symbol.js +7 -0
  133. package/dist/src/mcp/tools/get-architecture.js +11 -0
  134. package/dist/src/mcp/tools/graph-dependents.js +24 -0
  135. package/dist/src/mcp/tools/graph-neighborhood.js +58 -0
  136. package/dist/src/mcp/tools/graph-path.js +43 -0
  137. package/dist/src/mcp/tools/graph-query-utils.js +32 -0
  138. package/dist/src/mcp/tools/impact-guard.js +34 -0
  139. package/dist/src/mcp/tools/index-repository.js +1 -0
  140. package/dist/src/mcp/tools/index.js +20 -0
  141. package/dist/src/mcp/tools/memory-decisions.js +1 -0
  142. package/dist/src/mcp/tools/memory-forget.js +14 -0
  143. package/dist/src/mcp/tools/memory-recent.js +1 -0
  144. package/dist/src/mcp/tools/memory-remember.js +33 -0
  145. package/dist/src/mcp/tools/memory-rules.js +1 -0
  146. package/dist/src/mcp/tools/memory-search.js +18 -0
  147. package/dist/src/mcp/tools/memory-todos.js +1 -0
  148. package/dist/src/mcp/tools/project-context.js +25 -0
  149. package/dist/src/mcp/tools/search-code.js +21 -0
  150. package/dist/src/mcp/tools/semantic-code-search.js +33 -0
  151. package/dist/src/mcp/tools/snapshot-create.js +13 -0
  152. package/dist/src/mcp/tools/snapshot-list.js +7 -0
  153. package/dist/src/mcp/tools/snapshot-restore.js +13 -0
  154. package/dist/src/mcp/tools/trace-calls.js +37 -0
  155. package/dist/src/memory/activity.js +5 -0
  156. package/dist/src/memory/conflict-detector.js +105 -0
  157. package/dist/src/memory/consolidator.js +104 -0
  158. package/dist/src/memory/decay.js +59 -0
  159. package/dist/src/memory/decisions.js +3 -0
  160. package/dist/src/memory/deduplicate.js +25 -0
  161. package/dist/src/memory/index.js +11 -0
  162. package/dist/src/memory/maintenance.js +16 -0
  163. package/dist/src/memory/remember.js +3 -0
  164. package/dist/src/memory/rules.js +3 -0
  165. package/dist/src/memory/search.js +3 -0
  166. package/dist/src/memory/summaries.js +1 -0
  167. package/dist/src/memory/todos.js +3 -0
  168. package/dist/src/processor/decision-extractor.js +13 -0
  169. package/dist/src/processor/importance-scorer.js +22 -0
  170. package/dist/src/processor/index.js +7 -0
  171. package/dist/src/processor/memory-extractor.js +59 -0
  172. package/dist/src/processor/memory-processor.js +105 -0
  173. package/dist/src/processor/rule-extractor.js +13 -0
  174. package/dist/src/processor/summarizer.js +71 -0
  175. package/dist/src/processor/todo-extractor.js +12 -0
  176. package/dist/src/production/config-check.js +34 -0
  177. package/dist/src/production/doctor.js +58 -0
  178. package/dist/src/production/full-index.js +114 -0
  179. package/dist/src/production/health.js +58 -0
  180. package/dist/src/production/index-pipeline.js +151 -0
  181. package/dist/src/production/index.js +4 -0
  182. package/dist/src/production/project-lock.js +95 -0
  183. package/dist/src/production/project-status.js +16 -0
  184. package/dist/src/production/recovery.js +15 -0
  185. package/dist/src/production/snapshot-cli.js +58 -0
  186. package/dist/src/project-manual/cli.js +77 -0
  187. package/dist/src/project-manual/index.js +2 -0
  188. package/dist/src/project-manual/manager.js +147 -0
  189. package/dist/src/project-manual/types.js +1 -0
  190. package/dist/src/retrieval/bm25/index.js +1 -0
  191. package/dist/src/retrieval/bm25/search.js +1 -0
  192. package/dist/src/retrieval/bm25.js +30 -0
  193. package/dist/src/retrieval/context-budget.js +1 -0
  194. package/dist/src/retrieval/context-builder.js +22 -0
  195. package/dist/src/retrieval/graph/index.js +1 -0
  196. package/dist/src/retrieval/graph/search.js +1 -0
  197. package/dist/src/retrieval/hybrid/hybrid-search.js +1 -0
  198. package/dist/src/retrieval/hybrid/index.js +1 -0
  199. package/dist/src/retrieval/hybrid-search.js +68 -0
  200. package/dist/src/retrieval/importance.js +16 -0
  201. package/dist/src/retrieval/index.js +12 -0
  202. package/dist/src/retrieval/query-analyzer.js +32 -0
  203. package/dist/src/retrieval/query-classifier.js +1 -0
  204. package/dist/src/retrieval/query-expansion.js +1 -0
  205. package/dist/src/retrieval/recency.js +12 -0
  206. package/dist/src/retrieval/reranker/index.js +1 -0
  207. package/dist/src/retrieval/reranker/reranker.js +1 -0
  208. package/dist/src/retrieval/retrieval-engine.js +17 -0
  209. package/dist/src/retrieval/tokenizer.js +9 -0
  210. package/dist/src/retrieval/type-priority.js +10 -0
  211. package/dist/src/retrieval/types.js +1 -0
  212. package/dist/src/retrieval/vector/index.js +4 -0
  213. package/dist/src/retrieval/vector/metadata-filter.js +1 -0
  214. package/dist/src/retrieval/vector/persistence.js +67 -0
  215. package/dist/src/retrieval/vector/search.js +12 -0
  216. package/dist/src/retrieval/vector/test-persistence.js +36 -0
  217. package/dist/src/retrieval/vector/upsert.js +40 -0
  218. package/dist/src/retrieval/vector/vector-store.js +89 -0
  219. package/dist/src/retrieval/vector-hybrid-engine.js +91 -0
  220. package/dist/src/runtime/bootstrap.js +28 -0
  221. package/dist/src/runtime/graceful.js +17 -0
  222. package/dist/src/runtime/index.js +3 -0
  223. package/dist/src/runtime/toolnet-memory-runtime.js +156 -0
  224. package/dist/src/security/encryption.js +1 -0
  225. package/dist/src/security/file-filter.js +30 -0
  226. package/dist/src/security/index.js +3 -0
  227. package/dist/src/security/sanitizer.js +49 -0
  228. package/dist/src/security/secret-scanner.js +56 -0
  229. package/dist/src/session/agy/adapter.js +159 -0
  230. package/dist/src/session/agy/cli.js +87 -0
  231. package/dist/src/session/agy/hook-installer.js +62 -0
  232. package/dist/src/session/agy/hook.js +167 -0
  233. package/dist/src/session/agy/index.js +5 -0
  234. package/dist/src/session/agy/project-resolver.js +27 -0
  235. package/dist/src/session/agy/recovery.js +112 -0
  236. package/dist/src/session/agy/transcript.js +191 -0
  237. package/dist/src/session/codex/adapter.js +138 -0
  238. package/dist/src/session/codex/cli.js +236 -0
  239. package/dist/src/session/codex/context-hook-installer.js +70 -0
  240. package/dist/src/session/codex/context-hook.js +69 -0
  241. package/dist/src/session/codex/discovery.js +138 -0
  242. package/dist/src/session/codex/index.js +6 -0
  243. package/dist/src/session/codex/notify-installer.js +135 -0
  244. package/dist/src/session/codex/project-resolver.js +25 -0
  245. package/dist/src/session/codex/recovery.js +27 -0
  246. package/dist/src/session/codex/rollout.js +186 -0
  247. package/dist/src/session/core.js +239 -0
  248. package/dist/src/session/identity.js +57 -0
  249. package/dist/src/session/index.js +9 -0
  250. package/dist/src/session/learner/cli.js +62 -0
  251. package/dist/src/session/learner/extractor.js +461 -0
  252. package/dist/src/session/learner/index.js +4 -0
  253. package/dist/src/session/learner/journal.js +159 -0
  254. package/dist/src/session/learner/learner.js +124 -0
  255. package/dist/src/session/learner/types.js +1 -0
  256. package/dist/src/session/opencode/adapter.js +553 -0
  257. package/dist/src/session/opencode/cli.js +121 -0
  258. package/dist/src/session/opencode/index.js +2 -0
  259. package/dist/src/session/opencode/plugin-installer.js +230 -0
  260. package/dist/src/session/store.js +242 -0
  261. package/dist/src/session/types.js +1 -0
  262. package/dist/src/session/utils.js +47 -0
  263. package/dist/src/session/wal.js +303 -0
  264. package/dist/src/snapshot/index.js +2 -0
  265. package/dist/src/snapshot/manager.js +130 -0
  266. package/dist/src/snapshot/test-snapshot.js +28 -0
  267. package/dist/src/snapshot/types.js +1 -0
  268. package/dist/src/storage/architecture-store.js +37 -0
  269. package/dist/src/storage/cleanup-health.js +20 -0
  270. package/dist/src/storage/code-analysis-store.js +35 -0
  271. package/dist/src/storage/code-chunk-store.js +25 -0
  272. package/dist/src/storage/code-graph-store.js +24 -0
  273. package/dist/src/storage/code-manifest-store.js +24 -0
  274. package/dist/src/storage/code-vector-store.js +25 -0
  275. package/dist/src/storage/github/client.js +1 -0
  276. package/dist/src/storage/github/index.js +1 -0
  277. package/dist/src/storage/google-drive/client.js +1 -0
  278. package/dist/src/storage/google-drive/index.js +1 -0
  279. package/dist/src/storage/huggingface/client.js +116 -0
  280. package/dist/src/storage/huggingface/index.js +1 -0
  281. package/dist/src/storage/index.js +16 -0
  282. package/dist/src/storage/list-bucket-raw.js +14 -0
  283. package/dist/src/storage/list-bucket-tree.js +38 -0
  284. package/dist/src/storage/local/client.js +99 -0
  285. package/dist/src/storage/local/index.js +1 -0
  286. package/dist/src/storage/memory-store.js +30 -0
  287. package/dist/src/storage/project/cleanup-layout-v1.js +72 -0
  288. package/dist/src/storage/project/folder.js +15 -0
  289. package/dist/src/storage/project/index.js +3 -0
  290. package/dist/src/storage/project/layout.js +74 -0
  291. package/dist/src/storage/project/migrate-layout-v2.js +101 -0
  292. package/dist/src/storage/project/migrate.js +73 -0
  293. package/dist/src/storage/project/scoped-provider.js +165 -0
  294. package/dist/src/storage/provider.js +26 -0
  295. package/dist/src/storage/retrying-provider.js +23 -0
  296. package/dist/src/storage/test-connection.js +32 -0
  297. package/dist/src/storage/type-resolution-store.js +26 -0
  298. package/dist/src/storage/types.js +1 -0
  299. package/dist/src/storage/vector-store.js +30 -0
  300. package/dist/src/storage/visualization-store.js +25 -0
  301. package/dist/src/sync/compressor.js +1 -0
  302. package/dist/src/sync/conflict-resolver.js +1 -0
  303. package/dist/src/sync/downloader.js +1 -0
  304. package/dist/src/sync/index.js +1 -0
  305. package/dist/src/sync/sync-engine.js +1 -0
  306. package/dist/src/sync/upload-queue.js +1 -0
  307. package/dist/src/utils/retry.js +29 -0
  308. package/dist/src/visualization/server.js +270 -0
  309. package/dist/src/work-continuity/brief-cache.js +107 -0
  310. package/dist/src/work-continuity/brief.js +349 -0
  311. package/dist/src/work-continuity/cli.js +96 -0
  312. package/dist/src/work-continuity/context-cli.js +106 -0
  313. package/dist/src/work-continuity/context-runtime-cli.js +88 -0
  314. package/dist/src/work-continuity/extractor.js +339 -0
  315. package/dist/src/work-continuity/handoff.js +185 -0
  316. package/dist/src/work-continuity/index.js +14 -0
  317. package/dist/src/work-continuity/injection.js +84 -0
  318. package/dist/src/work-continuity/journal.js +49 -0
  319. package/dist/src/work-continuity/learner.js +127 -0
  320. package/dist/src/work-continuity/reducer.js +316 -0
  321. package/dist/src/work-continuity/semantic-extractor.js +360 -0
  322. package/dist/src/work-continuity/semantic-journal.js +55 -0
  323. package/dist/src/work-continuity/semantic-learner.js +125 -0
  324. package/dist/src/work-continuity/semantic-reducer.js +268 -0
  325. package/dist/src/work-continuity/semantic-types.js +1 -0
  326. package/dist/src/work-continuity/types.js +1 -0
  327. package/dist/visualization/public/index.html +2896 -0
  328. package/dist/visualization/public/vendor/3d-force-graph.min.js +5 -0
  329. package/package.json +69 -0
@@ -0,0 +1,147 @@
1
+ import { existsSync, mkdirSync, readFileSync, statSync, writeFileSync, } from "node:fs";
2
+ import { dirname, join, } from "node:path";
3
+ import { sha256, } from "../session/utils.js";
4
+ const MAX_MANUAL_BYTES = 64 * 1024;
5
+ export const PROJECT_MANUAL_TEMPLATE = `# ToolNet Project Operating Manual
6
+
7
+ This file contains persistent instructions for AI agents working on this project.
8
+
9
+ ## Critical Rules
10
+
11
+ <!--
12
+ Examples:
13
+
14
+ - [enforce] Never edit production files directly.
15
+ - [enforce] Edit source only in /path/to/source.
16
+ - [enforce] Deploy only with ./deploy.sh --apply
17
+ -->
18
+
19
+ ## Workflow
20
+
21
+ <!--
22
+ Describe the correct working process.
23
+ -->
24
+
25
+ ## Architecture
26
+
27
+ <!--
28
+ Important architecture conventions.
29
+ -->
30
+
31
+ ## Verification
32
+
33
+ <!--
34
+ Tests / QA required after changes.
35
+ -->
36
+
37
+ ## Known Gotchas
38
+
39
+ <!--
40
+ Things an AI agent should always remember.
41
+ -->
42
+
43
+ ## Preferences
44
+
45
+ <!--
46
+ - [advisory] Prefer small focused files.
47
+ -->
48
+ `;
49
+ export function projectManualPath(project) {
50
+ return join(project.rootPath, ".toolnet", "PROJECT.md");
51
+ }
52
+ function normalizeRuleText(value) {
53
+ return value
54
+ .normalize("NFKC")
55
+ .replace(/\s+/g, " ")
56
+ .trim();
57
+ }
58
+ function parseRules(content) {
59
+ const rules = [];
60
+ const seen = new Set();
61
+ const pattern = /^\s*[-*]\s+\[(enforce|advisory)\]\s+(.+?)\s*$/gimu;
62
+ let match;
63
+ while ((match =
64
+ pattern.exec(content))) {
65
+ const mode = match[1]
66
+ .toLowerCase();
67
+ const text = normalizeRuleText(match[2]);
68
+ if (!text) {
69
+ continue;
70
+ }
71
+ const key = `${mode}:${text.toLowerCase()}`;
72
+ if (seen.has(key)) {
73
+ continue;
74
+ }
75
+ seen.add(key);
76
+ rules.push({
77
+ id: sha256(key).slice(0, 24),
78
+ mode,
79
+ text,
80
+ source: "manual",
81
+ });
82
+ }
83
+ return rules;
84
+ }
85
+ export function ensureProjectManual(project) {
86
+ const file = projectManualPath(project);
87
+ if (existsSync(file)) {
88
+ return file;
89
+ }
90
+ mkdirSync(dirname(file), {
91
+ recursive: true,
92
+ });
93
+ writeFileSync(file, PROJECT_MANUAL_TEMPLATE, {
94
+ encoding: "utf8",
95
+ mode: 0o600,
96
+ });
97
+ return file;
98
+ }
99
+ export function loadProjectManual(project, createIfMissing = false) {
100
+ const file = createIfMissing
101
+ ? ensureProjectManual(project)
102
+ : projectManualPath(project);
103
+ if (!existsSync(file)) {
104
+ return null;
105
+ }
106
+ const size = statSync(file).size;
107
+ if (size >
108
+ MAX_MANUAL_BYTES) {
109
+ throw new Error(`PROJECT.md exceeds ${MAX_MANUAL_BYTES} bytes`);
110
+ }
111
+ const content = readFileSync(file, "utf8");
112
+ return {
113
+ path: file,
114
+ content,
115
+ digest: sha256(content),
116
+ rules: parseRules(content),
117
+ bytes: Buffer.byteLength(content, "utf8"),
118
+ updatedAt: new Date(statSync(file).mtimeMs).toISOString(),
119
+ };
120
+ }
121
+ export async function syncProjectManual(project, storage) {
122
+ const manual = loadProjectManual(project, true);
123
+ if (!manual) {
124
+ throw new Error("Project manual unavailable");
125
+ }
126
+ const prefix = `projects/${project.id}/project`;
127
+ await storage.put(`${prefix}/manual.md`, manual.content, "text/markdown");
128
+ await storage.put(`${prefix}/manual.json`, JSON.stringify({
129
+ version: 1,
130
+ projectId: project.id,
131
+ projectName: project.name,
132
+ digest: manual.digest,
133
+ bytes: manual.bytes,
134
+ ruleCount: manual.rules.length,
135
+ enforceRules: manual.rules
136
+ .filter(rule => rule.mode ===
137
+ "enforce")
138
+ .length,
139
+ advisoryRules: manual.rules
140
+ .filter(rule => rule.mode ===
141
+ "advisory")
142
+ .length,
143
+ updatedAt: manual.updatedAt,
144
+ }, null, 2) +
145
+ "\n", "application/json");
146
+ return manual;
147
+ }
@@ -0,0 +1 @@
1
+ export {};
@@ -0,0 +1 @@
1
+ export {};
@@ -0,0 +1 @@
1
+ export {};
@@ -0,0 +1,30 @@
1
+ import { tokenize } from "./tokenizer.js";
2
+ export class BM25Scorer {
3
+ score(query, memory) {
4
+ const queryTokens = tokenize(query);
5
+ const documentTokens = tokenize([
6
+ memory.content,
7
+ ...(memory.tags ?? []),
8
+ memory.type,
9
+ ].join(" "));
10
+ if (queryTokens.length === 0 ||
11
+ documentTokens.length === 0) {
12
+ return 0;
13
+ }
14
+ const frequencies = new Map();
15
+ for (const token of documentTokens) {
16
+ frequencies.set(token, (frequencies.get(token) ?? 0) + 1);
17
+ }
18
+ let score = 0;
19
+ for (const token of queryTokens) {
20
+ const tf = frequencies.get(token) ?? 0;
21
+ if (tf === 0) {
22
+ continue;
23
+ }
24
+ score +=
25
+ 1 +
26
+ Math.log(1 + tf);
27
+ }
28
+ return score / queryTokens.length;
29
+ }
30
+ }
@@ -0,0 +1 @@
1
+ export {};
@@ -0,0 +1,22 @@
1
+ export class ContextBuilder {
2
+ build(results, maxCharacters = 6000) {
3
+ const blocks = [];
4
+ let used = 0;
5
+ for (const result of results) {
6
+ const memory = result.memory;
7
+ const block = [
8
+ `[${memory.type.toUpperCase()}]`,
9
+ memory.content,
10
+ ].join(" ");
11
+ if (used +
12
+ block.length >
13
+ maxCharacters) {
14
+ break;
15
+ }
16
+ blocks.push(block);
17
+ used +=
18
+ block.length;
19
+ }
20
+ return blocks.join("\n");
21
+ }
22
+ }
@@ -0,0 +1 @@
1
+ export {};
@@ -0,0 +1 @@
1
+ export {};
@@ -0,0 +1 @@
1
+ export {};
@@ -0,0 +1 @@
1
+ export {};
@@ -0,0 +1,68 @@
1
+ import { BM25Scorer, } from "./bm25.js";
2
+ import { recencyScore, } from "./recency.js";
3
+ import { memoryImportanceScore, } from "./importance.js";
4
+ import { typePriority, } from "./type-priority.js";
5
+ import { QueryAnalyzer, } from "./query-analyzer.js";
6
+ export class HybridSearch {
7
+ bm25 = new BM25Scorer();
8
+ analyzer = new QueryAnalyzer();
9
+ search(query, memories, options = {}) {
10
+ const topK = options.topK ?? 8;
11
+ const minScore = options.minScore ?? 0.05;
12
+ const analysis = this.analyzer.analyze(query);
13
+ const results = [];
14
+ for (const memory of memories) {
15
+ if (options.types?.length &&
16
+ !options.types.includes(memory.type)) {
17
+ continue;
18
+ }
19
+ const keyword = this.bm25.score(query, memory);
20
+ const recency = recencyScore(memory);
21
+ const importance = memoryImportanceScore(memory);
22
+ let type = typePriority(memory.type);
23
+ if (analysis.preferredTypes
24
+ .includes(memory.type)) {
25
+ type = Math.min(1, type + 0.25);
26
+ }
27
+ /*
28
+ * Retrieval weighting:
29
+ *
30
+ * keyword 55%
31
+ * importance 20%
32
+ * recency 15%
33
+ * type 10%
34
+ */
35
+ const score = keyword * 0.55 +
36
+ importance * 0.20 +
37
+ recency * 0.15 +
38
+ type * 0.10;
39
+ /*
40
+ * Không cho memory hoàn toàn
41
+ * không liên quan lọt vào chỉ
42
+ * vì recency/importance cao.
43
+ */
44
+ // Keyword query phải có lexical match.
45
+ // Type/recency/importance chỉ dùng để rerank,
46
+ // không được tự kéo memory không liên quan vào Top-K.
47
+ if (keyword <= 0) {
48
+ continue;
49
+ }
50
+ if (score < minScore) {
51
+ continue;
52
+ }
53
+ results.push({
54
+ memory,
55
+ score,
56
+ scores: {
57
+ keyword,
58
+ recency,
59
+ importance,
60
+ type,
61
+ },
62
+ });
63
+ }
64
+ return results
65
+ .sort((a, b) => b.score - a.score)
66
+ .slice(0, topK);
67
+ }
68
+ }
@@ -0,0 +1,16 @@
1
+ import { effectiveImportanceScore, } from "../memory/decay.js";
2
+ const weights = {
3
+ critical: 1,
4
+ high: 0.8,
5
+ normal: 0.5,
6
+ temporary: 0.2,
7
+ };
8
+ export function importanceScore(importance) {
9
+ if (!importance) {
10
+ return 0.3;
11
+ }
12
+ return weights[importance] ?? 0.3;
13
+ }
14
+ export function memoryImportanceScore(memory) {
15
+ return (effectiveImportanceScore(memory) / 100);
16
+ }
@@ -0,0 +1,12 @@
1
+ export * from "./types.js";
2
+ export * from "./tokenizer.js";
3
+ export * from "./bm25.js";
4
+ export * from "./recency.js";
5
+ export * from "./importance.js";
6
+ export * from "./type-priority.js";
7
+ export * from "./query-analyzer.js";
8
+ export * from "./hybrid-search.js";
9
+ export * from "./context-builder.js";
10
+ export * from "./retrieval-engine.js";
11
+ export * from "./vector/index.js";
12
+ export * from "./vector-hybrid-engine.js";
@@ -0,0 +1,32 @@
1
+ export class QueryAnalyzer {
2
+ analyze(query) {
3
+ const text = query.toLowerCase();
4
+ const preferredTypes = [];
5
+ if (text.includes("quyết định") ||
6
+ text.includes("decision") ||
7
+ text.includes("đã chọn")) {
8
+ preferredTypes.push("decision");
9
+ }
10
+ if (text.includes("todo") ||
11
+ text.includes("cần làm") ||
12
+ text.includes("tiếp theo") ||
13
+ text.includes("chưa xong")) {
14
+ preferredTypes.push("todo");
15
+ }
16
+ if (text.includes("quy tắc") ||
17
+ text.includes("rule") ||
18
+ text.includes("không được") ||
19
+ text.includes("bắt buộc")) {
20
+ preferredTypes.push("rule");
21
+ }
22
+ if (text.includes("tóm tắt") ||
23
+ text.includes("summary") ||
24
+ text.includes("đã làm")) {
25
+ preferredTypes.push("summary");
26
+ }
27
+ return {
28
+ query,
29
+ preferredTypes,
30
+ };
31
+ }
32
+ }
@@ -0,0 +1 @@
1
+ export {};
@@ -0,0 +1 @@
1
+ export {};
@@ -0,0 +1,12 @@
1
+ export function recencyScore(memory, now = Date.now()) {
2
+ const raw = memory.updatedAt ??
3
+ memory.createdAt;
4
+ const timestamp = new Date(raw).getTime();
5
+ if (!Number.isFinite(timestamp)) {
6
+ return 0;
7
+ }
8
+ const ageDays = Math.max(0, now - timestamp) /
9
+ 86_400_000;
10
+ // ~50% score sau 30 ngày
11
+ return Math.exp((-Math.LN2 * ageDays) / 30);
12
+ }
@@ -0,0 +1 @@
1
+ export {};
@@ -0,0 +1 @@
1
+ export {};
@@ -0,0 +1,17 @@
1
+ import { HybridSearch, } from "./hybrid-search.js";
2
+ import { ContextBuilder, } from "./context-builder.js";
3
+ export class RetrievalEngine {
4
+ memory;
5
+ searcher = new HybridSearch();
6
+ contextBuilder = new ContextBuilder();
7
+ constructor(memory) {
8
+ this.memory = memory;
9
+ }
10
+ search(projectId, query, options = {}) {
11
+ return this.searcher.search(query, this.memory.list(projectId), options);
12
+ }
13
+ context(projectId, query, options = {}) {
14
+ const results = this.search(projectId, query, options);
15
+ return this.contextBuilder.build(results);
16
+ }
17
+ }
@@ -0,0 +1,9 @@
1
+ export function tokenize(text) {
2
+ return text
3
+ .toLowerCase()
4
+ .normalize("NFKC")
5
+ .replace(/[^\p{L}\p{N}_\-./]+/gu, " ")
6
+ .split(/\s+/)
7
+ .map((token) => token.trim())
8
+ .filter((token) => token.length > 1);
9
+ }
@@ -0,0 +1,10 @@
1
+ const priorities = {
2
+ rule: 1,
3
+ decision: 0.9,
4
+ todo: 0.8,
5
+ summary: 0.6,
6
+ activity: 0.3,
7
+ };
8
+ export function typePriority(type) {
9
+ return priorities[type] ?? 0.4;
10
+ }
@@ -0,0 +1 @@
1
+ export {};
@@ -0,0 +1,4 @@
1
+ export * from "./vector-store.js";
2
+ export * from "./upsert.js";
3
+ export * from "./search.js";
4
+ export * from "./persistence.js";
@@ -0,0 +1 @@
1
+ export {};
@@ -0,0 +1,67 @@
1
+ import { VectorIndexer, } from "./upsert.js";
2
+ export class VectorPersistenceManager {
3
+ projectId;
4
+ model;
5
+ embeddings;
6
+ store;
7
+ persistence;
8
+ constructor(projectId, model, embeddings, store, persistence) {
9
+ this.projectId = projectId;
10
+ this.model = model;
11
+ this.embeddings = embeddings;
12
+ this.store = store;
13
+ this.persistence = persistence;
14
+ }
15
+ async initialize(memories) {
16
+ let loaded = 0;
17
+ const snapshot = await this.persistence.load(this.projectId);
18
+ if (snapshot &&
19
+ snapshot.model ===
20
+ this.model) {
21
+ loaded =
22
+ this.store.importRecords(snapshot.records);
23
+ }
24
+ /*
25
+ * Xóa vector không còn memory tương ứng.
26
+ */
27
+ const validIds = new Set(memories.map((memory) => memory.id));
28
+ let removed = 0;
29
+ for (const record of this.store.exportProject(this.projectId)) {
30
+ if (!validIds.has(record.id)) {
31
+ if (this.store.remove(record.id)) {
32
+ removed++;
33
+ }
34
+ }
35
+ }
36
+ const indexer = new VectorIndexer(this.embeddings, this.store);
37
+ const indexed = await indexer.index(memories);
38
+ const records = this.store.exportProject(this.projectId);
39
+ const dimensions = records[0]
40
+ ?.vector.length ??
41
+ this.embeddings
42
+ .dimensions ??
43
+ 0;
44
+ let saved = false;
45
+ if (indexed > 0 ||
46
+ removed > 0 ||
47
+ !snapshot) {
48
+ await this.persistence.save({
49
+ version: 1,
50
+ projectId: this.projectId,
51
+ model: this.model,
52
+ dimensions,
53
+ updatedAt: new Date()
54
+ .toISOString(),
55
+ records,
56
+ });
57
+ saved = true;
58
+ }
59
+ return {
60
+ loaded,
61
+ indexed,
62
+ removed,
63
+ total: records.length,
64
+ saved,
65
+ };
66
+ }
67
+ }
@@ -0,0 +1,12 @@
1
+ export class VectorSearch {
2
+ embeddings;
3
+ store;
4
+ constructor(embeddings, store) {
5
+ this.embeddings = embeddings;
6
+ this.store = store;
7
+ }
8
+ async search(projectId, query, limit = 10) {
9
+ const vector = await this.embeddings.embed(query);
10
+ return this.store.search(projectId, vector, limit);
11
+ }
12
+ }
@@ -0,0 +1,36 @@
1
+ import "dotenv/config";
2
+ import { MemoryEngine, ProjectManager, loadConfig, } from "../../core/index.js";
3
+ import { createEmbeddingProvider, } from "../../embeddings/index.js";
4
+ import { createStorageProvider, MemoryStore, PersistentVectorStore, ProjectScopedStorageProvider, } from "../../storage/index.js";
5
+ import { VectorPersistenceManager, VectorStore, } from "./index.js";
6
+ async function main() {
7
+ const config = loadConfig();
8
+ const project = new ProjectManager()
9
+ .detect();
10
+ const memory = new MemoryEngine();
11
+ const rawStorage = createStorageProvider({
12
+ provider: config.storage.provider,
13
+ huggingface: config.storage.huggingface,
14
+ localRoot: config.storage.localRoot,
15
+ });
16
+ const storage = new ProjectScopedStorageProvider(rawStorage, project.id, project.name, project.remote ?? project.name);
17
+ const memoryStore = new MemoryStore(storage);
18
+ memory.importRecords(await memoryStore.load(project.id));
19
+ const embeddings = createEmbeddingProvider();
20
+ const vectors = new VectorStore();
21
+ const persistence = new PersistentVectorStore(storage);
22
+ const model = process.env
23
+ .HF_EMBEDDING_MODEL ??
24
+ "sentence-transformers/all-MiniLM-L6-v2";
25
+ const manager = new VectorPersistenceManager(project.id, model, embeddings, vectors, persistence);
26
+ const stats = await manager.initialize(memory.list(project.id));
27
+ console.log({
28
+ ok: true,
29
+ memories: memory.list(project.id).length,
30
+ ...stats,
31
+ });
32
+ }
33
+ main().catch((error) => {
34
+ console.error(error);
35
+ process.exit(1);
36
+ });
@@ -0,0 +1,40 @@
1
+ export class VectorIndexer {
2
+ embeddings;
3
+ store;
4
+ constructor(embeddings, store) {
5
+ this.embeddings = embeddings;
6
+ this.store = store;
7
+ }
8
+ async index(memories) {
9
+ const pending = memories.filter((memory) => !this.store.has(memory.id));
10
+ if (pending.length === 0) {
11
+ return 0;
12
+ }
13
+ const vectors = await this.embeddings
14
+ .embedMany(pending.map((memory) => [
15
+ memory.type,
16
+ memory.content,
17
+ ...(memory.tags ?? []),
18
+ ].join(" ")));
19
+ let indexed = 0;
20
+ for (let i = 0; i < pending.length; i++) {
21
+ const memory = pending[i];
22
+ const vector = vectors[i];
23
+ if (!memory ||
24
+ !vector) {
25
+ continue;
26
+ }
27
+ this.store.upsert({
28
+ id: memory.id,
29
+ projectId: memory.projectId,
30
+ vector,
31
+ metadata: {
32
+ type: memory.type,
33
+ updatedAt: memory.updatedAt,
34
+ },
35
+ });
36
+ indexed++;
37
+ }
38
+ return indexed;
39
+ }
40
+ }