@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,288 +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 { withKeyedLock } from "../state/keyed-mutex.js";
5
- import type { Action, ActionEdge } from "../types.js";
6
-
7
- export function registerActionsFunction(sdk: ISdk, kv: StateKV): void {
8
- sdk.registerFunction(
9
- { id: "mem::action-create" },
10
- async (data: {
11
- title: string;
12
- description?: string;
13
- priority?: number;
14
- createdBy?: string;
15
- project?: string;
16
- tags?: string[];
17
- parentId?: string;
18
- sourceObservationIds?: string[];
19
- sourceMemoryIds?: string[];
20
- edges?: Array<{ type: string; targetActionId: string }>;
21
- }) => {
22
- if (!data.title || typeof data.title !== "string") {
23
- return { success: false, error: "title is required" };
24
- }
25
-
26
- return withKeyedLock("mem:actions", async () => {
27
- const now = new Date().toISOString();
28
- const action: Action = {
29
- id: generateId("act"),
30
- title: data.title.trim(),
31
- description: (data.description || "").trim(),
32
- status: "pending",
33
- priority: Math.max(1, Math.min(10, data.priority || 5)),
34
- createdAt: now,
35
- updatedAt: now,
36
- createdBy: data.createdBy || "unknown",
37
- project: data.project,
38
- tags: data.tags || [],
39
- sourceObservationIds: data.sourceObservationIds || [],
40
- sourceMemoryIds: data.sourceMemoryIds || [],
41
- parentId: data.parentId,
42
- };
43
-
44
- if (data.parentId) {
45
- const parent = await kv.get<Action>(KV.actions, data.parentId);
46
- if (!parent) {
47
- return { success: false, error: "parent action not found" };
48
- }
49
- }
50
-
51
- const validEdgeTypes = [
52
- "requires",
53
- "unlocks",
54
- "spawned_by",
55
- "gated_by",
56
- "conflicts_with",
57
- ];
58
- const pendingEdges: ActionEdge[] = [];
59
- let hasRequires = false;
60
- if (data.edges && Array.isArray(data.edges)) {
61
- for (const e of data.edges) {
62
- if (!validEdgeTypes.includes(e.type)) {
63
- return { success: false, error: `invalid edge type: ${e.type}` };
64
- }
65
- const targetAction = await kv.get<Action>(KV.actions, e.targetActionId);
66
- if (!targetAction) {
67
- return { success: false, error: `target action not found: ${e.targetActionId}` };
68
- }
69
- if (e.type === "requires") hasRequires = true;
70
- pendingEdges.push({
71
- id: generateId("ae"),
72
- type: e.type as ActionEdge["type"],
73
- sourceActionId: action.id,
74
- targetActionId: e.targetActionId,
75
- createdAt: now,
76
- });
77
- }
78
- }
79
-
80
- if (hasRequires) {
81
- action.status = "blocked";
82
- }
83
-
84
- await kv.set(KV.actions, action.id, action);
85
-
86
- for (const edge of pendingEdges) {
87
- await kv.set(KV.actionEdges, edge.id, edge);
88
- }
89
-
90
- return { success: true, action, edges: pendingEdges };
91
- });
92
- },
93
- );
94
-
95
- sdk.registerFunction(
96
- { id: "mem::action-update" },
97
- async (data: {
98
- actionId: string;
99
- status?: Action["status"];
100
- title?: string;
101
- description?: string;
102
- priority?: number;
103
- assignedTo?: string;
104
- result?: string;
105
- tags?: string[];
106
- }) => {
107
- if (!data.actionId) {
108
- return { success: false, error: "actionId is required" };
109
- }
110
-
111
- return withKeyedLock(`mem:action:${data.actionId}`, async () => {
112
- const action = await kv.get<Action>(KV.actions, data.actionId);
113
- if (!action) {
114
- return { success: false, error: "action not found" };
115
- }
116
-
117
- if (data.status !== undefined) action.status = data.status;
118
- if (data.title !== undefined) action.title = data.title.trim();
119
- if (data.description !== undefined)
120
- action.description = data.description.trim();
121
- if (data.priority !== undefined)
122
- action.priority = Math.max(1, Math.min(10, data.priority));
123
- if (data.assignedTo !== undefined) action.assignedTo = data.assignedTo;
124
- if (data.result !== undefined) action.result = data.result;
125
- if (data.tags !== undefined) action.tags = data.tags;
126
- action.updatedAt = new Date().toISOString();
127
-
128
- await kv.set(KV.actions, action.id, action);
129
-
130
- if (data.status === "done") {
131
- await propagateCompletion(kv, action.id);
132
- }
133
-
134
- return { success: true, action };
135
- });
136
- },
137
- );
138
-
139
- sdk.registerFunction(
140
- { id: "mem::action-edge-create" },
141
- async (data: {
142
- sourceActionId: string;
143
- targetActionId: string;
144
- type: string;
145
- metadata?: Record<string, unknown>;
146
- }) => {
147
- if (!data.sourceActionId || !data.targetActionId || !data.type) {
148
- return {
149
- success: false,
150
- error: "sourceActionId, targetActionId, and type are required",
151
- };
152
- }
153
-
154
- const validTypes = [
155
- "requires",
156
- "unlocks",
157
- "spawned_by",
158
- "gated_by",
159
- "conflicts_with",
160
- ];
161
- if (!validTypes.includes(data.type)) {
162
- return {
163
- success: false,
164
- error: `type must be one of: ${validTypes.join(", ")}`,
165
- };
166
- }
167
-
168
- const sourceAction = await kv.get<Action>(KV.actions, data.sourceActionId);
169
- if (!sourceAction) {
170
- return { success: false, error: "source action not found" };
171
- }
172
- const targetAction = await kv.get<Action>(KV.actions, data.targetActionId);
173
- if (!targetAction) {
174
- return { success: false, error: "target action not found" };
175
- }
176
-
177
- const edge: ActionEdge = {
178
- id: generateId("ae"),
179
- type: data.type as ActionEdge["type"],
180
- sourceActionId: data.sourceActionId,
181
- targetActionId: data.targetActionId,
182
- createdAt: new Date().toISOString(),
183
- metadata: data.metadata,
184
- };
185
-
186
- await kv.set(KV.actionEdges, edge.id, edge);
187
- return { success: true, edge };
188
- },
189
- );
190
-
191
- sdk.registerFunction(
192
- { id: "mem::action-list" },
193
- async (data: {
194
- status?: string;
195
- project?: string;
196
- parentId?: string;
197
- tags?: string[];
198
- limit?: number;
199
- }) => {
200
- let actions = await kv.list<Action>(KV.actions);
201
-
202
- if (data.status) {
203
- actions = actions.filter((a) => a.status === data.status);
204
- }
205
- if (data.project) {
206
- actions = actions.filter((a) => a.project === data.project);
207
- }
208
- if (data.parentId) {
209
- actions = actions.filter((a) => a.parentId === data.parentId);
210
- }
211
- if (data.tags && data.tags.length > 0) {
212
- actions = actions.filter((a) =>
213
- data.tags!.some((t) => a.tags.includes(t)),
214
- );
215
- }
216
-
217
- actions.sort(
218
- (a, b) =>
219
- new Date(b.updatedAt).getTime() - new Date(a.updatedAt).getTime(),
220
- );
221
-
222
- const limit = data.limit || 50;
223
- return { success: true, actions: actions.slice(0, limit) };
224
- },
225
- );
226
-
227
- sdk.registerFunction(
228
- { id: "mem::action-get" },
229
- async (data: { actionId: string }) => {
230
- if (!data.actionId) {
231
- return { success: false, error: "actionId is required" };
232
- }
233
- const action = await kv.get<Action>(KV.actions, data.actionId);
234
- if (!action) {
235
- return { success: false, error: "action not found" };
236
- }
237
-
238
- const allEdges = await kv.list<ActionEdge>(KV.actionEdges);
239
- const edges = allEdges.filter(
240
- (e) =>
241
- e.sourceActionId === data.actionId ||
242
- e.targetActionId === data.actionId,
243
- );
244
-
245
- const children = (await kv.list<Action>(KV.actions)).filter(
246
- (a) => a.parentId === data.actionId,
247
- );
248
-
249
- return { success: true, action, edges, children };
250
- },
251
- );
252
- }
253
-
254
- async function propagateCompletion(
255
- kv: StateKV,
256
- completedActionId: string,
257
- ): Promise<void> {
258
- const allEdges = await kv.list<ActionEdge>(KV.actionEdges);
259
- const unlockEdges = allEdges.filter(
260
- (e) =>
261
- e.targetActionId === completedActionId &&
262
- (e.type === "requires" || e.type === "unlocks"),
263
- );
264
-
265
- const allActions = await kv.list<Action>(KV.actions);
266
- const actionMap = new Map(allActions.map((a) => [a.id, a]));
267
-
268
- for (const edge of unlockEdges) {
269
- const candidateId = edge.sourceActionId;
270
- await withKeyedLock(`mem:action:${candidateId}`, async () => {
271
- const action = await kv.get<Action>(KV.actions, candidateId);
272
- if (action && action.status === "blocked") {
273
- const deps = allEdges.filter(
274
- (e) => e.sourceActionId === action.id && e.type === "requires",
275
- );
276
- const allDone = deps.every((d) => {
277
- const target = actionMap.get(d.targetActionId);
278
- return target && target.status === "done";
279
- });
280
- if (allDone) {
281
- action.status = "pending";
282
- action.updatedAt = new Date().toISOString();
283
- await kv.set(KV.actions, action.id, action);
284
- }
285
- }
286
- });
287
- }
288
- }
@@ -1,61 +0,0 @@
1
- import type { AuditEntry } from "../types.js";
2
- import { KV, generateId } from "../state/schema.js";
3
- import type { StateKV } from "../state/kv.js";
4
-
5
- export async function recordAudit(
6
- kv: StateKV,
7
- operation: AuditEntry["operation"],
8
- functionId: string,
9
- targetIds: string[],
10
- details: Record<string, unknown> = {},
11
- qualityScore?: number,
12
- userId?: string,
13
- ): Promise<AuditEntry> {
14
- const entry: AuditEntry = {
15
- id: generateId("aud"),
16
- timestamp: new Date().toISOString(),
17
- operation,
18
- userId,
19
- functionId,
20
- targetIds,
21
- details,
22
- qualityScore,
23
- };
24
- await kv.set(KV.audit, entry.id, entry);
25
- return entry;
26
- }
27
-
28
- export async function queryAudit(
29
- kv: StateKV,
30
- filter?: {
31
- operation?: AuditEntry["operation"];
32
- dateFrom?: string;
33
- dateTo?: string;
34
- limit?: number;
35
- },
36
- ): Promise<AuditEntry[]> {
37
- const all = await kv.list<AuditEntry>(KV.audit);
38
- let entries = [...all].sort(
39
- (a, b) => new Date(b.timestamp).getTime() - new Date(a.timestamp).getTime(),
40
- );
41
-
42
- if (filter?.operation) {
43
- entries = entries.filter((e) => e.operation === filter.operation);
44
- }
45
- if (filter?.dateFrom) {
46
- const from = new Date(filter.dateFrom).getTime();
47
- if (Number.isNaN(from)) {
48
- throw new Error(`Invalid dateFrom: ${filter.dateFrom}`);
49
- }
50
- entries = entries.filter((e) => new Date(e.timestamp).getTime() >= from);
51
- }
52
- if (filter?.dateTo) {
53
- const to = new Date(filter.dateTo).getTime();
54
- if (Number.isNaN(to)) {
55
- throw new Error(`Invalid dateTo: ${filter.dateTo}`);
56
- }
57
- entries = entries.filter((e) => new Date(e.timestamp).getTime() <= to);
58
- }
59
-
60
- return entries.slice(0, filter?.limit || 100);
61
- }
@@ -1,169 +0,0 @@
1
- import type { ISdk } from "iii-sdk";
2
- import { getContext } from "iii-sdk";
3
- import type { Memory, CompressedObservation, Session } from "../types.js";
4
- import { KV, jaccardSimilarity } from "../state/schema.js";
5
- import { StateKV } from "../state/kv.js";
6
-
7
- const MS_PER_DAY = 24 * 60 * 60 * 1000;
8
- const CONTRADICTION_THRESHOLD = 0.9;
9
-
10
- interface AutoForgetResult {
11
- ttlExpired: string[];
12
- contradictions: Array<{
13
- memoryA: string;
14
- memoryB: string;
15
- similarity: number;
16
- }>;
17
- lowValueObs: string[];
18
- dryRun: boolean;
19
- }
20
-
21
- export function registerAutoForgetFunction(sdk: ISdk, kv: StateKV): void {
22
- sdk.registerFunction(
23
- {
24
- id: "mem::auto-forget",
25
- description:
26
- "Auto-forget expired (TTL), contradictory, and low-value data",
27
- },
28
- async (data: { dryRun?: boolean }): Promise<AutoForgetResult> => {
29
- const ctx = getContext();
30
- const dryRun = data?.dryRun ?? false;
31
- const now = Date.now();
32
-
33
- const result: AutoForgetResult = {
34
- ttlExpired: [],
35
- contradictions: [],
36
- lowValueObs: [],
37
- dryRun,
38
- };
39
-
40
- const memories = await kv.list<Memory>(KV.memories);
41
- const deletedIds = new Set<string>();
42
- for (const mem of memories) {
43
- if (mem.forgetAfter) {
44
- const expiry = new Date(mem.forgetAfter).getTime();
45
- if (now > expiry) {
46
- result.ttlExpired.push(mem.id);
47
- deletedIds.add(mem.id);
48
- if (!dryRun) {
49
- await kv.delete(KV.memories, mem.id);
50
- }
51
- }
52
- }
53
- }
54
-
55
- const latestMemories = memories
56
- .filter((m) => m.isLatest !== false && !deletedIds.has(m.id))
57
- .sort(
58
- (a, b) =>
59
- new Date(b.createdAt).getTime() - new Date(a.createdAt).getTime(),
60
- )
61
- .slice(0, 1000);
62
-
63
- const tokenCache = new Map<string, Set<string>>();
64
- for (const mem of latestMemories) {
65
- tokenCache.set(
66
- mem.id,
67
- new Set(
68
- mem.content
69
- .toLowerCase()
70
- .split(/\s+/)
71
- .filter((t) => t.length > 2),
72
- ),
73
- );
74
- }
75
-
76
- const memById = new Map(latestMemories.map((m) => [m.id, m]));
77
- const conceptIndex = new Map<string, string[]>();
78
- for (const mem of latestMemories) {
79
- const concepts = mem.concepts || [];
80
- for (const c of concepts) {
81
- const key = c.toLowerCase();
82
- if (!conceptIndex.has(key)) conceptIndex.set(key, []);
83
- conceptIndex.get(key)!.push(mem.id);
84
- }
85
- }
86
-
87
- const compared = new Set<string>();
88
- for (const [, memIds] of conceptIndex) {
89
- for (let i = 0; i < memIds.length; i++) {
90
- for (let j = i + 1; j < memIds.length; j++) {
91
- const key =
92
- memIds[i] < memIds[j]
93
- ? `${memIds[i]}|${memIds[j]}`
94
- : `${memIds[j]}|${memIds[i]}`;
95
- if (compared.has(key)) continue;
96
- compared.add(key);
97
-
98
- const setA = tokenCache.get(memIds[i])!;
99
- const setB = tokenCache.get(memIds[j])!;
100
- let intersection = 0;
101
- if (setA.size === 0 && setB.size === 0) continue;
102
- if (setA.size === 0 || setB.size === 0) continue;
103
- for (const word of setA) {
104
- if (setB.has(word)) intersection++;
105
- }
106
- const sim =
107
- intersection / (setA.size + setB.size - intersection);
108
-
109
- if (sim > CONTRADICTION_THRESHOLD) {
110
- const memA = memById.get(memIds[i])!;
111
- const memB = memById.get(memIds[j])!;
112
- result.contradictions.push({
113
- memoryA: memA.id,
114
- memoryB: memB.id,
115
- similarity: sim,
116
- });
117
-
118
- if (!dryRun) {
119
- const older =
120
- new Date(memA.createdAt).getTime() <
121
- new Date(memB.createdAt).getTime()
122
- ? memA
123
- : memB;
124
- older.isLatest = false;
125
- await kv.set(KV.memories, older.id, older);
126
- }
127
- }
128
- }
129
- }
130
- }
131
-
132
- const sessions = await kv.list<Session>(KV.sessions);
133
- const obsPerSession: CompressedObservation[][] = [];
134
- for (let batch = 0; batch < sessions.length; batch += 10) {
135
- const chunk = sessions.slice(batch, batch + 10);
136
- const results = await Promise.all(
137
- chunk.map((s) =>
138
- kv
139
- .list<CompressedObservation>(KV.observations(s.id))
140
- .catch(() => [] as CompressedObservation[]),
141
- ),
142
- );
143
- obsPerSession.push(...results);
144
- }
145
- for (let i = 0; i < sessions.length; i++) {
146
- for (const obs of obsPerSession[i]) {
147
- if (!obs.timestamp) continue;
148
- const age = now - new Date(obs.timestamp).getTime();
149
- if (age > 180 * MS_PER_DAY && (obs.importance ?? 5) <= 2) {
150
- result.lowValueObs.push(obs.id);
151
- if (!dryRun) {
152
- await kv
153
- .delete(KV.observations(sessions[i].id), obs.id)
154
- .catch(() => {});
155
- }
156
- }
157
- }
158
- }
159
-
160
- ctx.logger.info("Auto-forget complete", {
161
- ttlExpired: result.ttlExpired.length,
162
- contradictions: result.contradictions.length,
163
- lowValueObs: result.lowValueObs.length,
164
- dryRun,
165
- });
166
- return result;
167
- },
168
- );
169
- }
@@ -1,169 +0,0 @@
1
- import type { ISdk } from "iii-sdk";
2
- import type { StateKV } from "../state/kv.js";
3
- import { KV } from "../state/schema.js";
4
- import type { Session } from "../types.js";
5
- import { execFile } from "node:child_process";
6
- import { resolve } from "node:path";
7
-
8
- function execAsync(
9
- cmd: string,
10
- args: string[],
11
- cwd: string,
12
- ): Promise<string> {
13
- return new Promise((resolve, reject) => {
14
- execFile(cmd, args, { cwd, timeout: 5000 }, (err, stdout) => {
15
- if (err) reject(err);
16
- else resolve(stdout.trim());
17
- });
18
- });
19
- }
20
-
21
- export function registerBranchAwareFunction(sdk: ISdk, kv: StateKV): void {
22
- sdk.registerFunction(
23
- { id: "mem::detect-worktree" },
24
- async (data: { cwd: string }) => {
25
- if (!data.cwd) {
26
- return { success: false, error: "cwd is required" };
27
- }
28
-
29
- try {
30
- const gitDir = await execAsync(
31
- "git",
32
- ["rev-parse", "--git-dir"],
33
- data.cwd,
34
- );
35
- const commonDir = await execAsync(
36
- "git",
37
- ["rev-parse", "--git-common-dir"],
38
- data.cwd,
39
- );
40
- const branch = await execAsync(
41
- "git",
42
- ["rev-parse", "--abbrev-ref", "HEAD"],
43
- data.cwd,
44
- ).catch(() => "detached");
45
-
46
- const topLevel = await execAsync(
47
- "git",
48
- ["rev-parse", "--show-toplevel"],
49
- data.cwd,
50
- );
51
-
52
- const isWorktree = resolve(data.cwd, gitDir) !== resolve(data.cwd, commonDir);
53
- const mainRepoRoot = isWorktree
54
- ? resolve(data.cwd, commonDir, "..")
55
- : topLevel;
56
-
57
- return {
58
- success: true,
59
- isWorktree,
60
- branch,
61
- topLevel,
62
- mainRepoRoot,
63
- gitDir: resolve(data.cwd, gitDir),
64
- commonDir: resolve(data.cwd, commonDir),
65
- };
66
- } catch {
67
- return {
68
- success: true,
69
- isWorktree: false,
70
- branch: null,
71
- topLevel: data.cwd,
72
- mainRepoRoot: data.cwd,
73
- gitDir: null,
74
- commonDir: null,
75
- };
76
- }
77
- },
78
- );
79
-
80
- sdk.registerFunction(
81
- { id: "mem::list-worktrees" },
82
- async (data: { cwd: string }) => {
83
- if (!data.cwd) {
84
- return { success: false, error: "cwd is required" };
85
- }
86
-
87
- try {
88
- const output = await execAsync(
89
- "git",
90
- ["worktree", "list", "--porcelain"],
91
- data.cwd,
92
- );
93
-
94
- const worktrees: Array<{
95
- path: string;
96
- head: string;
97
- branch: string;
98
- bare: boolean;
99
- }> = [];
100
-
101
- const blocks = output.split("\n\n").filter(Boolean);
102
- for (const block of blocks) {
103
- const lines = block.split("\n");
104
- const wt: { path: string; head: string; branch: string; bare: boolean } = {
105
- path: "",
106
- head: "",
107
- branch: "",
108
- bare: false,
109
- };
110
- for (const line of lines) {
111
- if (line.startsWith("worktree ")) wt.path = line.slice(9);
112
- else if (line.startsWith("HEAD ")) wt.head = line.slice(5);
113
- else if (line.startsWith("branch "))
114
- wt.branch = line.slice(7).replace("refs/heads/", "");
115
- else if (line === "bare") wt.bare = true;
116
- }
117
- if (wt.path) worktrees.push(wt);
118
- }
119
-
120
- return { success: true, worktrees };
121
- } catch {
122
- return { success: true, worktrees: [] };
123
- }
124
- },
125
- );
126
-
127
- sdk.registerFunction(
128
- { id: "mem::branch-sessions" },
129
- async (data: { cwd: string; branch?: string }) => {
130
- if (!data.cwd) {
131
- return { success: false, error: "cwd is required" };
132
- }
133
-
134
- const worktreeInfo = await sdk.trigger<
135
- { cwd: string },
136
- {
137
- success: boolean;
138
- isWorktree: boolean;
139
- mainRepoRoot: string;
140
- branch: string | null;
141
- }
142
- >("mem::detect-worktree", { cwd: data.cwd });
143
-
144
- const projectRoot = worktreeInfo.mainRepoRoot || data.cwd;
145
- const branch = data.branch || worktreeInfo.branch;
146
-
147
- const sessions = await kv.list<Session>(KV.sessions);
148
-
149
- const matching = sessions.filter((s) => {
150
- if (s.project === projectRoot || s.cwd === projectRoot) return true;
151
- if (s.cwd.startsWith(projectRoot + "/")) return true;
152
- return false;
153
- });
154
-
155
- matching.sort(
156
- (a, b) =>
157
- new Date(b.startedAt).getTime() - new Date(a.startedAt).getTime(),
158
- );
159
-
160
- return {
161
- success: true,
162
- sessions: matching,
163
- projectRoot,
164
- branch,
165
- isWorktree: worktreeInfo.isWorktree,
166
- };
167
- },
168
- );
169
- }