@agentmemory/agentmemory 0.7.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 (259) hide show
  1. package/.claude-plugin/marketplace.json +14 -0
  2. package/.github/workflows/ci.yml +22 -0
  3. package/.github/workflows/publish.yml +28 -0
  4. package/AGENTS.md +113 -0
  5. package/LICENSE +190 -0
  6. package/README.md +828 -0
  7. package/assets/banner.png +0 -0
  8. package/assets/demo.gif +0 -0
  9. package/assets/demo.mp4 +0 -0
  10. package/benchmark/QUALITY.md +73 -0
  11. package/benchmark/REAL-EMBEDDINGS.md +67 -0
  12. package/benchmark/SCALE.md +110 -0
  13. package/benchmark/dataset.ts +293 -0
  14. package/benchmark/quality-eval.ts +643 -0
  15. package/benchmark/real-embeddings-eval.ts +405 -0
  16. package/benchmark/scale-eval.ts +398 -0
  17. package/dist/cli.d.mts +1 -0
  18. package/dist/cli.mjs +137 -0
  19. package/dist/cli.mjs.map +1 -0
  20. package/dist/docker-compose.yml +14 -0
  21. package/dist/hooks/notification.d.mts +1 -0
  22. package/dist/hooks/notification.mjs +45 -0
  23. package/dist/hooks/notification.mjs.map +1 -0
  24. package/dist/hooks/post-tool-failure.d.mts +1 -0
  25. package/dist/hooks/post-tool-failure.mjs +45 -0
  26. package/dist/hooks/post-tool-failure.mjs.map +1 -0
  27. package/dist/hooks/post-tool-use.d.mts +1 -0
  28. package/dist/hooks/post-tool-use.mjs +53 -0
  29. package/dist/hooks/post-tool-use.mjs.map +1 -0
  30. package/dist/hooks/pre-compact.d.mts +1 -0
  31. package/dist/hooks/pre-compact.mjs +50 -0
  32. package/dist/hooks/pre-compact.mjs.map +1 -0
  33. package/dist/hooks/pre-tool-use.d.mts +1 -0
  34. package/dist/hooks/pre-tool-use.mjs +69 -0
  35. package/dist/hooks/pre-tool-use.mjs.map +1 -0
  36. package/dist/hooks/prompt-submit.d.mts +1 -0
  37. package/dist/hooks/prompt-submit.mjs +40 -0
  38. package/dist/hooks/prompt-submit.mjs.map +1 -0
  39. package/dist/hooks/session-end.d.mts +1 -0
  40. package/dist/hooks/session-end.mjs +61 -0
  41. package/dist/hooks/session-end.mjs.map +1 -0
  42. package/dist/hooks/session-start.d.mts +1 -0
  43. package/dist/hooks/session-start.mjs +42 -0
  44. package/dist/hooks/session-start.mjs.map +1 -0
  45. package/dist/hooks/stop.d.mts +1 -0
  46. package/dist/hooks/stop.mjs +33 -0
  47. package/dist/hooks/stop.mjs.map +1 -0
  48. package/dist/hooks/subagent-start.d.mts +1 -0
  49. package/dist/hooks/subagent-start.mjs +43 -0
  50. package/dist/hooks/subagent-start.mjs.map +1 -0
  51. package/dist/hooks/subagent-stop.d.mts +1 -0
  52. package/dist/hooks/subagent-stop.mjs +45 -0
  53. package/dist/hooks/subagent-stop.mjs.map +1 -0
  54. package/dist/hooks/task-completed.d.mts +1 -0
  55. package/dist/hooks/task-completed.mjs +46 -0
  56. package/dist/hooks/task-completed.mjs.map +1 -0
  57. package/dist/iii-config.yaml +51 -0
  58. package/dist/index.d.mts +2 -0
  59. package/dist/index.mjs +13776 -0
  60. package/dist/index.mjs.map +1 -0
  61. package/dist/src-QxitMPfJ.mjs +13775 -0
  62. package/dist/src-QxitMPfJ.mjs.map +1 -0
  63. package/dist/standalone.d.mts +1 -0
  64. package/dist/standalone.mjs +1155 -0
  65. package/dist/standalone.mjs.map +1 -0
  66. package/dist/transformers-BX_tgxdO.mjs +38684 -0
  67. package/dist/transformers-BX_tgxdO.mjs.map +1 -0
  68. package/dist/transformers-KMm1i9no.mjs +38683 -0
  69. package/dist/transformers-KMm1i9no.mjs.map +1 -0
  70. package/docker-compose.yml +14 -0
  71. package/iii-config.yaml +51 -0
  72. package/package.json +59 -0
  73. package/plugin/.claude-plugin/plugin.json +10 -0
  74. package/plugin/hooks/hooks.json +77 -0
  75. package/plugin/scripts/diagnostics.mjs +551 -0
  76. package/plugin/scripts/notification.mjs +45 -0
  77. package/plugin/scripts/post-tool-failure.mjs +45 -0
  78. package/plugin/scripts/post-tool-use.mjs +53 -0
  79. package/plugin/scripts/pre-compact.mjs +50 -0
  80. package/plugin/scripts/pre-tool-use.mjs +69 -0
  81. package/plugin/scripts/prompt-submit.mjs +40 -0
  82. package/plugin/scripts/session-end.mjs +61 -0
  83. package/plugin/scripts/session-start.mjs +42 -0
  84. package/plugin/scripts/stop.mjs +33 -0
  85. package/plugin/scripts/subagent-start.mjs +43 -0
  86. package/plugin/scripts/subagent-stop.mjs +45 -0
  87. package/plugin/scripts/task-completed.mjs +46 -0
  88. package/plugin/skills/forget/SKILL.md +32 -0
  89. package/plugin/skills/recall/SKILL.md +18 -0
  90. package/plugin/skills/remember/SKILL.md +25 -0
  91. package/plugin/skills/session-history/SKILL.md +17 -0
  92. package/src/auth.ts +12 -0
  93. package/src/cli.ts +159 -0
  94. package/src/config.ts +221 -0
  95. package/src/eval/metrics-store.ts +65 -0
  96. package/src/eval/quality.ts +51 -0
  97. package/src/eval/schemas.ts +124 -0
  98. package/src/eval/self-correct.ts +28 -0
  99. package/src/eval/validator.ts +31 -0
  100. package/src/functions/actions.ts +288 -0
  101. package/src/functions/audit.ts +61 -0
  102. package/src/functions/auto-forget.ts +169 -0
  103. package/src/functions/branch-aware.ts +169 -0
  104. package/src/functions/cascade.ts +80 -0
  105. package/src/functions/checkpoints.ts +209 -0
  106. package/src/functions/claude-bridge.ts +161 -0
  107. package/src/functions/compress.ts +194 -0
  108. package/src/functions/consolidate.ts +212 -0
  109. package/src/functions/consolidation-pipeline.ts +258 -0
  110. package/src/functions/context.ts +169 -0
  111. package/src/functions/crystallize.ts +293 -0
  112. package/src/functions/dedup.ts +57 -0
  113. package/src/functions/diagnostics.ts +785 -0
  114. package/src/functions/enrich.ts +132 -0
  115. package/src/functions/evict.ts +163 -0
  116. package/src/functions/export-import.ts +508 -0
  117. package/src/functions/facets.ts +248 -0
  118. package/src/functions/file-index.ts +106 -0
  119. package/src/functions/flow-compress.ts +214 -0
  120. package/src/functions/frontier.ts +196 -0
  121. package/src/functions/governance.ts +131 -0
  122. package/src/functions/graph-retrieval.ts +277 -0
  123. package/src/functions/graph.ts +275 -0
  124. package/src/functions/leases.ts +216 -0
  125. package/src/functions/lessons.ts +253 -0
  126. package/src/functions/mesh.ts +434 -0
  127. package/src/functions/migrate.ts +165 -0
  128. package/src/functions/observe.ts +144 -0
  129. package/src/functions/obsidian-export.ts +310 -0
  130. package/src/functions/patterns.ts +138 -0
  131. package/src/functions/privacy.ts +39 -0
  132. package/src/functions/profile.ts +155 -0
  133. package/src/functions/query-expansion.ts +186 -0
  134. package/src/functions/relations.ts +237 -0
  135. package/src/functions/remember.ts +162 -0
  136. package/src/functions/retention.ts +235 -0
  137. package/src/functions/routines.ts +289 -0
  138. package/src/functions/search.ts +80 -0
  139. package/src/functions/sentinels.ts +417 -0
  140. package/src/functions/signals.ts +186 -0
  141. package/src/functions/sketches.ts +274 -0
  142. package/src/functions/sliding-window.ts +257 -0
  143. package/src/functions/smart-search.ts +115 -0
  144. package/src/functions/snapshot.ts +219 -0
  145. package/src/functions/summarize.ts +155 -0
  146. package/src/functions/team.ts +147 -0
  147. package/src/functions/temporal-graph.ts +476 -0
  148. package/src/functions/timeline.ts +138 -0
  149. package/src/functions/verify.ts +117 -0
  150. package/src/health/monitor.ts +110 -0
  151. package/src/health/thresholds.ts +73 -0
  152. package/src/hooks/notification.ts +52 -0
  153. package/src/hooks/post-tool-failure.ts +58 -0
  154. package/src/hooks/post-tool-use.ts +62 -0
  155. package/src/hooks/pre-compact.ts +60 -0
  156. package/src/hooks/pre-tool-use.ts +72 -0
  157. package/src/hooks/prompt-submit.ts +46 -0
  158. package/src/hooks/session-end.ts +71 -0
  159. package/src/hooks/session-start.ts +48 -0
  160. package/src/hooks/stop.ts +39 -0
  161. package/src/hooks/subagent-start.ts +49 -0
  162. package/src/hooks/subagent-stop.ts +54 -0
  163. package/src/hooks/task-completed.ts +54 -0
  164. package/src/index.ts +342 -0
  165. package/src/mcp/in-memory-kv.ts +61 -0
  166. package/src/mcp/server.ts +1455 -0
  167. package/src/mcp/standalone.ts +177 -0
  168. package/src/mcp/tools-registry.ts +769 -0
  169. package/src/mcp/transport.ts +91 -0
  170. package/src/prompts/compression.ts +67 -0
  171. package/src/prompts/consolidation.ts +48 -0
  172. package/src/prompts/graph-extraction.ts +35 -0
  173. package/src/prompts/summary.ts +38 -0
  174. package/src/prompts/xml.ts +26 -0
  175. package/src/providers/agent-sdk.ts +34 -0
  176. package/src/providers/anthropic.ts +35 -0
  177. package/src/providers/circuit-breaker.ts +82 -0
  178. package/src/providers/embedding/cohere.ts +46 -0
  179. package/src/providers/embedding/gemini.ts +54 -0
  180. package/src/providers/embedding/index.ts +39 -0
  181. package/src/providers/embedding/local.ts +52 -0
  182. package/src/providers/embedding/openai.ts +45 -0
  183. package/src/providers/embedding/openrouter.ts +51 -0
  184. package/src/providers/embedding/voyage.ts +46 -0
  185. package/src/providers/fallback-chain.ts +31 -0
  186. package/src/providers/index.ts +84 -0
  187. package/src/providers/openrouter.ts +71 -0
  188. package/src/providers/resilient.ts +37 -0
  189. package/src/state/hybrid-search.ts +295 -0
  190. package/src/state/index-persistence.ts +63 -0
  191. package/src/state/keyed-mutex.ts +18 -0
  192. package/src/state/kv.ts +33 -0
  193. package/src/state/schema.ts +71 -0
  194. package/src/state/search-index.ts +245 -0
  195. package/src/state/stemmer.ts +104 -0
  196. package/src/state/synonyms.ts +63 -0
  197. package/src/state/vector-index.ts +130 -0
  198. package/src/telemetry/setup.ts +116 -0
  199. package/src/triggers/api.ts +1904 -0
  200. package/src/triggers/events.ts +71 -0
  201. package/src/types.ts +769 -0
  202. package/src/version.ts +1 -0
  203. package/src/viewer/index.html +2497 -0
  204. package/src/viewer/server.ts +207 -0
  205. package/src/xenova.d.ts +3 -0
  206. package/test/actions.test.ts +490 -0
  207. package/test/audit.test.ts +108 -0
  208. package/test/auto-forget.test.ts +188 -0
  209. package/test/cascade.test.ts +277 -0
  210. package/test/checkpoints.test.ts +493 -0
  211. package/test/circuit-breaker.test.ts +107 -0
  212. package/test/claude-bridge.test.ts +178 -0
  213. package/test/confidence.test.ts +247 -0
  214. package/test/consistency.test.ts +61 -0
  215. package/test/consolidation-pipeline.test.ts +251 -0
  216. package/test/crystallize.test.ts +521 -0
  217. package/test/diagnostics.test.ts +638 -0
  218. package/test/embedding-provider.test.ts +49 -0
  219. package/test/enrich.test.ts +209 -0
  220. package/test/eval.test.ts +300 -0
  221. package/test/export-import.test.ts +251 -0
  222. package/test/facets.test.ts +448 -0
  223. package/test/fallback-chain.test.ts +93 -0
  224. package/test/frontier.test.ts +485 -0
  225. package/test/governance.test.ts +147 -0
  226. package/test/graph-retrieval.test.ts +186 -0
  227. package/test/graph.test.ts +160 -0
  228. package/test/helpers/mocks.ts +40 -0
  229. package/test/hybrid-search.test.ts +145 -0
  230. package/test/index-persistence.test.ts +124 -0
  231. package/test/integration.test.ts +265 -0
  232. package/test/leases.test.ts +399 -0
  233. package/test/mcp-prompts.test.ts +218 -0
  234. package/test/mcp-resources.test.ts +286 -0
  235. package/test/mcp-standalone.test.ts +113 -0
  236. package/test/mesh.test.ts +700 -0
  237. package/test/privacy.test.ts +87 -0
  238. package/test/profile.test.ts +161 -0
  239. package/test/query-expansion.test.ts +154 -0
  240. package/test/relations.test.ts +198 -0
  241. package/test/retention.test.ts +245 -0
  242. package/test/routines.test.ts +497 -0
  243. package/test/schema-fingerprint.test.ts +81 -0
  244. package/test/schema.test.ts +42 -0
  245. package/test/search-index.test.ts +128 -0
  246. package/test/sentinels.test.ts +626 -0
  247. package/test/signals.test.ts +410 -0
  248. package/test/sketches.test.ts +549 -0
  249. package/test/sliding-window.test.ts +199 -0
  250. package/test/smart-search.test.ts +169 -0
  251. package/test/snapshot.test.ts +165 -0
  252. package/test/team.test.ts +156 -0
  253. package/test/temporal-graph.test.ts +378 -0
  254. package/test/timeline.test.ts +148 -0
  255. package/test/vector-index.test.ts +79 -0
  256. package/test/verify.test.ts +209 -0
  257. package/test/xml.test.ts +65 -0
  258. package/tsconfig.json +22 -0
  259. package/tsdown.config.ts +62 -0
@@ -0,0 +1,212 @@
1
+ import type { ISdk } from "iii-sdk";
2
+ import { getContext } from "iii-sdk";
3
+ import type {
4
+ CompressedObservation,
5
+ Memory,
6
+ Session,
7
+ MemoryProvider,
8
+ } from "../types.js";
9
+ import { KV, generateId } from "../state/schema.js";
10
+ import { StateKV } from "../state/kv.js";
11
+
12
+ const CONSOLIDATION_SYSTEM = `You are a memory consolidation engine. Given a set of related observations from coding sessions, synthesize them into a single long-term memory.
13
+
14
+ Output XML:
15
+ <memory>
16
+ <type>pattern|preference|architecture|bug|workflow|fact</type>
17
+ <title>Concise memory title (max 80 chars)</title>
18
+ <content>2-4 sentence description of the learned insight</content>
19
+ <concepts>
20
+ <concept>key term</concept>
21
+ </concepts>
22
+ <files>
23
+ <file>relevant/file/path</file>
24
+ </files>
25
+ <strength>1-10 how confident/important this memory is</strength>
26
+ </memory>`;
27
+
28
+ import { getXmlTag, getXmlChildren } from "../prompts/xml.js";
29
+
30
+ function parseMemoryXml(
31
+ xml: string,
32
+ sessionIds: string[],
33
+ ): Omit<Memory, "id" | "createdAt" | "updatedAt"> | null {
34
+ const type = getXmlTag(xml, "type");
35
+ const title = getXmlTag(xml, "title");
36
+ const content = getXmlTag(xml, "content");
37
+ if (!type || !title || !content) return null;
38
+
39
+ const validTypes = new Set([
40
+ "pattern",
41
+ "preference",
42
+ "architecture",
43
+ "bug",
44
+ "workflow",
45
+ "fact",
46
+ ]);
47
+
48
+ return {
49
+ type: (validTypes.has(type) ? type : "fact") as Memory["type"],
50
+ title,
51
+ content,
52
+ concepts: getXmlChildren(xml, "concepts", "concept"),
53
+ files: getXmlChildren(xml, "files", "file"),
54
+ sessionIds,
55
+ strength: Math.max(
56
+ 1,
57
+ Math.min(10, parseInt(getXmlTag(xml, "strength") || "5", 10) || 5),
58
+ ),
59
+ version: 1,
60
+ isLatest: true,
61
+ };
62
+ }
63
+
64
+ export function registerConsolidateFunction(
65
+ sdk: ISdk,
66
+ kv: StateKV,
67
+ provider: MemoryProvider,
68
+ ): void {
69
+ sdk.registerFunction(
70
+ { id: "mem::consolidate" },
71
+ async (data: { project?: string; minObservations?: number }) => {
72
+ const ctx = getContext();
73
+ const minObs = data.minObservations ?? 10;
74
+
75
+ const sessions = await kv.list<Session>(KV.sessions);
76
+ const filtered = data.project
77
+ ? sessions.filter((s) => s.project === data.project)
78
+ : sessions;
79
+
80
+ const allObs: Array<CompressedObservation & { sid: string }> = [];
81
+ const obsPerSession: CompressedObservation[][] = [];
82
+ for (let batch = 0; batch < filtered.length; batch += 10) {
83
+ const chunk = filtered.slice(batch, batch + 10);
84
+ const results = await Promise.all(
85
+ chunk.map((s) =>
86
+ kv
87
+ .list<CompressedObservation>(KV.observations(s.id))
88
+ .catch(() => [] as CompressedObservation[]),
89
+ ),
90
+ );
91
+ obsPerSession.push(...results);
92
+ }
93
+ for (let i = 0; i < filtered.length; i++) {
94
+ for (const obs of obsPerSession[i]) {
95
+ if (obs.title && obs.importance >= 5) {
96
+ allObs.push({ ...obs, sid: filtered[i].id });
97
+ }
98
+ }
99
+ }
100
+
101
+ if (allObs.length < minObs) {
102
+ return { consolidated: 0, reason: "insufficient_observations" };
103
+ }
104
+
105
+ const conceptGroups = new Map<string, typeof allObs>();
106
+ for (const obs of allObs) {
107
+ for (const concept of obs.concepts) {
108
+ const key = concept.toLowerCase();
109
+ if (!conceptGroups.has(key)) conceptGroups.set(key, []);
110
+ conceptGroups.get(key)!.push(obs);
111
+ }
112
+ }
113
+
114
+ let consolidated = 0;
115
+ const existingMemories = await kv.list<Memory>(KV.memories);
116
+ const existingTitles = new Set(
117
+ existingMemories.map((m) => m.title.toLowerCase()),
118
+ );
119
+
120
+ const MAX_LLM_CALLS = 10;
121
+ let llmCallCount = 0;
122
+
123
+ const sortedGroups = [...conceptGroups.entries()]
124
+ .filter(([, g]) => g.length >= 3)
125
+ .sort((a, b) => b[1].length - a[1].length);
126
+
127
+ for (const [concept, obsGroup] of sortedGroups) {
128
+ if (llmCallCount >= MAX_LLM_CALLS) break;
129
+
130
+ const top = obsGroup
131
+ .sort((a, b) => b.importance - a.importance)
132
+ .slice(0, 8);
133
+ const sessionIds = [...new Set(top.map((o) => o.sid))];
134
+
135
+ const prompt = top
136
+ .map(
137
+ (o) =>
138
+ `[${o.type}] ${o.title}\n${o.narrative}\nFiles: ${o.files.join(", ")}\nImportance: ${o.importance}`,
139
+ )
140
+ .join("\n\n");
141
+
142
+ try {
143
+ const response = await Promise.race([
144
+ provider.compress(
145
+ CONSOLIDATION_SYSTEM,
146
+ `Concept: "${concept}"\n\nObservations:\n${prompt}`,
147
+ ),
148
+ new Promise<never>((_, reject) =>
149
+ setTimeout(() => reject(new Error("compress timeout")), 30_000),
150
+ ),
151
+ ]);
152
+ llmCallCount++;
153
+ const parsed = parseMemoryXml(response, sessionIds);
154
+ if (!parsed) continue;
155
+
156
+ const existingMatch = existingMemories.find(
157
+ (m) => m.title.toLowerCase() === parsed.title.toLowerCase(),
158
+ );
159
+
160
+ const now = new Date().toISOString();
161
+ const obsIds = [...new Set(top.map((o) => o.id))];
162
+ if (existingMatch) {
163
+ existingMatch.isLatest = false;
164
+ await kv.set(KV.memories, existingMatch.id, existingMatch);
165
+
166
+ const evolved: Memory = {
167
+ id: generateId("mem"),
168
+ createdAt: now,
169
+ updatedAt: now,
170
+ ...parsed,
171
+ version: (existingMatch.version || 1) + 1,
172
+ parentId: existingMatch.id,
173
+ supersedes: [
174
+ existingMatch.id,
175
+ ...(existingMatch.supersedes || []),
176
+ ],
177
+ sourceObservationIds: obsIds,
178
+ isLatest: true,
179
+ };
180
+ await kv.set(KV.memories, evolved.id, evolved);
181
+ existingTitles.add(evolved.title.toLowerCase());
182
+ consolidated++;
183
+ } else {
184
+ const memory: Memory = {
185
+ id: generateId("mem"),
186
+ createdAt: now,
187
+ updatedAt: now,
188
+ ...parsed,
189
+ sourceObservationIds: obsIds,
190
+ version: 1,
191
+ isLatest: true,
192
+ };
193
+ await kv.set(KV.memories, memory.id, memory);
194
+ existingTitles.add(memory.title.toLowerCase());
195
+ consolidated++;
196
+ }
197
+ } catch (err) {
198
+ ctx.logger.warn("Consolidation failed for concept", {
199
+ concept,
200
+ error: err instanceof Error ? err.message : String(err),
201
+ });
202
+ }
203
+ }
204
+
205
+ ctx.logger.info("Consolidation complete", {
206
+ consolidated,
207
+ totalObs: allObs.length,
208
+ });
209
+ return { consolidated, totalObservations: allObs.length };
210
+ },
211
+ );
212
+ }
@@ -0,0 +1,258 @@
1
+ import type { ISdk } from "iii-sdk";
2
+ import { getContext } from "iii-sdk";
3
+ import type {
4
+ SemanticMemory,
5
+ ProceduralMemory,
6
+ SessionSummary,
7
+ Memory,
8
+ MemoryProvider,
9
+ } from "../types.js";
10
+ import { KV, generateId } from "../state/schema.js";
11
+ import type { StateKV } from "../state/kv.js";
12
+ import {
13
+ SEMANTIC_MERGE_SYSTEM,
14
+ buildSemanticMergePrompt,
15
+ PROCEDURAL_EXTRACTION_SYSTEM,
16
+ buildProceduralExtractionPrompt,
17
+ } from "../prompts/consolidation.js";
18
+ import { recordAudit } from "./audit.js";
19
+ import { getConsolidationDecayDays, isConsolidationEnabled } from "../config.js";
20
+
21
+ function applyDecay(
22
+ items: Array<{
23
+ strength: number;
24
+ lastAccessedAt?: string;
25
+ updatedAt: string;
26
+ }>,
27
+ decayDays: number,
28
+ ): void {
29
+ if (decayDays <= 0 || !Number.isFinite(decayDays)) return;
30
+ const now = Date.now();
31
+ for (const item of items) {
32
+ const lastAccess = item.lastAccessedAt || item.updatedAt;
33
+ const daysSince =
34
+ (now - new Date(lastAccess).getTime()) / (1000 * 60 * 60 * 24);
35
+ if (daysSince > decayDays) {
36
+ const decayPeriods = Math.floor(daysSince / decayDays);
37
+ item.strength = Math.max(
38
+ 0.1,
39
+ item.strength * Math.pow(0.9, decayPeriods),
40
+ );
41
+ }
42
+ }
43
+ }
44
+
45
+ export function registerConsolidationPipelineFunction(
46
+ sdk: ISdk,
47
+ kv: StateKV,
48
+ provider: MemoryProvider,
49
+ ): void {
50
+ sdk.registerFunction(
51
+ { id: "mem::consolidate-pipeline" },
52
+ async (data?: { tier?: string; force?: boolean }) => {
53
+ if (!data?.force && !isConsolidationEnabled()) {
54
+ return { success: false, skipped: true, reason: "CONSOLIDATION_ENABLED is not set to true" };
55
+ }
56
+ const ctx = getContext();
57
+ const tier = data?.tier || "all";
58
+ const decayDays = getConsolidationDecayDays();
59
+ const results: Record<string, unknown> = {};
60
+
61
+ if (tier === "all" || tier === "semantic") {
62
+ const summaries = await kv.list<SessionSummary>(KV.summaries);
63
+ const existingSemantic = await kv.list<SemanticMemory>(KV.semantic);
64
+
65
+ if (summaries.length >= 5) {
66
+ const recentSummaries = summaries
67
+ .sort(
68
+ (a, b) =>
69
+ new Date(b.createdAt).getTime() -
70
+ new Date(a.createdAt).getTime(),
71
+ )
72
+ .slice(0, 20);
73
+
74
+ const prompt = buildSemanticMergePrompt(
75
+ recentSummaries.map((s) => ({
76
+ title: s.title,
77
+ narrative: s.narrative,
78
+ concepts: s.concepts,
79
+ })),
80
+ );
81
+
82
+ try {
83
+ const response = await provider.summarize(
84
+ SEMANTIC_MERGE_SYSTEM,
85
+ prompt,
86
+ );
87
+
88
+ const factRegex = /<fact\s+confidence="([^"]+)">([^<]+)<\/fact>/g;
89
+ let match;
90
+ let newFacts = 0;
91
+ const now = new Date().toISOString();
92
+
93
+ while ((match = factRegex.exec(response)) !== null) {
94
+ const parsedConf = parseFloat(match[1]);
95
+ const confidence = Number.isNaN(parsedConf) ? 0.5 : parsedConf;
96
+ const fact = match[2].trim();
97
+
98
+ const existing = existingSemantic.find(
99
+ (s) => s.fact.toLowerCase() === fact.toLowerCase(),
100
+ );
101
+ if (existing) {
102
+ existing.accessCount++;
103
+ existing.lastAccessedAt = now;
104
+ existing.updatedAt = now;
105
+ existing.confidence = Math.max(existing.confidence, confidence);
106
+ await kv.set(KV.semantic, existing.id, existing);
107
+ } else {
108
+ const sem: SemanticMemory = {
109
+ id: generateId("sem"),
110
+ fact,
111
+ confidence,
112
+ sourceSessionIds: recentSummaries.map((s) => s.sessionId),
113
+ sourceMemoryIds: [],
114
+ accessCount: 1,
115
+ lastAccessedAt: now,
116
+ strength: confidence,
117
+ createdAt: now,
118
+ updatedAt: now,
119
+ };
120
+ await kv.set(KV.semantic, sem.id, sem);
121
+ newFacts++;
122
+ }
123
+ }
124
+ results.semantic = { newFacts, totalSummaries: summaries.length };
125
+ } catch (err) {
126
+ const msg = err instanceof Error ? err.message : String(err);
127
+ ctx.logger.error("Semantic consolidation failed", { error: msg });
128
+ results.semantic = { error: msg };
129
+ }
130
+ } else {
131
+ results.semantic = {
132
+ skipped: true,
133
+ reason: "fewer than 5 summaries",
134
+ };
135
+ }
136
+ }
137
+
138
+ if (tier === "all" || tier === "procedural") {
139
+ const memories = await kv.list<Memory>(KV.memories);
140
+ const patterns = memories
141
+ .filter((m) => m.isLatest && m.type === "pattern")
142
+ .map((m) => ({
143
+ content: m.content,
144
+ frequency: m.sessionIds.length || 1,
145
+ }))
146
+ .filter((p) => p.frequency >= 2);
147
+
148
+ if (patterns.length >= 2) {
149
+ const prompt = buildProceduralExtractionPrompt(patterns);
150
+
151
+ try {
152
+ const response = await provider.summarize(
153
+ PROCEDURAL_EXTRACTION_SYSTEM,
154
+ prompt,
155
+ );
156
+
157
+ const procRegex =
158
+ /<procedure\s+name="([^"]+)"\s+trigger="([^"]+)">([\s\S]*?)<\/procedure>/g;
159
+ let match;
160
+ let newProcs = 0;
161
+ const now = new Date().toISOString();
162
+ const existingProcs = await kv.list<ProceduralMemory>(
163
+ KV.procedural,
164
+ );
165
+
166
+ while ((match = procRegex.exec(response)) !== null) {
167
+ const name = match[1];
168
+ const trigger = match[2];
169
+ const stepsBlock = match[3];
170
+ const steps: string[] = [];
171
+
172
+ const stepRegex = /<step>([^<]+)<\/step>/g;
173
+ let stepMatch;
174
+ while ((stepMatch = stepRegex.exec(stepsBlock)) !== null) {
175
+ steps.push(stepMatch[1].trim());
176
+ }
177
+
178
+ const existing = existingProcs.find(
179
+ (p) => p.name.toLowerCase() === name.toLowerCase(),
180
+ );
181
+ if (existing) {
182
+ existing.frequency++;
183
+ existing.updatedAt = now;
184
+ existing.strength = Math.min(1, existing.strength + 0.1);
185
+ await kv.set(KV.procedural, existing.id, existing);
186
+ } else {
187
+ const proc: ProceduralMemory = {
188
+ id: generateId("proc"),
189
+ name,
190
+ steps,
191
+ triggerCondition: trigger,
192
+ frequency: 1,
193
+ sourceSessionIds: [],
194
+ strength: 0.5,
195
+ createdAt: now,
196
+ updatedAt: now,
197
+ };
198
+ await kv.set(KV.procedural, proc.id, proc);
199
+ newProcs++;
200
+ }
201
+ }
202
+ results.procedural = {
203
+ newProcedures: newProcs,
204
+ patternsAnalyzed: patterns.length,
205
+ };
206
+ } catch (err) {
207
+ const msg = err instanceof Error ? err.message : String(err);
208
+ ctx.logger.error("Procedural extraction failed", { error: msg });
209
+ results.procedural = { error: msg };
210
+ }
211
+ } else {
212
+ results.procedural = {
213
+ skipped: true,
214
+ reason: "fewer than 2 recurring patterns",
215
+ };
216
+ }
217
+ }
218
+
219
+ if (tier === "all" || tier === "decay") {
220
+ const semantic = await kv.list<SemanticMemory>(KV.semantic);
221
+ applyDecay(semantic, decayDays);
222
+ for (const s of semantic) {
223
+ await kv.set(KV.semantic, s.id, s);
224
+ }
225
+
226
+ const procedural = await kv.list<ProceduralMemory>(KV.procedural);
227
+ applyDecay(procedural, decayDays);
228
+ for (const p of procedural) {
229
+ await kv.set(KV.procedural, p.id, p);
230
+ }
231
+
232
+ results.decay = {
233
+ semantic: semantic.length,
234
+ procedural: procedural.length,
235
+ };
236
+ }
237
+
238
+ if (process.env["OBSIDIAN_AUTO_EXPORT"] === "true") {
239
+ try {
240
+ await sdk.trigger("mem::obsidian-export", {});
241
+ results.obsidianExport = { success: true };
242
+ } catch (err) {
243
+ const msg = err instanceof Error ? err.message : String(err);
244
+ ctx.logger.warn("Obsidian auto-export failed", { error: msg });
245
+ results.obsidianExport = { success: false, error: msg };
246
+ }
247
+ }
248
+
249
+ await recordAudit(kv, "consolidate", "mem::consolidate-pipeline", [], {
250
+ tier,
251
+ results,
252
+ });
253
+
254
+ ctx.logger.info("Consolidation pipeline complete", { tier, results });
255
+ return { success: true, results };
256
+ },
257
+ );
258
+ }
@@ -0,0 +1,169 @@
1
+ import type { ISdk } from "iii-sdk";
2
+ import { getContext } from "iii-sdk";
3
+ import type {
4
+ Session,
5
+ CompressedObservation,
6
+ SessionSummary,
7
+ ContextBlock,
8
+ ProjectProfile,
9
+ } from "../types.js";
10
+ import { KV } from "../state/schema.js";
11
+ import { StateKV } from "../state/kv.js";
12
+
13
+ function estimateTokens(text: string): number {
14
+ return Math.ceil(text.length / 3);
15
+ }
16
+
17
+ function escapeXmlAttr(s: string): string {
18
+ return s
19
+ .replace(/&/g, "&amp;")
20
+ .replace(/"/g, "&quot;")
21
+ .replace(/</g, "&lt;")
22
+ .replace(/>/g, "&gt;");
23
+ }
24
+
25
+ export function registerContextFunction(
26
+ sdk: ISdk,
27
+ kv: StateKV,
28
+ tokenBudget: number,
29
+ ): void {
30
+ sdk.registerFunction(
31
+ {
32
+ id: "mem::context",
33
+ description: "Generate context for session injection",
34
+ },
35
+ async (data: { sessionId: string; project: string; budget?: number }) => {
36
+ const ctx = getContext();
37
+ const budget = data.budget || tokenBudget;
38
+ const blocks: ContextBlock[] = [];
39
+
40
+ const profile = await kv
41
+ .get<ProjectProfile>(KV.profiles, data.project)
42
+ .catch(() => null);
43
+ if (profile) {
44
+ const profileParts = [];
45
+ if (profile.topConcepts.length > 0) {
46
+ profileParts.push(
47
+ `Concepts: ${profile.topConcepts
48
+ .slice(0, 8)
49
+ .map((c) => c.concept)
50
+ .join(", ")}`,
51
+ );
52
+ }
53
+ if (profile.topFiles.length > 0) {
54
+ profileParts.push(
55
+ `Key files: ${profile.topFiles
56
+ .slice(0, 5)
57
+ .map((f) => f.file)
58
+ .join(", ")}`,
59
+ );
60
+ }
61
+ if (profile.conventions.length > 0) {
62
+ profileParts.push(`Conventions: ${profile.conventions.join("; ")}`);
63
+ }
64
+ if (profile.commonErrors.length > 0) {
65
+ profileParts.push(
66
+ `Common errors: ${profile.commonErrors.slice(0, 3).join("; ")}`,
67
+ );
68
+ }
69
+ if (profileParts.length > 0) {
70
+ const profileContent = `## Project Profile\n${profileParts.join("\n")}`;
71
+ blocks.push({
72
+ type: "memory",
73
+ content: profileContent,
74
+ tokens: estimateTokens(profileContent),
75
+ recency: new Date(profile.updatedAt).getTime(),
76
+ });
77
+ }
78
+ }
79
+
80
+ const allSessions = await kv.list<Session>(KV.sessions);
81
+ const sessions = allSessions
82
+ .filter((s) => s.project === data.project && s.id !== data.sessionId)
83
+ .sort(
84
+ (a, b) =>
85
+ new Date(b.startedAt).getTime() - new Date(a.startedAt).getTime(),
86
+ )
87
+ .slice(0, 10);
88
+
89
+ const summariesPerSession = await Promise.all(
90
+ sessions.map((s) =>
91
+ kv.get<SessionSummary>(KV.summaries, s.id).catch(() => null),
92
+ ),
93
+ );
94
+
95
+ const sessionsNeedingObs: number[] = [];
96
+ for (let i = 0; i < sessions.length; i++) {
97
+ const summary = summariesPerSession[i];
98
+ if (summary) {
99
+ const content = `## ${summary.title}\n${summary.narrative}\nDecisions: ${summary.keyDecisions.join("; ")}\nFiles: ${summary.filesModified.join(", ")}`;
100
+ blocks.push({
101
+ type: "summary",
102
+ content,
103
+ tokens: estimateTokens(content),
104
+ recency: new Date(summary.createdAt).getTime(),
105
+ });
106
+ } else {
107
+ sessionsNeedingObs.push(i);
108
+ }
109
+ }
110
+
111
+ const obsResults = await Promise.all(
112
+ sessionsNeedingObs.map((i) =>
113
+ kv
114
+ .list<CompressedObservation>(KV.observations(sessions[i].id))
115
+ .catch(() => []),
116
+ ),
117
+ );
118
+
119
+ for (let j = 0; j < sessionsNeedingObs.length; j++) {
120
+ const i = sessionsNeedingObs[j];
121
+ const observations = obsResults[j];
122
+ const important = observations.filter(
123
+ (o) => o.title && o.importance >= 5,
124
+ );
125
+
126
+ if (important.length > 0) {
127
+ const items = important
128
+ .sort((a, b) => b.importance - a.importance)
129
+ .slice(0, 5)
130
+ .map((o) => `- [${o.type}] ${o.title}: ${o.narrative}`)
131
+ .join("\n");
132
+ const content = `## Session ${sessions[i].id.slice(0, 8)} (${sessions[i].startedAt})\n${items}`;
133
+ blocks.push({
134
+ type: "observation",
135
+ content,
136
+ tokens: estimateTokens(content),
137
+ recency: new Date(sessions[i].startedAt).getTime(),
138
+ });
139
+ }
140
+ }
141
+
142
+ blocks.sort((a, b) => b.recency - a.recency);
143
+
144
+ let usedTokens = 0;
145
+ const selected: string[] = [];
146
+ const header = `<agentmemory-context project="${escapeXmlAttr(data.project)}">`;
147
+ const footer = `</agentmemory-context>`;
148
+ usedTokens += estimateTokens(header) + estimateTokens(footer);
149
+
150
+ for (const block of blocks) {
151
+ if (usedTokens + block.tokens > budget) break;
152
+ selected.push(block.content);
153
+ usedTokens += block.tokens;
154
+ }
155
+
156
+ if (selected.length === 0) {
157
+ ctx.logger.info("No context available", { project: data.project });
158
+ return { context: "", blocks: 0, tokens: 0 };
159
+ }
160
+
161
+ const result = `${header}\n${selected.join("\n\n")}\n${footer}`;
162
+ ctx.logger.info("Context generated", {
163
+ blocks: selected.length,
164
+ tokens: usedTokens,
165
+ });
166
+ return { context: result, blocks: selected.length, tokens: usedTokens };
167
+ },
168
+ );
169
+ }