@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,138 +0,0 @@
1
- import type { ISdk } from "iii-sdk";
2
- import { getContext } from "iii-sdk";
3
- import type { CompressedObservation, Session } from "../types.js";
4
- import { KV } from "../state/schema.js";
5
- import { StateKV } from "../state/kv.js";
6
-
7
- interface 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
- }
@@ -1,39 +0,0 @@
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
- }
@@ -1,155 +0,0 @@
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
- }
@@ -1,186 +0,0 @@
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
- }