@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,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, "&")
20
- .replace(/"/g, """)
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
- }
@@ -1,293 +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, Crystal, MemoryProvider } from "../types.js";
5
-
6
- interface CrystalDigest {
7
- narrative: string;
8
- keyOutcomes: string[];
9
- filesAffected: string[];
10
- lessons: string[];
11
- }
12
-
13
- const CRYSTALLIZE_SYSTEM = `You are summarizing a completed chain of agent actions into a compact digest.
14
- Extract: (1) what was accomplished in 1-2 sentences, (2) key decisions as bullet points,
15
- (3) files affected, (4) any lessons or patterns worth remembering.
16
- Return as JSON: { "narrative": "...", "keyOutcomes": ["..."], "filesAffected": ["..."], "lessons": ["..."] }`;
17
-
18
- export function registerCrystallizeFunction(
19
- sdk: ISdk,
20
- kv: StateKV,
21
- provider: MemoryProvider,
22
- ): void {
23
- sdk.registerFunction(
24
- { id: "mem::crystallize" },
25
- async (data: {
26
- actionIds: string[];
27
- sessionId?: string;
28
- project?: string;
29
- }) => {
30
- if (!data.actionIds || data.actionIds.length === 0) {
31
- return { success: false, error: "actionIds is required" };
32
- }
33
-
34
- const actions: Action[] = [];
35
- for (const id of data.actionIds) {
36
- const action = await kv.get<Action>(KV.actions, id);
37
- if (!action) {
38
- return { success: false, error: `action not found: ${id}` };
39
- }
40
- if (action.status !== "done" && action.status !== "cancelled") {
41
- return {
42
- success: false,
43
- error: `action ${id} has status "${action.status}", expected "done" or "cancelled"`,
44
- };
45
- }
46
- actions.push(action);
47
- }
48
-
49
- const allEdges = await kv.list<ActionEdge>(KV.actionEdges);
50
- const idSet = new Set(data.actionIds);
51
- const relevantEdges = allEdges.filter(
52
- (e) => idSet.has(e.sourceActionId) || idSet.has(e.targetActionId),
53
- );
54
-
55
- const prompt = buildChainText(actions, relevantEdges);
56
-
57
- try {
58
- const response = await provider.summarize(CRYSTALLIZE_SYSTEM, prompt);
59
- const digest = parseDigest(response);
60
-
61
- const crystal: Crystal = {
62
- id: generateId("crys"),
63
- narrative: digest.narrative,
64
- keyOutcomes: digest.keyOutcomes,
65
- filesAffected: digest.filesAffected,
66
- lessons: digest.lessons,
67
- sourceActionIds: data.actionIds,
68
- sessionId: data.sessionId,
69
- project: data.project,
70
- createdAt: new Date().toISOString(),
71
- };
72
-
73
- await kv.set(KV.crystals, crystal.id, crystal);
74
-
75
- await Promise.all(
76
- digest.lessons.map((lesson) =>
77
- sdk.trigger("mem::lesson-save", {
78
- content: lesson,
79
- context: crystal.narrative,
80
- confidence: 0.6,
81
- project: data.project,
82
- tags: [],
83
- source: "crystal",
84
- sourceIds: [crystal.id],
85
- }).catch(() => {}),
86
- ),
87
- );
88
-
89
- for (const action of actions) {
90
- const updated = { ...action, crystallizedInto: crystal.id };
91
- await kv.set(KV.actions, action.id, updated);
92
- }
93
-
94
- return { success: true, crystal };
95
- } catch (err) {
96
- return {
97
- success: false,
98
- error: `crystallization failed: ${String(err)}`,
99
- };
100
- }
101
- },
102
- );
103
-
104
- sdk.registerFunction(
105
- { id: "mem::crystal-list" },
106
- async (data: {
107
- project?: string;
108
- sessionId?: string;
109
- limit?: number;
110
- }) => {
111
- const limit = data.limit ?? 20;
112
- let crystals = await kv.list<Crystal>(KV.crystals);
113
-
114
- if (data.project) {
115
- crystals = crystals.filter((c) => c.project === data.project);
116
- }
117
- if (data.sessionId) {
118
- crystals = crystals.filter((c) => c.sessionId === data.sessionId);
119
- }
120
-
121
- crystals.sort(
122
- (a, b) =>
123
- new Date(b.createdAt).getTime() - new Date(a.createdAt).getTime(),
124
- );
125
-
126
- return { success: true, crystals: crystals.slice(0, limit) };
127
- },
128
- );
129
-
130
- sdk.registerFunction(
131
- { id: "mem::crystal-get" },
132
- async (data: { crystalId: string }) => {
133
- if (!data.crystalId) {
134
- return { success: false, error: "crystalId is required" };
135
- }
136
-
137
- const crystal = await kv.get<Crystal>(KV.crystals, data.crystalId);
138
- if (!crystal) {
139
- return { success: false, error: "crystal not found" };
140
- }
141
-
142
- return { success: true, crystal };
143
- },
144
- );
145
-
146
- sdk.registerFunction(
147
- { id: "mem::auto-crystallize" },
148
- async (data: {
149
- olderThanDays?: number;
150
- project?: string;
151
- dryRun?: boolean;
152
- }) => {
153
- const olderThanDays = data.olderThanDays ?? 7;
154
- const dryRun = data.dryRun ?? false;
155
- const cutoff = Date.now() - olderThanDays * 24 * 60 * 60 * 1000;
156
-
157
- let allActions = await kv.list<CrystallizableAction>(KV.actions);
158
-
159
- allActions = allActions.filter(
160
- (a) =>
161
- a.status === "done" &&
162
- !a.crystallizedInto &&
163
- new Date(a.createdAt).getTime() < cutoff,
164
- );
165
-
166
- if (data.project) {
167
- allActions = allActions.filter((a) => a.project === data.project);
168
- }
169
-
170
- if (allActions.length === 0) {
171
- return { success: true, groupCount: 0, crystalIds: [] };
172
- }
173
-
174
- const groups = new Map<string, Action[]>();
175
- for (const action of allActions) {
176
- const key = action.parentId ?? action.project ?? "_ungrouped";
177
- const group = groups.get(key);
178
- if (group) {
179
- group.push(action);
180
- } else {
181
- groups.set(key, [action]);
182
- }
183
- }
184
-
185
- if (dryRun) {
186
- const groupSummaries = Array.from(groups.entries()).map(
187
- ([key, actions]) => ({
188
- groupKey: key,
189
- actionCount: actions.length,
190
- actionIds: actions.map((a) => a.id),
191
- }),
192
- );
193
- return {
194
- success: true,
195
- dryRun: true,
196
- groupCount: groups.size,
197
- groups: groupSummaries,
198
- crystalIds: [],
199
- };
200
- }
201
-
202
- const crystalIds: string[] = [];
203
- for (const [, groupActions] of groups) {
204
- const actionIds = groupActions.map((a) => a.id);
205
- const project = groupActions[0].project;
206
-
207
- try {
208
- const result = (await sdk.trigger("mem::crystallize", {
209
- actionIds,
210
- project,
211
- })) as { success: boolean; crystal?: Crystal };
212
-
213
- if (result.success && result.crystal) {
214
- crystalIds.push(result.crystal.id);
215
- }
216
- } catch {
217
- continue;
218
- }
219
- }
220
-
221
- return {
222
- success: true,
223
- groupCount: groups.size,
224
- crystalIds,
225
- };
226
- },
227
- );
228
- }
229
-
230
- function buildChainText(actions: Action[], edges: ActionEdge[]): string {
231
- const lines: string[] = ["## Completed Action Chain\n"];
232
-
233
- const sorted = [...actions].sort(
234
- (a, b) =>
235
- new Date(a.createdAt).getTime() - new Date(b.createdAt).getTime(),
236
- );
237
-
238
- for (const action of sorted) {
239
- lines.push(`### ${action.title}`);
240
- if (action.description) lines.push(action.description);
241
- if (action.result) lines.push(`Result: ${action.result}`);
242
- lines.push(
243
- `Tags: ${(action.tags ?? []).join(", ")}`,
244
- );
245
- lines.push("");
246
- }
247
-
248
- if (edges.length > 0) {
249
- lines.push("## Dependencies");
250
- for (const edge of edges) {
251
- lines.push(
252
- `- ${edge.sourceActionId} --${edge.type}--> ${edge.targetActionId}`,
253
- );
254
- }
255
- }
256
-
257
- return lines.join("\n");
258
- }
259
-
260
- function parseDigest(response: string): CrystalDigest {
261
- try {
262
- const jsonMatch = response.match(/\{[\s\S]*\}/);
263
- if (!jsonMatch) {
264
- return {
265
- narrative: response,
266
- keyOutcomes: [],
267
- filesAffected: [],
268
- lessons: [],
269
- };
270
- }
271
- const parsed = JSON.parse(jsonMatch[0]) as Record<string, unknown>;
272
- return {
273
- narrative:
274
- typeof parsed.narrative === "string" ? parsed.narrative : response,
275
- keyOutcomes: Array.isArray(parsed.keyOutcomes)
276
- ? (parsed.keyOutcomes as string[])
277
- : [],
278
- filesAffected: Array.isArray(parsed.filesAffected)
279
- ? (parsed.filesAffected as string[])
280
- : [],
281
- lessons: Array.isArray(parsed.lessons)
282
- ? (parsed.lessons as string[])
283
- : [],
284
- };
285
- } catch {
286
- return {
287
- narrative: response,
288
- keyOutcomes: [],
289
- filesAffected: [],
290
- lessons: [],
291
- };
292
- }
293
- }
@@ -1,57 +0,0 @@
1
- import { createHash } from "node:crypto";
2
-
3
- const TTL_MS = 5 * 60 * 1000;
4
- const CLEANUP_INTERVAL_MS = 60_000;
5
-
6
- interface DedupEntry {
7
- hash: string;
8
- expiresAt: number;
9
- }
10
-
11
- export class DedupMap {
12
- private entries = new Map<string, DedupEntry>();
13
- private cleanupTimer: ReturnType<typeof setInterval>;
14
-
15
- constructor() {
16
- this.cleanupTimer = setInterval(() => this.cleanup(), CLEANUP_INTERVAL_MS);
17
- this.cleanupTimer.unref();
18
- }
19
-
20
- computeHash(sessionId: string, toolName: string, toolInput: unknown): string {
21
- const input =
22
- typeof toolInput === "string"
23
- ? toolInput.slice(0, 500)
24
- : JSON.stringify(toolInput ?? "").slice(0, 500);
25
- const raw = `${sessionId}:${toolName}:${input}`;
26
- return createHash("sha256").update(raw).digest("hex");
27
- }
28
-
29
- isDuplicate(hash: string): boolean {
30
- const entry = this.entries.get(hash);
31
- if (!entry) return false;
32
- if (Date.now() > entry.expiresAt) {
33
- this.entries.delete(hash);
34
- return false;
35
- }
36
- return true;
37
- }
38
-
39
- record(hash: string): void {
40
- this.entries.set(hash, { hash, expiresAt: Date.now() + TTL_MS });
41
- }
42
-
43
- private cleanup(): void {
44
- const now = Date.now();
45
- for (const [key, entry] of this.entries) {
46
- if (now > entry.expiresAt) this.entries.delete(key);
47
- }
48
- }
49
-
50
- stop(): void {
51
- clearInterval(this.cleanupTimer);
52
- }
53
-
54
- get size(): number {
55
- return this.entries.size;
56
- }
57
- }