@agentmemory/agentmemory 0.7.0 → 0.7.3

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (218) hide show
  1. package/AGENTS.md +2 -2
  2. package/README.md +76 -82
  3. package/dist/cli.mjs +99 -32
  4. package/dist/cli.mjs.map +1 -1
  5. package/dist/index.mjs +4 -2
  6. package/dist/index.mjs.map +1 -1
  7. package/dist/{src-QxitMPfJ.mjs → src-sYZDDbiA.mjs} +5 -3
  8. package/dist/src-sYZDDbiA.mjs.map +1 -0
  9. package/dist/standalone.mjs +1 -1
  10. package/dist/standalone.mjs.map +1 -1
  11. package/package.json +11 -1
  12. package/plugin/.claude-plugin/plugin.json +1 -1
  13. package/plugin/scripts/notification.d.mts +1 -0
  14. package/plugin/scripts/notification.mjs.map +1 -0
  15. package/plugin/scripts/post-tool-failure.d.mts +1 -0
  16. package/plugin/scripts/post-tool-failure.mjs.map +1 -0
  17. package/plugin/scripts/post-tool-use.d.mts +1 -0
  18. package/plugin/scripts/post-tool-use.mjs.map +1 -0
  19. package/plugin/scripts/pre-compact.d.mts +1 -0
  20. package/plugin/scripts/pre-compact.mjs.map +1 -0
  21. package/plugin/scripts/pre-tool-use.d.mts +1 -0
  22. package/plugin/scripts/pre-tool-use.mjs.map +1 -0
  23. package/plugin/scripts/prompt-submit.d.mts +1 -0
  24. package/plugin/scripts/prompt-submit.mjs.map +1 -0
  25. package/plugin/scripts/session-end.d.mts +1 -0
  26. package/plugin/scripts/session-end.mjs.map +1 -0
  27. package/plugin/scripts/session-start.d.mts +1 -0
  28. package/plugin/scripts/session-start.mjs.map +1 -0
  29. package/plugin/scripts/stop.d.mts +1 -0
  30. package/plugin/scripts/stop.mjs.map +1 -0
  31. package/plugin/scripts/subagent-start.d.mts +1 -0
  32. package/plugin/scripts/subagent-start.mjs.map +1 -0
  33. package/plugin/scripts/subagent-stop.d.mts +1 -0
  34. package/plugin/scripts/subagent-stop.mjs.map +1 -0
  35. package/plugin/scripts/task-completed.d.mts +1 -0
  36. package/plugin/scripts/task-completed.mjs.map +1 -0
  37. package/.claude-plugin/marketplace.json +0 -14
  38. package/.github/workflows/ci.yml +0 -22
  39. package/.github/workflows/publish.yml +0 -28
  40. package/assets/banner.png +0 -0
  41. package/assets/demo.gif +0 -0
  42. package/assets/demo.mp4 +0 -0
  43. package/benchmark/QUALITY.md +0 -73
  44. package/benchmark/REAL-EMBEDDINGS.md +0 -67
  45. package/benchmark/SCALE.md +0 -110
  46. package/benchmark/dataset.ts +0 -293
  47. package/benchmark/quality-eval.ts +0 -643
  48. package/benchmark/real-embeddings-eval.ts +0 -405
  49. package/benchmark/scale-eval.ts +0 -398
  50. package/dist/src-QxitMPfJ.mjs.map +0 -1
  51. package/src/auth.ts +0 -12
  52. package/src/cli.ts +0 -159
  53. package/src/config.ts +0 -221
  54. package/src/eval/metrics-store.ts +0 -65
  55. package/src/eval/quality.ts +0 -51
  56. package/src/eval/schemas.ts +0 -124
  57. package/src/eval/self-correct.ts +0 -28
  58. package/src/eval/validator.ts +0 -31
  59. package/src/functions/actions.ts +0 -288
  60. package/src/functions/audit.ts +0 -61
  61. package/src/functions/auto-forget.ts +0 -169
  62. package/src/functions/branch-aware.ts +0 -169
  63. package/src/functions/cascade.ts +0 -80
  64. package/src/functions/checkpoints.ts +0 -209
  65. package/src/functions/claude-bridge.ts +0 -161
  66. package/src/functions/compress.ts +0 -194
  67. package/src/functions/consolidate.ts +0 -212
  68. package/src/functions/consolidation-pipeline.ts +0 -258
  69. package/src/functions/context.ts +0 -169
  70. package/src/functions/crystallize.ts +0 -293
  71. package/src/functions/dedup.ts +0 -57
  72. package/src/functions/diagnostics.ts +0 -785
  73. package/src/functions/enrich.ts +0 -132
  74. package/src/functions/evict.ts +0 -163
  75. package/src/functions/export-import.ts +0 -508
  76. package/src/functions/facets.ts +0 -248
  77. package/src/functions/file-index.ts +0 -106
  78. package/src/functions/flow-compress.ts +0 -214
  79. package/src/functions/frontier.ts +0 -196
  80. package/src/functions/governance.ts +0 -131
  81. package/src/functions/graph-retrieval.ts +0 -277
  82. package/src/functions/graph.ts +0 -275
  83. package/src/functions/leases.ts +0 -216
  84. package/src/functions/lessons.ts +0 -253
  85. package/src/functions/mesh.ts +0 -434
  86. package/src/functions/migrate.ts +0 -165
  87. package/src/functions/observe.ts +0 -144
  88. package/src/functions/obsidian-export.ts +0 -310
  89. package/src/functions/patterns.ts +0 -138
  90. package/src/functions/privacy.ts +0 -39
  91. package/src/functions/profile.ts +0 -155
  92. package/src/functions/query-expansion.ts +0 -186
  93. package/src/functions/relations.ts +0 -237
  94. package/src/functions/remember.ts +0 -162
  95. package/src/functions/retention.ts +0 -235
  96. package/src/functions/routines.ts +0 -289
  97. package/src/functions/search.ts +0 -80
  98. package/src/functions/sentinels.ts +0 -417
  99. package/src/functions/signals.ts +0 -186
  100. package/src/functions/sketches.ts +0 -274
  101. package/src/functions/sliding-window.ts +0 -257
  102. package/src/functions/smart-search.ts +0 -115
  103. package/src/functions/snapshot.ts +0 -219
  104. package/src/functions/summarize.ts +0 -155
  105. package/src/functions/team.ts +0 -147
  106. package/src/functions/temporal-graph.ts +0 -476
  107. package/src/functions/timeline.ts +0 -138
  108. package/src/functions/verify.ts +0 -117
  109. package/src/health/monitor.ts +0 -110
  110. package/src/health/thresholds.ts +0 -73
  111. package/src/hooks/notification.ts +0 -52
  112. package/src/hooks/post-tool-failure.ts +0 -58
  113. package/src/hooks/post-tool-use.ts +0 -62
  114. package/src/hooks/pre-compact.ts +0 -60
  115. package/src/hooks/pre-tool-use.ts +0 -72
  116. package/src/hooks/prompt-submit.ts +0 -46
  117. package/src/hooks/session-end.ts +0 -71
  118. package/src/hooks/session-start.ts +0 -48
  119. package/src/hooks/stop.ts +0 -39
  120. package/src/hooks/subagent-start.ts +0 -49
  121. package/src/hooks/subagent-stop.ts +0 -54
  122. package/src/hooks/task-completed.ts +0 -54
  123. package/src/index.ts +0 -342
  124. package/src/mcp/in-memory-kv.ts +0 -61
  125. package/src/mcp/server.ts +0 -1455
  126. package/src/mcp/standalone.ts +0 -177
  127. package/src/mcp/tools-registry.ts +0 -769
  128. package/src/mcp/transport.ts +0 -91
  129. package/src/prompts/compression.ts +0 -67
  130. package/src/prompts/consolidation.ts +0 -48
  131. package/src/prompts/graph-extraction.ts +0 -35
  132. package/src/prompts/summary.ts +0 -38
  133. package/src/prompts/xml.ts +0 -26
  134. package/src/providers/agent-sdk.ts +0 -34
  135. package/src/providers/anthropic.ts +0 -35
  136. package/src/providers/circuit-breaker.ts +0 -82
  137. package/src/providers/embedding/cohere.ts +0 -46
  138. package/src/providers/embedding/gemini.ts +0 -54
  139. package/src/providers/embedding/index.ts +0 -39
  140. package/src/providers/embedding/local.ts +0 -52
  141. package/src/providers/embedding/openai.ts +0 -45
  142. package/src/providers/embedding/openrouter.ts +0 -51
  143. package/src/providers/embedding/voyage.ts +0 -46
  144. package/src/providers/fallback-chain.ts +0 -31
  145. package/src/providers/index.ts +0 -84
  146. package/src/providers/openrouter.ts +0 -71
  147. package/src/providers/resilient.ts +0 -37
  148. package/src/state/hybrid-search.ts +0 -295
  149. package/src/state/index-persistence.ts +0 -63
  150. package/src/state/keyed-mutex.ts +0 -18
  151. package/src/state/kv.ts +0 -33
  152. package/src/state/schema.ts +0 -71
  153. package/src/state/search-index.ts +0 -245
  154. package/src/state/stemmer.ts +0 -104
  155. package/src/state/synonyms.ts +0 -63
  156. package/src/state/vector-index.ts +0 -130
  157. package/src/telemetry/setup.ts +0 -116
  158. package/src/triggers/api.ts +0 -1904
  159. package/src/triggers/events.ts +0 -71
  160. package/src/types.ts +0 -769
  161. package/src/version.ts +0 -1
  162. package/src/viewer/index.html +0 -2497
  163. package/src/viewer/server.ts +0 -207
  164. package/src/xenova.d.ts +0 -3
  165. package/test/actions.test.ts +0 -490
  166. package/test/audit.test.ts +0 -108
  167. package/test/auto-forget.test.ts +0 -188
  168. package/test/cascade.test.ts +0 -277
  169. package/test/checkpoints.test.ts +0 -493
  170. package/test/circuit-breaker.test.ts +0 -107
  171. package/test/claude-bridge.test.ts +0 -178
  172. package/test/confidence.test.ts +0 -247
  173. package/test/consistency.test.ts +0 -61
  174. package/test/consolidation-pipeline.test.ts +0 -251
  175. package/test/crystallize.test.ts +0 -521
  176. package/test/diagnostics.test.ts +0 -638
  177. package/test/embedding-provider.test.ts +0 -49
  178. package/test/enrich.test.ts +0 -209
  179. package/test/eval.test.ts +0 -300
  180. package/test/export-import.test.ts +0 -251
  181. package/test/facets.test.ts +0 -448
  182. package/test/fallback-chain.test.ts +0 -93
  183. package/test/frontier.test.ts +0 -485
  184. package/test/governance.test.ts +0 -147
  185. package/test/graph-retrieval.test.ts +0 -186
  186. package/test/graph.test.ts +0 -160
  187. package/test/helpers/mocks.ts +0 -40
  188. package/test/hybrid-search.test.ts +0 -145
  189. package/test/index-persistence.test.ts +0 -124
  190. package/test/integration.test.ts +0 -265
  191. package/test/leases.test.ts +0 -399
  192. package/test/mcp-prompts.test.ts +0 -218
  193. package/test/mcp-resources.test.ts +0 -286
  194. package/test/mcp-standalone.test.ts +0 -113
  195. package/test/mesh.test.ts +0 -700
  196. package/test/privacy.test.ts +0 -87
  197. package/test/profile.test.ts +0 -161
  198. package/test/query-expansion.test.ts +0 -154
  199. package/test/relations.test.ts +0 -198
  200. package/test/retention.test.ts +0 -245
  201. package/test/routines.test.ts +0 -497
  202. package/test/schema-fingerprint.test.ts +0 -81
  203. package/test/schema.test.ts +0 -42
  204. package/test/search-index.test.ts +0 -128
  205. package/test/sentinels.test.ts +0 -626
  206. package/test/signals.test.ts +0 -410
  207. package/test/sketches.test.ts +0 -549
  208. package/test/sliding-window.test.ts +0 -199
  209. package/test/smart-search.test.ts +0 -169
  210. package/test/snapshot.test.ts +0 -165
  211. package/test/team.test.ts +0 -156
  212. package/test/temporal-graph.test.ts +0 -378
  213. package/test/timeline.test.ts +0 -148
  214. package/test/vector-index.test.ts +0 -79
  215. package/test/verify.test.ts +0 -209
  216. package/test/xml.test.ts +0 -65
  217. package/tsconfig.json +0 -22
  218. package/tsdown.config.ts +0 -62
package/src/auth.ts DELETED
@@ -1,12 +0,0 @@
1
- import { timingSafeEqual, createHmac, randomBytes } from "node:crypto";
2
-
3
- const hmacKey = randomBytes(32);
4
-
5
- export function timingSafeCompare(a: string, b: string): boolean {
6
- const hmacA = createHmac("sha256", hmacKey).update(a).digest();
7
- const hmacB = createHmac("sha256", hmacKey).update(b).digest();
8
- return timingSafeEqual(hmacA, hmacB);
9
- }
10
-
11
- export const VIEWER_CSP =
12
- "default-src 'none'; script-src 'unsafe-inline'; style-src 'unsafe-inline'; connect-src 'self' ws://localhost:* wss://localhost:*; img-src 'self'; font-src 'self'";
package/src/cli.ts DELETED
@@ -1,159 +0,0 @@
1
- #!/usr/bin/env node
2
-
3
- import { spawn, execFileSync } from "node:child_process";
4
- import { existsSync } from "node:fs";
5
- import { join, dirname } from "node:path";
6
- import { fileURLToPath } from "node:url";
7
-
8
- const __dirname = dirname(fileURLToPath(import.meta.url));
9
-
10
- const args = process.argv.slice(2);
11
-
12
- if (args.includes("--help") || args.includes("-h")) {
13
- console.log(`
14
- agentmemory — persistent memory for AI coding agents
15
-
16
- Usage: agentmemory [options]
17
-
18
- Options:
19
- --help, -h Show this help
20
- --tools all|core Tool visibility (default: core = 7 tools)
21
- --no-engine Skip auto-starting iii-engine
22
- --port <N> Override REST port (default: 3111)
23
-
24
- Environment:
25
- AGENTMEMORY_TOOLS=all Expose all 41 MCP tools
26
- AGENTMEMORY_SECRET=xxx Auth secret for REST/MCP
27
- CONSOLIDATION_ENABLED=true Enable auto-consolidation (off by default)
28
- OBSIDIAN_AUTO_EXPORT=true Auto-export on consolidation
29
-
30
- Quick start:
31
- npx agentmemory # auto-starts iii-engine, runs worker
32
- npx agentmemory-mcp # standalone MCP server (no engine needed)
33
- `);
34
- process.exit(0);
35
- }
36
-
37
- const toolsIdx = args.indexOf("--tools");
38
- if (toolsIdx !== -1 && args[toolsIdx + 1]) {
39
- process.env["AGENTMEMORY_TOOLS"] = args[toolsIdx + 1];
40
- }
41
-
42
- const portIdx = args.indexOf("--port");
43
- if (portIdx !== -1 && args[portIdx + 1]) {
44
- process.env["III_REST_PORT"] = args[portIdx + 1];
45
- }
46
-
47
- const skipEngine = args.includes("--no-engine");
48
-
49
- function getRestPort(): number {
50
- return parseInt(process.env["III_REST_PORT"] || "3111", 10) || 3111;
51
- }
52
-
53
- async function isEngineRunning(): Promise<boolean> {
54
- try {
55
- const res = await fetch(`http://localhost:${getRestPort()}/agentmemory/livez`, {
56
- signal: AbortSignal.timeout(2000),
57
- });
58
- return res.ok;
59
- } catch {
60
- return false;
61
- }
62
- }
63
-
64
- function findIiiConfig(): string {
65
- const candidates = [
66
- join(__dirname, "iii-config.yaml"),
67
- join(__dirname, "..", "iii-config.yaml"),
68
- join(process.cwd(), "iii-config.yaml"),
69
- ];
70
- for (const c of candidates) {
71
- if (existsSync(c)) return c;
72
- }
73
- return "";
74
- }
75
-
76
- function whichBinary(name: string): string | null {
77
- const cmd = process.platform === "win32" ? "where" : "which";
78
- try {
79
- return execFileSync(cmd, [name], { encoding: "utf-8" }).trim().split("\n")[0];
80
- } catch {
81
- return null;
82
- }
83
- }
84
-
85
- async function startEngine(): Promise<boolean> {
86
- const configPath = findIiiConfig();
87
-
88
- const iiiBin = whichBinary("iii");
89
- if (iiiBin && configPath) {
90
- console.log(`[agentmemory] Starting iii-engine: ${iiiBin} --config ${configPath}`);
91
- const child = spawn(iiiBin, ["--config", configPath], {
92
- detached: true,
93
- stdio: "ignore",
94
- });
95
- child.unref();
96
- return true;
97
- }
98
-
99
- const dockerCompose = join(__dirname, "..", "docker-compose.yml");
100
- const dcExists = existsSync(dockerCompose) || existsSync(join(process.cwd(), "docker-compose.yml"));
101
- const dockerBin = whichBinary("docker");
102
-
103
- if (dockerBin && dcExists) {
104
- const composeFile = existsSync(dockerCompose) ? dockerCompose : join(process.cwd(), "docker-compose.yml");
105
- console.log(`[agentmemory] Starting iii-engine via Docker...`);
106
- const child = spawn(dockerBin, ["compose", "-f", composeFile, "up", "-d"], {
107
- detached: true,
108
- stdio: "ignore",
109
- });
110
- child.unref();
111
- return true;
112
- }
113
-
114
- return false;
115
- }
116
-
117
- async function waitForEngine(timeoutMs: number): Promise<boolean> {
118
- const start = Date.now();
119
- while (Date.now() - start < timeoutMs) {
120
- if (await isEngineRunning()) return true;
121
- await new Promise((r) => setTimeout(r, 500));
122
- }
123
- return false;
124
- }
125
-
126
- async function main() {
127
- if (!skipEngine && !(await isEngineRunning())) {
128
- const started = await startEngine();
129
- if (!started) {
130
- console.error(`
131
- [agentmemory] iii-engine is not running and could not be auto-started.
132
-
133
- Install one of:
134
- 1. iii CLI: npm install -g iii-engine
135
- 2. Docker: docker compose up -d (with docker-compose.yml)
136
-
137
- Or run with --no-engine to connect to a remote engine.
138
- `);
139
- process.exit(1);
140
- }
141
-
142
- console.log(`[agentmemory] Waiting for iii-engine to start...`);
143
- const ready = await waitForEngine(15000);
144
- if (!ready) {
145
- const port = getRestPort();
146
- console.error(`[agentmemory] iii-engine did not become ready within 15s.`);
147
- console.error(`[agentmemory] Check that ports ${port}, ${port + 1}, 49134 are available.`);
148
- process.exit(1);
149
- }
150
- console.log(`[agentmemory] iii-engine is ready.`);
151
- }
152
-
153
- await import("./index.js");
154
- }
155
-
156
- main().catch((err) => {
157
- console.error(`[agentmemory] Fatal:`, err);
158
- process.exit(1);
159
- });
package/src/config.ts DELETED
@@ -1,221 +0,0 @@
1
- import { existsSync, readFileSync } from "node:fs";
2
- import { join } from "node:path";
3
- import { homedir } from "node:os";
4
- import type {
5
- AgentMemoryConfig,
6
- ProviderConfig,
7
- EmbeddingConfig,
8
- FallbackConfig,
9
- ClaudeBridgeConfig,
10
- TeamConfig,
11
- } from "./types.js";
12
-
13
- function safeParseInt(value: string | undefined, fallback: number): number {
14
- if (!value) return fallback;
15
- const parsed = parseInt(value, 10);
16
- return Number.isNaN(parsed) ? fallback : parsed;
17
- }
18
-
19
- const DATA_DIR = join(homedir(), ".agentmemory");
20
- const ENV_FILE = join(DATA_DIR, ".env");
21
-
22
- function loadEnvFile(): Record<string, string> {
23
- if (!existsSync(ENV_FILE)) return {};
24
- const content = readFileSync(ENV_FILE, "utf-8");
25
- const vars: Record<string, string> = {};
26
- for (const line of content.split("\n")) {
27
- const trimmed = line.trim();
28
- if (!trimmed || trimmed.startsWith("#")) continue;
29
- const eqIdx = trimmed.indexOf("=");
30
- if (eqIdx === -1) continue;
31
- const key = trimmed.slice(0, eqIdx).trim();
32
- let val = trimmed.slice(eqIdx + 1).trim();
33
- if (
34
- (val.startsWith('"') && val.endsWith('"')) ||
35
- (val.startsWith("'") && val.endsWith("'"))
36
- ) {
37
- val = val.slice(1, -1);
38
- }
39
- vars[key] = val;
40
- }
41
- return vars;
42
- }
43
-
44
- function detectProvider(env: Record<string, string>): ProviderConfig {
45
- const maxTokens = parseInt(env["MAX_TOKENS"] || "4096", 10);
46
-
47
- if (env["ANTHROPIC_API_KEY"]) {
48
- return {
49
- provider: "anthropic",
50
- model: env["ANTHROPIC_MODEL"] || "claude-sonnet-4-20250514",
51
- maxTokens,
52
- };
53
- }
54
- if (env["GEMINI_API_KEY"]) {
55
- return {
56
- provider: "gemini",
57
- model: env["GEMINI_MODEL"] || "gemini-2.0-flash",
58
- maxTokens,
59
- };
60
- }
61
- if (env["OPENROUTER_API_KEY"]) {
62
- return {
63
- provider: "openrouter",
64
- model: env["OPENROUTER_MODEL"] || "anthropic/claude-sonnet-4-20250514",
65
- maxTokens,
66
- };
67
- }
68
- return {
69
- provider: "agent-sdk",
70
- model: "claude-sonnet-4-20250514",
71
- maxTokens: 4096,
72
- };
73
- }
74
-
75
- export function loadConfig(): AgentMemoryConfig {
76
- const env = getMergedEnv();
77
-
78
- const provider = detectProvider(env);
79
-
80
- return {
81
- engineUrl: env["III_ENGINE_URL"] || "ws://localhost:49134",
82
- restPort: parseInt(env["III_REST_PORT"] || "3111", 10) || 3111,
83
- streamsPort: parseInt(env["III_STREAMS_PORT"] || "3112", 10) || 3112,
84
- provider,
85
- tokenBudget: safeParseInt(env["TOKEN_BUDGET"], 2000),
86
- maxObservationsPerSession: safeParseInt(env["MAX_OBS_PER_SESSION"], 500),
87
- compressionModel: provider.model,
88
- dataDir: DATA_DIR,
89
- };
90
- }
91
-
92
- function getMergedEnv(
93
- overrides?: Record<string, string>,
94
- ): Record<string, string> {
95
- const fileEnv = loadEnvFile();
96
- return { ...fileEnv, ...process.env, ...overrides } as Record<string, string>;
97
- }
98
-
99
- export function getEnvVar(key: string): string | undefined {
100
- return getMergedEnv()[key];
101
- }
102
-
103
- export function loadEmbeddingConfig(): EmbeddingConfig {
104
- const env = getMergedEnv();
105
- let bm25Weight = parseFloat(env["BM25_WEIGHT"] || "0.4");
106
- let vectorWeight = parseFloat(env["VECTOR_WEIGHT"] || "0.6");
107
- bm25Weight =
108
- isNaN(bm25Weight) || bm25Weight < 0 ? 0.4 : Math.min(bm25Weight, 1);
109
- vectorWeight =
110
- isNaN(vectorWeight) || vectorWeight < 0 ? 0.6 : Math.min(vectorWeight, 1);
111
- return {
112
- provider: env["EMBEDDING_PROVIDER"] || undefined,
113
- bm25Weight,
114
- vectorWeight,
115
- };
116
- }
117
-
118
- export function detectEmbeddingProvider(
119
- env?: Record<string, string>,
120
- ): string | null {
121
- const source = env ?? getMergedEnv();
122
- const forced = source["EMBEDDING_PROVIDER"];
123
- if (forced) return forced;
124
-
125
- if (source["GEMINI_API_KEY"]) return "gemini";
126
- if (source["OPENAI_API_KEY"]) return "openai";
127
- if (source["VOYAGE_API_KEY"]) return "voyage";
128
- if (source["COHERE_API_KEY"]) return "cohere";
129
- if (source["OPENROUTER_API_KEY"]) return "openrouter";
130
- return null;
131
- }
132
-
133
- export function loadClaudeBridgeConfig(): ClaudeBridgeConfig {
134
- const env = getMergedEnv();
135
- const enabled = env["CLAUDE_MEMORY_BRIDGE"] === "true";
136
- const projectPath = env["CLAUDE_PROJECT_PATH"] || "";
137
- const lineBudget = safeParseInt(env["CLAUDE_MEMORY_LINE_BUDGET"], 200);
138
- let memoryFilePath = "";
139
- if (enabled && projectPath) {
140
- const safePath = projectPath.replace(/[/\\]/g, "-").replace(/^-/, "");
141
- memoryFilePath = join(
142
- homedir(),
143
- ".claude",
144
- "projects",
145
- safePath,
146
- "memory",
147
- "MEMORY.md",
148
- );
149
- }
150
- return { enabled, projectPath, memoryFilePath, lineBudget };
151
- }
152
-
153
- export function loadTeamConfig(): TeamConfig | null {
154
- const env = getMergedEnv();
155
- const teamId = env["TEAM_ID"];
156
- const userId = env["USER_ID"];
157
- if (!teamId || !userId) return null;
158
- const mode = env["TEAM_MODE"] === "shared" ? "shared" : "private";
159
- return { teamId, userId, mode };
160
- }
161
-
162
- export function loadSnapshotConfig(): {
163
- enabled: boolean;
164
- interval: number;
165
- dir: string;
166
- } {
167
- const env = getMergedEnv();
168
- return {
169
- enabled: env["SNAPSHOT_ENABLED"] === "true",
170
- interval: safeParseInt(env["SNAPSHOT_INTERVAL"], 3600),
171
- dir: env["SNAPSHOT_DIR"] || join(homedir(), ".agentmemory", "snapshots"),
172
- };
173
- }
174
-
175
- export function isGraphExtractionEnabled(): boolean {
176
- return getMergedEnv()["GRAPH_EXTRACTION_ENABLED"] === "true";
177
- }
178
-
179
- export function getGraphBatchSize(): number {
180
- return safeParseInt(getMergedEnv()["GRAPH_EXTRACTION_BATCH_SIZE"], 10);
181
- }
182
-
183
- export function isConsolidationEnabled(): boolean {
184
- return getMergedEnv()["CONSOLIDATION_ENABLED"] === "true";
185
- }
186
-
187
- export function getConsolidationDecayDays(): number {
188
- return safeParseInt(getMergedEnv()["CONSOLIDATION_DECAY_DAYS"], 30);
189
- }
190
-
191
- export function isStandaloneMcp(): boolean {
192
- return getMergedEnv()["STANDALONE_MCP"] === "true";
193
- }
194
-
195
- export function getStandalonePersistPath(): string {
196
- const env = getMergedEnv();
197
- return (
198
- env["STANDALONE_PERSIST_PATH"] ||
199
- join(homedir(), ".agentmemory", "standalone.json")
200
- );
201
- }
202
-
203
- const VALID_PROVIDERS = new Set([
204
- "anthropic",
205
- "gemini",
206
- "openrouter",
207
- "agent-sdk",
208
- ]);
209
-
210
- export function loadFallbackConfig(): FallbackConfig {
211
- const env = getMergedEnv();
212
- const raw = env["FALLBACK_PROVIDERS"] || "";
213
- const providers = raw
214
- .split(",")
215
- .map((p) => p.trim())
216
- .filter(
217
- (p): p is FallbackConfig["providers"][number] =>
218
- Boolean(p) && VALID_PROVIDERS.has(p),
219
- );
220
- return { providers };
221
- }
@@ -1,65 +0,0 @@
1
- import type { FunctionMetrics } from "../types.js";
2
- import type { StateKV } from "../state/kv.js";
3
- import { KV } from "../state/schema.js";
4
-
5
- export class MetricsStore {
6
- private cache = new Map<string, FunctionMetrics>();
7
- private qualityCallCounts = new Map<string, number>();
8
-
9
- constructor(private kv: StateKV) {}
10
-
11
- async record(
12
- functionId: string,
13
- latencyMs: number,
14
- success: boolean,
15
- qualityScore?: number,
16
- ): Promise<void> {
17
- let m = this.cache.get(functionId);
18
- if (!m) {
19
- m = (await this.kv.get<FunctionMetrics>(KV.metrics, functionId)) ?? {
20
- functionId,
21
- totalCalls: 0,
22
- successCount: 0,
23
- failureCount: 0,
24
- avgLatencyMs: 0,
25
- avgQualityScore: 0,
26
- };
27
- }
28
-
29
- const prev = m.totalCalls;
30
- m.totalCalls += 1;
31
- m.avgLatencyMs = (m.avgLatencyMs * prev + latencyMs) / m.totalCalls;
32
- if (success) {
33
- m.successCount += 1;
34
- } else {
35
- m.failureCount += 1;
36
- }
37
- if (qualityScore !== undefined) {
38
- const prevQualityCalls = this.qualityCallCounts.get(functionId) || 0;
39
- m.avgQualityScore =
40
- (m.avgQualityScore * prevQualityCalls + qualityScore) /
41
- (prevQualityCalls + 1);
42
- this.qualityCallCounts.set(functionId, prevQualityCalls + 1);
43
- }
44
-
45
- this.cache.set(functionId, m);
46
- await this.kv.set(KV.metrics, functionId, m).catch(() => {});
47
- }
48
-
49
- async get(functionId: string): Promise<FunctionMetrics | null> {
50
- return (
51
- this.cache.get(functionId) ??
52
- (await this.kv.get<FunctionMetrics>(KV.metrics, functionId))
53
- );
54
- }
55
-
56
- async getAll(): Promise<FunctionMetrics[]> {
57
- const kvMetrics = await this.kv
58
- .list<FunctionMetrics>(KV.metrics)
59
- .catch(() => []);
60
- const merged = new Map<string, FunctionMetrics>();
61
- for (const m of kvMetrics) merged.set(m.functionId, m);
62
- for (const [id, m] of this.cache) merged.set(id, m);
63
- return Array.from(merged.values());
64
- }
65
- }
@@ -1,51 +0,0 @@
1
- export function scoreCompression(obs: {
2
- type?: string;
3
- title?: string;
4
- facts?: string[];
5
- narrative?: string;
6
- concepts?: string[];
7
- importance?: number;
8
- }): number {
9
- let score = 0;
10
- if (obs.facts && obs.facts.length > 0) score += 25;
11
- if (obs.facts && obs.facts.length >= 3) score += 10;
12
- if (obs.narrative && obs.narrative.length >= 20) score += 20;
13
- if (obs.narrative && obs.narrative.length >= 50) score += 5;
14
- if (obs.title && obs.title.length >= 5 && obs.title.length <= 120) score += 15;
15
- if (obs.concepts && obs.concepts.length > 0) score += 15;
16
- if (obs.importance && obs.importance >= 1 && obs.importance <= 10) score += 10;
17
- return Math.min(100, score);
18
- }
19
-
20
- export function scoreSummary(summary: {
21
- title?: string;
22
- narrative?: string;
23
- keyDecisions?: string[];
24
- filesModified?: string[];
25
- concepts?: string[];
26
- }): number {
27
- let score = 0;
28
- if (summary.title && summary.title.length >= 5) score += 20;
29
- if (summary.narrative && summary.narrative.length >= 20) score += 25;
30
- if (summary.narrative && summary.narrative.length >= 100) score += 5;
31
- if (summary.keyDecisions && summary.keyDecisions.length > 0) score += 20;
32
- if (summary.filesModified && summary.filesModified.length > 0) score += 15;
33
- if (summary.concepts && summary.concepts.length > 0) score += 15;
34
- return Math.min(100, score);
35
- }
36
-
37
- export function scoreContextRelevance(
38
- context: string,
39
- project: string,
40
- ): number {
41
- let score = 0;
42
- if (context.length > 0) score += 20;
43
- if (project && context.toLowerCase().includes(project.toLowerCase())) score += 20;
44
- if (context.includes("<")) score += 15;
45
- const sectionCount = (context.match(/<\w+>/g) || []).length;
46
- if (sectionCount >= 2) score += 15;
47
- if (sectionCount >= 4) score += 10;
48
- if (context.length >= 100) score += 10;
49
- if (context.length >= 500) score += 10;
50
- return Math.min(100, score);
51
- }
@@ -1,124 +0,0 @@
1
- import { z } from "zod";
2
-
3
- const HookTypeEnum = z.enum([
4
- "session_start",
5
- "prompt_submit",
6
- "pre_tool_use",
7
- "post_tool_use",
8
- "post_tool_failure",
9
- "pre_compact",
10
- "subagent_start",
11
- "subagent_stop",
12
- "notification",
13
- "task_completed",
14
- "stop",
15
- "session_end",
16
- ]);
17
-
18
- const ObservationTypeEnum = z.enum([
19
- "file_read",
20
- "file_write",
21
- "file_edit",
22
- "command_run",
23
- "search",
24
- "web_fetch",
25
- "conversation",
26
- "error",
27
- "decision",
28
- "discovery",
29
- "subagent",
30
- "notification",
31
- "task",
32
- "other",
33
- ]);
34
-
35
- export const ObserveInputSchema = z.object({
36
- hookType: HookTypeEnum,
37
- sessionId: z.string().min(1),
38
- project: z.string().min(1),
39
- cwd: z.string().min(1),
40
- timestamp: z.string().min(1),
41
- data: z.unknown(),
42
- });
43
-
44
- export const CompressOutputSchema = z.object({
45
- type: ObservationTypeEnum,
46
- title: z.string().min(1).max(120),
47
- subtitle: z.string().optional(),
48
- facts: z.array(z.string()).min(1),
49
- narrative: z.string().min(10),
50
- concepts: z.array(z.string()),
51
- files: z.array(z.string()),
52
- importance: z.number().int().min(1).max(10),
53
- });
54
-
55
- export const SummaryOutputSchema = z.object({
56
- title: z.string().min(1),
57
- narrative: z.string().min(20),
58
- keyDecisions: z.array(z.string()),
59
- filesModified: z.array(z.string()),
60
- concepts: z.array(z.string()),
61
- });
62
-
63
- export const SearchInputSchema = z.object({
64
- query: z.string().min(1),
65
- limit: z.number().int().positive().optional(),
66
- });
67
-
68
- export const ContextInputSchema = z.object({
69
- sessionId: z.string().min(1),
70
- project: z.string().min(1),
71
- budget: z.number().positive().optional(),
72
- });
73
-
74
- export const RememberInputSchema = z.object({
75
- content: z.string().min(1),
76
- type: z
77
- .enum(["pattern", "preference", "architecture", "bug", "workflow", "fact"])
78
- .optional(),
79
- concepts: z.array(z.string()).optional(),
80
- files: z.array(z.string()).optional(),
81
- });
82
-
83
- export const SmartSearchInputSchema = z.object({
84
- query: z.string().optional(),
85
- expandIds: z.array(z.string()).optional(),
86
- limit: z.number().int().positive().optional(),
87
- });
88
-
89
- export const TimelineInputSchema = z.object({
90
- anchor: z.string().min(1),
91
- project: z.string().optional(),
92
- before: z.number().int().nonnegative().optional(),
93
- after: z.number().int().nonnegative().optional(),
94
- });
95
-
96
- export const ProfileInputSchema = z.object({
97
- project: z.string().min(1),
98
- refresh: z.boolean().optional(),
99
- });
100
-
101
- export const RelateInputSchema = z.object({
102
- sourceId: z.string().min(1),
103
- targetId: z.string().min(1),
104
- type: z.enum(["supersedes", "extends", "derives", "contradicts", "related"]),
105
- });
106
-
107
- export const EvolveInputSchema = z.object({
108
- memoryId: z.string().min(1),
109
- newContent: z.string().min(1),
110
- newTitle: z.string().optional(),
111
- });
112
-
113
- export const ExportImportInputSchema = z.object({
114
- exportData: z.object({
115
- version: z.union([z.literal("0.3.0"), z.literal("0.4.0")]),
116
- exportedAt: z.string(),
117
- sessions: z.array(z.unknown()),
118
- observations: z.record(z.string(), z.array(z.unknown())),
119
- memories: z.array(z.unknown()),
120
- summaries: z.array(z.unknown()),
121
- profiles: z.array(z.unknown()).optional(),
122
- }),
123
- strategy: z.enum(["merge", "replace", "skip"]).optional(),
124
- });
@@ -1,28 +0,0 @@
1
- import type { MemoryProvider } from "../types.js";
2
-
3
- const STRICTER_SUFFIX = `
4
-
5
- IMPORTANT: Your previous response was invalid. Please ensure your output strictly follows the required XML format. Every required field must be present with valid values.`;
6
-
7
- export async function compressWithRetry(
8
- provider: MemoryProvider,
9
- systemPrompt: string,
10
- userPrompt: string,
11
- validator: (response: string) => { valid: boolean; errors?: string[] },
12
- maxRetries = 1,
13
- ): Promise<{ response: string; retried: boolean }> {
14
- const first = await provider.compress(systemPrompt, userPrompt);
15
- const result = validator(first);
16
- if (result.valid) return { response: first, retried: false };
17
-
18
- for (let i = 0; i < maxRetries; i++) {
19
- const retry = await provider.compress(
20
- systemPrompt + STRICTER_SUFFIX,
21
- userPrompt,
22
- );
23
- const retryResult = validator(retry);
24
- if (retryResult.valid) return { response: retry, retried: true };
25
- }
26
-
27
- return { response: first, retried: true };
28
- }
@@ -1,31 +0,0 @@
1
- import type { z } from "zod";
2
- import type { EvalResult } from "../types.js";
3
-
4
- export function validateInput<T>(
5
- schema: z.ZodType<T>,
6
- data: unknown,
7
- functionId: string,
8
- ): { valid: true; data: T } | { valid: false; result: EvalResult } {
9
- const parsed = schema.safeParse(data);
10
- if (parsed.success) {
11
- return { valid: true, data: parsed.data };
12
- }
13
- return {
14
- valid: false,
15
- result: {
16
- valid: false,
17
- errors: parsed.error.issues.map((i) => `${i.path.join(".")}: ${i.message}`),
18
- qualityScore: 0,
19
- latencyMs: 0,
20
- functionId,
21
- },
22
- };
23
- }
24
-
25
- export function validateOutput<T>(
26
- schema: z.ZodType<T>,
27
- data: unknown,
28
- functionId: string,
29
- ): { valid: true; data: T } | { valid: false; result: EvalResult } {
30
- return validateInput(schema, data, functionId);
31
- }