@openchamber/web 1.18.4 → 1.19.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 (207) hide show
  1. package/README.md +1 -0
  2. package/dist/assets/{CodeMirrorCommentWidgets-4qZbrEXU.js → CodeMirrorCommentWidgets-DAvopJvy.js} +1 -1
  3. package/dist/assets/{CommitSection-MJmntVPJ.js → CommitSection-D9cV-qR9.js} +1 -1
  4. package/dist/assets/{DiagramEditor-jnG3Hbxg.js → DiagramEditor-B9NCadU7.js} +1 -1
  5. package/dist/assets/DiagramView-LKGBwf4G.js +1 -0
  6. package/dist/assets/{DiffView-DZIoOnV7.js → DiffView-BWNq-0ov.js} +2 -2
  7. package/dist/assets/FilesView-DB-Q0Gkz.js +14 -0
  8. package/dist/assets/{GitView-DBFrDDBv.js → GitView-DsWXqWx3.js} +3 -3
  9. package/dist/assets/{JsonTreeView-DLW2Wy1g.js → JsonTreeView-h4dHASlq.js} +1 -1
  10. package/dist/assets/MarkdownImageGallery-n0ikH-xm.js +1 -0
  11. package/dist/assets/MarkdownRendererImpl-CT2mjx-s.js +12 -0
  12. package/dist/assets/OnboardingScreen-CDjgzxEe.js +1 -0
  13. package/dist/assets/{PatchDiff-BuLPx7AN.js → PatchDiff-jPKTJje5.js} +1 -1
  14. package/dist/assets/{PierreDiffViewer-BHm4Yr0X.js → PierreDiffViewer-D_Gt4A_6.js} +1 -1
  15. package/dist/assets/PlanView-UvuxIl9-.js +4 -0
  16. package/dist/assets/SessionSwitcherDropdown-xKU4LRuQ.js +1 -0
  17. package/dist/assets/SettingsView-3B9VN6Ys.js +28 -0
  18. package/dist/assets/SettingsWindow-CqQNDKNd.js +1 -0
  19. package/dist/assets/{ToolOutputDialog-Za6V4VMJ.js → ToolOutputDialog-PmjlAxVE.js} +6 -6
  20. package/dist/assets/{ToolPartDiffPreview-BL-9ixyC.js → ToolPartDiffPreview-B34Xw9wq.js} +1 -1
  21. package/dist/assets/{VirtualizedFileDiff-CwGocYQd.js → VirtualizedFileDiff-B37yB9jZ.js} +3 -3
  22. package/dist/assets/{WalkthroughView-5DyvN03T.js → WalkthroughView-Bxun3k66.js} +2 -2
  23. package/dist/assets/{computeVirtualFileMetrics-Da00Jg7M.js → computeVirtualFileMetrics-DYFv_yZS.js} +2 -2
  24. package/dist/assets/contextPanelEmbeddedChat-BO1wRpaN.js +1 -0
  25. package/dist/assets/de-DbV6CLxv.js +9 -0
  26. package/dist/assets/document-attachments-DFAWlG3U.js +31 -0
  27. package/dist/assets/es-CVDlyzZ4.js +15 -0
  28. package/dist/assets/fr-Czc-p0g-.js +13 -0
  29. package/dist/assets/index-1OhiMDBz.css +1 -0
  30. package/dist/assets/index-BSvmTvZl.js +1 -0
  31. package/dist/assets/index-DzriVon2.js +7 -0
  32. package/dist/assets/{isDiffPlainText-D9YpoLrV.js → isDiffPlainText-DwHKxDYc.js} +1 -1
  33. package/dist/assets/{isFilePlainText-gTibdNIe.js → isFilePlainText-Dwq6ILxo.js} +1 -1
  34. package/dist/assets/ja-dwc9NM_S.js +15 -0
  35. package/dist/assets/ko-Ds1DZ8FX.js +15 -0
  36. package/dist/assets/{lua-BgMRiT3U.js → lua-VAEuO923.js} +1 -1
  37. package/dist/assets/main-BF51IOVF.js +921 -0
  38. package/dist/assets/{main-D7UcL3VQ.js → main-D7UPARut.js} +2 -2
  39. package/dist/assets/markdownCore-BgeBDwD3.js +2 -0
  40. package/dist/assets/{miniChat-O_GVoEbc.js → miniChat-BISXSGOo.js} +2 -2
  41. package/dist/assets/mobile-BnYxVuvw.js +2 -0
  42. package/dist/assets/{patchFileDiff-KNkxM1C1.js → patchFileDiff-BEDPDypx.js} +2 -2
  43. package/dist/assets/pl-CLiTO7i-.js +15 -0
  44. package/dist/assets/pt-BR-GIimJgpK.js +15 -0
  45. package/dist/assets/renderElectronMiniChatApp-BaOy72Gi.js +2 -0
  46. package/dist/assets/{renderMobileApp-toj9cXoh.js → renderMobileApp-BiMbzPq9.js} +7 -7
  47. package/dist/assets/runtimeEndpointReset-BMBRhIbf.js +15 -0
  48. package/dist/assets/scheduledTasksApi-01zzfzqH.js +1 -0
  49. package/dist/assets/{shikiHighlight-C7LTbwFx.js → shikiHighlight-DXYW46vW.js} +1 -1
  50. package/dist/assets/uk-DLfgD1ki.js +15 -0
  51. package/dist/assets/{useAppFontEffects-BikB6enL.js → useAppFontEffects-CbzHzFop.js} +139 -142
  52. package/dist/assets/{useInlineCommentController-CYPvYJDt.js → useInlineCommentController-CegKdDXi.js} +2 -2
  53. package/dist/assets/{vendor-base-ui-D_V6hAcE.js → vendor-base-ui-BYlZTzrw.js} +1 -1
  54. package/dist/assets/vendor-codemirror-autocomplete-DzPz9Wgq.js +1 -0
  55. package/dist/assets/vendor-codemirror-commands-B7H_j0iU.js +1 -0
  56. package/dist/assets/{vendor-codemirror-lang-angular-CgY7_gQ1.js → vendor-codemirror-lang-angular-DEPs2M5t.js} +1 -1
  57. package/dist/assets/{vendor-codemirror-lang-cpp-B5Ta4enQ.js → vendor-codemirror-lang-cpp-DhkseaMo.js} +1 -1
  58. package/dist/assets/{vendor-codemirror-lang-css-VgNqFSH-.js → vendor-codemirror-lang-css-O0cZX78y.js} +1 -1
  59. package/dist/assets/{vendor-codemirror-lang-go-LxLz62pp.js → vendor-codemirror-lang-go-fMdQYcON.js} +1 -1
  60. package/dist/assets/vendor-codemirror-lang-html-CfgK872x.js +1 -0
  61. package/dist/assets/{vendor-codemirror-lang-java-Bksi1PH4.js → vendor-codemirror-lang-java-CQj4S3zl.js} +1 -1
  62. package/dist/assets/vendor-codemirror-lang-javascript-Cc2ZYbgX.js +13 -0
  63. package/dist/assets/{vendor-codemirror-lang-jinja-C7npuDD7.js → vendor-codemirror-lang-jinja-BmZZv8g-.js} +1 -1
  64. package/dist/assets/{vendor-codemirror-lang-json-ryCw7nab.js → vendor-codemirror-lang-json-CMBS2tG9.js} +1 -1
  65. package/dist/assets/{vendor-codemirror-lang-less-BxsZJD6N.js → vendor-codemirror-lang-less-C6Eo8hVS.js} +1 -1
  66. package/dist/assets/{vendor-codemirror-lang-liquid-De6qch10.js → vendor-codemirror-lang-liquid-DSTR47-H.js} +1 -1
  67. package/dist/assets/vendor-codemirror-lang-markdown-BPGOH9ye.js +1 -0
  68. package/dist/assets/{vendor-codemirror-lang-php-Cm1es33p.js → vendor-codemirror-lang-php-DD9udfPH.js} +1 -1
  69. package/dist/assets/{vendor-codemirror-lang-python-N414WYK-.js → vendor-codemirror-lang-python-HahnQaAS.js} +1 -1
  70. package/dist/assets/{vendor-codemirror-lang-rust-C_WuUStH.js → vendor-codemirror-lang-rust-nLTovbjv.js} +1 -1
  71. package/dist/assets/{vendor-codemirror-lang-sass-8UHTCAOM.js → vendor-codemirror-lang-sass-pL2Yc72v.js} +1 -1
  72. package/dist/assets/{vendor-codemirror-lang-sql-CV3sMA5D.js → vendor-codemirror-lang-sql-BVBnan19.js} +1 -1
  73. package/dist/assets/{vendor-codemirror-lang-vue-DzvC1Dhk.js → vendor-codemirror-lang-vue-BqGzJVm1.js} +1 -1
  74. package/dist/assets/{vendor-codemirror-lang-wast-jlr-LDdA.js → vendor-codemirror-lang-wast-B0_m5DqU.js} +1 -1
  75. package/dist/assets/{vendor-codemirror-lang-xml-CrO63OVp.js → vendor-codemirror-lang-xml-Dj3voadT.js} +1 -1
  76. package/dist/assets/{vendor-codemirror-lang-yaml-dxi6CISW.js → vendor-codemirror-lang-yaml-yu-9Z5u7.js} +1 -1
  77. package/dist/assets/vendor-codemirror-language-BgPj_McA.js +3 -0
  78. package/dist/assets/{vendor-codemirror-language-data-CLHw8NWn.js → vendor-codemirror-language-data-CiAYDJXN.js} +2 -2
  79. package/dist/assets/vendor-codemirror-search-BmS-GmcX.js +2 -0
  80. package/dist/assets/{vendor-codemirror-state-CNWM3Q8V.js → vendor-codemirror-state-C9awkmn-.js} +5 -5
  81. package/dist/assets/vendor-codemirror-view-CiLROUVV.js +4 -0
  82. package/dist/assets/vendor-replit-codemirror-vim-B2DJlAhT.js +6 -0
  83. package/dist/assets/vendor-replit-codemirror-vim-core-FHzKdNUS.js +34 -0
  84. package/dist/assets/vendor-zod-adaMkgkm.js +39 -0
  85. package/dist/assets/{web-components-GMc3oR3i.js → web-components-DCLjCO9n.js} +1 -1
  86. package/dist/assets/zh-CN-DkeP5awK.js +15 -0
  87. package/dist/assets/zh-TW-BocaFm3d.js +15 -0
  88. package/dist/index.html +4 -4
  89. package/dist/mini-chat.html +3 -3
  90. package/dist/mobile.html +3 -3
  91. package/package.json +1 -1
  92. package/server/index.js +116 -3
  93. package/server/lib/agent-memory/actions.js +243 -0
  94. package/server/lib/agent-memory/actions.test.js +343 -0
  95. package/server/lib/agent-memory/feature-flag.js +19 -0
  96. package/server/lib/agent-memory/feature-flag.test.js +38 -0
  97. package/server/lib/agent-memory/project-resolution.js +56 -0
  98. package/server/lib/agent-memory/project-resolution.test.js +85 -0
  99. package/server/lib/agent-memory/routes.http.test.js +270 -0
  100. package/server/lib/agent-memory/routes.js +169 -0
  101. package/server/lib/agent-memory/runtime.js +427 -0
  102. package/server/lib/agent-memory/runtime.test.js +344 -0
  103. package/server/lib/agent-memory/threat-patterns.js +61 -0
  104. package/server/lib/agent-memory/threat-patterns.test.js +61 -0
  105. package/server/lib/agent-tool/DOCUMENTATION.md +14 -0
  106. package/server/lib/agent-tool/runtime.js +63 -13
  107. package/server/lib/agent-tool/runtime.test.js +85 -2
  108. package/server/lib/context-obligatory/runtime.js +34 -3
  109. package/server/lib/context-obligatory/runtime.test.js +114 -0
  110. package/server/lib/fs/DOCUMENTATION.md +3 -0
  111. package/server/lib/fs/routes.js +149 -32
  112. package/server/lib/fs/routes.test.js +225 -0
  113. package/server/lib/git/DOCUMENTATION.md +8 -0
  114. package/server/lib/git/service.js +121 -67
  115. package/server/lib/git/service.test.js +129 -0
  116. package/server/lib/github/DOCUMENTATION.md +14 -3
  117. package/server/lib/github/pr-status.js +188 -83
  118. package/server/lib/github/pr-status.test.js +182 -0
  119. package/server/lib/github/routes.js +36 -30
  120. package/server/lib/notifications/template-runtime.js +2 -3
  121. package/server/lib/openchamber-control/action-resolution.test.js +65 -0
  122. package/server/lib/openchamber-control/actions.js +78 -0
  123. package/server/lib/openchamber-control/service.js +7 -0
  124. package/server/lib/openchamber-sessions/routes.js +14 -0
  125. package/server/lib/opencode/DOCUMENTATION.md +6 -4
  126. package/server/lib/opencode/claude-cli-auth.js +60 -0
  127. package/server/lib/opencode/claude-cli-auth.test.js +54 -0
  128. package/server/lib/opencode/feature-routes-runtime.js +11 -0
  129. package/server/lib/opencode/plugins.js +12 -3
  130. package/server/lib/opencode/plugins.test.js +18 -0
  131. package/server/lib/opencode/proxy-agent-wiring.test.js +152 -0
  132. package/server/lib/opencode/proxy.js +116 -6
  133. package/server/lib/opencode/proxy.test.js +158 -1
  134. package/server/lib/opencode/routes.js +4 -1
  135. package/server/lib/opencode/settings-helpers.js +11 -0
  136. package/server/lib/opencode/settings-helpers.test.js +35 -0
  137. package/server/lib/opencode/settings-runtime.js +51 -0
  138. package/server/lib/opencode/shared.js +120 -16
  139. package/server/lib/opencode/shared.test.js +185 -1
  140. package/server/lib/project-context/DOCUMENTATION.md +158 -0
  141. package/server/lib/project-context/routes.http.test.js +264 -0
  142. package/server/lib/project-context/routes.js +237 -0
  143. package/server/lib/project-context/runtime.js +667 -0
  144. package/server/lib/project-context/runtime.test.js +498 -0
  145. package/server/lib/quota/DOCUMENTATION.md +16 -1
  146. package/server/lib/quota/providers/claude/auth.js +113 -0
  147. package/server/lib/quota/providers/claude/auth.test.js +117 -0
  148. package/server/lib/quota/providers/claude/index.js +151 -0
  149. package/server/lib/quota/providers/claude/index.test.js +147 -0
  150. package/server/lib/quota/providers/claude/transforms.js +127 -0
  151. package/server/lib/quota/providers/claude/transforms.test.js +82 -0
  152. package/server/lib/quota/providers/command-code.js +90 -0
  153. package/server/lib/quota/providers/command-code.test.js +72 -0
  154. package/server/lib/quota/providers/index.js +22 -2
  155. package/server/lib/quota/providers/index.test.js +10 -1
  156. package/server/lib/quota/utils/formatters.js +2 -1
  157. package/server/lib/scheduled-tasks/runtime.js +21 -2
  158. package/server/lib/session-knowledge/DOCUMENTATION.md +87 -0
  159. package/server/lib/session-knowledge/routes.js +107 -0
  160. package/server/lib/session-knowledge/runtime.js +331 -0
  161. package/server/lib/session-knowledge/runtime.test.js +275 -0
  162. package/server/lib/skills-catalog/DOCUMENTATION.md +22 -22
  163. package/server/lib/skills-catalog/curated-sources.js +1 -1
  164. package/server/lib/skills-catalog/curated-sources.test.js +10 -0
  165. package/server/lib/small-model/index.js +8 -0
  166. package/server/lib/small-model/index.test.js +31 -1
  167. package/server/lib/small-model/routes.js +3 -1
  168. package/dist/assets/DiagramView-CFXxgg_a.js +0 -1
  169. package/dist/assets/FilesView-BKL6YlKG.js +0 -14
  170. package/dist/assets/MarkdownImageGallery-DKIylIK7.js +0 -1
  171. package/dist/assets/MarkdownRendererImpl-CLv8hxvv.js +0 -12
  172. package/dist/assets/OnboardingScreen-D2Y6djMw.js +0 -1
  173. package/dist/assets/PlanView-ZYEJn8A_.js +0 -4
  174. package/dist/assets/SessionSwitcherDropdown-rro-SsaO.js +0 -1
  175. package/dist/assets/SettingsView-5RmswFZe.js +0 -28
  176. package/dist/assets/SettingsWindow-BZhAYFdS.js +0 -1
  177. package/dist/assets/contextPanelEmbeddedChat-B-bSg3P5.js +0 -1
  178. package/dist/assets/de-u7gSnqWs.js +0 -9
  179. package/dist/assets/document-attachments-CX_YaDsu.js +0 -30
  180. package/dist/assets/es-T9O7aAOr.js +0 -15
  181. package/dist/assets/fr-Oor7ewbE.js +0 -13
  182. package/dist/assets/index-BzIpNlNE.css +0 -1
  183. package/dist/assets/index-C0yNhuZw.js +0 -1
  184. package/dist/assets/index-DRpChWux.js +0 -7
  185. package/dist/assets/ja-DHpqbVmr.js +0 -15
  186. package/dist/assets/ko-CwLkS3nx.js +0 -15
  187. package/dist/assets/main-DPMd2iKS.js +0 -915
  188. package/dist/assets/markdownCore-DDrHVneM.js +0 -2
  189. package/dist/assets/mobile-Br4TtAqc.js +0 -2
  190. package/dist/assets/pl-CcZILN8q.js +0 -15
  191. package/dist/assets/pt-BR-DYHhVK6o.js +0 -15
  192. package/dist/assets/renderElectronMiniChatApp-CJpdxTT1.js +0 -2
  193. package/dist/assets/runtimeEndpointReset-BVmispdD.js +0 -13
  194. package/dist/assets/scheduledTasksApi-ByKya3Un.js +0 -1
  195. package/dist/assets/uk-BA2kZR38.js +0 -15
  196. package/dist/assets/vendor-codemirror-autocomplete-BjbBRsUA.js +0 -1
  197. package/dist/assets/vendor-codemirror-commands-ARAOgp1x.js +0 -1
  198. package/dist/assets/vendor-codemirror-lang-html-B3Qe3OpS.js +0 -1
  199. package/dist/assets/vendor-codemirror-lang-javascript-Bbw3D7r0.js +0 -13
  200. package/dist/assets/vendor-codemirror-lang-markdown-FGQydhTc.js +0 -1
  201. package/dist/assets/vendor-codemirror-language-DUOssd4j.js +0 -3
  202. package/dist/assets/vendor-codemirror-search-8kyQdB3f.js +0 -2
  203. package/dist/assets/vendor-codemirror-view-DSzLbZiS.js +0 -4
  204. package/dist/assets/vendor-replit-codemirror-vim-B0Ecqnlh.js +0 -39
  205. package/dist/assets/zh-CN-dlOQK6v9.js +0 -15
  206. package/dist/assets/zh-TW-BnqQ-WL5.js +0 -15
  207. package/server/lib/quota/providers/claude.js +0 -107
@@ -0,0 +1,427 @@
1
+ /**
2
+ * Agent memory storage.
3
+ *
4
+ * What the agent has learned and chose to keep, in two scopes:
5
+ *
6
+ * - **project** — `<projectsDir>/<projectId>/memory.json`. How this codebase
7
+ * works, what was decided, where things live.
8
+ * - **global** — `<userConfigRoot>/memory.json`. Who the user is and how they
9
+ * want to be worked with. It belongs to no project, so it cannot live under
10
+ * one.
11
+ *
12
+ * The split is not cosmetic. A wrong project fact costs one project and is
13
+ * noticed quickly; a wrong global fact quietly shapes every session in every
14
+ * project, and the user has no code to check it against. Global memory is
15
+ * therefore deliberately narrower: fewer entries, and only the types that
16
+ * genuinely have no other home.
17
+ *
18
+ * This is NOT the notes surface. Notes are what the user writes for themselves
19
+ * and hands to the agent by pinning; memory is what the agent writes for
20
+ * itself. Keeping them apart keeps an agent mistake out of the user's notes.
21
+ *
22
+ * Because the agent writes here unprompted, two invariants guard the store:
23
+ *
24
+ * - **Restatements replace.** A memory the agent phrases differently the second
25
+ * time supersedes the first rather than sitting beside it, so the store
26
+ * cannot fill with variants of one fact that later disagree.
27
+ * - **Timestamps are the record of change.** The panel derives "new" and
28
+ * "changed" from `createdAt` and `updatedAt` against when the user last
29
+ * looked, so what the agent stored without asking stays visible without the
30
+ * store carrying any review state of its own.
31
+ */
32
+
33
+ const MEMORY_VERSION = 1;
34
+
35
+ /**
36
+ * Titles are what every session carries, so their combined length is the
37
+ * standing cost of memory. Short enough to keep a full store's index modest,
38
+ * long enough to say what an entry is about.
39
+ */
40
+ const MEMORY_TITLE_MAX_LENGTH = 60;
41
+ const MEMORY_BODY_MAX_LENGTH = 2000;
42
+
43
+ /** Global memory stays small on purpose: it is the highest-blast-radius store. */
44
+ const GLOBAL_MEMORY_MAX_ITEMS = 60;
45
+ const PROJECT_MEMORY_MAX_ITEMS = 200;
46
+
47
+ /**
48
+ * `fact` — something true about the project or the user.
49
+ * `preference` — how the user wants work done.
50
+ * `reference` — a pointer to a resource that is hard to rediscover.
51
+ */
52
+ const MEMORY_TYPES = new Set(['fact', 'preference', 'reference']);
53
+
54
+ import { findThreatPattern } from './threat-patterns.js';
55
+
56
+ const PROJECT_ID_PATTERN = /^[a-zA-Z0-9._:-]+$/;
57
+
58
+ /**
59
+ * Two entries are the same memory when this much of the incoming one is already
60
+ * in the stored one. Set high on purpose: merging two genuinely different
61
+ * memories destroys one of them silently, which is far worse than keeping a
62
+ * near-duplicate the user can see and delete.
63
+ */
64
+ const DUPLICATE_OVERLAP_THRESHOLD = 0.75;
65
+
66
+ /**
67
+ * Below this many meaningful words, overlap is noise — "use bun" and "use npm"
68
+ * share half their tokens. Short entries fall back to exact-title matching.
69
+ */
70
+ const DUPLICATE_MIN_TOKENS = 4;
71
+
72
+ /**
73
+ * Words carried by almost every sentence, so their overlap says nothing about
74
+ * whether two memories mean the same thing.
75
+ */
76
+ const STOP_WORDS = new Set([
77
+ 'a', 'an', 'and', 'are', 'as', 'at', 'be', 'but', 'by', 'for', 'from', 'has',
78
+ 'have', 'in', 'into', 'is', 'it', 'its', 'not', 'of', 'on', 'or', 'that',
79
+ 'the', 'their', 'them', 'they', 'this', 'to', 'was', 'were', 'when', 'with',
80
+ ]);
81
+
82
+ const tokenize = (value) => {
83
+ const tokens = new Set();
84
+ for (const raw of String(value).toLowerCase().split(/[^\p{L}\p{N}]+/u)) {
85
+ if (raw.length < 3 || STOP_WORDS.has(raw)) continue;
86
+ tokens.add(raw);
87
+ }
88
+ return tokens;
89
+ };
90
+
91
+ /** How much of `incoming` is already present in `existing`, in `[0, 1]`. */
92
+ const overlapFraction = (incoming, existing) => {
93
+ if (incoming.size === 0) return 0;
94
+ let shared = 0;
95
+ for (const token of incoming) {
96
+ if (existing.has(token)) shared += 1;
97
+ }
98
+ return shared / incoming.size;
99
+ };
100
+
101
+ /**
102
+ * The stored entry a new one should replace, or null for a genuinely new
103
+ * memory.
104
+ *
105
+ * Exact title match alone is not enough: an agent that re-learns the same fact
106
+ * phrases it differently each time ("run UI tests per file" / "UI tests must be
107
+ * run one file at a time"), and storing both leaves the two free to drift apart
108
+ * until they contradict each other. Comparing the wording catches the restated
109
+ * duplicate that the title check misses.
110
+ */
111
+ const findSupersededEntry = (entries, title, body) => {
112
+ const lowerTitle = title.toLowerCase();
113
+ const exact = entries.find((entry) => entry.title.toLowerCase() === lowerTitle);
114
+ if (exact) return exact;
115
+
116
+ const incoming = tokenize(`${title} ${body}`);
117
+ if (incoming.size < DUPLICATE_MIN_TOKENS) return null;
118
+
119
+ let best = null;
120
+ let bestScore = 0;
121
+ for (const entry of entries) {
122
+ const score = overlapFraction(incoming, tokenize(`${entry.title} ${entry.body}`));
123
+ if (score >= DUPLICATE_OVERLAP_THRESHOLD && score > bestScore) {
124
+ best = entry;
125
+ bestScore = score;
126
+ }
127
+ }
128
+ return best;
129
+ };
130
+
131
+ const asNonEmptyString = (value) => {
132
+ if (typeof value !== 'string') return null;
133
+ const trimmed = value.trim();
134
+ return trimmed.length > 0 ? trimmed : null;
135
+ };
136
+
137
+ const clampLength = (value, maxLength) => {
138
+ if (typeof value !== 'string') return '';
139
+ return value.length > maxLength ? value.slice(0, maxLength) : value;
140
+ };
141
+
142
+ const isObjectRecord = (value) => Boolean(value) && typeof value === 'object' && !Array.isArray(value);
143
+
144
+ const limitForScope = (scope) => (scope === 'global' ? GLOBAL_MEMORY_MAX_ITEMS : PROJECT_MEMORY_MAX_ITEMS);
145
+
146
+ const sanitizeEntries = (value, now, scope) => {
147
+ if (!Array.isArray(value)) return [];
148
+
149
+ const result = [];
150
+ const seen = new Set();
151
+ for (const entry of value) {
152
+ if (result.length >= limitForScope(scope)) break;
153
+ if (!isObjectRecord(entry)) continue;
154
+
155
+ const id = asNonEmptyString(entry.id);
156
+ const title = clampLength(asNonEmptyString(entry.title) || '', MEMORY_TITLE_MAX_LENGTH);
157
+ const body = clampLength(typeof entry.body === 'string' ? entry.body : '', MEMORY_BODY_MAX_LENGTH).trim();
158
+ if (!id || !title || !body || seen.has(id)) continue;
159
+ seen.add(id);
160
+
161
+ const createdAt = Number.isFinite(entry.createdAt) && entry.createdAt >= 0 ? entry.createdAt : now;
162
+ const sessionId = asNonEmptyString(entry.sessionId);
163
+ result.push({
164
+ id,
165
+ title,
166
+ body,
167
+ type: MEMORY_TYPES.has(entry.type) ? entry.type : 'fact',
168
+ createdAt,
169
+ updatedAt: Number.isFinite(entry.updatedAt) && entry.updatedAt >= 0 ? entry.updatedAt : createdAt,
170
+ // Re-checked on every read, not trusted from the file: an entry written
171
+ // before a pattern existed, or edited on disk since, is judged now.
172
+ ...(findThreatPattern(`${title}\n${body}`) ? { flagged: true } : {}),
173
+ ...(sessionId ? { sessionId } : {}),
174
+ });
175
+ }
176
+
177
+ return result.sort((a, b) => b.updatedAt - a.updatedAt);
178
+ };
179
+
180
+ const createEmptyMemory = () => ({ version: MEMORY_VERSION, entries: [] });
181
+
182
+ export const createAgentMemoryRuntime = (deps) => {
183
+ const { fsPromises, path, projectsDirPath, userConfigRoot, createId } = deps;
184
+
185
+ const idFactory = typeof createId === 'function'
186
+ ? createId
187
+ : () => (typeof crypto !== 'undefined' && typeof crypto.randomUUID === 'function'
188
+ ? crypto.randomUUID()
189
+ : `mem_${Date.now()}_${Math.random().toString(36).slice(2, 10)}`);
190
+
191
+ const writeLocks = new Map();
192
+
193
+ const sanitizeProjectId = (projectId) => {
194
+ const value = asNonEmptyString(projectId);
195
+ if (!value) {
196
+ throw new Error('projectId is required');
197
+ }
198
+ if (!PROJECT_ID_PATTERN.test(value)) {
199
+ throw new Error('projectId contains unsupported characters');
200
+ }
201
+ return value;
202
+ };
203
+
204
+ /** `target` is `{ scope: 'global' }` or `{ scope: 'project', projectId }`. */
205
+ const resolveTarget = (target) => {
206
+ if (target?.scope === 'global') {
207
+ return { scope: 'global', key: 'global', filePath: path.join(userConfigRoot, 'memory.json') };
208
+ }
209
+ if (target?.scope === 'project') {
210
+ const projectId = sanitizeProjectId(target.projectId);
211
+ return {
212
+ scope: 'project',
213
+ key: `project:${projectId}`,
214
+ filePath: path.join(projectsDirPath, projectId, 'memory.json'),
215
+ };
216
+ }
217
+ throw new Error('scope is required');
218
+ };
219
+
220
+ const readJson = async (filePath) => {
221
+ let raw;
222
+ try {
223
+ raw = await fsPromises.readFile(filePath, 'utf8');
224
+ } catch (error) {
225
+ if (error && error.code === 'ENOENT') return { missing: true, value: null };
226
+ throw error;
227
+ }
228
+ try {
229
+ const parsed = JSON.parse(raw);
230
+ return { missing: false, value: isObjectRecord(parsed) ? parsed : null };
231
+ } catch {
232
+ return { missing: false, value: null };
233
+ }
234
+ };
235
+
236
+ const writeJsonAtomic = async (filePath, value) => {
237
+ const temporaryPath = `${filePath}.tmp-${process.pid}-${Date.now()}-${Math.random().toString(16).slice(2)}`;
238
+ await fsPromises.mkdir(path.dirname(filePath), { recursive: true });
239
+ await fsPromises.writeFile(temporaryPath, JSON.stringify(value, null, 2), 'utf8');
240
+ await fsPromises.rename(temporaryPath, filePath);
241
+ };
242
+
243
+ const withWriteLock = async (key, mutate) => {
244
+ const previous = writeLocks.get(key) || Promise.resolve();
245
+ let release;
246
+ const next = new Promise((resolve) => { release = resolve; });
247
+ const chained = previous.finally(() => next);
248
+ writeLocks.set(key, chained);
249
+
250
+ await previous;
251
+ try {
252
+ return await mutate();
253
+ } finally {
254
+ release();
255
+ if (writeLocks.get(key) === chained) {
256
+ writeLocks.delete(key);
257
+ }
258
+ }
259
+ };
260
+
261
+ /**
262
+ * Missing is authoritative empty; malformed is a failure. An agent that reads
263
+ * "no memory" from a corrupt file would cheerfully rewrite everything it
264
+ * thought it had lost.
265
+ */
266
+ const read = async (target) => {
267
+ const resolved = resolveTarget(target);
268
+ const stored = await readJson(resolved.filePath);
269
+
270
+ if (!stored.missing && !stored.value) {
271
+ throw new Error('Stored agent memory is malformed');
272
+ }
273
+ if (stored.missing) {
274
+ return createEmptyMemory();
275
+ }
276
+
277
+ return {
278
+ version: MEMORY_VERSION,
279
+ entries: sanitizeEntries(stored.value.entries, Date.now(), resolved.scope),
280
+ };
281
+ };
282
+
283
+ const write = async (resolved, entries) => {
284
+ await writeJsonAtomic(resolved.filePath, { version: MEMORY_VERSION, entries });
285
+ };
286
+
287
+ const create = async (target, value) => {
288
+ const resolved = resolveTarget(target);
289
+ const title = clampLength(asNonEmptyString(value?.title) || '', MEMORY_TITLE_MAX_LENGTH);
290
+ const body = clampLength(typeof value?.body === 'string' ? value.body : '', MEMORY_BODY_MAX_LENGTH).trim();
291
+ if (!title) throw new Error('title is required');
292
+ if (!body) throw new Error('body is required');
293
+
294
+ return withWriteLock(resolved.key, async () => {
295
+ const now = Date.now();
296
+ const current = await read(target);
297
+
298
+ // A restatement of something already stored is an update, not a second
299
+ // copy: an agent re-learning a fact each session would otherwise fill the
300
+ // store with near-duplicates and contradict itself.
301
+ //
302
+ // Checked before the capacity limit, because replacing an entry does not
303
+ // grow the store — a full store must still be able to correct itself.
304
+ const existing = findSupersededEntry(current.entries, title, body);
305
+ if (existing) {
306
+ const updated = {
307
+ ...existing,
308
+ title,
309
+ body,
310
+ updatedAt: now,
311
+ ...(MEMORY_TYPES.has(value?.type) ? { type: value.type } : {}),
312
+ };
313
+ const entries = current.entries.map((entry) => (entry.id === existing.id ? updated : entry));
314
+ await write(resolved, entries);
315
+ return { entry: updated, entries, replaced: true };
316
+ }
317
+
318
+ const limit = limitForScope(resolved.scope);
319
+ if (current.entries.length >= limit) {
320
+ // Handed its own titles and told what to do with them. A bare "full"
321
+ // leaves the agent with a dead end, when the useful move — merge the
322
+ // overlapping entries, drop the stale ones, then retry — is something
323
+ // only it can judge.
324
+ const titles = current.entries.map((entry) => `- ${entry.title}`).join('\n');
325
+ throw new Error(
326
+ `${resolved.scope} memory is full (${current.entries.length}/${limit} entries). `
327
+ + 'Consolidate before saving anything else: merge overlapping entries by saving one '
328
+ + 'under an existing title, and delete what is stale or wrong. Then retry this save, '
329
+ + `all in this turn. Current entries:\n${titles}`,
330
+ );
331
+ }
332
+
333
+ const sessionId = asNonEmptyString(value?.sessionId);
334
+ const entry = {
335
+ id: idFactory(),
336
+ title,
337
+ body,
338
+ type: MEMORY_TYPES.has(value?.type) ? value.type : 'fact',
339
+ createdAt: now,
340
+ updatedAt: now,
341
+ ...(findThreatPattern(`${title}\n${body}`) ? { flagged: true } : {}),
342
+ ...(sessionId ? { sessionId } : {}),
343
+ };
344
+ const entries = [entry, ...current.entries];
345
+ await write(resolved, entries);
346
+ return { entry, entries, replaced: false };
347
+ });
348
+ };
349
+
350
+ /**
351
+ * A user correction. The agent rewrites by saving the same memory again, so
352
+ * this exists for the panel: a memory worded badly enough to mislead should
353
+ * be fixable where it is read, not only deletable.
354
+ */
355
+ const update = async (target, memoryId, patch) => {
356
+ const resolved = resolveTarget(target);
357
+ const id = asNonEmptyString(memoryId);
358
+ if (!id) throw new Error('memoryId is required');
359
+
360
+ const hasTitle = typeof patch?.title === 'string';
361
+ const hasBody = typeof patch?.body === 'string';
362
+ const hasType = MEMORY_TYPES.has(patch?.type);
363
+ if (!hasTitle && !hasBody && !hasType) {
364
+ throw new Error('title, body or type is required');
365
+ }
366
+ const title = hasTitle ? clampLength(patch.title, MEMORY_TITLE_MAX_LENGTH).trim() : null;
367
+ const body = hasBody ? clampLength(patch.body, MEMORY_BODY_MAX_LENGTH).trim() : null;
368
+ if (hasTitle && !title) throw new Error('title is required');
369
+ if (hasBody && !body) throw new Error('body is required');
370
+
371
+ return withWriteLock(resolved.key, async () => {
372
+ const current = await read(target);
373
+ const existing = current.entries.find((entry) => entry.id === id);
374
+ if (!existing) {
375
+ return null;
376
+ }
377
+
378
+ const updated = {
379
+ ...existing,
380
+ ...(hasTitle ? { title } : {}),
381
+ ...(hasBody ? { body } : {}),
382
+ ...(hasType ? { type: patch.type } : {}),
383
+ updatedAt: Date.now(),
384
+ };
385
+ const entries = current.entries.map((entry) => (entry.id === id ? updated : entry));
386
+ await write(resolved, entries);
387
+ return { entry: updated, entries };
388
+ });
389
+ };
390
+
391
+ const remove = async (target, memoryId) => {
392
+ const resolved = resolveTarget(target);
393
+ const id = asNonEmptyString(memoryId);
394
+ if (!id) throw new Error('memoryId is required');
395
+
396
+ return withWriteLock(resolved.key, async () => {
397
+ const current = await read(target);
398
+ if (!current.entries.some((entry) => entry.id === id)) {
399
+ return { deleted: false, entries: current.entries };
400
+ }
401
+ const entries = current.entries.filter((entry) => entry.id !== id);
402
+ await write(resolved, entries);
403
+ return { deleted: true, entries };
404
+ });
405
+ };
406
+
407
+ /**
408
+ * Both scopes at once, for the session index. A failure in one scope must not
409
+ * hide the other: losing the project half should not also erase what the
410
+ * agent knows about the user.
411
+ */
412
+ const readAll = async (projectId) => {
413
+ const settled = await Promise.allSettled([
414
+ read({ scope: 'global' }),
415
+ projectId ? read({ scope: 'project', projectId }) : Promise.resolve(createEmptyMemory()),
416
+ ]);
417
+
418
+ return {
419
+ global: settled[0].status === 'fulfilled' ? settled[0].value.entries : [],
420
+ project: settled[1].status === 'fulfilled' ? settled[1].value.entries : [],
421
+ globalFailed: settled[0].status === 'rejected',
422
+ projectFailed: settled[1].status === 'rejected',
423
+ };
424
+ };
425
+
426
+ return { read, readAll, create, update, remove, resolveTarget };
427
+ };