@agentmemory/agentmemory 0.7.0 → 0.7.3

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 (218) hide show
  1. package/AGENTS.md +2 -2
  2. package/README.md +76 -82
  3. package/dist/cli.mjs +99 -32
  4. package/dist/cli.mjs.map +1 -1
  5. package/dist/index.mjs +4 -2
  6. package/dist/index.mjs.map +1 -1
  7. package/dist/{src-QxitMPfJ.mjs → src-sYZDDbiA.mjs} +5 -3
  8. package/dist/src-sYZDDbiA.mjs.map +1 -0
  9. package/dist/standalone.mjs +1 -1
  10. package/dist/standalone.mjs.map +1 -1
  11. package/package.json +11 -1
  12. package/plugin/.claude-plugin/plugin.json +1 -1
  13. package/plugin/scripts/notification.d.mts +1 -0
  14. package/plugin/scripts/notification.mjs.map +1 -0
  15. package/plugin/scripts/post-tool-failure.d.mts +1 -0
  16. package/plugin/scripts/post-tool-failure.mjs.map +1 -0
  17. package/plugin/scripts/post-tool-use.d.mts +1 -0
  18. package/plugin/scripts/post-tool-use.mjs.map +1 -0
  19. package/plugin/scripts/pre-compact.d.mts +1 -0
  20. package/plugin/scripts/pre-compact.mjs.map +1 -0
  21. package/plugin/scripts/pre-tool-use.d.mts +1 -0
  22. package/plugin/scripts/pre-tool-use.mjs.map +1 -0
  23. package/plugin/scripts/prompt-submit.d.mts +1 -0
  24. package/plugin/scripts/prompt-submit.mjs.map +1 -0
  25. package/plugin/scripts/session-end.d.mts +1 -0
  26. package/plugin/scripts/session-end.mjs.map +1 -0
  27. package/plugin/scripts/session-start.d.mts +1 -0
  28. package/plugin/scripts/session-start.mjs.map +1 -0
  29. package/plugin/scripts/stop.d.mts +1 -0
  30. package/plugin/scripts/stop.mjs.map +1 -0
  31. package/plugin/scripts/subagent-start.d.mts +1 -0
  32. package/plugin/scripts/subagent-start.mjs.map +1 -0
  33. package/plugin/scripts/subagent-stop.d.mts +1 -0
  34. package/plugin/scripts/subagent-stop.mjs.map +1 -0
  35. package/plugin/scripts/task-completed.d.mts +1 -0
  36. package/plugin/scripts/task-completed.mjs.map +1 -0
  37. package/.claude-plugin/marketplace.json +0 -14
  38. package/.github/workflows/ci.yml +0 -22
  39. package/.github/workflows/publish.yml +0 -28
  40. package/assets/banner.png +0 -0
  41. package/assets/demo.gif +0 -0
  42. package/assets/demo.mp4 +0 -0
  43. package/benchmark/QUALITY.md +0 -73
  44. package/benchmark/REAL-EMBEDDINGS.md +0 -67
  45. package/benchmark/SCALE.md +0 -110
  46. package/benchmark/dataset.ts +0 -293
  47. package/benchmark/quality-eval.ts +0 -643
  48. package/benchmark/real-embeddings-eval.ts +0 -405
  49. package/benchmark/scale-eval.ts +0 -398
  50. package/dist/src-QxitMPfJ.mjs.map +0 -1
  51. package/src/auth.ts +0 -12
  52. package/src/cli.ts +0 -159
  53. package/src/config.ts +0 -221
  54. package/src/eval/metrics-store.ts +0 -65
  55. package/src/eval/quality.ts +0 -51
  56. package/src/eval/schemas.ts +0 -124
  57. package/src/eval/self-correct.ts +0 -28
  58. package/src/eval/validator.ts +0 -31
  59. package/src/functions/actions.ts +0 -288
  60. package/src/functions/audit.ts +0 -61
  61. package/src/functions/auto-forget.ts +0 -169
  62. package/src/functions/branch-aware.ts +0 -169
  63. package/src/functions/cascade.ts +0 -80
  64. package/src/functions/checkpoints.ts +0 -209
  65. package/src/functions/claude-bridge.ts +0 -161
  66. package/src/functions/compress.ts +0 -194
  67. package/src/functions/consolidate.ts +0 -212
  68. package/src/functions/consolidation-pipeline.ts +0 -258
  69. package/src/functions/context.ts +0 -169
  70. package/src/functions/crystallize.ts +0 -293
  71. package/src/functions/dedup.ts +0 -57
  72. package/src/functions/diagnostics.ts +0 -785
  73. package/src/functions/enrich.ts +0 -132
  74. package/src/functions/evict.ts +0 -163
  75. package/src/functions/export-import.ts +0 -508
  76. package/src/functions/facets.ts +0 -248
  77. package/src/functions/file-index.ts +0 -106
  78. package/src/functions/flow-compress.ts +0 -214
  79. package/src/functions/frontier.ts +0 -196
  80. package/src/functions/governance.ts +0 -131
  81. package/src/functions/graph-retrieval.ts +0 -277
  82. package/src/functions/graph.ts +0 -275
  83. package/src/functions/leases.ts +0 -216
  84. package/src/functions/lessons.ts +0 -253
  85. package/src/functions/mesh.ts +0 -434
  86. package/src/functions/migrate.ts +0 -165
  87. package/src/functions/observe.ts +0 -144
  88. package/src/functions/obsidian-export.ts +0 -310
  89. package/src/functions/patterns.ts +0 -138
  90. package/src/functions/privacy.ts +0 -39
  91. package/src/functions/profile.ts +0 -155
  92. package/src/functions/query-expansion.ts +0 -186
  93. package/src/functions/relations.ts +0 -237
  94. package/src/functions/remember.ts +0 -162
  95. package/src/functions/retention.ts +0 -235
  96. package/src/functions/routines.ts +0 -289
  97. package/src/functions/search.ts +0 -80
  98. package/src/functions/sentinels.ts +0 -417
  99. package/src/functions/signals.ts +0 -186
  100. package/src/functions/sketches.ts +0 -274
  101. package/src/functions/sliding-window.ts +0 -257
  102. package/src/functions/smart-search.ts +0 -115
  103. package/src/functions/snapshot.ts +0 -219
  104. package/src/functions/summarize.ts +0 -155
  105. package/src/functions/team.ts +0 -147
  106. package/src/functions/temporal-graph.ts +0 -476
  107. package/src/functions/timeline.ts +0 -138
  108. package/src/functions/verify.ts +0 -117
  109. package/src/health/monitor.ts +0 -110
  110. package/src/health/thresholds.ts +0 -73
  111. package/src/hooks/notification.ts +0 -52
  112. package/src/hooks/post-tool-failure.ts +0 -58
  113. package/src/hooks/post-tool-use.ts +0 -62
  114. package/src/hooks/pre-compact.ts +0 -60
  115. package/src/hooks/pre-tool-use.ts +0 -72
  116. package/src/hooks/prompt-submit.ts +0 -46
  117. package/src/hooks/session-end.ts +0 -71
  118. package/src/hooks/session-start.ts +0 -48
  119. package/src/hooks/stop.ts +0 -39
  120. package/src/hooks/subagent-start.ts +0 -49
  121. package/src/hooks/subagent-stop.ts +0 -54
  122. package/src/hooks/task-completed.ts +0 -54
  123. package/src/index.ts +0 -342
  124. package/src/mcp/in-memory-kv.ts +0 -61
  125. package/src/mcp/server.ts +0 -1455
  126. package/src/mcp/standalone.ts +0 -177
  127. package/src/mcp/tools-registry.ts +0 -769
  128. package/src/mcp/transport.ts +0 -91
  129. package/src/prompts/compression.ts +0 -67
  130. package/src/prompts/consolidation.ts +0 -48
  131. package/src/prompts/graph-extraction.ts +0 -35
  132. package/src/prompts/summary.ts +0 -38
  133. package/src/prompts/xml.ts +0 -26
  134. package/src/providers/agent-sdk.ts +0 -34
  135. package/src/providers/anthropic.ts +0 -35
  136. package/src/providers/circuit-breaker.ts +0 -82
  137. package/src/providers/embedding/cohere.ts +0 -46
  138. package/src/providers/embedding/gemini.ts +0 -54
  139. package/src/providers/embedding/index.ts +0 -39
  140. package/src/providers/embedding/local.ts +0 -52
  141. package/src/providers/embedding/openai.ts +0 -45
  142. package/src/providers/embedding/openrouter.ts +0 -51
  143. package/src/providers/embedding/voyage.ts +0 -46
  144. package/src/providers/fallback-chain.ts +0 -31
  145. package/src/providers/index.ts +0 -84
  146. package/src/providers/openrouter.ts +0 -71
  147. package/src/providers/resilient.ts +0 -37
  148. package/src/state/hybrid-search.ts +0 -295
  149. package/src/state/index-persistence.ts +0 -63
  150. package/src/state/keyed-mutex.ts +0 -18
  151. package/src/state/kv.ts +0 -33
  152. package/src/state/schema.ts +0 -71
  153. package/src/state/search-index.ts +0 -245
  154. package/src/state/stemmer.ts +0 -104
  155. package/src/state/synonyms.ts +0 -63
  156. package/src/state/vector-index.ts +0 -130
  157. package/src/telemetry/setup.ts +0 -116
  158. package/src/triggers/api.ts +0 -1904
  159. package/src/triggers/events.ts +0 -71
  160. package/src/types.ts +0 -769
  161. package/src/version.ts +0 -1
  162. package/src/viewer/index.html +0 -2497
  163. package/src/viewer/server.ts +0 -207
  164. package/src/xenova.d.ts +0 -3
  165. package/test/actions.test.ts +0 -490
  166. package/test/audit.test.ts +0 -108
  167. package/test/auto-forget.test.ts +0 -188
  168. package/test/cascade.test.ts +0 -277
  169. package/test/checkpoints.test.ts +0 -493
  170. package/test/circuit-breaker.test.ts +0 -107
  171. package/test/claude-bridge.test.ts +0 -178
  172. package/test/confidence.test.ts +0 -247
  173. package/test/consistency.test.ts +0 -61
  174. package/test/consolidation-pipeline.test.ts +0 -251
  175. package/test/crystallize.test.ts +0 -521
  176. package/test/diagnostics.test.ts +0 -638
  177. package/test/embedding-provider.test.ts +0 -49
  178. package/test/enrich.test.ts +0 -209
  179. package/test/eval.test.ts +0 -300
  180. package/test/export-import.test.ts +0 -251
  181. package/test/facets.test.ts +0 -448
  182. package/test/fallback-chain.test.ts +0 -93
  183. package/test/frontier.test.ts +0 -485
  184. package/test/governance.test.ts +0 -147
  185. package/test/graph-retrieval.test.ts +0 -186
  186. package/test/graph.test.ts +0 -160
  187. package/test/helpers/mocks.ts +0 -40
  188. package/test/hybrid-search.test.ts +0 -145
  189. package/test/index-persistence.test.ts +0 -124
  190. package/test/integration.test.ts +0 -265
  191. package/test/leases.test.ts +0 -399
  192. package/test/mcp-prompts.test.ts +0 -218
  193. package/test/mcp-resources.test.ts +0 -286
  194. package/test/mcp-standalone.test.ts +0 -113
  195. package/test/mesh.test.ts +0 -700
  196. package/test/privacy.test.ts +0 -87
  197. package/test/profile.test.ts +0 -161
  198. package/test/query-expansion.test.ts +0 -154
  199. package/test/relations.test.ts +0 -198
  200. package/test/retention.test.ts +0 -245
  201. package/test/routines.test.ts +0 -497
  202. package/test/schema-fingerprint.test.ts +0 -81
  203. package/test/schema.test.ts +0 -42
  204. package/test/search-index.test.ts +0 -128
  205. package/test/sentinels.test.ts +0 -626
  206. package/test/signals.test.ts +0 -410
  207. package/test/sketches.test.ts +0 -549
  208. package/test/sliding-window.test.ts +0 -199
  209. package/test/smart-search.test.ts +0 -169
  210. package/test/snapshot.test.ts +0 -165
  211. package/test/team.test.ts +0 -156
  212. package/test/temporal-graph.test.ts +0 -378
  213. package/test/timeline.test.ts +0 -148
  214. package/test/vector-index.test.ts +0 -79
  215. package/test/verify.test.ts +0 -209
  216. package/test/xml.test.ts +0 -65
  217. package/tsconfig.json +0 -22
  218. package/tsdown.config.ts +0 -62
@@ -1,476 +0,0 @@
1
- import type { ISdk } from "iii-sdk";
2
- import { getContext } from "iii-sdk";
3
- import type {
4
- GraphNode,
5
- GraphEdge,
6
- GraphEdgeType,
7
- EdgeContext,
8
- TemporalState,
9
- MemoryProvider,
10
- } from "../types.js";
11
- import { KV, generateId } from "../state/schema.js";
12
- import type { StateKV } from "../state/kv.js";
13
-
14
- const TEMPORAL_EXTRACTION_SYSTEM = `You are a temporal knowledge extraction engine. Given observations, extract entities AND their temporal relationships with full context metadata.
15
-
16
- For each relationship, you MUST provide:
17
- 1. Semantic relation type
18
- 2. Temporal validity (when this fact became true in the real world)
19
- 3. Context metadata: WHY this relationship exists, what reasoning led to it, what alternatives were considered
20
-
21
- Output EXACTLY this XML:
22
- <temporal_graph>
23
- <entities>
24
- <entity type="file|function|concept|error|decision|pattern|library|person|project|preference|location|organization|event" name="exact name">
25
- <property key="key">value</property>
26
- <alias>alternate name</alias>
27
- </entity>
28
- </entities>
29
- <relationships>
30
- <relationship type="uses|imports|modifies|causes|fixes|depends_on|related_to|works_at|prefers|blocked_by|caused_by|optimizes_for|rejected|avoids|located_in|succeeded_by"
31
- source="entity name" target="entity name" weight="0.1-1.0"
32
- valid_from="ISO date or 'unknown'" valid_to="ISO date or 'current'">
33
- <reasoning>WHY this relationship exists</reasoning>
34
- <sentiment>positive|negative|neutral</sentiment>
35
- <alternatives>
36
- <alt>alternative that was considered</alt>
37
- </alternatives>
38
- </relationship>
39
- </relationships>
40
- </temporal_graph>
41
-
42
- Rules:
43
- - NEVER overwrite existing relationships — always create new versioned edges
44
- - Extract temporal validity from context clues ("since last month", "in 2024", "currently")
45
- - Capture reasoning/motivation behind each relationship
46
- - Weight relationships by directness: 1.0 = explicit statement, 0.5 = inferred, 0.1 = speculative`;
47
-
48
- function parseTemporalGraphXml(
49
- xml: string,
50
- observationIds: string[],
51
- ): { nodes: GraphNode[]; edges: GraphEdge[] } {
52
- const nodes: GraphNode[] = [];
53
- const edges: GraphEdge[] = [];
54
- const now = new Date().toISOString();
55
-
56
- const entityRegex =
57
- /<entity\s+type="([^"]+)"\s+name="([^"]+)"[^>]*>([\s\S]*?)<\/entity>/g;
58
- let match;
59
- while ((match = entityRegex.exec(xml)) !== null) {
60
- const type = match[1] as GraphNode["type"];
61
- const name = match[2];
62
- const propsBlock = match[3];
63
- const properties: Record<string, string> = {};
64
- const aliases: string[] = [];
65
-
66
- const propRegex = /<property\s+key="([^"]+)">([^<]*)<\/property>/g;
67
- let propMatch;
68
- while ((propMatch = propRegex.exec(propsBlock)) !== null) {
69
- properties[propMatch[1]] = propMatch[2];
70
- }
71
-
72
- const aliasRegex = /<alias>([^<]+)<\/alias>/g;
73
- while ((propMatch = aliasRegex.exec(propsBlock)) !== null) {
74
- aliases.push(propMatch[1]);
75
- }
76
-
77
- nodes.push({
78
- id: generateId("gn"),
79
- type,
80
- name,
81
- properties,
82
- sourceObservationIds: observationIds,
83
- createdAt: now,
84
- aliases: aliases.length > 0 ? aliases : undefined,
85
- });
86
- }
87
-
88
- const relRegex =
89
- /<relationship\s+type="([^"]+)"\s+source="([^"]+)"\s+target="([^"]+)"\s+weight="([^"]+)"(?:\s+valid_from="([^"]*)")?(?:\s+valid_to="([^"]*)")?[^>]*>([\s\S]*?)<\/relationship>/g;
90
- while ((match = relRegex.exec(xml)) !== null) {
91
- const type = match[1] as GraphEdgeType;
92
- const sourceName = match[2];
93
- const targetName = match[3];
94
- const parsedWeight = parseFloat(match[4]);
95
- const weight = Number.isNaN(parsedWeight) ? 0.5 : parsedWeight;
96
- const validFrom = match[5] || undefined;
97
- const validTo = match[6] || undefined;
98
- const metaBlock = match[7] || "";
99
-
100
- const sourceNode = nodes.find(
101
- (n) =>
102
- n.name === sourceName ||
103
- (n.aliases && n.aliases.includes(sourceName)),
104
- );
105
- const targetNode = nodes.find(
106
- (n) =>
107
- n.name === targetName ||
108
- (n.aliases && n.aliases.includes(targetName)),
109
- );
110
-
111
- if (sourceNode && targetNode) {
112
- const reasoning =
113
- metaBlock.match(/<reasoning>([^<]*)<\/reasoning>/)?.[1] || undefined;
114
- const sentiment =
115
- metaBlock.match(/<sentiment>([^<]*)<\/sentiment>/)?.[1] || undefined;
116
- const alternatives: string[] = [];
117
- const altRegex = /<alt>([^<]+)<\/alt>/g;
118
- let altMatch;
119
- while ((altMatch = altRegex.exec(metaBlock)) !== null) {
120
- alternatives.push(altMatch[1]);
121
- }
122
-
123
- const context: EdgeContext = {};
124
- if (reasoning) context.reasoning = reasoning;
125
- if (sentiment) context.sentiment = sentiment;
126
- if (alternatives.length > 0) context.alternatives = alternatives;
127
- context.confidence = Math.max(0, Math.min(1, weight));
128
-
129
- edges.push({
130
- id: generateId("ge"),
131
- type,
132
- sourceNodeId: sourceNode.id,
133
- targetNodeId: targetNode.id,
134
- weight: Math.max(0, Math.min(1, weight)),
135
- sourceObservationIds: observationIds,
136
- createdAt: now,
137
- tcommit: now,
138
- tvalid:
139
- validFrom && validFrom !== "unknown" ? validFrom : undefined,
140
- tvalidEnd:
141
- validTo && validTo !== "current" ? validTo : undefined,
142
- context: Object.keys(context).length > 0 ? context : undefined,
143
- version: 1,
144
- isLatest: true,
145
- });
146
- }
147
- }
148
-
149
- return { nodes, edges };
150
- }
151
-
152
- export function registerTemporalGraphFunctions(
153
- sdk: ISdk,
154
- kv: StateKV,
155
- provider: MemoryProvider,
156
- ): void {
157
- sdk.registerFunction(
158
- {
159
- id: "mem::temporal-graph-extract",
160
- description:
161
- "Extract temporal knowledge graph with context metadata from observations",
162
- },
163
- async (data: {
164
- observations: Array<{
165
- id: string;
166
- title: string;
167
- narrative: string;
168
- concepts: string[];
169
- files: string[];
170
- type: string;
171
- timestamp: string;
172
- }>;
173
- }) => {
174
- const ctx = getContext();
175
- if (!data.observations || data.observations.length === 0) {
176
- return { success: false, error: "No observations provided" };
177
- }
178
-
179
- const items = data.observations
180
- .map(
181
- (o, i) =>
182
- `[${i + 1}] Type: ${o.type}\nTimestamp: ${o.timestamp}\nTitle: ${o.title}\nNarrative: ${o.narrative}\nConcepts: ${(o.concepts ?? []).join(", ")}\nFiles: ${(o.files ?? []).join(", ")}`,
183
- )
184
- .join("\n\n");
185
-
186
- try {
187
- const response = await provider.compress(
188
- TEMPORAL_EXTRACTION_SYSTEM,
189
- `Extract temporal knowledge graph from:\n\n${items}`,
190
- );
191
-
192
- const obsIds = data.observations.map((o) => o.id);
193
- const { nodes, edges } = parseTemporalGraphXml(response, obsIds);
194
-
195
- const existingNodes = await kv.list<GraphNode>(KV.graphNodes);
196
- const existingEdges = await kv.list<GraphEdge>(KV.graphEdges);
197
-
198
- const idRemap = new Map<string, string>();
199
- for (const node of nodes) {
200
- const existing = existingNodes.find(
201
- (n) =>
202
- n.name === node.name && n.type === node.type,
203
- );
204
- if (existing) {
205
- const oldId = node.id;
206
- const merged = {
207
- ...existing,
208
- sourceObservationIds: [
209
- ...new Set([
210
- ...existing.sourceObservationIds,
211
- ...obsIds,
212
- ]),
213
- ],
214
- properties: { ...existing.properties, ...node.properties },
215
- updatedAt: new Date().toISOString(),
216
- aliases: [
217
- ...new Set([
218
- ...(existing.aliases || []),
219
- ...(node.aliases || []),
220
- ]),
221
- ],
222
- };
223
- if (merged.aliases.length === 0) delete (merged as any).aliases;
224
- await kv.set(KV.graphNodes, existing.id, merged);
225
- node.id = existing.id;
226
- idRemap.set(oldId, existing.id);
227
- } else {
228
- await kv.set(KV.graphNodes, node.id, node);
229
- existingNodes.push(node);
230
- }
231
- }
232
-
233
- for (const edge of edges) {
234
- if (idRemap.has(edge.sourceNodeId)) {
235
- edge.sourceNodeId = idRemap.get(edge.sourceNodeId)!;
236
- }
237
- if (idRemap.has(edge.targetNodeId)) {
238
- edge.targetNodeId = idRemap.get(edge.targetNodeId)!;
239
- }
240
- const existingKey = `${edge.sourceNodeId}|${edge.targetNodeId}|${edge.type}`;
241
- const existingEdge = existingEdges.find(
242
- (e) =>
243
- `${e.sourceNodeId}|${e.targetNodeId}|${e.type}` ===
244
- existingKey,
245
- );
246
-
247
- if (existingEdge) {
248
- const updatedOld = {
249
- ...existingEdge,
250
- isLatest: false,
251
- tvalidEnd:
252
- existingEdge.tvalidEnd || new Date().toISOString(),
253
- supersededBy: edge.id,
254
- };
255
- await kv.set(KV.graphEdges, existingEdge.id, updatedOld);
256
-
257
- await kv.set(KV.graphEdgeHistory, existingEdge.id, updatedOld);
258
-
259
- edge.version = (existingEdge.version || 1) + 1;
260
- }
261
-
262
- await kv.set(KV.graphEdges, edge.id, edge);
263
- existingEdges.push(edge);
264
- }
265
-
266
- ctx.logger.info("Temporal graph extraction complete", {
267
- nodes: nodes.length,
268
- edges: edges.length,
269
- });
270
- return {
271
- success: true,
272
- nodesAdded: nodes.length,
273
- edgesAdded: edges.length,
274
- };
275
- } catch (err) {
276
- const msg = err instanceof Error ? err.message : String(err);
277
- ctx.logger.error("Temporal graph extraction failed", { error: msg });
278
- return { success: false, error: msg };
279
- }
280
- },
281
- );
282
-
283
- sdk.registerFunction(
284
- {
285
- id: "mem::temporal-query",
286
- description:
287
- "Query entity state at a specific point in time with full history",
288
- },
289
- async (data: {
290
- entityName: string;
291
- asOf?: string;
292
- includeHistory?: boolean;
293
- }): Promise<TemporalState | { error: string }> => {
294
- const allNodes = await kv.list<GraphNode>(KV.graphNodes);
295
- const allEdges = await kv.list<GraphEdge>(KV.graphEdges);
296
-
297
- const entity = allNodes.find(
298
- (n) =>
299
- n.name.toLowerCase() === data.entityName.toLowerCase() ||
300
- (n.aliases &&
301
- n.aliases.some(
302
- (a) =>
303
- a.toLowerCase() === data.entityName.toLowerCase(),
304
- )),
305
- );
306
-
307
- if (!entity) {
308
- return { error: `Entity "${data.entityName}" not found` } as any;
309
- }
310
-
311
- const relatedEdges = allEdges.filter(
312
- (e) => e.sourceNodeId === entity.id || e.targetNodeId === entity.id,
313
- );
314
-
315
- const historicalEdges = await kv
316
- .list<GraphEdge>(KV.graphEdgeHistory)
317
- .catch(() => [] as GraphEdge[]);
318
- const entityHistory = historicalEdges.filter(
319
- (e) => e.sourceNodeId === entity.id || e.targetNodeId === entity.id,
320
- );
321
-
322
- const allEntityEdges = [...relatedEdges, ...entityHistory];
323
-
324
- if (data.asOf) {
325
- const asOfTime = new Date(data.asOf).getTime();
326
- const validEdges = allEntityEdges.filter((e) => {
327
- const commitTime = new Date(
328
- e.tcommit || e.createdAt,
329
- ).getTime();
330
- if (commitTime > asOfTime) return false;
331
- if (e.tvalid) {
332
- const validTime = new Date(e.tvalid).getTime();
333
- if (validTime > asOfTime) return false;
334
- }
335
- if (e.tvalidEnd) {
336
- const endTime = new Date(e.tvalidEnd).getTime();
337
- if (endTime < asOfTime) return false;
338
- }
339
- return true;
340
- });
341
-
342
- const currentEdges = getLatestByKey(validEdges);
343
- const historical = data.includeHistory ? validEdges : [];
344
-
345
- return {
346
- entity,
347
- currentEdges,
348
- historicalEdges: historical,
349
- timeline: buildTimeline(allEntityEdges),
350
- };
351
- }
352
-
353
- const currentEdges = relatedEdges.filter(
354
- (e) => e.isLatest !== false,
355
- );
356
-
357
- return {
358
- entity,
359
- currentEdges,
360
- historicalEdges: data.includeHistory ? entityHistory : [],
361
- timeline: buildTimeline(allEntityEdges),
362
- };
363
- },
364
- );
365
-
366
- sdk.registerFunction(
367
- {
368
- id: "mem::differential-state",
369
- description:
370
- "Compute state changes between two entities over time",
371
- },
372
- async (data: {
373
- entityName: string;
374
- from?: string;
375
- to?: string;
376
- }) => {
377
- const allNodes = await kv.list<GraphNode>(KV.graphNodes);
378
- const allEdges = await kv.list<GraphEdge>(KV.graphEdges);
379
- const historicalEdges = await kv
380
- .list<GraphEdge>(KV.graphEdgeHistory)
381
- .catch(() => [] as GraphEdge[]);
382
-
383
- const entity = allNodes.find(
384
- (n) => n.name.toLowerCase() === data.entityName.toLowerCase(),
385
- );
386
- if (!entity) return { error: "Entity not found" };
387
-
388
- const allEntityEdges = [
389
- ...allEdges.filter(
390
- (e) =>
391
- e.sourceNodeId === entity.id || e.targetNodeId === entity.id,
392
- ),
393
- ...historicalEdges.filter(
394
- (e) =>
395
- e.sourceNodeId === entity.id || e.targetNodeId === entity.id,
396
- ),
397
- ];
398
-
399
- allEntityEdges.sort(
400
- (a, b) =>
401
- new Date(a.tcommit || a.createdAt).getTime() -
402
- new Date(b.tcommit || b.createdAt).getTime(),
403
- );
404
-
405
- const fromTime = data.from
406
- ? new Date(data.from).getTime()
407
- : 0;
408
- const toTime = data.to
409
- ? new Date(data.to).getTime()
410
- : Date.now();
411
-
412
- const filtered = allEntityEdges.filter((e) => {
413
- const t = new Date(e.tcommit || e.createdAt).getTime();
414
- return t >= fromTime && t <= toTime;
415
- });
416
-
417
- const changes = filtered.map((e) => ({
418
- type: e.type,
419
- target:
420
- e.sourceNodeId === entity.id
421
- ? e.targetNodeId
422
- : e.sourceNodeId,
423
- validFrom: e.tvalid || e.createdAt,
424
- validTo: e.tvalidEnd,
425
- reasoning: e.context?.reasoning,
426
- sentiment: e.context?.sentiment,
427
- version: e.version || 1,
428
- isLatest: e.isLatest !== false,
429
- }));
430
-
431
- return {
432
- entity: entity.name,
433
- totalChanges: changes.length,
434
- changes,
435
- };
436
- },
437
- );
438
- }
439
-
440
- function getLatestByKey(edges: GraphEdge[]): GraphEdge[] {
441
- const byKey = new Map<string, GraphEdge>();
442
- for (const e of edges) {
443
- const key = `${e.sourceNodeId}|${e.targetNodeId}|${e.type}`;
444
- const existing = byKey.get(key);
445
- if (
446
- !existing ||
447
- new Date(e.tcommit || e.createdAt).getTime() >
448
- new Date(existing.tcommit || existing.createdAt).getTime()
449
- ) {
450
- byKey.set(key, e);
451
- }
452
- }
453
- return Array.from(byKey.values());
454
- }
455
-
456
- function buildTimeline(
457
- edges: GraphEdge[],
458
- ): Array<{
459
- edge: GraphEdge;
460
- validFrom: string;
461
- validTo?: string;
462
- context?: EdgeContext;
463
- }> {
464
- const sorted = [...edges].sort(
465
- (a, b) =>
466
- new Date(a.tcommit || a.createdAt).getTime() -
467
- new Date(b.tcommit || b.createdAt).getTime(),
468
- );
469
-
470
- return sorted.map((e) => ({
471
- edge: e,
472
- validFrom: e.tvalid || e.createdAt,
473
- validTo: e.tvalidEnd,
474
- context: e.context,
475
- }));
476
- }
@@ -1,138 +0,0 @@
1
- import type { ISdk } from "iii-sdk";
2
- import { getContext } from "iii-sdk";
3
- import type {
4
- CompressedObservation,
5
- Session,
6
- TimelineEntry,
7
- } from "../types.js";
8
- import { KV } from "../state/schema.js";
9
- import { StateKV } from "../state/kv.js";
10
-
11
- export function registerTimelineFunction(sdk: ISdk, kv: StateKV): void {
12
- sdk.registerFunction(
13
- {
14
- id: "mem::timeline",
15
- description: "Get chronological observations around an anchor point",
16
- },
17
- async (data: {
18
- anchor: string;
19
- project?: string;
20
- before?: number;
21
- after?: number;
22
- }) => {
23
- const ctx = getContext();
24
- const before = Math.max(0, Math.floor(data.before ?? 5));
25
- const after = Math.max(0, Math.floor(data.after ?? 5));
26
-
27
- if (!data.anchor || typeof data.anchor !== "string") {
28
- return { entries: [], anchor: data.anchor, reason: "invalid_anchor" };
29
- }
30
-
31
- let anchorTime: number;
32
- const isoPattern = /^\d{4}-\d{2}-\d{2}/;
33
- if (isoPattern.test(data.anchor)) {
34
- anchorTime = new Date(data.anchor).getTime();
35
- if (isNaN(anchorTime)) {
36
- return { entries: [], anchor: data.anchor, reason: "invalid_date" };
37
- }
38
- } else {
39
- const searchResults = await findByKeyword(
40
- kv,
41
- data.anchor,
42
- data.project,
43
- );
44
- if (searchResults.length === 0) {
45
- return { entries: [], anchor: data.anchor, reason: "no_match" };
46
- }
47
- anchorTime = new Date(searchResults[0].timestamp).getTime();
48
- }
49
-
50
- const sessions = await kv.list<Session>(KV.sessions);
51
- const filtered = data.project
52
- ? sessions.filter((s) => s.project === data.project)
53
- : sessions;
54
-
55
- const allObs: Array<CompressedObservation & { sid: string }> = [];
56
- for (const session of filtered) {
57
- const observations = await kv.list<CompressedObservation>(
58
- KV.observations(session.id),
59
- );
60
- for (const obs of observations) {
61
- if (obs.title && obs.timestamp) {
62
- allObs.push({ ...obs, sid: session.id });
63
- }
64
- }
65
- }
66
-
67
- allObs.sort(
68
- (a, b) =>
69
- new Date(a.timestamp).getTime() - new Date(b.timestamp).getTime(),
70
- );
71
-
72
- let anchorIdx = 0;
73
- let minDist = Infinity;
74
- for (let i = 0; i < allObs.length; i++) {
75
- const dist = Math.abs(
76
- new Date(allObs[i].timestamp).getTime() - anchorTime,
77
- );
78
- if (dist < minDist) {
79
- minDist = dist;
80
- anchorIdx = i;
81
- }
82
- }
83
-
84
- const startIdx = Math.max(0, anchorIdx - before);
85
- const endIdx = Math.min(allObs.length - 1, anchorIdx + after);
86
- const entries: TimelineEntry[] = [];
87
-
88
- for (let i = startIdx; i <= endIdx; i++) {
89
- const obs = allObs[i];
90
- const { sid, ...observation } = obs;
91
- entries.push({
92
- observation,
93
- sessionId: sid,
94
- relativePosition: i - anchorIdx,
95
- });
96
- }
97
-
98
- ctx.logger.info("Timeline retrieved", {
99
- anchor: data.anchor,
100
- entries: entries.length,
101
- });
102
- return { entries, anchorIndex: anchorIdx - startIdx };
103
- },
104
- );
105
- }
106
-
107
- async function findByKeyword(
108
- kv: StateKV,
109
- keyword: string,
110
- project?: string,
111
- ): Promise<CompressedObservation[]> {
112
- const sessions = await kv.list<Session>(KV.sessions);
113
- const filtered = project
114
- ? sessions.filter((s) => s.project === project)
115
- : sessions;
116
-
117
- const lower = keyword.toLowerCase();
118
- const matches: CompressedObservation[] = [];
119
-
120
- for (const session of filtered) {
121
- const observations = await kv.list<CompressedObservation>(
122
- KV.observations(session.id),
123
- );
124
- for (const obs of observations) {
125
- if (
126
- obs.title?.toLowerCase().includes(lower) ||
127
- obs.narrative?.toLowerCase().includes(lower) ||
128
- obs.concepts?.some((c) => c.toLowerCase().includes(lower))
129
- ) {
130
- matches.push(obs);
131
- }
132
- }
133
- }
134
-
135
- return matches.sort(
136
- (a, b) => new Date(b.timestamp).getTime() - new Date(a.timestamp).getTime(),
137
- );
138
- }