@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,212 +0,0 @@
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
- }
@@ -1,258 +0,0 @@
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
- }
@@ -1,169 +0,0 @@
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
- }