@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,138 @@
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 Pattern {
8
+ type: "co_change" | "error_repeat" | "workflow";
9
+ description: string;
10
+ files: string[];
11
+ frequency: number;
12
+ sessions: string[];
13
+ }
14
+
15
+ export function registerPatternsFunction(sdk: ISdk, kv: StateKV): void {
16
+ sdk.registerFunction(
17
+ { id: "mem::patterns" },
18
+ async (data: { project?: string }) => {
19
+ const ctx = getContext();
20
+ const patterns: Pattern[] = [];
21
+
22
+ const sessions = await kv.list<Session>(KV.sessions);
23
+ const filtered = data.project
24
+ ? sessions.filter((s) => s.project === data.project)
25
+ : sessions;
26
+
27
+ const fileCoOccurrences = new Map<string, number>();
28
+ const fileSessionMap = new Map<string, Set<string>>();
29
+ const errorPatterns = new Map<
30
+ string,
31
+ { count: number; sessions: Set<string> }
32
+ >();
33
+
34
+ for (const session of filtered) {
35
+ const observations = await kv.list<CompressedObservation>(
36
+ KV.observations(session.id),
37
+ );
38
+ if (!observations.length) continue;
39
+
40
+ const sessionFiles = new Set<string>();
41
+ for (const obs of observations) {
42
+ if (!obs.files) continue;
43
+ for (const f of obs.files) {
44
+ sessionFiles.add(f);
45
+ if (!fileSessionMap.has(f)) fileSessionMap.set(f, new Set());
46
+ fileSessionMap.get(f)!.add(session.id);
47
+ }
48
+
49
+ if (obs.type === "error" && obs.title) {
50
+ const key = obs.title.toLowerCase();
51
+ if (!errorPatterns.has(key)) {
52
+ errorPatterns.set(key, { count: 0, sessions: new Set() });
53
+ }
54
+ const ep = errorPatterns.get(key)!;
55
+ ep.count++;
56
+ ep.sessions.add(session.id);
57
+ }
58
+ }
59
+
60
+ const fileList = [...sessionFiles].sort();
61
+ for (let i = 0; i < fileList.length; i++) {
62
+ for (let j = i + 1; j < fileList.length; j++) {
63
+ const pair = `${fileList[i]}::${fileList[j]}`;
64
+ fileCoOccurrences.set(pair, (fileCoOccurrences.get(pair) || 0) + 1);
65
+ }
66
+ }
67
+ }
68
+
69
+ for (const [pair, count] of fileCoOccurrences) {
70
+ if (count < 3) continue;
71
+ const [fileA, fileB] = pair.split("::");
72
+ const sessionsA = fileSessionMap.get(fileA) || new Set();
73
+ const sessionsB = fileSessionMap.get(fileB) || new Set();
74
+ const commonSessions = [...sessionsA].filter((s) => sessionsB.has(s));
75
+
76
+ patterns.push({
77
+ type: "co_change",
78
+ description: `${fileA} and ${fileB} are frequently modified together`,
79
+ files: [fileA, fileB],
80
+ frequency: count,
81
+ sessions: commonSessions,
82
+ });
83
+ }
84
+
85
+ for (const [
86
+ errorKey,
87
+ { count, sessions: errorSessions },
88
+ ] of errorPatterns) {
89
+ if (count < 2) continue;
90
+ patterns.push({
91
+ type: "error_repeat",
92
+ description: `Recurring error: ${errorKey}`,
93
+ files: [],
94
+ frequency: count,
95
+ sessions: [...errorSessions],
96
+ });
97
+ }
98
+
99
+ patterns.sort((a, b) => b.frequency - a.frequency);
100
+
101
+ ctx.logger.info("Pattern detection complete", {
102
+ patterns: patterns.length,
103
+ sessions: filtered.length,
104
+ });
105
+
106
+ return { patterns: patterns.slice(0, 20) };
107
+ },
108
+ );
109
+
110
+ sdk.registerFunction(
111
+ { id: "mem::generate-rules" },
112
+ async (data: { project?: string }) => {
113
+ const ctx = getContext();
114
+ const result = await sdk.trigger<
115
+ { project?: string },
116
+ { patterns: Pattern[] }
117
+ >("mem::patterns", data);
118
+
119
+ const rules: string[] = [];
120
+
121
+ for (const pattern of result.patterns) {
122
+ if (pattern.type === "co_change" && pattern.frequency >= 4) {
123
+ rules.push(
124
+ `When modifying ${pattern.files[0]}, also check ${pattern.files[1]} (co-changed ${pattern.frequency} times).`,
125
+ );
126
+ }
127
+ if (pattern.type === "error_repeat" && pattern.frequency >= 3) {
128
+ rules.push(
129
+ `Watch for: ${pattern.description} (occurred ${pattern.frequency} times across ${pattern.sessions.length} sessions).`,
130
+ );
131
+ }
132
+ }
133
+
134
+ ctx.logger.info("Rules generated", { count: rules.length });
135
+ return { rules };
136
+ },
137
+ );
138
+ }
@@ -0,0 +1,39 @@
1
+ import type { ISdk } from "iii-sdk";
2
+
3
+ const PRIVATE_TAG_RE = /<private>[\s\S]*?<\/private>/gi;
4
+
5
+ const SECRET_PATTERN_SOURCES = [
6
+ /(?:api[_-]?key|secret|token|password|credential|auth)[\s]*[=:]\s*["']?[A-Za-z0-9_\-/.+]{20,}["']?/gi,
7
+ /(?:sk|pk|rk|ak)-[A-Za-z0-9]{20,}/g,
8
+ /sk-ant-[A-Za-z0-9\-_]{20,}/g,
9
+ /ghp_[A-Za-z0-9]{36}/g,
10
+ /github_pat_[A-Za-z0-9_]{22,}/g,
11
+ /xoxb-[A-Za-z0-9\-]+/g,
12
+ /AKIA[0-9A-Z]{16}/g,
13
+ /AIza[A-Za-z0-9\-_]{35}/g,
14
+ /eyJ[A-Za-z0-9_-]{10,}\.[A-Za-z0-9_-]{10,}\.[A-Za-z0-9_-]{10,}/g,
15
+ /npm_[A-Za-z0-9]{36}/g,
16
+ /glpat-[A-Za-z0-9\-_]{20,}/g,
17
+ /dop_v1_[A-Za-z0-9]{64}/g,
18
+ ];
19
+
20
+ export function stripPrivateData(input: string): string {
21
+ let result = input.replace(PRIVATE_TAG_RE, "[REDACTED]");
22
+ for (const source of SECRET_PATTERN_SOURCES) {
23
+ const pattern = new RegExp(source.source, source.flags);
24
+ result = result.replace(pattern, "[REDACTED_SECRET]");
25
+ }
26
+ return result;
27
+ }
28
+
29
+ export function registerPrivacyFunction(sdk: ISdk): void {
30
+ sdk.registerFunction(
31
+ {
32
+ id: "mem::privacy",
33
+ description: "Strip private tags and secrets from input",
34
+ },
35
+ async (data: { input: string }) => {
36
+ return { output: stripPrivateData(data.input) };
37
+ },
38
+ );
39
+ }
@@ -0,0 +1,155 @@
1
+ import type { ISdk } from "iii-sdk";
2
+ import { getContext } from "iii-sdk";
3
+ import type {
4
+ CompressedObservation,
5
+ Session,
6
+ ProjectProfile,
7
+ } from "../types.js";
8
+ import { KV } from "../state/schema.js";
9
+ import { StateKV } from "../state/kv.js";
10
+
11
+ export function registerProfileFunction(sdk: ISdk, kv: StateKV): void {
12
+ sdk.registerFunction(
13
+ {
14
+ id: "mem::profile",
15
+ description: "Generate or retrieve a project profile from aggregated data",
16
+ },
17
+ async (data: { project: string; refresh?: boolean }) => {
18
+ const ctx = getContext();
19
+
20
+ if (!data.refresh) {
21
+ const cached = await kv
22
+ .get<ProjectProfile>(KV.profiles, data.project)
23
+ .catch(() => null);
24
+ if (cached) {
25
+ const age = Date.now() - new Date(cached.updatedAt).getTime();
26
+ if (age < 3600_000) {
27
+ return { profile: cached, cached: true };
28
+ }
29
+ }
30
+ }
31
+
32
+ const sessions = await kv.list<Session>(KV.sessions);
33
+ const projectSessions = sessions.filter(
34
+ (s) => s.project === data.project,
35
+ );
36
+
37
+ if (projectSessions.length === 0) {
38
+ return { profile: null, reason: "no_sessions" };
39
+ }
40
+
41
+ const conceptFreq = new Map<string, number>();
42
+ const fileFreq = new Map<string, number>();
43
+ const errors: string[] = [];
44
+ const recentActivity: string[] = [];
45
+ let totalObs = 0;
46
+
47
+ const sortedSessions = projectSessions.sort(
48
+ (a, b) =>
49
+ new Date(b.startedAt).getTime() - new Date(a.startedAt).getTime(),
50
+ );
51
+
52
+ const top20Sessions = sortedSessions.slice(0, 20);
53
+ const obsPerSession = await Promise.all(
54
+ top20Sessions.map((s) =>
55
+ kv
56
+ .list<CompressedObservation>(KV.observations(s.id))
57
+ .catch(() => [] as CompressedObservation[]),
58
+ ),
59
+ );
60
+
61
+ for (let i = 0; i < top20Sessions.length; i++) {
62
+ const session = top20Sessions[i];
63
+ const observations = obsPerSession[i];
64
+ totalObs += observations.length;
65
+
66
+ for (const obs of observations) {
67
+ for (const concept of obs.concepts || []) {
68
+ conceptFreq.set(concept, (conceptFreq.get(concept) || 0) + 1);
69
+ }
70
+ for (const file of obs.files || []) {
71
+ fileFreq.set(file, (fileFreq.get(file) || 0) + 1);
72
+ }
73
+ if (obs.type === "error") {
74
+ errors.push(obs.title);
75
+ }
76
+ }
77
+
78
+ const important = observations
79
+ .filter((o) => o.importance >= 7)
80
+ .sort((a, b) => b.importance - a.importance);
81
+ if (important.length > 0) {
82
+ recentActivity.push(
83
+ `[${session.startedAt.slice(0, 10)}] ${important[0].title}`,
84
+ );
85
+ }
86
+ }
87
+
88
+ const topConcepts = Array.from(conceptFreq.entries())
89
+ .sort((a, b) => b[1] - a[1])
90
+ .slice(0, 15)
91
+ .map(([concept, frequency]) => ({ concept, frequency }));
92
+
93
+ const topFiles = Array.from(fileFreq.entries())
94
+ .sort((a, b) => b[1] - a[1])
95
+ .slice(0, 15)
96
+ .map(([file, frequency]) => ({ file, frequency }));
97
+
98
+ const uniqueErrors = [...new Set(errors)].slice(0, 10);
99
+
100
+ const profile: ProjectProfile = {
101
+ project: data.project,
102
+ updatedAt: new Date().toISOString(),
103
+ topConcepts,
104
+ topFiles,
105
+ conventions: extractConventions(topConcepts, topFiles),
106
+ commonErrors: uniqueErrors,
107
+ recentActivity: recentActivity.slice(0, 10),
108
+ sessionCount: projectSessions.length,
109
+ totalObservations: totalObs,
110
+ };
111
+
112
+ await kv.set(KV.profiles, data.project, profile);
113
+
114
+ ctx.logger.info("Profile generated", {
115
+ project: data.project,
116
+ sessions: projectSessions.length,
117
+ observations: totalObs,
118
+ });
119
+ return { profile, cached: false };
120
+ },
121
+ );
122
+ }
123
+
124
+ function extractConventions(
125
+ concepts: Array<{ concept: string; frequency: number }>,
126
+ files: Array<{ file: string; frequency: number }>,
127
+ ): string[] {
128
+ const conventions: string[] = [];
129
+
130
+ const tsFiles = files.filter((f) => f.file.endsWith(".ts")).length;
131
+ const jsFiles = files.filter((f) => f.file.endsWith(".js")).length;
132
+ if (tsFiles > jsFiles && tsFiles > 0) {
133
+ conventions.push("TypeScript project");
134
+ }
135
+
136
+ const srcFiles = files.filter((f) => f.file.includes("/src/")).length;
137
+ if (srcFiles > files.length * 0.5) {
138
+ conventions.push("Standard src/ directory structure");
139
+ }
140
+
141
+ const testFiles = files.filter(
142
+ (f) => f.file.includes("test") || f.file.includes("spec"),
143
+ ).length;
144
+ if (testFiles > 0) {
145
+ conventions.push("Has test files");
146
+ }
147
+
148
+ for (const { concept, frequency } of concepts.slice(0, 5)) {
149
+ if (frequency >= 3) {
150
+ conventions.push(`Frequently uses: ${concept}`);
151
+ }
152
+ }
153
+
154
+ return conventions;
155
+ }
@@ -0,0 +1,186 @@
1
+ import type { ISdk } from "iii-sdk";
2
+ import { getContext } from "iii-sdk";
3
+ import type { MemoryProvider, QueryExpansion } from "../types.js";
4
+
5
+ const QUERY_EXPANSION_SYSTEM = `You are a query expansion engine for a memory retrieval system. Given a user query, generate diverse reformulations to maximize recall.
6
+
7
+ Output EXACTLY this XML:
8
+ <expansion>
9
+ <reformulations>
10
+ <query>semantically diverse rephrasing 1</query>
11
+ <query>semantically diverse rephrasing 2</query>
12
+ <query>semantically diverse rephrasing 3</query>
13
+ </reformulations>
14
+ <temporal>
15
+ <query>time-concretized version if applicable</query>
16
+ </temporal>
17
+ <entities>
18
+ <entity>extracted entity name 1</entity>
19
+ <entity>extracted entity name 2</entity>
20
+ </entities>
21
+ </expansion>
22
+
23
+ Rules:
24
+ - Generate 3-5 reformulations capturing different interpretations
25
+ - Include paraphrases, domain-specific restatements, and abstract/concrete variants
26
+ - Extract any named entities (people, files, projects, libraries, concepts)
27
+ - If the query mentions time ("last week", "recently"), generate temporal concretizations
28
+ - Each reformulation should capture a distinct facet of intent
29
+ - Keep reformulations concise (under 100 chars each)`;
30
+
31
+ function parseExpansionXml(xml: string): QueryExpansion | null {
32
+ const reformulations: string[] = [];
33
+ const queryRegex =
34
+ /<reformulations>[\s\S]*?<\/reformulations>/;
35
+ const reformBlock = xml.match(queryRegex);
36
+ if (reformBlock) {
37
+ const qRegex = /<query>([^<]+)<\/query>/g;
38
+ let match;
39
+ while ((match = qRegex.exec(reformBlock[0])) !== null) {
40
+ reformulations.push(match[1].trim());
41
+ }
42
+ }
43
+
44
+ const temporalConcretizations: string[] = [];
45
+ const tempBlock = xml.match(/<temporal>[\s\S]*?<\/temporal>/);
46
+ if (tempBlock) {
47
+ const qRegex = /<query>([^<]+)<\/query>/g;
48
+ let match;
49
+ while ((match = qRegex.exec(tempBlock[0])) !== null) {
50
+ temporalConcretizations.push(match[1].trim());
51
+ }
52
+ }
53
+
54
+ const entityExtractions: string[] = [];
55
+ const entityRegex = /<entity>([^<]+)<\/entity>/g;
56
+ let match;
57
+ while ((match = entityRegex.exec(xml)) !== null) {
58
+ entityExtractions.push(match[1].trim());
59
+ }
60
+
61
+ return {
62
+ original: "",
63
+ reformulations,
64
+ temporalConcretizations,
65
+ entityExtractions,
66
+ };
67
+ }
68
+
69
+ export function registerQueryExpansionFunction(
70
+ sdk: ISdk,
71
+ provider: MemoryProvider,
72
+ ): void {
73
+ sdk.registerFunction(
74
+ {
75
+ id: "mem::expand-query",
76
+ description:
77
+ "Generate diverse query reformulations for improved recall",
78
+ },
79
+ async (data: { query: string; maxReformulations?: number }) => {
80
+ const ctx = getContext();
81
+ const maxR = data.maxReformulations ?? 5;
82
+
83
+ try {
84
+ const response = await provider.compress(
85
+ QUERY_EXPANSION_SYSTEM,
86
+ `Expand this query for memory retrieval:\n\n"${data.query}"`,
87
+ );
88
+
89
+ const parsed = parseExpansionXml(response);
90
+ if (!parsed) {
91
+ ctx.logger.warn("Failed to parse query expansion");
92
+ return {
93
+ success: true,
94
+ expansion: {
95
+ original: data.query,
96
+ reformulations: [],
97
+ temporalConcretizations: [],
98
+ entityExtractions: [],
99
+ },
100
+ };
101
+ }
102
+
103
+ parsed.original = data.query;
104
+ parsed.reformulations = parsed.reformulations.slice(0, maxR);
105
+
106
+ ctx.logger.info("Query expanded", {
107
+ original: data.query,
108
+ reformulations: parsed.reformulations.length,
109
+ entities: parsed.entityExtractions.length,
110
+ });
111
+
112
+ return { success: true, expansion: parsed };
113
+ } catch (err) {
114
+ const msg = err instanceof Error ? err.message : String(err);
115
+ ctx.logger.error("Query expansion failed", { error: msg });
116
+ return {
117
+ success: true,
118
+ expansion: {
119
+ original: data.query,
120
+ reformulations: [],
121
+ temporalConcretizations: [],
122
+ entityExtractions: [],
123
+ },
124
+ };
125
+ }
126
+ },
127
+ );
128
+ }
129
+
130
+ export function extractEntitiesFromQuery(query: string): string[] {
131
+ const entities: string[] = [];
132
+ const quoted = query.match(/"([^"]+)"/g);
133
+ if (quoted) {
134
+ for (const q of quoted) {
135
+ entities.push(q.replace(/"/g, ""));
136
+ }
137
+ }
138
+ const capitalized = query.match(/\b[A-Z][a-zA-Z0-9_.-]+\b/g);
139
+ if (capitalized) {
140
+ const stopWords = new Set([
141
+ "The",
142
+ "This",
143
+ "That",
144
+ "What",
145
+ "When",
146
+ "Where",
147
+ "How",
148
+ "Why",
149
+ "Who",
150
+ "Which",
151
+ "Did",
152
+ "Does",
153
+ "Do",
154
+ "Is",
155
+ "Are",
156
+ "Was",
157
+ "Were",
158
+ "Has",
159
+ "Have",
160
+ "Had",
161
+ "Can",
162
+ "Could",
163
+ "Would",
164
+ "Should",
165
+ "Will",
166
+ "May",
167
+ "Might",
168
+ "If",
169
+ "And",
170
+ "But",
171
+ "Or",
172
+ "Not",
173
+ "For",
174
+ "From",
175
+ "With",
176
+ "About",
177
+ "After",
178
+ "Before",
179
+ "Between",
180
+ ]);
181
+ for (const c of capitalized) {
182
+ if (!stopWords.has(c)) entities.push(c);
183
+ }
184
+ }
185
+ return [...new Set(entities)];
186
+ }