@agentmemory/agentmemory 0.7.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (259) hide show
  1. package/.claude-plugin/marketplace.json +14 -0
  2. package/.github/workflows/ci.yml +22 -0
  3. package/.github/workflows/publish.yml +28 -0
  4. package/AGENTS.md +113 -0
  5. package/LICENSE +190 -0
  6. package/README.md +828 -0
  7. package/assets/banner.png +0 -0
  8. package/assets/demo.gif +0 -0
  9. package/assets/demo.mp4 +0 -0
  10. package/benchmark/QUALITY.md +73 -0
  11. package/benchmark/REAL-EMBEDDINGS.md +67 -0
  12. package/benchmark/SCALE.md +110 -0
  13. package/benchmark/dataset.ts +293 -0
  14. package/benchmark/quality-eval.ts +643 -0
  15. package/benchmark/real-embeddings-eval.ts +405 -0
  16. package/benchmark/scale-eval.ts +398 -0
  17. package/dist/cli.d.mts +1 -0
  18. package/dist/cli.mjs +137 -0
  19. package/dist/cli.mjs.map +1 -0
  20. package/dist/docker-compose.yml +14 -0
  21. package/dist/hooks/notification.d.mts +1 -0
  22. package/dist/hooks/notification.mjs +45 -0
  23. package/dist/hooks/notification.mjs.map +1 -0
  24. package/dist/hooks/post-tool-failure.d.mts +1 -0
  25. package/dist/hooks/post-tool-failure.mjs +45 -0
  26. package/dist/hooks/post-tool-failure.mjs.map +1 -0
  27. package/dist/hooks/post-tool-use.d.mts +1 -0
  28. package/dist/hooks/post-tool-use.mjs +53 -0
  29. package/dist/hooks/post-tool-use.mjs.map +1 -0
  30. package/dist/hooks/pre-compact.d.mts +1 -0
  31. package/dist/hooks/pre-compact.mjs +50 -0
  32. package/dist/hooks/pre-compact.mjs.map +1 -0
  33. package/dist/hooks/pre-tool-use.d.mts +1 -0
  34. package/dist/hooks/pre-tool-use.mjs +69 -0
  35. package/dist/hooks/pre-tool-use.mjs.map +1 -0
  36. package/dist/hooks/prompt-submit.d.mts +1 -0
  37. package/dist/hooks/prompt-submit.mjs +40 -0
  38. package/dist/hooks/prompt-submit.mjs.map +1 -0
  39. package/dist/hooks/session-end.d.mts +1 -0
  40. package/dist/hooks/session-end.mjs +61 -0
  41. package/dist/hooks/session-end.mjs.map +1 -0
  42. package/dist/hooks/session-start.d.mts +1 -0
  43. package/dist/hooks/session-start.mjs +42 -0
  44. package/dist/hooks/session-start.mjs.map +1 -0
  45. package/dist/hooks/stop.d.mts +1 -0
  46. package/dist/hooks/stop.mjs +33 -0
  47. package/dist/hooks/stop.mjs.map +1 -0
  48. package/dist/hooks/subagent-start.d.mts +1 -0
  49. package/dist/hooks/subagent-start.mjs +43 -0
  50. package/dist/hooks/subagent-start.mjs.map +1 -0
  51. package/dist/hooks/subagent-stop.d.mts +1 -0
  52. package/dist/hooks/subagent-stop.mjs +45 -0
  53. package/dist/hooks/subagent-stop.mjs.map +1 -0
  54. package/dist/hooks/task-completed.d.mts +1 -0
  55. package/dist/hooks/task-completed.mjs +46 -0
  56. package/dist/hooks/task-completed.mjs.map +1 -0
  57. package/dist/iii-config.yaml +51 -0
  58. package/dist/index.d.mts +2 -0
  59. package/dist/index.mjs +13776 -0
  60. package/dist/index.mjs.map +1 -0
  61. package/dist/src-QxitMPfJ.mjs +13775 -0
  62. package/dist/src-QxitMPfJ.mjs.map +1 -0
  63. package/dist/standalone.d.mts +1 -0
  64. package/dist/standalone.mjs +1155 -0
  65. package/dist/standalone.mjs.map +1 -0
  66. package/dist/transformers-BX_tgxdO.mjs +38684 -0
  67. package/dist/transformers-BX_tgxdO.mjs.map +1 -0
  68. package/dist/transformers-KMm1i9no.mjs +38683 -0
  69. package/dist/transformers-KMm1i9no.mjs.map +1 -0
  70. package/docker-compose.yml +14 -0
  71. package/iii-config.yaml +51 -0
  72. package/package.json +59 -0
  73. package/plugin/.claude-plugin/plugin.json +10 -0
  74. package/plugin/hooks/hooks.json +77 -0
  75. package/plugin/scripts/diagnostics.mjs +551 -0
  76. package/plugin/scripts/notification.mjs +45 -0
  77. package/plugin/scripts/post-tool-failure.mjs +45 -0
  78. package/plugin/scripts/post-tool-use.mjs +53 -0
  79. package/plugin/scripts/pre-compact.mjs +50 -0
  80. package/plugin/scripts/pre-tool-use.mjs +69 -0
  81. package/plugin/scripts/prompt-submit.mjs +40 -0
  82. package/plugin/scripts/session-end.mjs +61 -0
  83. package/plugin/scripts/session-start.mjs +42 -0
  84. package/plugin/scripts/stop.mjs +33 -0
  85. package/plugin/scripts/subagent-start.mjs +43 -0
  86. package/plugin/scripts/subagent-stop.mjs +45 -0
  87. package/plugin/scripts/task-completed.mjs +46 -0
  88. package/plugin/skills/forget/SKILL.md +32 -0
  89. package/plugin/skills/recall/SKILL.md +18 -0
  90. package/plugin/skills/remember/SKILL.md +25 -0
  91. package/plugin/skills/session-history/SKILL.md +17 -0
  92. package/src/auth.ts +12 -0
  93. package/src/cli.ts +159 -0
  94. package/src/config.ts +221 -0
  95. package/src/eval/metrics-store.ts +65 -0
  96. package/src/eval/quality.ts +51 -0
  97. package/src/eval/schemas.ts +124 -0
  98. package/src/eval/self-correct.ts +28 -0
  99. package/src/eval/validator.ts +31 -0
  100. package/src/functions/actions.ts +288 -0
  101. package/src/functions/audit.ts +61 -0
  102. package/src/functions/auto-forget.ts +169 -0
  103. package/src/functions/branch-aware.ts +169 -0
  104. package/src/functions/cascade.ts +80 -0
  105. package/src/functions/checkpoints.ts +209 -0
  106. package/src/functions/claude-bridge.ts +161 -0
  107. package/src/functions/compress.ts +194 -0
  108. package/src/functions/consolidate.ts +212 -0
  109. package/src/functions/consolidation-pipeline.ts +258 -0
  110. package/src/functions/context.ts +169 -0
  111. package/src/functions/crystallize.ts +293 -0
  112. package/src/functions/dedup.ts +57 -0
  113. package/src/functions/diagnostics.ts +785 -0
  114. package/src/functions/enrich.ts +132 -0
  115. package/src/functions/evict.ts +163 -0
  116. package/src/functions/export-import.ts +508 -0
  117. package/src/functions/facets.ts +248 -0
  118. package/src/functions/file-index.ts +106 -0
  119. package/src/functions/flow-compress.ts +214 -0
  120. package/src/functions/frontier.ts +196 -0
  121. package/src/functions/governance.ts +131 -0
  122. package/src/functions/graph-retrieval.ts +277 -0
  123. package/src/functions/graph.ts +275 -0
  124. package/src/functions/leases.ts +216 -0
  125. package/src/functions/lessons.ts +253 -0
  126. package/src/functions/mesh.ts +434 -0
  127. package/src/functions/migrate.ts +165 -0
  128. package/src/functions/observe.ts +144 -0
  129. package/src/functions/obsidian-export.ts +310 -0
  130. package/src/functions/patterns.ts +138 -0
  131. package/src/functions/privacy.ts +39 -0
  132. package/src/functions/profile.ts +155 -0
  133. package/src/functions/query-expansion.ts +186 -0
  134. package/src/functions/relations.ts +237 -0
  135. package/src/functions/remember.ts +162 -0
  136. package/src/functions/retention.ts +235 -0
  137. package/src/functions/routines.ts +289 -0
  138. package/src/functions/search.ts +80 -0
  139. package/src/functions/sentinels.ts +417 -0
  140. package/src/functions/signals.ts +186 -0
  141. package/src/functions/sketches.ts +274 -0
  142. package/src/functions/sliding-window.ts +257 -0
  143. package/src/functions/smart-search.ts +115 -0
  144. package/src/functions/snapshot.ts +219 -0
  145. package/src/functions/summarize.ts +155 -0
  146. package/src/functions/team.ts +147 -0
  147. package/src/functions/temporal-graph.ts +476 -0
  148. package/src/functions/timeline.ts +138 -0
  149. package/src/functions/verify.ts +117 -0
  150. package/src/health/monitor.ts +110 -0
  151. package/src/health/thresholds.ts +73 -0
  152. package/src/hooks/notification.ts +52 -0
  153. package/src/hooks/post-tool-failure.ts +58 -0
  154. package/src/hooks/post-tool-use.ts +62 -0
  155. package/src/hooks/pre-compact.ts +60 -0
  156. package/src/hooks/pre-tool-use.ts +72 -0
  157. package/src/hooks/prompt-submit.ts +46 -0
  158. package/src/hooks/session-end.ts +71 -0
  159. package/src/hooks/session-start.ts +48 -0
  160. package/src/hooks/stop.ts +39 -0
  161. package/src/hooks/subagent-start.ts +49 -0
  162. package/src/hooks/subagent-stop.ts +54 -0
  163. package/src/hooks/task-completed.ts +54 -0
  164. package/src/index.ts +342 -0
  165. package/src/mcp/in-memory-kv.ts +61 -0
  166. package/src/mcp/server.ts +1455 -0
  167. package/src/mcp/standalone.ts +177 -0
  168. package/src/mcp/tools-registry.ts +769 -0
  169. package/src/mcp/transport.ts +91 -0
  170. package/src/prompts/compression.ts +67 -0
  171. package/src/prompts/consolidation.ts +48 -0
  172. package/src/prompts/graph-extraction.ts +35 -0
  173. package/src/prompts/summary.ts +38 -0
  174. package/src/prompts/xml.ts +26 -0
  175. package/src/providers/agent-sdk.ts +34 -0
  176. package/src/providers/anthropic.ts +35 -0
  177. package/src/providers/circuit-breaker.ts +82 -0
  178. package/src/providers/embedding/cohere.ts +46 -0
  179. package/src/providers/embedding/gemini.ts +54 -0
  180. package/src/providers/embedding/index.ts +39 -0
  181. package/src/providers/embedding/local.ts +52 -0
  182. package/src/providers/embedding/openai.ts +45 -0
  183. package/src/providers/embedding/openrouter.ts +51 -0
  184. package/src/providers/embedding/voyage.ts +46 -0
  185. package/src/providers/fallback-chain.ts +31 -0
  186. package/src/providers/index.ts +84 -0
  187. package/src/providers/openrouter.ts +71 -0
  188. package/src/providers/resilient.ts +37 -0
  189. package/src/state/hybrid-search.ts +295 -0
  190. package/src/state/index-persistence.ts +63 -0
  191. package/src/state/keyed-mutex.ts +18 -0
  192. package/src/state/kv.ts +33 -0
  193. package/src/state/schema.ts +71 -0
  194. package/src/state/search-index.ts +245 -0
  195. package/src/state/stemmer.ts +104 -0
  196. package/src/state/synonyms.ts +63 -0
  197. package/src/state/vector-index.ts +130 -0
  198. package/src/telemetry/setup.ts +116 -0
  199. package/src/triggers/api.ts +1904 -0
  200. package/src/triggers/events.ts +71 -0
  201. package/src/types.ts +769 -0
  202. package/src/version.ts +1 -0
  203. package/src/viewer/index.html +2497 -0
  204. package/src/viewer/server.ts +207 -0
  205. package/src/xenova.d.ts +3 -0
  206. package/test/actions.test.ts +490 -0
  207. package/test/audit.test.ts +108 -0
  208. package/test/auto-forget.test.ts +188 -0
  209. package/test/cascade.test.ts +277 -0
  210. package/test/checkpoints.test.ts +493 -0
  211. package/test/circuit-breaker.test.ts +107 -0
  212. package/test/claude-bridge.test.ts +178 -0
  213. package/test/confidence.test.ts +247 -0
  214. package/test/consistency.test.ts +61 -0
  215. package/test/consolidation-pipeline.test.ts +251 -0
  216. package/test/crystallize.test.ts +521 -0
  217. package/test/diagnostics.test.ts +638 -0
  218. package/test/embedding-provider.test.ts +49 -0
  219. package/test/enrich.test.ts +209 -0
  220. package/test/eval.test.ts +300 -0
  221. package/test/export-import.test.ts +251 -0
  222. package/test/facets.test.ts +448 -0
  223. package/test/fallback-chain.test.ts +93 -0
  224. package/test/frontier.test.ts +485 -0
  225. package/test/governance.test.ts +147 -0
  226. package/test/graph-retrieval.test.ts +186 -0
  227. package/test/graph.test.ts +160 -0
  228. package/test/helpers/mocks.ts +40 -0
  229. package/test/hybrid-search.test.ts +145 -0
  230. package/test/index-persistence.test.ts +124 -0
  231. package/test/integration.test.ts +265 -0
  232. package/test/leases.test.ts +399 -0
  233. package/test/mcp-prompts.test.ts +218 -0
  234. package/test/mcp-resources.test.ts +286 -0
  235. package/test/mcp-standalone.test.ts +113 -0
  236. package/test/mesh.test.ts +700 -0
  237. package/test/privacy.test.ts +87 -0
  238. package/test/profile.test.ts +161 -0
  239. package/test/query-expansion.test.ts +154 -0
  240. package/test/relations.test.ts +198 -0
  241. package/test/retention.test.ts +245 -0
  242. package/test/routines.test.ts +497 -0
  243. package/test/schema-fingerprint.test.ts +81 -0
  244. package/test/schema.test.ts +42 -0
  245. package/test/search-index.test.ts +128 -0
  246. package/test/sentinels.test.ts +626 -0
  247. package/test/signals.test.ts +410 -0
  248. package/test/sketches.test.ts +549 -0
  249. package/test/sliding-window.test.ts +199 -0
  250. package/test/smart-search.test.ts +169 -0
  251. package/test/snapshot.test.ts +165 -0
  252. package/test/team.test.ts +156 -0
  253. package/test/temporal-graph.test.ts +378 -0
  254. package/test/timeline.test.ts +148 -0
  255. package/test/vector-index.test.ts +79 -0
  256. package/test/verify.test.ts +209 -0
  257. package/test/xml.test.ts +65 -0
  258. package/tsconfig.json +22 -0
  259. package/tsdown.config.ts +62 -0
@@ -0,0 +1,209 @@
1
+ import { describe, it, expect, beforeEach, vi } from "vitest";
2
+
3
+ vi.mock("iii-sdk", () => ({
4
+ getContext: () => ({
5
+ logger: { info: vi.fn(), error: vi.fn(), warn: vi.fn() },
6
+ }),
7
+ }));
8
+
9
+ import { registerEnrichFunction } from "../src/functions/enrich.js";
10
+ import type { Memory } from "../src/types.js";
11
+
12
+ function mockKV() {
13
+ const store = new Map<string, Map<string, unknown>>();
14
+ return {
15
+ get: async <T>(scope: string, key: string): Promise<T | null> => {
16
+ return (store.get(scope)?.get(key) as T) ?? null;
17
+ },
18
+ set: async <T>(scope: string, key: string, data: T): Promise<T> => {
19
+ if (!store.has(scope)) store.set(scope, new Map());
20
+ store.get(scope)!.set(key, data);
21
+ return data;
22
+ },
23
+ delete: async (scope: string, key: string): Promise<void> => {
24
+ store.get(scope)?.delete(key);
25
+ },
26
+ list: async <T>(scope: string): Promise<T[]> => {
27
+ const entries = store.get(scope);
28
+ return entries ? (Array.from(entries.values()) as T[]) : [];
29
+ },
30
+ };
31
+ }
32
+
33
+ function makeMemory(overrides: Partial<Memory> = {}): Memory {
34
+ return {
35
+ id: "mem_1",
36
+ createdAt: new Date().toISOString(),
37
+ updatedAt: new Date().toISOString(),
38
+ type: "bug",
39
+ title: "Known bug",
40
+ content: "Null pointer in handler",
41
+ concepts: ["bug"],
42
+ files: ["src/handler.ts"],
43
+ sessionIds: ["ses_1"],
44
+ strength: 5,
45
+ version: 1,
46
+ isLatest: true,
47
+ ...overrides,
48
+ };
49
+ }
50
+
51
+ function mockSdk() {
52
+ const functions = new Map<string, Function>();
53
+ const triggerOverrides = new Map<string, Function>();
54
+ return {
55
+ registerFunction: (opts: { id: string }, handler: Function) => {
56
+ functions.set(opts.id, handler);
57
+ },
58
+ registerTrigger: () => {},
59
+ trigger: async (id: string, data: unknown) => {
60
+ if (triggerOverrides.has(id)) {
61
+ return triggerOverrides.get(id)!(data);
62
+ }
63
+ const fn = functions.get(id);
64
+ if (!fn) throw new Error(`No function: ${id}`);
65
+ return fn(data);
66
+ },
67
+ overrideTrigger: (id: string, handler: Function) => {
68
+ triggerOverrides.set(id, handler);
69
+ },
70
+ getFunction: (id: string) => functions.get(id),
71
+ };
72
+ }
73
+
74
+ describe("Enrich Function", () => {
75
+ let sdk: ReturnType<typeof mockSdk>;
76
+ let kv: ReturnType<typeof mockKV>;
77
+
78
+ beforeEach(() => {
79
+ sdk = mockSdk();
80
+ kv = mockKV();
81
+ registerEnrichFunction(sdk as never, kv as never);
82
+ });
83
+
84
+ it("returns file context and relevant memories", async () => {
85
+ sdk.overrideTrigger(
86
+ "mem::file-context",
87
+ async () => ({ context: "File was edited in session ses_1" }),
88
+ );
89
+ sdk.overrideTrigger("mem::search", async () => ({
90
+ results: [
91
+ { observation: { narrative: "User fixed a bug in handler" } },
92
+ ],
93
+ }));
94
+
95
+ const bugMem = makeMemory({
96
+ id: "bug_1",
97
+ files: ["src/handler.ts"],
98
+ type: "bug",
99
+ });
100
+ await kv.set("mem:memories", "bug_1", bugMem);
101
+
102
+ const result = (await sdk.trigger("mem::enrich", {
103
+ sessionId: "ses_1",
104
+ files: ["src/handler.ts"],
105
+ })) as { context: string; truncated: boolean };
106
+
107
+ expect(result.context).toContain("File was edited in session ses_1");
108
+ expect(result.context).toContain("agentmemory-relevant-context");
109
+ expect(result.context).toContain("agentmemory-past-errors");
110
+ expect(result.truncated).toBe(false);
111
+ });
112
+
113
+ it("extracts terms from Grep/Glob pattern for search", async () => {
114
+ let capturedQuery = "";
115
+ sdk.overrideTrigger("mem::file-context", async () => ({ context: "" }));
116
+ sdk.overrideTrigger("mem::search", async (data: any) => {
117
+ capturedQuery = data.query;
118
+ return { results: [] };
119
+ });
120
+
121
+ await sdk.trigger("mem::enrich", {
122
+ sessionId: "ses_1",
123
+ files: ["src/utils.ts"],
124
+ terms: ["handleError"],
125
+ toolName: "Grep",
126
+ });
127
+
128
+ expect(capturedQuery).toContain("handleError");
129
+ });
130
+
131
+ it("truncates context at 4000 chars", async () => {
132
+ const longContext = "x".repeat(5000);
133
+ sdk.overrideTrigger(
134
+ "mem::file-context",
135
+ async () => ({ context: longContext }),
136
+ );
137
+ sdk.overrideTrigger("mem::search", async () => ({ results: [] }));
138
+
139
+ const result = (await sdk.trigger("mem::enrich", {
140
+ sessionId: "ses_1",
141
+ files: ["src/big.ts"],
142
+ })) as { context: string; truncated: boolean };
143
+
144
+ expect(result.context.length).toBe(4000);
145
+ expect(result.truncated).toBe(true);
146
+ });
147
+
148
+ it("returns empty context when no data found", async () => {
149
+ sdk.overrideTrigger("mem::file-context", async () => ({ context: "" }));
150
+ sdk.overrideTrigger("mem::search", async () => ({ results: [] }));
151
+
152
+ const result = (await sdk.trigger("mem::enrich", {
153
+ sessionId: "ses_1",
154
+ files: ["src/new-file.ts"],
155
+ })) as { context: string; truncated: boolean };
156
+
157
+ expect(result.context).toBe("");
158
+ expect(result.truncated).toBe(false);
159
+ });
160
+
161
+ it("handles failed triggers without crashing", async () => {
162
+ sdk.overrideTrigger("mem::file-context", async () => {
163
+ throw new Error("file-context failed");
164
+ });
165
+ sdk.overrideTrigger("mem::search", async () => {
166
+ throw new Error("search failed");
167
+ });
168
+
169
+ const result = (await sdk.trigger("mem::enrich", {
170
+ sessionId: "ses_1",
171
+ files: ["src/handler.ts"],
172
+ })) as { context: string; truncated: boolean };
173
+
174
+ expect(result.context).toBeDefined();
175
+ expect(result.truncated).toBe(false);
176
+ });
177
+
178
+ it("includes bug memories that overlap with requested files", async () => {
179
+ sdk.overrideTrigger("mem::file-context", async () => ({ context: "" }));
180
+ sdk.overrideTrigger("mem::search", async () => ({ results: [] }));
181
+
182
+ const bugMem = makeMemory({
183
+ id: "bug_match",
184
+ type: "bug",
185
+ title: "Race condition",
186
+ content: "Race condition in worker pool",
187
+ files: ["src/worker.ts"],
188
+ isLatest: true,
189
+ });
190
+ const nonBugMem = makeMemory({
191
+ id: "pattern_1",
192
+ type: "pattern",
193
+ title: "Code pattern",
194
+ content: "Singleton pattern used",
195
+ files: ["src/worker.ts"],
196
+ isLatest: true,
197
+ });
198
+ await kv.set("mem:memories", "bug_match", bugMem);
199
+ await kv.set("mem:memories", "pattern_1", nonBugMem);
200
+
201
+ const result = (await sdk.trigger("mem::enrich", {
202
+ sessionId: "ses_1",
203
+ files: ["src/worker.ts"],
204
+ })) as { context: string; truncated: boolean };
205
+
206
+ expect(result.context).toContain("Race condition");
207
+ expect(result.context).not.toContain("Singleton pattern");
208
+ });
209
+ });
@@ -0,0 +1,300 @@
1
+ import { describe, it, expect } from "vitest";
2
+ import {
3
+ ObserveInputSchema,
4
+ CompressOutputSchema,
5
+ SummaryOutputSchema,
6
+ SearchInputSchema,
7
+ ContextInputSchema,
8
+ RememberInputSchema,
9
+ } from "../src/eval/schemas.js";
10
+ import { validateInput, validateOutput } from "../src/eval/validator.js";
11
+ import {
12
+ scoreCompression,
13
+ scoreSummary,
14
+ scoreContextRelevance,
15
+ } from "../src/eval/quality.js";
16
+
17
+ describe("Zod Schemas", () => {
18
+ describe("ObserveInputSchema", () => {
19
+ it("accepts valid input", () => {
20
+ const result = ObserveInputSchema.safeParse({
21
+ hookType: "post_tool_use",
22
+ sessionId: "ses_abc",
23
+ project: "my-project",
24
+ cwd: "/home/user",
25
+ timestamp: "2026-01-01T00:00:00Z",
26
+ data: { tool_name: "Read" },
27
+ });
28
+ expect(result.success).toBe(true);
29
+ });
30
+
31
+ it("rejects missing sessionId", () => {
32
+ const result = ObserveInputSchema.safeParse({
33
+ hookType: "post_tool_use",
34
+ project: "my-project",
35
+ cwd: "/home/user",
36
+ timestamp: "2026-01-01T00:00:00Z",
37
+ data: {},
38
+ });
39
+ expect(result.success).toBe(false);
40
+ });
41
+
42
+ it("rejects invalid hookType", () => {
43
+ const result = ObserveInputSchema.safeParse({
44
+ hookType: "invalid_hook",
45
+ sessionId: "ses_abc",
46
+ project: "my-project",
47
+ cwd: "/home/user",
48
+ timestamp: "2026-01-01T00:00:00Z",
49
+ data: {},
50
+ });
51
+ expect(result.success).toBe(false);
52
+ });
53
+ });
54
+
55
+ describe("CompressOutputSchema", () => {
56
+ it("accepts valid output", () => {
57
+ const result = CompressOutputSchema.safeParse({
58
+ type: "file_edit",
59
+ title: "Edit auth module",
60
+ facts: ["Added JWT validation"],
61
+ narrative: "Modified the auth middleware to validate tokens",
62
+ concepts: ["auth"],
63
+ files: ["src/auth.ts"],
64
+ importance: 7,
65
+ });
66
+ expect(result.success).toBe(true);
67
+ });
68
+
69
+ it("rejects empty facts array", () => {
70
+ const result = CompressOutputSchema.safeParse({
71
+ type: "file_edit",
72
+ title: "Edit auth module",
73
+ facts: [],
74
+ narrative: "Modified the auth middleware to validate tokens",
75
+ concepts: [],
76
+ files: [],
77
+ importance: 5,
78
+ });
79
+ expect(result.success).toBe(false);
80
+ });
81
+
82
+ it("rejects title over 120 chars", () => {
83
+ const result = CompressOutputSchema.safeParse({
84
+ type: "file_edit",
85
+ title: "x".repeat(121),
86
+ facts: ["fact"],
87
+ narrative: "A narrative that is long enough",
88
+ concepts: [],
89
+ files: [],
90
+ importance: 5,
91
+ });
92
+ expect(result.success).toBe(false);
93
+ });
94
+
95
+ it("rejects importance outside 1-10", () => {
96
+ const result = CompressOutputSchema.safeParse({
97
+ type: "file_edit",
98
+ title: "Test",
99
+ facts: ["fact"],
100
+ narrative: "A valid narrative here",
101
+ concepts: [],
102
+ files: [],
103
+ importance: 11,
104
+ });
105
+ expect(result.success).toBe(false);
106
+ });
107
+
108
+ it("rejects narrative under 10 chars", () => {
109
+ const result = CompressOutputSchema.safeParse({
110
+ type: "file_edit",
111
+ title: "Test",
112
+ facts: ["fact"],
113
+ narrative: "short",
114
+ concepts: [],
115
+ files: [],
116
+ importance: 5,
117
+ });
118
+ expect(result.success).toBe(false);
119
+ });
120
+ });
121
+
122
+ describe("SummaryOutputSchema", () => {
123
+ it("accepts valid summary", () => {
124
+ const result = SummaryOutputSchema.safeParse({
125
+ title: "Session Summary",
126
+ narrative: "This session focused on implementing authentication features and fixing bugs",
127
+ keyDecisions: ["Use JWT"],
128
+ filesModified: ["auth.ts"],
129
+ concepts: ["auth"],
130
+ });
131
+ expect(result.success).toBe(true);
132
+ });
133
+
134
+ it("rejects short narrative", () => {
135
+ const result = SummaryOutputSchema.safeParse({
136
+ title: "Summary",
137
+ narrative: "Too short",
138
+ keyDecisions: [],
139
+ filesModified: [],
140
+ concepts: [],
141
+ });
142
+ expect(result.success).toBe(false);
143
+ });
144
+ });
145
+
146
+ describe("SearchInputSchema", () => {
147
+ it("accepts valid search", () => {
148
+ expect(SearchInputSchema.safeParse({ query: "auth" }).success).toBe(true);
149
+ });
150
+
151
+ it("accepts search with limit", () => {
152
+ expect(
153
+ SearchInputSchema.safeParse({ query: "auth", limit: 10 }).success,
154
+ ).toBe(true);
155
+ });
156
+
157
+ it("rejects empty query", () => {
158
+ expect(SearchInputSchema.safeParse({ query: "" }).success).toBe(false);
159
+ });
160
+ });
161
+
162
+ describe("ContextInputSchema", () => {
163
+ it("accepts valid input", () => {
164
+ expect(
165
+ ContextInputSchema.safeParse({
166
+ sessionId: "ses_1",
167
+ project: "proj",
168
+ }).success,
169
+ ).toBe(true);
170
+ });
171
+ });
172
+
173
+ describe("RememberInputSchema", () => {
174
+ it("accepts valid input", () => {
175
+ expect(
176
+ RememberInputSchema.safeParse({
177
+ content: "Always use TypeScript",
178
+ type: "preference",
179
+ }).success,
180
+ ).toBe(true);
181
+ });
182
+
183
+ it("rejects empty content", () => {
184
+ expect(
185
+ RememberInputSchema.safeParse({ content: "" }).success,
186
+ ).toBe(false);
187
+ });
188
+ });
189
+ });
190
+
191
+ describe("Validator", () => {
192
+ it("returns valid with correct data", () => {
193
+ const result = validateInput(SearchInputSchema, { query: "test" }, "search");
194
+ expect(result.valid).toBe(true);
195
+ if (result.valid) {
196
+ expect(result.data.query).toBe("test");
197
+ }
198
+ });
199
+
200
+ it("returns invalid with error details", () => {
201
+ const result = validateInput(SearchInputSchema, { query: "" }, "search");
202
+ expect(result.valid).toBe(false);
203
+ if (!result.valid) {
204
+ expect(result.result.functionId).toBe("search");
205
+ expect(result.result.errors.length).toBeGreaterThan(0);
206
+ }
207
+ });
208
+
209
+ it("validateOutput works same as validateInput", () => {
210
+ const result = validateOutput(
211
+ CompressOutputSchema,
212
+ {
213
+ type: "file_edit",
214
+ title: "Test",
215
+ facts: ["a"],
216
+ narrative: "A long enough narrative",
217
+ concepts: [],
218
+ files: [],
219
+ importance: 5,
220
+ },
221
+ "compress",
222
+ );
223
+ expect(result.valid).toBe(true);
224
+ });
225
+ });
226
+
227
+ describe("Quality Scoring", () => {
228
+ describe("scoreCompression", () => {
229
+ it("returns 0 for empty object", () => {
230
+ expect(scoreCompression({})).toBe(0);
231
+ });
232
+
233
+ it("returns 100 for perfect observation", () => {
234
+ const score = scoreCompression({
235
+ type: "file_edit",
236
+ title: "A good title",
237
+ facts: ["fact 1", "fact 2", "fact 3"],
238
+ narrative: "A narrative that is definitely more than fifty characters long and provides good context",
239
+ concepts: ["auth", "jwt"],
240
+ importance: 7,
241
+ });
242
+ expect(score).toBe(100);
243
+ });
244
+
245
+ it("scores partial observations between 0 and 100", () => {
246
+ const score = scoreCompression({
247
+ title: "Test",
248
+ facts: ["one"],
249
+ narrative: "Short but valid narrative",
250
+ });
251
+ expect(score).toBeGreaterThan(0);
252
+ expect(score).toBeLessThan(100);
253
+ });
254
+ });
255
+
256
+ describe("scoreSummary", () => {
257
+ it("returns 0 for empty object", () => {
258
+ expect(scoreSummary({})).toBe(0);
259
+ });
260
+
261
+ it("returns high score for complete summary", () => {
262
+ const score = scoreSummary({
263
+ title: "Session Summary Title",
264
+ narrative:
265
+ "This is a detailed narrative about what happened during the session with enough content to be meaningful and complete for review purposes",
266
+ keyDecisions: ["Used JWT for auth", "Chose PostgreSQL"],
267
+ filesModified: ["src/auth.ts", "src/db.ts"],
268
+ concepts: ["authentication", "database"],
269
+ });
270
+ expect(score).toBeGreaterThanOrEqual(90);
271
+ });
272
+ });
273
+
274
+ describe("scoreContextRelevance", () => {
275
+ it("returns 0 for empty context", () => {
276
+ expect(scoreContextRelevance("", "proj")).toBe(0);
277
+ });
278
+
279
+ it("scores higher when project is mentioned", () => {
280
+ const withProject = scoreContextRelevance(
281
+ "<context>This is for my-project with details</context>",
282
+ "my-project",
283
+ );
284
+ const without = scoreContextRelevance(
285
+ "<context>Some generic context details</context>",
286
+ "my-project",
287
+ );
288
+ expect(withProject).toBeGreaterThan(without);
289
+ });
290
+
291
+ it("scores higher with more XML sections", () => {
292
+ const multi = scoreContextRelevance(
293
+ "<summary>A</summary><observations>B</observations><memories>C</memories><patterns>D</patterns>",
294
+ "test",
295
+ );
296
+ const single = scoreContextRelevance("<summary>A</summary>", "test");
297
+ expect(multi).toBeGreaterThan(single);
298
+ });
299
+ });
300
+ });