@modusensus/dsh-mneme 0.6.7 → 0.6.9

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 (139) hide show
  1. package/.github/workflows/test.yml +32 -0
  2. package/.release-notes-v0.6.9.md +13 -0
  3. package/CHANGELOG.md +89 -0
  4. package/LICENSE +21 -21
  5. package/README.md +219 -463
  6. package/SECURITY.md +544 -0
  7. package/docs/devlog/2026-08-14-dsh-mneme-dev-log.md +247 -0
  8. package/docs/devlog/2026-08-15-dsh-mneme-audit-stress-dev-log.md +145 -0
  9. package/docs/devlog/2026-08-15-dsh-mneme-pipeline-dev-log.md +56 -0
  10. package/docs/devlog/2026-08-15-dsh-mneme-reflection-dev-log.md +77 -0
  11. package/docs/devlog/2026-08-15-dsh-mneme-review-fixes-dev-log.md +64 -0
  12. package/docs/devlog/2026-08-15-dsh-mneme-semantic-dev-log.md +90 -0
  13. package/dsh-mneme/CHANGELOG.md +248 -0
  14. package/dsh-mneme/LICENSE +21 -0
  15. package/dsh-mneme/README.md +465 -0
  16. package/{cordis.patch.yml → dsh-mneme/cordis.patch.yml} +15 -15
  17. package/dsh-mneme/docs/AGENT_MEMORY_RESEARCH.md +183 -0
  18. package/dsh-mneme/docs/ENTITIES.md +245 -0
  19. package/dsh-mneme/docs/LOCAL_MODEL.md +141 -0
  20. package/dsh-mneme/docs/MIGRATION.md +127 -0
  21. package/dsh-mneme/docs/SEMANTIC.md +256 -0
  22. package/dsh-mneme/docs/SLEEP.md +163 -0
  23. package/{lib → dsh-mneme/lib}/api.js +783 -783
  24. package/{lib → dsh-mneme/lib}/client.js +1757 -1757
  25. package/{src → dsh-mneme/lib}/commands.js +64 -64
  26. package/{lib → dsh-mneme/lib}/config.js +298 -288
  27. package/{lib → dsh-mneme/lib}/dream/clustering.js +118 -118
  28. package/{src → dsh-mneme/lib}/dream/decisions.js +488 -439
  29. package/{lib → dsh-mneme/lib}/dream/sleep.js +561 -554
  30. package/{src → dsh-mneme/lib}/dream/tag-extractor.js +156 -156
  31. package/{lib → dsh-mneme/lib}/dream.js +958 -929
  32. package/{src → dsh-mneme/lib}/embedding.js +154 -154
  33. package/{src → dsh-mneme/lib}/entities/extractor.js +242 -242
  34. package/{src → dsh-mneme/lib}/hot-memory.js +53 -53
  35. package/{lib → dsh-mneme/lib}/index.js +361 -361
  36. package/{src → dsh-mneme/lib}/inject.js +208 -208
  37. package/{lib → dsh-mneme/lib}/local-embedder.js +282 -282
  38. package/{lib → dsh-mneme/lib}/mirror.js +170 -170
  39. package/{lib → dsh-mneme/lib}/parser/tag.js +59 -59
  40. package/{lib → dsh-mneme/lib}/parser/wiki-link.js +38 -38
  41. package/{src → dsh-mneme/lib}/quality-filter.js +123 -123
  42. package/{lib → dsh-mneme/lib}/reranker.js +218 -218
  43. package/{lib → dsh-mneme/lib}/search/adaptive.js +22 -22
  44. package/{lib → dsh-mneme/lib}/search/bm25.js +96 -96
  45. package/{src → dsh-mneme/lib}/search/tag-boost.js +61 -61
  46. package/{src → dsh-mneme/lib}/service.js +1726 -1726
  47. package/{lib → dsh-mneme/lib}/settings.js +172 -172
  48. package/{lib → dsh-mneme/lib}/store.js +2238 -2238
  49. package/{lib → dsh-mneme/lib}/summarize.js +236 -236
  50. package/{lib → dsh-mneme/lib}/tools.js +290 -290
  51. package/{lib → dsh-mneme/lib}/vector-index.js +116 -116
  52. package/dsh-mneme/package-lock.json +1936 -0
  53. package/dsh-mneme/package.json +80 -0
  54. package/{scripts → dsh-mneme/scripts}/benchmark-embed.js +201 -201
  55. package/{scripts → dsh-mneme/scripts}/benchmark-recall.js +133 -133
  56. package/{scripts → dsh-mneme/scripts}/benchmark-rerank.js +166 -166
  57. package/{scripts → dsh-mneme/scripts}/e2e-dsh.js +218 -218
  58. package/{scripts → dsh-mneme/scripts}/stress-dsh.js +255 -255
  59. package/{scripts → dsh-mneme/scripts}/sync-lib.js +52 -52
  60. package/{src → dsh-mneme/src}/api.js +783 -783
  61. package/{lib → dsh-mneme/src}/commands.js +64 -64
  62. package/{src → dsh-mneme/src}/config.js +298 -288
  63. package/{src → dsh-mneme/src}/dream/clustering.js +118 -118
  64. package/{lib → dsh-mneme/src}/dream/decisions.js +488 -439
  65. package/{src → dsh-mneme/src}/dream/sleep.js +561 -554
  66. package/{lib → dsh-mneme/src}/dream/tag-extractor.js +156 -156
  67. package/{src → dsh-mneme/src}/dream.js +958 -929
  68. package/{lib → dsh-mneme/src}/embedding.js +154 -154
  69. package/{lib → dsh-mneme/src}/entities/extractor.js +242 -242
  70. package/{lib → dsh-mneme/src}/hot-memory.js +53 -53
  71. package/{src → dsh-mneme/src}/index.js +361 -361
  72. package/{lib → dsh-mneme/src}/inject.js +208 -208
  73. package/{src → dsh-mneme/src}/local-embedder.js +282 -282
  74. package/{src → dsh-mneme/src}/mirror.js +170 -170
  75. package/{src → dsh-mneme/src}/parser/tag.js +59 -59
  76. package/{src → dsh-mneme/src}/parser/wiki-link.js +38 -38
  77. package/{lib → dsh-mneme/src}/quality-filter.js +123 -123
  78. package/{src → dsh-mneme/src}/reranker.js +218 -218
  79. package/{src → dsh-mneme/src}/search/adaptive.js +22 -22
  80. package/{src → dsh-mneme/src}/search/bm25.js +96 -96
  81. package/{lib → dsh-mneme/src}/search/tag-boost.js +61 -61
  82. package/{lib → dsh-mneme/src}/service.js +1726 -1726
  83. package/{src → dsh-mneme/src}/settings.js +172 -172
  84. package/{src → dsh-mneme/src}/store.js +2238 -2238
  85. package/{src → dsh-mneme/src}/summarize.js +236 -236
  86. package/{src → dsh-mneme/src}/tools.js +290 -290
  87. package/{src → dsh-mneme/src}/vector-index.js +116 -116
  88. package/{test → dsh-mneme/test}/api.test.js +594 -594
  89. package/{test → dsh-mneme/test}/audit.test.js +448 -448
  90. package/{test → dsh-mneme/test}/benchmark.test.js +35 -35
  91. package/{test → dsh-mneme/test}/boundary-v0625.test.js +82 -82
  92. package/{test → dsh-mneme/test}/client.test.js +368 -368
  93. package/{test → dsh-mneme/test}/clustering.test.js +100 -100
  94. package/{test → dsh-mneme/test}/commands.test.js +69 -69
  95. package/{test → dsh-mneme/test}/config.test.js +50 -50
  96. package/{test → dsh-mneme/test}/conflict-freeze.test.js +290 -290
  97. package/{test → dsh-mneme/test}/directory.test.js +134 -134
  98. package/{test → dsh-mneme/test}/dream.test.js +1060 -901
  99. package/{test → dsh-mneme/test}/entities.test.js +522 -522
  100. package/{test → dsh-mneme/test}/epistemic.test.js +298 -298
  101. package/{test → dsh-mneme/test}/fnew-0112.test.js +311 -311
  102. package/{test → dsh-mneme/test}/fnew-03.test.js +422 -422
  103. package/{test → dsh-mneme/test}/graph-api.test.js +175 -175
  104. package/{test → dsh-mneme/test}/helpers/dream-mock.js +82 -82
  105. package/{test → dsh-mneme/test}/hot-memory.test.js +174 -174
  106. package/{test → dsh-mneme/test}/inject.test.js +103 -103
  107. package/{test → dsh-mneme/test}/llm-audit.test.js +279 -279
  108. package/{test → dsh-mneme/test}/local-embedder.test.js +227 -227
  109. package/{test → dsh-mneme/test}/mirror-dirty.test.js +424 -424
  110. package/{test → dsh-mneme/test}/mirror-edit-digest.test.js +187 -187
  111. package/{test → dsh-mneme/test}/mirror-generation.test.js +499 -499
  112. package/{test → dsh-mneme/test}/mirror.test.js +249 -249
  113. package/{test → dsh-mneme/test}/normalize-decisions.test.js +120 -120
  114. package/{test → dsh-mneme/test}/peer-blockers.test.js +190 -190
  115. package/{test → dsh-mneme/test}/policy-epoch.test.js +259 -259
  116. package/{test → dsh-mneme/test}/provenance.test.js +103 -103
  117. package/{test → dsh-mneme/test}/quality-filter.test.js +118 -118
  118. package/{test → dsh-mneme/test}/reasoning-effort.test.js +199 -199
  119. package/{test → dsh-mneme/test}/recall-evals.test.js +235 -235
  120. package/{test → dsh-mneme/test}/recall-layer.test.js +315 -315
  121. package/{test → dsh-mneme/test}/receipt-chain.test.js +451 -451
  122. package/{test → dsh-mneme/test}/reflection.test.js +226 -226
  123. package/{test → dsh-mneme/test}/reranker.test.js +240 -240
  124. package/{test → dsh-mneme/test}/search-fusion.test.js +90 -90
  125. package/{test → dsh-mneme/test}/semantic.test.js +124 -124
  126. package/{test → dsh-mneme/test}/service-search.test.js +199 -199
  127. package/{test → dsh-mneme/test}/service.test.js +435 -435
  128. package/{test → dsh-mneme/test}/settings.test.js +118 -118
  129. package/{test → dsh-mneme/test}/sleep.test.js +365 -365
  130. package/{test → dsh-mneme/test}/store.test.js +436 -436
  131. package/{test → dsh-mneme/test}/stress.test.js +209 -209
  132. package/{test → dsh-mneme/test}/summarize.test.js +191 -191
  133. package/{test → dsh-mneme/test}/tag-boost.test.js +125 -125
  134. package/{test → dsh-mneme/test}/tag.test.js +312 -312
  135. package/{test → dsh-mneme/test}/tools.test.js +285 -285
  136. package/{test → dsh-mneme/test}/vector-index.test.js +221 -221
  137. package/{test → dsh-mneme/test}/wiki-link.test.js +332 -332
  138. package/package.json +18 -40
  139. package//346/250/252/345/271/205.png +0 -0
@@ -1,242 +1,242 @@
1
- const VALID_TYPES = new Set(["person", "project", "concept", "technology", "organization"]);
2
- const VALID_RELATIONS = new Set(["uses", "depends_on", "part_of", "related_to"]);
3
- const MAX_MEMORY_CHARS = 4000;
4
-
5
- function buildSystemPrompt(config) {
6
- const maxEntities = config.entityExtractionMaxEntities ?? 10;
7
- const maxAttrs = config.entityExtractionMaxAttrs ?? 20;
8
-
9
- return `You are an entity extraction engine. Extract named entities, their attributes, and relations from the given text.
10
-
11
- RULES:
12
- - Entities are concrete people, projects, technologies, concepts, or organizations.
13
- - Attributes are characteristic states of an entity. Only extract attributes explicitly mentioned in the text.
14
- - Do NOT infer, guess, or hallucinate. Only extract what is clearly stated.
15
- - Use canonical names (full name / primary name). Do NOT merge synonyms — different spellings of the same person are different entities.
16
- - Output MUST be strict JSON with this exact structure:
17
- {
18
- "entities": [
19
- {"name": "string", "type": "person|project|concept|technology|organization", "attrs": [{"key": "string", "value": "string", "confidence": 0.9}]}
20
- ],
21
- "relations": [
22
- {"from": "entityName", "to": "entityName", "type": "uses|depends_on|part_of|related_to"}
23
- ]
24
- }
25
-
26
- CONSTRAINTS:
27
- - "type" must be one of: person, project, concept, technology, organization. If unsure, use "concept".
28
- - "relations" from/to must reference entity names from the "entities" list.
29
- - Maximum ${maxEntities} entities. Maximum ${maxAttrs} attributes per entity. Truncate if exceeded.
30
- - Only include entity-related attributes. Ignore irrelevant miscellaneous details.
31
- - Return ONLY the JSON object. No explanations, no markdown, no code fences.`;
32
- }
33
-
34
- function buildUserMessage(memoryText) {
35
- const truncated = memoryText.length > MAX_MEMORY_CHARS
36
- ? memoryText.slice(0, MAX_MEMORY_CHARS) + "..."
37
- : memoryText;
38
- return truncated;
39
- }
40
-
41
- function extractJsonFromText(text) {
42
- if (!text || typeof text !== "string") return null;
43
-
44
- // Try direct parse first
45
- try {
46
- return JSON.parse(text);
47
- } catch {
48
- // fall through
49
- }
50
-
51
- // Try to find first {...} block
52
- const match = text.match(/\{[\s\S]*\}/);
53
- if (match) {
54
- try {
55
- return JSON.parse(match[0]);
56
- } catch {
57
- return null;
58
- }
59
- }
60
-
61
- return null;
62
- }
63
-
64
- function sanitizeType(type) {
65
- if (VALID_TYPES.has(type)) return type;
66
- return "concept";
67
- }
68
-
69
- function sanitizeConfidence(conf) {
70
- const num = Number(conf);
71
- if (Number.isNaN(num)) return 0.9;
72
- return Math.min(1, Math.max(0, num));
73
- }
74
-
75
- function sanitizeRelationType(type) {
76
- if (VALID_RELATIONS.has(type)) return type;
77
- return "related_to";
78
- }
79
-
80
- function sanitizeExtractedData(data, config) {
81
- const maxEntities = config.entityExtractionMaxEntities ?? 10;
82
- const maxAttrs = config.entityExtractionMaxAttrs ?? 20;
83
-
84
- if (!data || !Array.isArray(data.entities)) {
85
- throw new Error("Invalid extraction: missing entities array");
86
- }
87
-
88
- const entities = [];
89
- const seenNames = new Set();
90
-
91
- for (const rawEntity of data.entities.slice(0, maxEntities)) {
92
- if (!rawEntity || typeof rawEntity.name !== "string" || !rawEntity.name.trim()) continue;
93
-
94
- const name = rawEntity.name.trim();
95
- if (seenNames.has(name)) continue;
96
- seenNames.add(name);
97
-
98
- const attrs = [];
99
- if (Array.isArray(rawEntity.attrs)) {
100
- for (const rawAttr of rawEntity.attrs.slice(0, maxAttrs)) {
101
- if (!rawAttr || typeof rawAttr.key !== "string" || typeof rawAttr.value !== "string") continue;
102
- attrs.push({
103
- key: rawAttr.key.trim(),
104
- value: rawAttr.value.trim(),
105
- confidence: sanitizeConfidence(rawAttr.confidence)
106
- });
107
- }
108
- }
109
-
110
- entities.push({
111
- name,
112
- type: sanitizeType(rawEntity.type),
113
- attrs
114
- });
115
- }
116
-
117
- const relations = [];
118
- if (Array.isArray(data.relations)) {
119
- for (const rawRel of data.relations) {
120
- if (!rawRel || typeof rawRel.from !== "string" || typeof rawRel.to !== "string") continue;
121
- if (!seenNames.has(rawRel.from) || !seenNames.has(rawRel.to)) continue;
122
- relations.push({
123
- from: rawRel.from,
124
- to: rawRel.to,
125
- type: sanitizeRelationType(rawRel.type)
126
- });
127
- }
128
- }
129
-
130
- return { entities, relations };
131
- }
132
-
133
- async function resolveEntity(entity, store) {
134
- const existing = store.findEntityByName(entity.name);
135
- if (existing) {
136
- store.updateEntity(existing.id, {});
137
- return existing.id;
138
- }
139
- const created = store.createEntity({ name: entity.name, type: entity.type });
140
- return created.id;
141
- }
142
-
143
- export async function extractEntities(memory, { store, config, callLLM, logger }) {
144
- try {
145
- if (!memory || !memory.content) {
146
- return { ok: false, error: "Invalid memory: missing content" };
147
- }
148
-
149
- const model = config.entityExtractionModel || null;
150
- const systemPrompt = buildSystemPrompt(config);
151
- const userText = buildUserMessage(memory.content);
152
-
153
- const messages = [
154
- { role: "system", content: [{ type: "text", text: systemPrompt }] },
155
- { role: "user", content: [{ type: "text", text: userText }] }
156
- ];
157
-
158
- const options = model ? { model } : {};
159
- const llmResponse = await callLLM(messages, options);
160
-
161
- if (!llmResponse) {
162
- return { ok: false, error: "LLM returned empty response" };
163
- }
164
-
165
- const rawData = extractJsonFromText(llmResponse);
166
- if (!rawData) {
167
- return { ok: false, error: "Failed to parse JSON from LLM response" };
168
- }
169
-
170
- const { entities, relations } = sanitizeExtractedData(rawData, config);
171
-
172
- const resolvedEntities = [];
173
- const entityIdMap = new Map();
174
- let skipCount = 0;
175
-
176
- // Resolve entities
177
- for (const entity of entities) {
178
- try {
179
- const entityId = await resolveEntity(entity, store);
180
- entityIdMap.set(entity.name, entityId);
181
- resolvedEntities.push({ ...entity, entity_id: entityId });
182
- } catch (err) {
183
- skipCount++;
184
- logger?.warn?.(`[extractor] Failed to resolve entity "${entity.name}":`, err.message);
185
- }
186
- }
187
-
188
- // Record attributes
189
- const attrs = [];
190
- for (const entity of resolvedEntities) {
191
- for (const attr of entity.attrs) {
192
- try {
193
- const saved = store.saveAttr({
194
- entity_id: entity.entity_id,
195
- attr_key: attr.key,
196
- attr_value: String(attr.value),
197
- memory_id: memory.id,
198
- confidence: attr.confidence,
199
- source: "llm_extract"
200
- });
201
- attrs.push(saved);
202
- } catch (err) {
203
- skipCount++;
204
- logger?.warn?.(`[extractor] Failed to save attr "${attr.key}" for entity "${entity.name}":`, err.message);
205
- }
206
- }
207
- }
208
-
209
- // Record relations
210
- const savedRelations = [];
211
- for (const rel of relations) {
212
- const fromId = entityIdMap.get(rel.from);
213
- const toId = entityIdMap.get(rel.to);
214
- if (!fromId || !toId) continue;
215
-
216
- try {
217
- const saved = store.saveRelation({
218
- from_entity: fromId,
219
- to_entity: toId,
220
- relation_type: rel.type,
221
- memory_id: memory.id,
222
- metadata: { model: model || "default" }
223
- });
224
- savedRelations.push(saved);
225
- } catch (err) {
226
- skipCount++;
227
- logger?.warn?.(`[extractor] Failed to save relation "${rel.from} -> ${rel.to}":`, err.message);
228
- }
229
- }
230
-
231
- return {
232
- ok: true,
233
- entities: resolvedEntities,
234
- attrs,
235
- relations: savedRelations,
236
- skipped: skipCount
237
- };
238
-
239
- } catch (err) {
240
- return { ok: false, error: String(err) };
241
- }
242
- }
1
+ const VALID_TYPES = new Set(["person", "project", "concept", "technology", "organization"]);
2
+ const VALID_RELATIONS = new Set(["uses", "depends_on", "part_of", "related_to"]);
3
+ const MAX_MEMORY_CHARS = 4000;
4
+
5
+ function buildSystemPrompt(config) {
6
+ const maxEntities = config.entityExtractionMaxEntities ?? 10;
7
+ const maxAttrs = config.entityExtractionMaxAttrs ?? 20;
8
+
9
+ return `You are an entity extraction engine. Extract named entities, their attributes, and relations from the given text.
10
+
11
+ RULES:
12
+ - Entities are concrete people, projects, technologies, concepts, or organizations.
13
+ - Attributes are characteristic states of an entity. Only extract attributes explicitly mentioned in the text.
14
+ - Do NOT infer, guess, or hallucinate. Only extract what is clearly stated.
15
+ - Use canonical names (full name / primary name). Do NOT merge synonyms — different spellings of the same person are different entities.
16
+ - Output MUST be strict JSON with this exact structure:
17
+ {
18
+ "entities": [
19
+ {"name": "string", "type": "person|project|concept|technology|organization", "attrs": [{"key": "string", "value": "string", "confidence": 0.9}]}
20
+ ],
21
+ "relations": [
22
+ {"from": "entityName", "to": "entityName", "type": "uses|depends_on|part_of|related_to"}
23
+ ]
24
+ }
25
+
26
+ CONSTRAINTS:
27
+ - "type" must be one of: person, project, concept, technology, organization. If unsure, use "concept".
28
+ - "relations" from/to must reference entity names from the "entities" list.
29
+ - Maximum ${maxEntities} entities. Maximum ${maxAttrs} attributes per entity. Truncate if exceeded.
30
+ - Only include entity-related attributes. Ignore irrelevant miscellaneous details.
31
+ - Return ONLY the JSON object. No explanations, no markdown, no code fences.`;
32
+ }
33
+
34
+ function buildUserMessage(memoryText) {
35
+ const truncated = memoryText.length > MAX_MEMORY_CHARS
36
+ ? memoryText.slice(0, MAX_MEMORY_CHARS) + "..."
37
+ : memoryText;
38
+ return truncated;
39
+ }
40
+
41
+ function extractJsonFromText(text) {
42
+ if (!text || typeof text !== "string") return null;
43
+
44
+ // Try direct parse first
45
+ try {
46
+ return JSON.parse(text);
47
+ } catch {
48
+ // fall through
49
+ }
50
+
51
+ // Try to find first {...} block
52
+ const match = text.match(/\{[\s\S]*\}/);
53
+ if (match) {
54
+ try {
55
+ return JSON.parse(match[0]);
56
+ } catch {
57
+ return null;
58
+ }
59
+ }
60
+
61
+ return null;
62
+ }
63
+
64
+ function sanitizeType(type) {
65
+ if (VALID_TYPES.has(type)) return type;
66
+ return "concept";
67
+ }
68
+
69
+ function sanitizeConfidence(conf) {
70
+ const num = Number(conf);
71
+ if (Number.isNaN(num)) return 0.9;
72
+ return Math.min(1, Math.max(0, num));
73
+ }
74
+
75
+ function sanitizeRelationType(type) {
76
+ if (VALID_RELATIONS.has(type)) return type;
77
+ return "related_to";
78
+ }
79
+
80
+ function sanitizeExtractedData(data, config) {
81
+ const maxEntities = config.entityExtractionMaxEntities ?? 10;
82
+ const maxAttrs = config.entityExtractionMaxAttrs ?? 20;
83
+
84
+ if (!data || !Array.isArray(data.entities)) {
85
+ throw new Error("Invalid extraction: missing entities array");
86
+ }
87
+
88
+ const entities = [];
89
+ const seenNames = new Set();
90
+
91
+ for (const rawEntity of data.entities.slice(0, maxEntities)) {
92
+ if (!rawEntity || typeof rawEntity.name !== "string" || !rawEntity.name.trim()) continue;
93
+
94
+ const name = rawEntity.name.trim();
95
+ if (seenNames.has(name)) continue;
96
+ seenNames.add(name);
97
+
98
+ const attrs = [];
99
+ if (Array.isArray(rawEntity.attrs)) {
100
+ for (const rawAttr of rawEntity.attrs.slice(0, maxAttrs)) {
101
+ if (!rawAttr || typeof rawAttr.key !== "string" || typeof rawAttr.value !== "string") continue;
102
+ attrs.push({
103
+ key: rawAttr.key.trim(),
104
+ value: rawAttr.value.trim(),
105
+ confidence: sanitizeConfidence(rawAttr.confidence)
106
+ });
107
+ }
108
+ }
109
+
110
+ entities.push({
111
+ name,
112
+ type: sanitizeType(rawEntity.type),
113
+ attrs
114
+ });
115
+ }
116
+
117
+ const relations = [];
118
+ if (Array.isArray(data.relations)) {
119
+ for (const rawRel of data.relations) {
120
+ if (!rawRel || typeof rawRel.from !== "string" || typeof rawRel.to !== "string") continue;
121
+ if (!seenNames.has(rawRel.from) || !seenNames.has(rawRel.to)) continue;
122
+ relations.push({
123
+ from: rawRel.from,
124
+ to: rawRel.to,
125
+ type: sanitizeRelationType(rawRel.type)
126
+ });
127
+ }
128
+ }
129
+
130
+ return { entities, relations };
131
+ }
132
+
133
+ async function resolveEntity(entity, store) {
134
+ const existing = store.findEntityByName(entity.name);
135
+ if (existing) {
136
+ store.updateEntity(existing.id, {});
137
+ return existing.id;
138
+ }
139
+ const created = store.createEntity({ name: entity.name, type: entity.type });
140
+ return created.id;
141
+ }
142
+
143
+ export async function extractEntities(memory, { store, config, callLLM, logger }) {
144
+ try {
145
+ if (!memory || !memory.content) {
146
+ return { ok: false, error: "Invalid memory: missing content" };
147
+ }
148
+
149
+ const model = config.entityExtractionModel || null;
150
+ const systemPrompt = buildSystemPrompt(config);
151
+ const userText = buildUserMessage(memory.content);
152
+
153
+ const messages = [
154
+ { role: "system", content: [{ type: "text", text: systemPrompt }] },
155
+ { role: "user", content: [{ type: "text", text: userText }] }
156
+ ];
157
+
158
+ const options = model ? { model } : {};
159
+ const llmResponse = await callLLM(messages, options);
160
+
161
+ if (!llmResponse) {
162
+ return { ok: false, error: "LLM returned empty response" };
163
+ }
164
+
165
+ const rawData = extractJsonFromText(llmResponse);
166
+ if (!rawData) {
167
+ return { ok: false, error: "Failed to parse JSON from LLM response" };
168
+ }
169
+
170
+ const { entities, relations } = sanitizeExtractedData(rawData, config);
171
+
172
+ const resolvedEntities = [];
173
+ const entityIdMap = new Map();
174
+ let skipCount = 0;
175
+
176
+ // Resolve entities
177
+ for (const entity of entities) {
178
+ try {
179
+ const entityId = await resolveEntity(entity, store);
180
+ entityIdMap.set(entity.name, entityId);
181
+ resolvedEntities.push({ ...entity, entity_id: entityId });
182
+ } catch (err) {
183
+ skipCount++;
184
+ logger?.warn?.(`[extractor] Failed to resolve entity "${entity.name}":`, err.message);
185
+ }
186
+ }
187
+
188
+ // Record attributes
189
+ const attrs = [];
190
+ for (const entity of resolvedEntities) {
191
+ for (const attr of entity.attrs) {
192
+ try {
193
+ const saved = store.saveAttr({
194
+ entity_id: entity.entity_id,
195
+ attr_key: attr.key,
196
+ attr_value: String(attr.value),
197
+ memory_id: memory.id,
198
+ confidence: attr.confidence,
199
+ source: "llm_extract"
200
+ });
201
+ attrs.push(saved);
202
+ } catch (err) {
203
+ skipCount++;
204
+ logger?.warn?.(`[extractor] Failed to save attr "${attr.key}" for entity "${entity.name}":`, err.message);
205
+ }
206
+ }
207
+ }
208
+
209
+ // Record relations
210
+ const savedRelations = [];
211
+ for (const rel of relations) {
212
+ const fromId = entityIdMap.get(rel.from);
213
+ const toId = entityIdMap.get(rel.to);
214
+ if (!fromId || !toId) continue;
215
+
216
+ try {
217
+ const saved = store.saveRelation({
218
+ from_entity: fromId,
219
+ to_entity: toId,
220
+ relation_type: rel.type,
221
+ memory_id: memory.id,
222
+ metadata: { model: model || "default" }
223
+ });
224
+ savedRelations.push(saved);
225
+ } catch (err) {
226
+ skipCount++;
227
+ logger?.warn?.(`[extractor] Failed to save relation "${rel.from} -> ${rel.to}":`, err.message);
228
+ }
229
+ }
230
+
231
+ return {
232
+ ok: true,
233
+ entities: resolvedEntities,
234
+ attrs,
235
+ relations: savedRelations,
236
+ skipped: skipCount
237
+ };
238
+
239
+ } catch (err) {
240
+ return { ok: false, error: String(err) };
241
+ }
242
+ }
@@ -1,53 +1,53 @@
1
- // Session-scoped hot memory (v0.5.0 召回率优化 1.3): a short-term buffer of
2
- // the latest dialogue rounds, kept strictly apart from the long-term memory
3
- // store. The injector renders it ahead of the long-term recall block so the
4
- // agent sees "what we were just talking about" without those rounds ever
5
- // being persisted as memories. Bounded two ways: maxRounds (count) and
6
- // maxTokens (budget) — whichever evicts first.
7
-
8
- // CJK-aware token estimate: one Chinese character ≈ 0.6 tokens (clustering
9
- // behavior of mainstream tokenizers), one ASCII char ≈ 0.25.
10
- export function estimateTokens(text) {
11
- const s = String(text ?? "");
12
- let cjk = 0;
13
- for (const ch of s) if (ch >= "\u4e00" && ch <= "\u9fff") cjk++;
14
- return Math.ceil(cjk * 0.6 + (s.length - cjk) * 0.25);
15
- }
16
-
17
- /**
18
- * @param {{maxRounds?: number, maxTokens?: number}} opts
19
- * @returns {{add(round: {query: string, response?: string}): void,
20
- * getContext(): string,
21
- * rounds(): Array, clear(): void}}
22
- */
23
- export function createHotMemory({ maxRounds = 5, maxTokens = 2000 } = {}) {
24
- // Entry defense: a non-positive or non-integer maxRounds (0, -1, 1.5, NaN,
25
- // null, "2") would make the eviction while-loop unbounded — the buffer can
26
- // never shrink below `buffer.length > maxRounds`, so `add` would spin forever.
27
- // Fall back to the defaults so a hostile/buggy caller can never wedge the
28
- // hot-memory buffer in an infinite loop.
29
- maxRounds = (Number.isInteger(maxRounds) && maxRounds > 0) ? maxRounds : 5;
30
- maxTokens = (Number.isFinite(maxTokens) && maxTokens > 0) ? maxTokens : 2000;
31
- const buffer = [];
32
-
33
- function totalTokens() {
34
- return buffer.reduce(
35
- (sum, r) => sum + estimateTokens(`Q: ${r.query}\nA: ${r.response ?? ""}`),
36
- 0
37
- );
38
- }
39
-
40
- return {
41
- add(round) {
42
- if (!round?.query) return;
43
- buffer.push({ query: String(round.query), response: String(round.response ?? "") });
44
- while (buffer.length > maxRounds) buffer.shift();
45
- while (buffer.length > 1 && totalTokens() > maxTokens) buffer.shift();
46
- },
47
- getContext() {
48
- return buffer.map((r) => `Q: ${r.query}\nA: ${r.response ?? ""}`).join("\n\n");
49
- },
50
- rounds: () => [...buffer],
51
- clear() { buffer.length = 0; }
52
- };
53
- }
1
+ // Session-scoped hot memory (v0.5.0 召回率优化 1.3): a short-term buffer of
2
+ // the latest dialogue rounds, kept strictly apart from the long-term memory
3
+ // store. The injector renders it ahead of the long-term recall block so the
4
+ // agent sees "what we were just talking about" without those rounds ever
5
+ // being persisted as memories. Bounded two ways: maxRounds (count) and
6
+ // maxTokens (budget) — whichever evicts first.
7
+
8
+ // CJK-aware token estimate: one Chinese character ≈ 0.6 tokens (clustering
9
+ // behavior of mainstream tokenizers), one ASCII char ≈ 0.25.
10
+ export function estimateTokens(text) {
11
+ const s = String(text ?? "");
12
+ let cjk = 0;
13
+ for (const ch of s) if (ch >= "\u4e00" && ch <= "\u9fff") cjk++;
14
+ return Math.ceil(cjk * 0.6 + (s.length - cjk) * 0.25);
15
+ }
16
+
17
+ /**
18
+ * @param {{maxRounds?: number, maxTokens?: number}} opts
19
+ * @returns {{add(round: {query: string, response?: string}): void,
20
+ * getContext(): string,
21
+ * rounds(): Array, clear(): void}}
22
+ */
23
+ export function createHotMemory({ maxRounds = 5, maxTokens = 2000 } = {}) {
24
+ // Entry defense: a non-positive or non-integer maxRounds (0, -1, 1.5, NaN,
25
+ // null, "2") would make the eviction while-loop unbounded — the buffer can
26
+ // never shrink below `buffer.length > maxRounds`, so `add` would spin forever.
27
+ // Fall back to the defaults so a hostile/buggy caller can never wedge the
28
+ // hot-memory buffer in an infinite loop.
29
+ maxRounds = (Number.isInteger(maxRounds) && maxRounds > 0) ? maxRounds : 5;
30
+ maxTokens = (Number.isFinite(maxTokens) && maxTokens > 0) ? maxTokens : 2000;
31
+ const buffer = [];
32
+
33
+ function totalTokens() {
34
+ return buffer.reduce(
35
+ (sum, r) => sum + estimateTokens(`Q: ${r.query}\nA: ${r.response ?? ""}`),
36
+ 0
37
+ );
38
+ }
39
+
40
+ return {
41
+ add(round) {
42
+ if (!round?.query) return;
43
+ buffer.push({ query: String(round.query), response: String(round.response ?? "") });
44
+ while (buffer.length > maxRounds) buffer.shift();
45
+ while (buffer.length > 1 && totalTokens() > maxTokens) buffer.shift();
46
+ },
47
+ getContext() {
48
+ return buffer.map((r) => `Q: ${r.query}\nA: ${r.response ?? ""}`).join("\n\n");
49
+ },
50
+ rounds: () => [...buffer],
51
+ clear() { buffer.length = 0; }
52
+ };
53
+ }