@agentmemory/agentmemory 0.7.2 → 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 (217) hide show
  1. package/AGENTS.md +2 -2
  2. package/README.md +41 -68
  3. package/dist/cli.mjs +3 -3
  4. package/dist/index.mjs +3 -2
  5. package/dist/index.mjs.map +1 -1
  6. package/dist/{src-1fTKFEtN.mjs → src-sYZDDbiA.mjs} +4 -3
  7. package/dist/src-sYZDDbiA.mjs.map +1 -0
  8. package/dist/standalone.mjs +1 -1
  9. package/dist/standalone.mjs.map +1 -1
  10. package/package.json +10 -1
  11. package/plugin/.claude-plugin/plugin.json +1 -1
  12. package/plugin/scripts/notification.d.mts +1 -0
  13. package/plugin/scripts/notification.mjs.map +1 -0
  14. package/plugin/scripts/post-tool-failure.d.mts +1 -0
  15. package/plugin/scripts/post-tool-failure.mjs.map +1 -0
  16. package/plugin/scripts/post-tool-use.d.mts +1 -0
  17. package/plugin/scripts/post-tool-use.mjs.map +1 -0
  18. package/plugin/scripts/pre-compact.d.mts +1 -0
  19. package/plugin/scripts/pre-compact.mjs.map +1 -0
  20. package/plugin/scripts/pre-tool-use.d.mts +1 -0
  21. package/plugin/scripts/pre-tool-use.mjs.map +1 -0
  22. package/plugin/scripts/prompt-submit.d.mts +1 -0
  23. package/plugin/scripts/prompt-submit.mjs.map +1 -0
  24. package/plugin/scripts/session-end.d.mts +1 -0
  25. package/plugin/scripts/session-end.mjs.map +1 -0
  26. package/plugin/scripts/session-start.d.mts +1 -0
  27. package/plugin/scripts/session-start.mjs.map +1 -0
  28. package/plugin/scripts/stop.d.mts +1 -0
  29. package/plugin/scripts/stop.mjs.map +1 -0
  30. package/plugin/scripts/subagent-start.d.mts +1 -0
  31. package/plugin/scripts/subagent-start.mjs.map +1 -0
  32. package/plugin/scripts/subagent-stop.d.mts +1 -0
  33. package/plugin/scripts/subagent-stop.mjs.map +1 -0
  34. package/plugin/scripts/task-completed.d.mts +1 -0
  35. package/plugin/scripts/task-completed.mjs.map +1 -0
  36. package/.claude-plugin/marketplace.json +0 -14
  37. package/.github/workflows/ci.yml +0 -22
  38. package/.github/workflows/publish.yml +0 -28
  39. package/assets/banner.png +0 -0
  40. package/assets/demo.gif +0 -0
  41. package/assets/demo.mp4 +0 -0
  42. package/benchmark/QUALITY.md +0 -73
  43. package/benchmark/REAL-EMBEDDINGS.md +0 -67
  44. package/benchmark/SCALE.md +0 -110
  45. package/benchmark/dataset.ts +0 -293
  46. package/benchmark/quality-eval.ts +0 -643
  47. package/benchmark/real-embeddings-eval.ts +0 -405
  48. package/benchmark/scale-eval.ts +0 -398
  49. package/dist/src-1fTKFEtN.mjs.map +0 -1
  50. package/src/auth.ts +0 -12
  51. package/src/cli.ts +0 -251
  52. package/src/config.ts +0 -221
  53. package/src/eval/metrics-store.ts +0 -65
  54. package/src/eval/quality.ts +0 -51
  55. package/src/eval/schemas.ts +0 -124
  56. package/src/eval/self-correct.ts +0 -28
  57. package/src/eval/validator.ts +0 -31
  58. package/src/functions/actions.ts +0 -288
  59. package/src/functions/audit.ts +0 -61
  60. package/src/functions/auto-forget.ts +0 -169
  61. package/src/functions/branch-aware.ts +0 -169
  62. package/src/functions/cascade.ts +0 -80
  63. package/src/functions/checkpoints.ts +0 -209
  64. package/src/functions/claude-bridge.ts +0 -161
  65. package/src/functions/compress.ts +0 -194
  66. package/src/functions/consolidate.ts +0 -212
  67. package/src/functions/consolidation-pipeline.ts +0 -258
  68. package/src/functions/context.ts +0 -169
  69. package/src/functions/crystallize.ts +0 -293
  70. package/src/functions/dedup.ts +0 -57
  71. package/src/functions/diagnostics.ts +0 -785
  72. package/src/functions/enrich.ts +0 -132
  73. package/src/functions/evict.ts +0 -163
  74. package/src/functions/export-import.ts +0 -508
  75. package/src/functions/facets.ts +0 -248
  76. package/src/functions/file-index.ts +0 -106
  77. package/src/functions/flow-compress.ts +0 -214
  78. package/src/functions/frontier.ts +0 -196
  79. package/src/functions/governance.ts +0 -131
  80. package/src/functions/graph-retrieval.ts +0 -277
  81. package/src/functions/graph.ts +0 -275
  82. package/src/functions/leases.ts +0 -216
  83. package/src/functions/lessons.ts +0 -253
  84. package/src/functions/mesh.ts +0 -434
  85. package/src/functions/migrate.ts +0 -165
  86. package/src/functions/observe.ts +0 -144
  87. package/src/functions/obsidian-export.ts +0 -310
  88. package/src/functions/patterns.ts +0 -138
  89. package/src/functions/privacy.ts +0 -39
  90. package/src/functions/profile.ts +0 -155
  91. package/src/functions/query-expansion.ts +0 -186
  92. package/src/functions/relations.ts +0 -237
  93. package/src/functions/remember.ts +0 -162
  94. package/src/functions/retention.ts +0 -235
  95. package/src/functions/routines.ts +0 -289
  96. package/src/functions/search.ts +0 -80
  97. package/src/functions/sentinels.ts +0 -417
  98. package/src/functions/signals.ts +0 -186
  99. package/src/functions/sketches.ts +0 -274
  100. package/src/functions/sliding-window.ts +0 -257
  101. package/src/functions/smart-search.ts +0 -115
  102. package/src/functions/snapshot.ts +0 -219
  103. package/src/functions/summarize.ts +0 -155
  104. package/src/functions/team.ts +0 -147
  105. package/src/functions/temporal-graph.ts +0 -476
  106. package/src/functions/timeline.ts +0 -138
  107. package/src/functions/verify.ts +0 -117
  108. package/src/health/monitor.ts +0 -110
  109. package/src/health/thresholds.ts +0 -73
  110. package/src/hooks/notification.ts +0 -52
  111. package/src/hooks/post-tool-failure.ts +0 -58
  112. package/src/hooks/post-tool-use.ts +0 -62
  113. package/src/hooks/pre-compact.ts +0 -60
  114. package/src/hooks/pre-tool-use.ts +0 -72
  115. package/src/hooks/prompt-submit.ts +0 -46
  116. package/src/hooks/session-end.ts +0 -71
  117. package/src/hooks/session-start.ts +0 -48
  118. package/src/hooks/stop.ts +0 -39
  119. package/src/hooks/subagent-start.ts +0 -49
  120. package/src/hooks/subagent-stop.ts +0 -54
  121. package/src/hooks/task-completed.ts +0 -54
  122. package/src/index.ts +0 -342
  123. package/src/mcp/in-memory-kv.ts +0 -61
  124. package/src/mcp/server.ts +0 -1455
  125. package/src/mcp/standalone.ts +0 -177
  126. package/src/mcp/tools-registry.ts +0 -769
  127. package/src/mcp/transport.ts +0 -91
  128. package/src/prompts/compression.ts +0 -67
  129. package/src/prompts/consolidation.ts +0 -48
  130. package/src/prompts/graph-extraction.ts +0 -35
  131. package/src/prompts/summary.ts +0 -38
  132. package/src/prompts/xml.ts +0 -26
  133. package/src/providers/agent-sdk.ts +0 -34
  134. package/src/providers/anthropic.ts +0 -35
  135. package/src/providers/circuit-breaker.ts +0 -82
  136. package/src/providers/embedding/cohere.ts +0 -46
  137. package/src/providers/embedding/gemini.ts +0 -54
  138. package/src/providers/embedding/index.ts +0 -39
  139. package/src/providers/embedding/local.ts +0 -52
  140. package/src/providers/embedding/openai.ts +0 -45
  141. package/src/providers/embedding/openrouter.ts +0 -51
  142. package/src/providers/embedding/voyage.ts +0 -46
  143. package/src/providers/fallback-chain.ts +0 -31
  144. package/src/providers/index.ts +0 -84
  145. package/src/providers/openrouter.ts +0 -71
  146. package/src/providers/resilient.ts +0 -37
  147. package/src/state/hybrid-search.ts +0 -295
  148. package/src/state/index-persistence.ts +0 -63
  149. package/src/state/keyed-mutex.ts +0 -18
  150. package/src/state/kv.ts +0 -33
  151. package/src/state/schema.ts +0 -71
  152. package/src/state/search-index.ts +0 -245
  153. package/src/state/stemmer.ts +0 -104
  154. package/src/state/synonyms.ts +0 -63
  155. package/src/state/vector-index.ts +0 -130
  156. package/src/telemetry/setup.ts +0 -116
  157. package/src/triggers/api.ts +0 -1904
  158. package/src/triggers/events.ts +0 -71
  159. package/src/types.ts +0 -769
  160. package/src/version.ts +0 -1
  161. package/src/viewer/index.html +0 -2556
  162. package/src/viewer/server.ts +0 -207
  163. package/src/xenova.d.ts +0 -3
  164. package/test/actions.test.ts +0 -490
  165. package/test/audit.test.ts +0 -108
  166. package/test/auto-forget.test.ts +0 -188
  167. package/test/cascade.test.ts +0 -277
  168. package/test/checkpoints.test.ts +0 -493
  169. package/test/circuit-breaker.test.ts +0 -107
  170. package/test/claude-bridge.test.ts +0 -178
  171. package/test/confidence.test.ts +0 -247
  172. package/test/consistency.test.ts +0 -61
  173. package/test/consolidation-pipeline.test.ts +0 -251
  174. package/test/crystallize.test.ts +0 -521
  175. package/test/diagnostics.test.ts +0 -638
  176. package/test/embedding-provider.test.ts +0 -49
  177. package/test/enrich.test.ts +0 -209
  178. package/test/eval.test.ts +0 -300
  179. package/test/export-import.test.ts +0 -251
  180. package/test/facets.test.ts +0 -448
  181. package/test/fallback-chain.test.ts +0 -93
  182. package/test/frontier.test.ts +0 -485
  183. package/test/governance.test.ts +0 -147
  184. package/test/graph-retrieval.test.ts +0 -186
  185. package/test/graph.test.ts +0 -160
  186. package/test/helpers/mocks.ts +0 -40
  187. package/test/hybrid-search.test.ts +0 -145
  188. package/test/index-persistence.test.ts +0 -124
  189. package/test/integration.test.ts +0 -265
  190. package/test/leases.test.ts +0 -399
  191. package/test/mcp-prompts.test.ts +0 -218
  192. package/test/mcp-resources.test.ts +0 -286
  193. package/test/mcp-standalone.test.ts +0 -113
  194. package/test/mesh.test.ts +0 -700
  195. package/test/privacy.test.ts +0 -87
  196. package/test/profile.test.ts +0 -161
  197. package/test/query-expansion.test.ts +0 -154
  198. package/test/relations.test.ts +0 -198
  199. package/test/retention.test.ts +0 -245
  200. package/test/routines.test.ts +0 -497
  201. package/test/schema-fingerprint.test.ts +0 -81
  202. package/test/schema.test.ts +0 -42
  203. package/test/search-index.test.ts +0 -128
  204. package/test/sentinels.test.ts +0 -626
  205. package/test/signals.test.ts +0 -410
  206. package/test/sketches.test.ts +0 -549
  207. package/test/sliding-window.test.ts +0 -199
  208. package/test/smart-search.test.ts +0 -169
  209. package/test/snapshot.test.ts +0 -165
  210. package/test/team.test.ts +0 -156
  211. package/test/temporal-graph.test.ts +0 -378
  212. package/test/timeline.test.ts +0 -148
  213. package/test/vector-index.test.ts +0 -79
  214. package/test/verify.test.ts +0 -209
  215. package/test/xml.test.ts +0 -65
  216. package/tsconfig.json +0 -22
  217. package/tsdown.config.ts +0 -62
@@ -1,248 +0,0 @@
1
- import type { ISdk } from "iii-sdk";
2
- import type { StateKV } from "../state/kv.js";
3
- import { KV, generateId } from "../state/schema.js";
4
- import type { Facet } from "../types.js";
5
-
6
- export function registerFacetsFunction(sdk: ISdk, kv: StateKV): void {
7
- sdk.registerFunction(
8
- { id: "mem::facet-tag" },
9
- async (data: {
10
- targetId: string;
11
- targetType: string;
12
- dimension: string;
13
- value: string;
14
- }) => {
15
- if (!data.targetId || typeof data.targetId !== "string") {
16
- return { success: false, error: "targetId is required" };
17
- }
18
-
19
- const validTypes = ["action", "memory", "observation"];
20
- if (!validTypes.includes(data.targetType)) {
21
- return {
22
- success: false,
23
- error: `targetType must be one of: ${validTypes.join(", ")}`,
24
- };
25
- }
26
-
27
- if (
28
- !data.dimension ||
29
- typeof data.dimension !== "string" ||
30
- data.dimension.trim() === ""
31
- ) {
32
- return { success: false, error: "dimension is required" };
33
- }
34
-
35
- if (
36
- !data.value ||
37
- typeof data.value !== "string" ||
38
- data.value.trim() === ""
39
- ) {
40
- return { success: false, error: "value is required" };
41
- }
42
-
43
- const dimension = data.dimension.trim();
44
- const value = data.value.trim();
45
-
46
- const existing = await kv.list<Facet>(KV.facets);
47
- const duplicate = existing.find(
48
- (f) =>
49
- f.targetId === data.targetId &&
50
- f.dimension === dimension &&
51
- f.value === value,
52
- );
53
- if (duplicate) {
54
- return { success: true, facet: duplicate, skipped: true };
55
- }
56
-
57
- const facet: Facet = {
58
- id: generateId("fct"),
59
- targetId: data.targetId,
60
- targetType: data.targetType as Facet["targetType"],
61
- dimension,
62
- value,
63
- createdAt: new Date().toISOString(),
64
- };
65
-
66
- await kv.set(KV.facets, facet.id, facet);
67
- return { success: true, facet };
68
- },
69
- );
70
-
71
- sdk.registerFunction(
72
- { id: "mem::facet-untag" },
73
- async (data: {
74
- targetId: string;
75
- dimension: string;
76
- value?: string;
77
- }) => {
78
- if (!data.targetId) {
79
- return { success: false, error: "targetId is required" };
80
- }
81
- if (!data.dimension) {
82
- return { success: false, error: "dimension is required" };
83
- }
84
-
85
- const all = await kv.list<Facet>(KV.facets);
86
- const matches = all.filter((f) => {
87
- if (f.targetId !== data.targetId || f.dimension !== data.dimension) {
88
- return false;
89
- }
90
- if (data.value !== undefined) {
91
- return f.value === data.value;
92
- }
93
- return true;
94
- });
95
-
96
- for (const f of matches) {
97
- await kv.delete(KV.facets, f.id);
98
- }
99
-
100
- return { success: true, removed: matches.length };
101
- },
102
- );
103
-
104
- sdk.registerFunction(
105
- { id: "mem::facet-query" },
106
- async (data: {
107
- matchAll?: string[];
108
- matchAny?: string[];
109
- targetType?: string;
110
- limit?: number;
111
- }) => {
112
- if (
113
- (!data.matchAll || data.matchAll.length === 0) &&
114
- (!data.matchAny || data.matchAny.length === 0)
115
- ) {
116
- return {
117
- success: false,
118
- error: "at least one of matchAll or matchAny is required",
119
- };
120
- }
121
-
122
- const all = await kv.list<Facet>(KV.facets);
123
- const filtered = data.targetType
124
- ? all.filter((f) => f.targetType === data.targetType)
125
- : all;
126
-
127
- const targetFacetMap = new Map<string, { targetType: string; facetKeys: Set<string> }>();
128
- for (const f of filtered) {
129
- const key = `${f.dimension}:${f.value}`;
130
- let entry = targetFacetMap.get(f.targetId);
131
- if (!entry) {
132
- entry = { targetType: f.targetType, facetKeys: new Set() };
133
- targetFacetMap.set(f.targetId, entry);
134
- }
135
- entry.facetKeys.add(key);
136
- }
137
-
138
- const results: Array<{ targetId: string; targetType: string; matchedFacets: string[] }> = [];
139
-
140
- for (const [targetId, entry] of targetFacetMap) {
141
- const matched: string[] = [];
142
-
143
- if (data.matchAll && data.matchAll.length > 0) {
144
- const allPresent = data.matchAll.every((k) => entry.facetKeys.has(k));
145
- if (!allPresent) continue;
146
- for (const k of data.matchAll) {
147
- if (!matched.includes(k)) matched.push(k);
148
- }
149
- }
150
-
151
- if (data.matchAny && data.matchAny.length > 0) {
152
- const anyPresent = data.matchAny.filter((k) => entry.facetKeys.has(k));
153
- if (anyPresent.length === 0) continue;
154
- for (const k of anyPresent) {
155
- if (!matched.includes(k)) matched.push(k);
156
- }
157
- }
158
-
159
- results.push({
160
- targetId,
161
- targetType: entry.targetType,
162
- matchedFacets: matched,
163
- });
164
- }
165
-
166
- const limit = data.limit || 50;
167
- return { success: true, results: results.slice(0, limit) };
168
- },
169
- );
170
-
171
- sdk.registerFunction(
172
- { id: "mem::facet-get" },
173
- async (data: { targetId: string }) => {
174
- if (!data.targetId) {
175
- return { success: false, error: "targetId is required" };
176
- }
177
-
178
- const all = await kv.list<Facet>(KV.facets);
179
- const targetFacets = all.filter((f) => f.targetId === data.targetId);
180
-
181
- const dimMap = new Map<string, string[]>();
182
- for (const f of targetFacets) {
183
- let values = dimMap.get(f.dimension);
184
- if (!values) {
185
- values = [];
186
- dimMap.set(f.dimension, values);
187
- }
188
- values.push(f.value);
189
- }
190
-
191
- const dimensions = Array.from(dimMap.entries()).map(([dimension, values]) => ({
192
- dimension,
193
- values,
194
- }));
195
-
196
- return { success: true, dimensions };
197
- },
198
- );
199
-
200
- sdk.registerFunction(
201
- { id: "mem::facet-stats" },
202
- async (data: { targetType?: string }) => {
203
- const all = await kv.list<Facet>(KV.facets);
204
- const filtered = data.targetType
205
- ? all.filter((f) => f.targetType === data.targetType)
206
- : all;
207
-
208
- const dimMap = new Map<string, Map<string, number>>();
209
- for (const f of filtered) {
210
- let valueMap = dimMap.get(f.dimension);
211
- if (!valueMap) {
212
- valueMap = new Map();
213
- dimMap.set(f.dimension, valueMap);
214
- }
215
- valueMap.set(f.value, (valueMap.get(f.value) || 0) + 1);
216
- }
217
-
218
- const dimensions = Array.from(dimMap.entries()).map(([dimension, valueMap]) => ({
219
- dimension,
220
- values: Array.from(valueMap.entries()).map(([value, count]) => ({
221
- value,
222
- count,
223
- })),
224
- }));
225
-
226
- return { success: true, dimensions, totalFacets: filtered.length };
227
- },
228
- );
229
-
230
- sdk.registerFunction(
231
- { id: "mem::facet-dimensions" },
232
- async () => {
233
- const all = await kv.list<Facet>(KV.facets);
234
-
235
- const counts = new Map<string, number>();
236
- for (const f of all) {
237
- counts.set(f.dimension, (counts.get(f.dimension) || 0) + 1);
238
- }
239
-
240
- const dimensions = Array.from(counts.entries()).map(([dimension, count]) => ({
241
- dimension,
242
- count,
243
- }));
244
-
245
- return { success: true, dimensions };
246
- },
247
- );
248
- }
@@ -1,106 +0,0 @@
1
- import type { ISdk } from "iii-sdk";
2
- import { getContext } from "iii-sdk";
3
- import type { CompressedObservation, Session } from "../types.js";
4
- import { KV } from "../state/schema.js";
5
- import { StateKV } from "../state/kv.js";
6
-
7
- interface FileHistory {
8
- file: string;
9
- observations: Array<{
10
- sessionId: string;
11
- obsId: string;
12
- type: string;
13
- title: string;
14
- narrative: string;
15
- importance: number;
16
- timestamp: string;
17
- }>;
18
- }
19
-
20
- export function registerFileIndexFunction(sdk: ISdk, kv: StateKV): void {
21
- sdk.registerFunction(
22
- { id: "mem::file-context" },
23
- async (data: { sessionId: string; files: string[]; project?: string }) => {
24
- const ctx = getContext();
25
- const results: FileHistory[] = [];
26
-
27
- const sessions = await kv.list<Session>(KV.sessions);
28
- let otherSessions = sessions.filter((s) => s.id !== data.sessionId);
29
- if (data.project) {
30
- otherSessions = otherSessions.filter((s) => s.project === data.project);
31
- }
32
- otherSessions = otherSessions
33
- .sort(
34
- (a, b) =>
35
- new Date(b.startedAt).getTime() - new Date(a.startedAt).getTime(),
36
- )
37
- .slice(0, 15);
38
-
39
- const obsCache = new Map<string, CompressedObservation[]>();
40
- for (const session of otherSessions) {
41
- obsCache.set(
42
- session.id,
43
- await kv.list<CompressedObservation>(KV.observations(session.id)),
44
- );
45
- }
46
-
47
- for (const file of data.files) {
48
- const history: FileHistory = { file, observations: [] };
49
- const normalizedFile = file.replace(/^\.\//, "");
50
-
51
- for (const session of otherSessions) {
52
- const observations = obsCache.get(session.id) || [];
53
-
54
- for (const obs of observations) {
55
- if (!obs.files || !obs.title) continue;
56
- const matches = obs.files.some(
57
- (f) =>
58
- f === file ||
59
- f === normalizedFile ||
60
- f.endsWith(`/${normalizedFile}`) ||
61
- normalizedFile.endsWith(`/${f}`),
62
- );
63
- if (matches && obs.importance >= 4) {
64
- history.observations.push({
65
- sessionId: session.id,
66
- obsId: obs.id,
67
- type: obs.type,
68
- title: obs.title,
69
- narrative: obs.narrative,
70
- importance: obs.importance,
71
- timestamp: obs.timestamp,
72
- });
73
- }
74
- }
75
- }
76
-
77
- history.observations.sort((a, b) => b.importance - a.importance);
78
- history.observations = history.observations.slice(0, 5);
79
-
80
- if (history.observations.length > 0) {
81
- results.push(history);
82
- }
83
- }
84
-
85
- if (results.length === 0) {
86
- return { context: "" };
87
- }
88
-
89
- const lines: string[] = ["<agentmemory-file-context>"];
90
- for (const fh of results) {
91
- lines.push(`## ${fh.file}`);
92
- for (const obs of fh.observations) {
93
- lines.push(`- [${obs.type}] ${obs.title}: ${obs.narrative}`);
94
- }
95
- }
96
- lines.push("</agentmemory-file-context>");
97
-
98
- const context = lines.join("\n");
99
- ctx.logger.info("File context generated", {
100
- files: data.files.length,
101
- results: results.length,
102
- });
103
- return { context };
104
- },
105
- );
106
- }
@@ -1,214 +0,0 @@
1
- import type { ISdk } from "iii-sdk";
2
- import type { StateKV } from "../state/kv.js";
3
- import { KV, generateId } from "../state/schema.js";
4
- import type { Action, ActionEdge, RoutineRun, MemoryProvider } from "../types.js";
5
-
6
- const FLOW_COMPRESS_SYSTEM = `You are a workflow summarizer. Given a completed action chain, produce a concise summary capturing:
7
- 1. The overall goal and outcome
8
- 2. Key steps taken and their results
9
- 3. Any notable decisions or discoveries
10
- 4. Lessons learned
11
-
12
- Output as XML:
13
- <summary>
14
- <goal>What was the workflow trying to achieve</goal>
15
- <outcome>What happened</outcome>
16
- <steps>Numbered list of key steps</steps>
17
- <discoveries>Any new insights or discoveries</discoveries>
18
- <lesson>What to remember for next time</lesson>
19
- </summary>`;
20
-
21
- export function registerFlowCompressFunction(
22
- sdk: ISdk,
23
- kv: StateKV,
24
- provider: MemoryProvider,
25
- ): void {
26
- sdk.registerFunction(
27
- { id: "mem::flow-compress" },
28
- async (data: { runId?: string; actionIds?: string[]; project?: string }) => {
29
- let actionsToCompress: Action[] = [];
30
-
31
- if (data.runId) {
32
- const run = await kv.get<RoutineRun>(KV.routineRuns, data.runId);
33
- if (!run) {
34
- return { success: false, error: "run not found" };
35
- }
36
- for (const id of run.actionIds) {
37
- const action = await kv.get<Action>(KV.actions, id);
38
- if (action) actionsToCompress.push(action);
39
- }
40
- } else if (data.actionIds && data.actionIds.length > 0) {
41
- for (const id of data.actionIds) {
42
- const action = await kv.get<Action>(KV.actions, id);
43
- if (action) actionsToCompress.push(action);
44
- }
45
- } else if (data.project) {
46
- const allActions = await kv.list<Action>(KV.actions);
47
- actionsToCompress = allActions.filter(
48
- (a) => a.project === data.project && a.status === "done",
49
- );
50
- } else {
51
- return {
52
- success: false,
53
- error: "runId, actionIds, or project is required",
54
- };
55
- }
56
-
57
- const doneActions = actionsToCompress.filter(
58
- (a) => a.status === "done",
59
- );
60
- if (doneActions.length === 0) {
61
- return {
62
- success: true,
63
- message: "No completed actions to compress",
64
- compressed: 0,
65
- };
66
- }
67
-
68
- const allEdges = await kv.list<ActionEdge>(KV.actionEdges);
69
- const relevantIds = new Set(doneActions.map((a) => a.id));
70
- const relevantEdges = allEdges.filter(
71
- (e) =>
72
- relevantIds.has(e.sourceActionId) ||
73
- relevantIds.has(e.targetActionId),
74
- );
75
-
76
- const prompt = buildFlowPrompt(doneActions, relevantEdges);
77
-
78
- try {
79
- const response = await provider.summarize(
80
- FLOW_COMPRESS_SYSTEM,
81
- prompt,
82
- );
83
- const summary = parseFlowSummary(response);
84
-
85
- const memory = {
86
- id: generateId("mem"),
87
- createdAt: new Date().toISOString(),
88
- updatedAt: new Date().toISOString(),
89
- type: "workflow" as const,
90
- title: summary.goal || `Workflow: ${doneActions.length} actions`,
91
- content: formatSummary(summary),
92
- concepts: extractConcepts(doneActions),
93
- files: extractFiles(doneActions),
94
- sessionIds: [],
95
- strength: 1.0,
96
- version: 1,
97
- isLatest: true,
98
- metadata: {
99
- flowCompressed: true,
100
- actionCount: doneActions.length,
101
- actionIds: doneActions.map((a) => a.id),
102
- },
103
- };
104
-
105
- await kv.set(KV.memories, memory.id, memory);
106
-
107
- return {
108
- success: true,
109
- compressed: doneActions.length,
110
- memoryId: memory.id,
111
- summary,
112
- };
113
- } catch (err) {
114
- return {
115
- success: false,
116
- error: `compression failed: ${String(err)}`,
117
- compressed: 0,
118
- };
119
- }
120
- },
121
- );
122
- }
123
-
124
- function buildFlowPrompt(
125
- actions: Action[],
126
- edges: ActionEdge[],
127
- ): string {
128
- const lines: string[] = ["## Completed Action Chain\n"];
129
-
130
- const sorted = [...actions].sort(
131
- (a, b) =>
132
- new Date(a.createdAt).getTime() - new Date(b.createdAt).getTime(),
133
- );
134
-
135
- for (const action of sorted) {
136
- lines.push(`### ${action.title}`);
137
- if (action.description) lines.push(action.description);
138
- if (action.result) lines.push(`Result: ${action.result}`);
139
- lines.push(`Priority: ${action.priority}, Tags: ${(action.tags ?? []).join(", ")}`);
140
- lines.push("");
141
- }
142
-
143
- if (edges.length > 0) {
144
- lines.push("## Dependencies");
145
- for (const edge of edges) {
146
- lines.push(`- ${edge.sourceActionId} --${edge.type}--> ${edge.targetActionId}`);
147
- }
148
- }
149
-
150
- return lines.join("\n");
151
- }
152
-
153
- function parseFlowSummary(response: string): {
154
- goal: string;
155
- outcome: string;
156
- steps: string;
157
- discoveries: string;
158
- lesson: string;
159
- } {
160
- const extract = (tag: string): string => {
161
- const match = response.match(
162
- new RegExp(`<${tag}>([\\s\\S]*?)</${tag}>`),
163
- );
164
- return match ? match[1].trim() : "";
165
- };
166
- return {
167
- goal: extract("goal"),
168
- outcome: extract("outcome"),
169
- steps: extract("steps"),
170
- discoveries: extract("discoveries"),
171
- lesson: extract("lesson"),
172
- };
173
- }
174
-
175
- function formatSummary(s: {
176
- goal: string;
177
- outcome: string;
178
- steps: string;
179
- discoveries: string;
180
- lesson: string;
181
- }): string {
182
- const parts: string[] = [];
183
- if (s.goal) parts.push(`Goal: ${s.goal}`);
184
- if (s.outcome) parts.push(`Outcome: ${s.outcome}`);
185
- if (s.steps) parts.push(`Steps: ${s.steps}`);
186
- if (s.discoveries) parts.push(`Discoveries: ${s.discoveries}`);
187
- if (s.lesson) parts.push(`Lesson: ${s.lesson}`);
188
- return parts.join("\n\n");
189
- }
190
-
191
- function extractConcepts(actions: Action[]): string[] {
192
- const concepts = new Set<string>();
193
- for (const a of actions) {
194
- for (const tag of a.tags ?? []) {
195
- if (!tag.startsWith("routine:")) concepts.add(tag);
196
- }
197
- }
198
- return Array.from(concepts);
199
- }
200
-
201
- function extractFiles(actions: Action[]): string[] {
202
- const files = new Set<string>();
203
- for (const a of actions) {
204
- if (a.metadata && typeof a.metadata === "object") {
205
- const meta = a.metadata as Record<string, unknown>;
206
- if (Array.isArray(meta.files)) {
207
- for (const f of meta.files) {
208
- if (typeof f === "string") files.add(f);
209
- }
210
- }
211
- }
212
- }
213
- return Array.from(files);
214
- }