@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.
- package/AGENTS.md +2 -2
- package/README.md +41 -68
- package/dist/cli.mjs +3 -3
- package/dist/index.mjs +3 -2
- package/dist/index.mjs.map +1 -1
- package/dist/{src-1fTKFEtN.mjs → src-sYZDDbiA.mjs} +4 -3
- package/dist/src-sYZDDbiA.mjs.map +1 -0
- package/dist/standalone.mjs +1 -1
- package/dist/standalone.mjs.map +1 -1
- package/package.json +10 -1
- package/plugin/.claude-plugin/plugin.json +1 -1
- package/plugin/scripts/notification.d.mts +1 -0
- package/plugin/scripts/notification.mjs.map +1 -0
- package/plugin/scripts/post-tool-failure.d.mts +1 -0
- package/plugin/scripts/post-tool-failure.mjs.map +1 -0
- package/plugin/scripts/post-tool-use.d.mts +1 -0
- package/plugin/scripts/post-tool-use.mjs.map +1 -0
- package/plugin/scripts/pre-compact.d.mts +1 -0
- package/plugin/scripts/pre-compact.mjs.map +1 -0
- package/plugin/scripts/pre-tool-use.d.mts +1 -0
- package/plugin/scripts/pre-tool-use.mjs.map +1 -0
- package/plugin/scripts/prompt-submit.d.mts +1 -0
- package/plugin/scripts/prompt-submit.mjs.map +1 -0
- package/plugin/scripts/session-end.d.mts +1 -0
- package/plugin/scripts/session-end.mjs.map +1 -0
- package/plugin/scripts/session-start.d.mts +1 -0
- package/plugin/scripts/session-start.mjs.map +1 -0
- package/plugin/scripts/stop.d.mts +1 -0
- package/plugin/scripts/stop.mjs.map +1 -0
- package/plugin/scripts/subagent-start.d.mts +1 -0
- package/plugin/scripts/subagent-start.mjs.map +1 -0
- package/plugin/scripts/subagent-stop.d.mts +1 -0
- package/plugin/scripts/subagent-stop.mjs.map +1 -0
- package/plugin/scripts/task-completed.d.mts +1 -0
- package/plugin/scripts/task-completed.mjs.map +1 -0
- package/.claude-plugin/marketplace.json +0 -14
- package/.github/workflows/ci.yml +0 -22
- package/.github/workflows/publish.yml +0 -28
- package/assets/banner.png +0 -0
- package/assets/demo.gif +0 -0
- package/assets/demo.mp4 +0 -0
- package/benchmark/QUALITY.md +0 -73
- package/benchmark/REAL-EMBEDDINGS.md +0 -67
- package/benchmark/SCALE.md +0 -110
- package/benchmark/dataset.ts +0 -293
- package/benchmark/quality-eval.ts +0 -643
- package/benchmark/real-embeddings-eval.ts +0 -405
- package/benchmark/scale-eval.ts +0 -398
- package/dist/src-1fTKFEtN.mjs.map +0 -1
- package/src/auth.ts +0 -12
- package/src/cli.ts +0 -251
- package/src/config.ts +0 -221
- package/src/eval/metrics-store.ts +0 -65
- package/src/eval/quality.ts +0 -51
- package/src/eval/schemas.ts +0 -124
- package/src/eval/self-correct.ts +0 -28
- package/src/eval/validator.ts +0 -31
- package/src/functions/actions.ts +0 -288
- package/src/functions/audit.ts +0 -61
- package/src/functions/auto-forget.ts +0 -169
- package/src/functions/branch-aware.ts +0 -169
- package/src/functions/cascade.ts +0 -80
- package/src/functions/checkpoints.ts +0 -209
- package/src/functions/claude-bridge.ts +0 -161
- package/src/functions/compress.ts +0 -194
- package/src/functions/consolidate.ts +0 -212
- package/src/functions/consolidation-pipeline.ts +0 -258
- package/src/functions/context.ts +0 -169
- package/src/functions/crystallize.ts +0 -293
- package/src/functions/dedup.ts +0 -57
- package/src/functions/diagnostics.ts +0 -785
- package/src/functions/enrich.ts +0 -132
- package/src/functions/evict.ts +0 -163
- package/src/functions/export-import.ts +0 -508
- package/src/functions/facets.ts +0 -248
- package/src/functions/file-index.ts +0 -106
- package/src/functions/flow-compress.ts +0 -214
- package/src/functions/frontier.ts +0 -196
- package/src/functions/governance.ts +0 -131
- package/src/functions/graph-retrieval.ts +0 -277
- package/src/functions/graph.ts +0 -275
- package/src/functions/leases.ts +0 -216
- package/src/functions/lessons.ts +0 -253
- package/src/functions/mesh.ts +0 -434
- package/src/functions/migrate.ts +0 -165
- package/src/functions/observe.ts +0 -144
- package/src/functions/obsidian-export.ts +0 -310
- package/src/functions/patterns.ts +0 -138
- package/src/functions/privacy.ts +0 -39
- package/src/functions/profile.ts +0 -155
- package/src/functions/query-expansion.ts +0 -186
- package/src/functions/relations.ts +0 -237
- package/src/functions/remember.ts +0 -162
- package/src/functions/retention.ts +0 -235
- package/src/functions/routines.ts +0 -289
- package/src/functions/search.ts +0 -80
- package/src/functions/sentinels.ts +0 -417
- package/src/functions/signals.ts +0 -186
- package/src/functions/sketches.ts +0 -274
- package/src/functions/sliding-window.ts +0 -257
- package/src/functions/smart-search.ts +0 -115
- package/src/functions/snapshot.ts +0 -219
- package/src/functions/summarize.ts +0 -155
- package/src/functions/team.ts +0 -147
- package/src/functions/temporal-graph.ts +0 -476
- package/src/functions/timeline.ts +0 -138
- package/src/functions/verify.ts +0 -117
- package/src/health/monitor.ts +0 -110
- package/src/health/thresholds.ts +0 -73
- package/src/hooks/notification.ts +0 -52
- package/src/hooks/post-tool-failure.ts +0 -58
- package/src/hooks/post-tool-use.ts +0 -62
- package/src/hooks/pre-compact.ts +0 -60
- package/src/hooks/pre-tool-use.ts +0 -72
- package/src/hooks/prompt-submit.ts +0 -46
- package/src/hooks/session-end.ts +0 -71
- package/src/hooks/session-start.ts +0 -48
- package/src/hooks/stop.ts +0 -39
- package/src/hooks/subagent-start.ts +0 -49
- package/src/hooks/subagent-stop.ts +0 -54
- package/src/hooks/task-completed.ts +0 -54
- package/src/index.ts +0 -342
- package/src/mcp/in-memory-kv.ts +0 -61
- package/src/mcp/server.ts +0 -1455
- package/src/mcp/standalone.ts +0 -177
- package/src/mcp/tools-registry.ts +0 -769
- package/src/mcp/transport.ts +0 -91
- package/src/prompts/compression.ts +0 -67
- package/src/prompts/consolidation.ts +0 -48
- package/src/prompts/graph-extraction.ts +0 -35
- package/src/prompts/summary.ts +0 -38
- package/src/prompts/xml.ts +0 -26
- package/src/providers/agent-sdk.ts +0 -34
- package/src/providers/anthropic.ts +0 -35
- package/src/providers/circuit-breaker.ts +0 -82
- package/src/providers/embedding/cohere.ts +0 -46
- package/src/providers/embedding/gemini.ts +0 -54
- package/src/providers/embedding/index.ts +0 -39
- package/src/providers/embedding/local.ts +0 -52
- package/src/providers/embedding/openai.ts +0 -45
- package/src/providers/embedding/openrouter.ts +0 -51
- package/src/providers/embedding/voyage.ts +0 -46
- package/src/providers/fallback-chain.ts +0 -31
- package/src/providers/index.ts +0 -84
- package/src/providers/openrouter.ts +0 -71
- package/src/providers/resilient.ts +0 -37
- package/src/state/hybrid-search.ts +0 -295
- package/src/state/index-persistence.ts +0 -63
- package/src/state/keyed-mutex.ts +0 -18
- package/src/state/kv.ts +0 -33
- package/src/state/schema.ts +0 -71
- package/src/state/search-index.ts +0 -245
- package/src/state/stemmer.ts +0 -104
- package/src/state/synonyms.ts +0 -63
- package/src/state/vector-index.ts +0 -130
- package/src/telemetry/setup.ts +0 -116
- package/src/triggers/api.ts +0 -1904
- package/src/triggers/events.ts +0 -71
- package/src/types.ts +0 -769
- package/src/version.ts +0 -1
- package/src/viewer/index.html +0 -2556
- package/src/viewer/server.ts +0 -207
- package/src/xenova.d.ts +0 -3
- package/test/actions.test.ts +0 -490
- package/test/audit.test.ts +0 -108
- package/test/auto-forget.test.ts +0 -188
- package/test/cascade.test.ts +0 -277
- package/test/checkpoints.test.ts +0 -493
- package/test/circuit-breaker.test.ts +0 -107
- package/test/claude-bridge.test.ts +0 -178
- package/test/confidence.test.ts +0 -247
- package/test/consistency.test.ts +0 -61
- package/test/consolidation-pipeline.test.ts +0 -251
- package/test/crystallize.test.ts +0 -521
- package/test/diagnostics.test.ts +0 -638
- package/test/embedding-provider.test.ts +0 -49
- package/test/enrich.test.ts +0 -209
- package/test/eval.test.ts +0 -300
- package/test/export-import.test.ts +0 -251
- package/test/facets.test.ts +0 -448
- package/test/fallback-chain.test.ts +0 -93
- package/test/frontier.test.ts +0 -485
- package/test/governance.test.ts +0 -147
- package/test/graph-retrieval.test.ts +0 -186
- package/test/graph.test.ts +0 -160
- package/test/helpers/mocks.ts +0 -40
- package/test/hybrid-search.test.ts +0 -145
- package/test/index-persistence.test.ts +0 -124
- package/test/integration.test.ts +0 -265
- package/test/leases.test.ts +0 -399
- package/test/mcp-prompts.test.ts +0 -218
- package/test/mcp-resources.test.ts +0 -286
- package/test/mcp-standalone.test.ts +0 -113
- package/test/mesh.test.ts +0 -700
- package/test/privacy.test.ts +0 -87
- package/test/profile.test.ts +0 -161
- package/test/query-expansion.test.ts +0 -154
- package/test/relations.test.ts +0 -198
- package/test/retention.test.ts +0 -245
- package/test/routines.test.ts +0 -497
- package/test/schema-fingerprint.test.ts +0 -81
- package/test/schema.test.ts +0 -42
- package/test/search-index.test.ts +0 -128
- package/test/sentinels.test.ts +0 -626
- package/test/signals.test.ts +0 -410
- package/test/sketches.test.ts +0 -549
- package/test/sliding-window.test.ts +0 -199
- package/test/smart-search.test.ts +0 -169
- package/test/snapshot.test.ts +0 -165
- package/test/team.test.ts +0 -156
- package/test/temporal-graph.test.ts +0 -378
- package/test/timeline.test.ts +0 -148
- package/test/vector-index.test.ts +0 -79
- package/test/verify.test.ts +0 -209
- package/test/xml.test.ts +0 -65
- package/tsconfig.json +0 -22
- package/tsdown.config.ts +0 -62
|
@@ -1,194 +0,0 @@
|
|
|
1
|
-
import type { ISdk } from "iii-sdk";
|
|
2
|
-
import { getContext } from "iii-sdk";
|
|
3
|
-
import type {
|
|
4
|
-
RawObservation,
|
|
5
|
-
CompressedObservation,
|
|
6
|
-
ObservationType,
|
|
7
|
-
MemoryProvider,
|
|
8
|
-
} from "../types.js";
|
|
9
|
-
import { KV, STREAM } from "../state/schema.js";
|
|
10
|
-
import { StateKV } from "../state/kv.js";
|
|
11
|
-
import {
|
|
12
|
-
COMPRESSION_SYSTEM,
|
|
13
|
-
buildCompressionPrompt,
|
|
14
|
-
} from "../prompts/compression.js";
|
|
15
|
-
import { getXmlTag, getXmlChildren } from "../prompts/xml.js";
|
|
16
|
-
import { getSearchIndex } from "./search.js";
|
|
17
|
-
import { CompressOutputSchema } from "../eval/schemas.js";
|
|
18
|
-
import { validateOutput } from "../eval/validator.js";
|
|
19
|
-
import { scoreCompression } from "../eval/quality.js";
|
|
20
|
-
import { compressWithRetry } from "../eval/self-correct.js";
|
|
21
|
-
import type { MetricsStore } from "../eval/metrics-store.js";
|
|
22
|
-
|
|
23
|
-
const VALID_TYPES = new Set<string>([
|
|
24
|
-
"file_read",
|
|
25
|
-
"file_write",
|
|
26
|
-
"file_edit",
|
|
27
|
-
"command_run",
|
|
28
|
-
"search",
|
|
29
|
-
"web_fetch",
|
|
30
|
-
"conversation",
|
|
31
|
-
"error",
|
|
32
|
-
"decision",
|
|
33
|
-
"discovery",
|
|
34
|
-
"subagent",
|
|
35
|
-
"notification",
|
|
36
|
-
"task",
|
|
37
|
-
"other",
|
|
38
|
-
]);
|
|
39
|
-
|
|
40
|
-
function parseCompressionXml(
|
|
41
|
-
xml: string,
|
|
42
|
-
): Omit<CompressedObservation, "id" | "sessionId" | "timestamp"> | null {
|
|
43
|
-
const rawType = getXmlTag(xml, "type");
|
|
44
|
-
const title = getXmlTag(xml, "title");
|
|
45
|
-
if (!rawType || !title) return null;
|
|
46
|
-
const type = VALID_TYPES.has(rawType) ? rawType : "other";
|
|
47
|
-
|
|
48
|
-
return {
|
|
49
|
-
type: type as ObservationType,
|
|
50
|
-
title,
|
|
51
|
-
subtitle: getXmlTag(xml, "subtitle") || undefined,
|
|
52
|
-
facts: getXmlChildren(xml, "facts", "fact"),
|
|
53
|
-
narrative: getXmlTag(xml, "narrative"),
|
|
54
|
-
concepts: getXmlChildren(xml, "concepts", "concept"),
|
|
55
|
-
files: getXmlChildren(xml, "files", "file"),
|
|
56
|
-
importance: Math.max(
|
|
57
|
-
1,
|
|
58
|
-
Math.min(10, parseInt(getXmlTag(xml, "importance") || "5", 10) || 5),
|
|
59
|
-
),
|
|
60
|
-
};
|
|
61
|
-
}
|
|
62
|
-
|
|
63
|
-
export function registerCompressFunction(
|
|
64
|
-
sdk: ISdk,
|
|
65
|
-
kv: StateKV,
|
|
66
|
-
provider: MemoryProvider,
|
|
67
|
-
metricsStore?: MetricsStore,
|
|
68
|
-
): void {
|
|
69
|
-
sdk.registerFunction(
|
|
70
|
-
{
|
|
71
|
-
id: "mem::compress",
|
|
72
|
-
description: "Compress a raw observation using LLM",
|
|
73
|
-
},
|
|
74
|
-
async (data: {
|
|
75
|
-
observationId: string;
|
|
76
|
-
sessionId: string;
|
|
77
|
-
raw: RawObservation;
|
|
78
|
-
}) => {
|
|
79
|
-
const ctx = getContext();
|
|
80
|
-
const startMs = Date.now();
|
|
81
|
-
const prompt = buildCompressionPrompt({
|
|
82
|
-
hookType: data.raw.hookType,
|
|
83
|
-
toolName: data.raw.toolName,
|
|
84
|
-
toolInput: data.raw.toolInput,
|
|
85
|
-
toolOutput: data.raw.toolOutput,
|
|
86
|
-
userPrompt: data.raw.userPrompt,
|
|
87
|
-
timestamp: data.raw.timestamp,
|
|
88
|
-
});
|
|
89
|
-
|
|
90
|
-
try {
|
|
91
|
-
const validator = (response: string) => {
|
|
92
|
-
const parsed = parseCompressionXml(response);
|
|
93
|
-
if (!parsed) return { valid: false, errors: ["xml_parse_failed"] };
|
|
94
|
-
const result = validateOutput(
|
|
95
|
-
CompressOutputSchema,
|
|
96
|
-
parsed,
|
|
97
|
-
"mem::compress",
|
|
98
|
-
);
|
|
99
|
-
return result.valid
|
|
100
|
-
? { valid: true }
|
|
101
|
-
: { valid: false, errors: result.result.errors };
|
|
102
|
-
};
|
|
103
|
-
|
|
104
|
-
const { response, retried } = await compressWithRetry(
|
|
105
|
-
provider,
|
|
106
|
-
COMPRESSION_SYSTEM,
|
|
107
|
-
prompt,
|
|
108
|
-
validator,
|
|
109
|
-
1,
|
|
110
|
-
);
|
|
111
|
-
|
|
112
|
-
const parsed = parseCompressionXml(response);
|
|
113
|
-
if (!parsed) {
|
|
114
|
-
const latencyMs = Date.now() - startMs;
|
|
115
|
-
if (metricsStore) {
|
|
116
|
-
await metricsStore.record("mem::compress", latencyMs, false);
|
|
117
|
-
}
|
|
118
|
-
ctx.logger.warn("Failed to parse compression XML", {
|
|
119
|
-
obsId: data.observationId,
|
|
120
|
-
retried,
|
|
121
|
-
});
|
|
122
|
-
return { success: false, error: "parse_failed" };
|
|
123
|
-
}
|
|
124
|
-
|
|
125
|
-
const qualityScore = scoreCompression(parsed);
|
|
126
|
-
|
|
127
|
-
const compressed: CompressedObservation = {
|
|
128
|
-
id: data.observationId,
|
|
129
|
-
sessionId: data.sessionId,
|
|
130
|
-
timestamp: data.raw.timestamp,
|
|
131
|
-
...parsed,
|
|
132
|
-
confidence: qualityScore / 100,
|
|
133
|
-
};
|
|
134
|
-
|
|
135
|
-
await kv.set(
|
|
136
|
-
KV.observations(data.sessionId),
|
|
137
|
-
data.observationId,
|
|
138
|
-
compressed,
|
|
139
|
-
);
|
|
140
|
-
|
|
141
|
-
getSearchIndex().add(compressed);
|
|
142
|
-
|
|
143
|
-
sdk.triggerVoid("stream::set", {
|
|
144
|
-
stream_name: STREAM.name,
|
|
145
|
-
group_id: STREAM.group(data.sessionId),
|
|
146
|
-
item_id: data.observationId,
|
|
147
|
-
data: { type: "compressed", observation: compressed },
|
|
148
|
-
});
|
|
149
|
-
|
|
150
|
-
sdk.triggerVoid("stream::set", {
|
|
151
|
-
stream_name: STREAM.name,
|
|
152
|
-
group_id: STREAM.viewerGroup,
|
|
153
|
-
item_id: data.observationId,
|
|
154
|
-
data: {
|
|
155
|
-
type: "compressed",
|
|
156
|
-
observation: compressed,
|
|
157
|
-
sessionId: data.sessionId,
|
|
158
|
-
},
|
|
159
|
-
});
|
|
160
|
-
|
|
161
|
-
const latencyMs = Date.now() - startMs;
|
|
162
|
-
if (metricsStore) {
|
|
163
|
-
await metricsStore.record(
|
|
164
|
-
"mem::compress",
|
|
165
|
-
latencyMs,
|
|
166
|
-
true,
|
|
167
|
-
qualityScore,
|
|
168
|
-
);
|
|
169
|
-
}
|
|
170
|
-
|
|
171
|
-
ctx.logger.info("Observation compressed", {
|
|
172
|
-
obsId: data.observationId,
|
|
173
|
-
type: compressed.type,
|
|
174
|
-
importance: compressed.importance,
|
|
175
|
-
qualityScore,
|
|
176
|
-
retried,
|
|
177
|
-
});
|
|
178
|
-
|
|
179
|
-
return { success: true, compressed, qualityScore };
|
|
180
|
-
} catch (err) {
|
|
181
|
-
const msg = err instanceof Error ? err.message : String(err);
|
|
182
|
-
const latencyMs = Date.now() - startMs;
|
|
183
|
-
if (metricsStore) {
|
|
184
|
-
await metricsStore.record("mem::compress", latencyMs, false);
|
|
185
|
-
}
|
|
186
|
-
ctx.logger.error("Compression failed", {
|
|
187
|
-
obsId: data.observationId,
|
|
188
|
-
error: msg,
|
|
189
|
-
});
|
|
190
|
-
return { success: false, error: "compression_failed" };
|
|
191
|
-
}
|
|
192
|
-
},
|
|
193
|
-
);
|
|
194
|
-
}
|
|
@@ -1,212 +0,0 @@
|
|
|
1
|
-
import type { ISdk } from "iii-sdk";
|
|
2
|
-
import { getContext } from "iii-sdk";
|
|
3
|
-
import type {
|
|
4
|
-
CompressedObservation,
|
|
5
|
-
Memory,
|
|
6
|
-
Session,
|
|
7
|
-
MemoryProvider,
|
|
8
|
-
} from "../types.js";
|
|
9
|
-
import { KV, generateId } from "../state/schema.js";
|
|
10
|
-
import { StateKV } from "../state/kv.js";
|
|
11
|
-
|
|
12
|
-
const CONSOLIDATION_SYSTEM = `You are a memory consolidation engine. Given a set of related observations from coding sessions, synthesize them into a single long-term memory.
|
|
13
|
-
|
|
14
|
-
Output XML:
|
|
15
|
-
<memory>
|
|
16
|
-
<type>pattern|preference|architecture|bug|workflow|fact</type>
|
|
17
|
-
<title>Concise memory title (max 80 chars)</title>
|
|
18
|
-
<content>2-4 sentence description of the learned insight</content>
|
|
19
|
-
<concepts>
|
|
20
|
-
<concept>key term</concept>
|
|
21
|
-
</concepts>
|
|
22
|
-
<files>
|
|
23
|
-
<file>relevant/file/path</file>
|
|
24
|
-
</files>
|
|
25
|
-
<strength>1-10 how confident/important this memory is</strength>
|
|
26
|
-
</memory>`;
|
|
27
|
-
|
|
28
|
-
import { getXmlTag, getXmlChildren } from "../prompts/xml.js";
|
|
29
|
-
|
|
30
|
-
function parseMemoryXml(
|
|
31
|
-
xml: string,
|
|
32
|
-
sessionIds: string[],
|
|
33
|
-
): Omit<Memory, "id" | "createdAt" | "updatedAt"> | null {
|
|
34
|
-
const type = getXmlTag(xml, "type");
|
|
35
|
-
const title = getXmlTag(xml, "title");
|
|
36
|
-
const content = getXmlTag(xml, "content");
|
|
37
|
-
if (!type || !title || !content) return null;
|
|
38
|
-
|
|
39
|
-
const validTypes = new Set([
|
|
40
|
-
"pattern",
|
|
41
|
-
"preference",
|
|
42
|
-
"architecture",
|
|
43
|
-
"bug",
|
|
44
|
-
"workflow",
|
|
45
|
-
"fact",
|
|
46
|
-
]);
|
|
47
|
-
|
|
48
|
-
return {
|
|
49
|
-
type: (validTypes.has(type) ? type : "fact") as Memory["type"],
|
|
50
|
-
title,
|
|
51
|
-
content,
|
|
52
|
-
concepts: getXmlChildren(xml, "concepts", "concept"),
|
|
53
|
-
files: getXmlChildren(xml, "files", "file"),
|
|
54
|
-
sessionIds,
|
|
55
|
-
strength: Math.max(
|
|
56
|
-
1,
|
|
57
|
-
Math.min(10, parseInt(getXmlTag(xml, "strength") || "5", 10) || 5),
|
|
58
|
-
),
|
|
59
|
-
version: 1,
|
|
60
|
-
isLatest: true,
|
|
61
|
-
};
|
|
62
|
-
}
|
|
63
|
-
|
|
64
|
-
export function registerConsolidateFunction(
|
|
65
|
-
sdk: ISdk,
|
|
66
|
-
kv: StateKV,
|
|
67
|
-
provider: MemoryProvider,
|
|
68
|
-
): void {
|
|
69
|
-
sdk.registerFunction(
|
|
70
|
-
{ id: "mem::consolidate" },
|
|
71
|
-
async (data: { project?: string; minObservations?: number }) => {
|
|
72
|
-
const ctx = getContext();
|
|
73
|
-
const minObs = data.minObservations ?? 10;
|
|
74
|
-
|
|
75
|
-
const sessions = await kv.list<Session>(KV.sessions);
|
|
76
|
-
const filtered = data.project
|
|
77
|
-
? sessions.filter((s) => s.project === data.project)
|
|
78
|
-
: sessions;
|
|
79
|
-
|
|
80
|
-
const allObs: Array<CompressedObservation & { sid: string }> = [];
|
|
81
|
-
const obsPerSession: CompressedObservation[][] = [];
|
|
82
|
-
for (let batch = 0; batch < filtered.length; batch += 10) {
|
|
83
|
-
const chunk = filtered.slice(batch, batch + 10);
|
|
84
|
-
const results = await Promise.all(
|
|
85
|
-
chunk.map((s) =>
|
|
86
|
-
kv
|
|
87
|
-
.list<CompressedObservation>(KV.observations(s.id))
|
|
88
|
-
.catch(() => [] as CompressedObservation[]),
|
|
89
|
-
),
|
|
90
|
-
);
|
|
91
|
-
obsPerSession.push(...results);
|
|
92
|
-
}
|
|
93
|
-
for (let i = 0; i < filtered.length; i++) {
|
|
94
|
-
for (const obs of obsPerSession[i]) {
|
|
95
|
-
if (obs.title && obs.importance >= 5) {
|
|
96
|
-
allObs.push({ ...obs, sid: filtered[i].id });
|
|
97
|
-
}
|
|
98
|
-
}
|
|
99
|
-
}
|
|
100
|
-
|
|
101
|
-
if (allObs.length < minObs) {
|
|
102
|
-
return { consolidated: 0, reason: "insufficient_observations" };
|
|
103
|
-
}
|
|
104
|
-
|
|
105
|
-
const conceptGroups = new Map<string, typeof allObs>();
|
|
106
|
-
for (const obs of allObs) {
|
|
107
|
-
for (const concept of obs.concepts) {
|
|
108
|
-
const key = concept.toLowerCase();
|
|
109
|
-
if (!conceptGroups.has(key)) conceptGroups.set(key, []);
|
|
110
|
-
conceptGroups.get(key)!.push(obs);
|
|
111
|
-
}
|
|
112
|
-
}
|
|
113
|
-
|
|
114
|
-
let consolidated = 0;
|
|
115
|
-
const existingMemories = await kv.list<Memory>(KV.memories);
|
|
116
|
-
const existingTitles = new Set(
|
|
117
|
-
existingMemories.map((m) => m.title.toLowerCase()),
|
|
118
|
-
);
|
|
119
|
-
|
|
120
|
-
const MAX_LLM_CALLS = 10;
|
|
121
|
-
let llmCallCount = 0;
|
|
122
|
-
|
|
123
|
-
const sortedGroups = [...conceptGroups.entries()]
|
|
124
|
-
.filter(([, g]) => g.length >= 3)
|
|
125
|
-
.sort((a, b) => b[1].length - a[1].length);
|
|
126
|
-
|
|
127
|
-
for (const [concept, obsGroup] of sortedGroups) {
|
|
128
|
-
if (llmCallCount >= MAX_LLM_CALLS) break;
|
|
129
|
-
|
|
130
|
-
const top = obsGroup
|
|
131
|
-
.sort((a, b) => b.importance - a.importance)
|
|
132
|
-
.slice(0, 8);
|
|
133
|
-
const sessionIds = [...new Set(top.map((o) => o.sid))];
|
|
134
|
-
|
|
135
|
-
const prompt = top
|
|
136
|
-
.map(
|
|
137
|
-
(o) =>
|
|
138
|
-
`[${o.type}] ${o.title}\n${o.narrative}\nFiles: ${o.files.join(", ")}\nImportance: ${o.importance}`,
|
|
139
|
-
)
|
|
140
|
-
.join("\n\n");
|
|
141
|
-
|
|
142
|
-
try {
|
|
143
|
-
const response = await Promise.race([
|
|
144
|
-
provider.compress(
|
|
145
|
-
CONSOLIDATION_SYSTEM,
|
|
146
|
-
`Concept: "${concept}"\n\nObservations:\n${prompt}`,
|
|
147
|
-
),
|
|
148
|
-
new Promise<never>((_, reject) =>
|
|
149
|
-
setTimeout(() => reject(new Error("compress timeout")), 30_000),
|
|
150
|
-
),
|
|
151
|
-
]);
|
|
152
|
-
llmCallCount++;
|
|
153
|
-
const parsed = parseMemoryXml(response, sessionIds);
|
|
154
|
-
if (!parsed) continue;
|
|
155
|
-
|
|
156
|
-
const existingMatch = existingMemories.find(
|
|
157
|
-
(m) => m.title.toLowerCase() === parsed.title.toLowerCase(),
|
|
158
|
-
);
|
|
159
|
-
|
|
160
|
-
const now = new Date().toISOString();
|
|
161
|
-
const obsIds = [...new Set(top.map((o) => o.id))];
|
|
162
|
-
if (existingMatch) {
|
|
163
|
-
existingMatch.isLatest = false;
|
|
164
|
-
await kv.set(KV.memories, existingMatch.id, existingMatch);
|
|
165
|
-
|
|
166
|
-
const evolved: Memory = {
|
|
167
|
-
id: generateId("mem"),
|
|
168
|
-
createdAt: now,
|
|
169
|
-
updatedAt: now,
|
|
170
|
-
...parsed,
|
|
171
|
-
version: (existingMatch.version || 1) + 1,
|
|
172
|
-
parentId: existingMatch.id,
|
|
173
|
-
supersedes: [
|
|
174
|
-
existingMatch.id,
|
|
175
|
-
...(existingMatch.supersedes || []),
|
|
176
|
-
],
|
|
177
|
-
sourceObservationIds: obsIds,
|
|
178
|
-
isLatest: true,
|
|
179
|
-
};
|
|
180
|
-
await kv.set(KV.memories, evolved.id, evolved);
|
|
181
|
-
existingTitles.add(evolved.title.toLowerCase());
|
|
182
|
-
consolidated++;
|
|
183
|
-
} else {
|
|
184
|
-
const memory: Memory = {
|
|
185
|
-
id: generateId("mem"),
|
|
186
|
-
createdAt: now,
|
|
187
|
-
updatedAt: now,
|
|
188
|
-
...parsed,
|
|
189
|
-
sourceObservationIds: obsIds,
|
|
190
|
-
version: 1,
|
|
191
|
-
isLatest: true,
|
|
192
|
-
};
|
|
193
|
-
await kv.set(KV.memories, memory.id, memory);
|
|
194
|
-
existingTitles.add(memory.title.toLowerCase());
|
|
195
|
-
consolidated++;
|
|
196
|
-
}
|
|
197
|
-
} catch (err) {
|
|
198
|
-
ctx.logger.warn("Consolidation failed for concept", {
|
|
199
|
-
concept,
|
|
200
|
-
error: err instanceof Error ? err.message : String(err),
|
|
201
|
-
});
|
|
202
|
-
}
|
|
203
|
-
}
|
|
204
|
-
|
|
205
|
-
ctx.logger.info("Consolidation complete", {
|
|
206
|
-
consolidated,
|
|
207
|
-
totalObs: allObs.length,
|
|
208
|
-
});
|
|
209
|
-
return { consolidated, totalObservations: allObs.length };
|
|
210
|
-
},
|
|
211
|
-
);
|
|
212
|
-
}
|
|
@@ -1,258 +0,0 @@
|
|
|
1
|
-
import type { ISdk } from "iii-sdk";
|
|
2
|
-
import { getContext } from "iii-sdk";
|
|
3
|
-
import type {
|
|
4
|
-
SemanticMemory,
|
|
5
|
-
ProceduralMemory,
|
|
6
|
-
SessionSummary,
|
|
7
|
-
Memory,
|
|
8
|
-
MemoryProvider,
|
|
9
|
-
} from "../types.js";
|
|
10
|
-
import { KV, generateId } from "../state/schema.js";
|
|
11
|
-
import type { StateKV } from "../state/kv.js";
|
|
12
|
-
import {
|
|
13
|
-
SEMANTIC_MERGE_SYSTEM,
|
|
14
|
-
buildSemanticMergePrompt,
|
|
15
|
-
PROCEDURAL_EXTRACTION_SYSTEM,
|
|
16
|
-
buildProceduralExtractionPrompt,
|
|
17
|
-
} from "../prompts/consolidation.js";
|
|
18
|
-
import { recordAudit } from "./audit.js";
|
|
19
|
-
import { getConsolidationDecayDays, isConsolidationEnabled } from "../config.js";
|
|
20
|
-
|
|
21
|
-
function applyDecay(
|
|
22
|
-
items: Array<{
|
|
23
|
-
strength: number;
|
|
24
|
-
lastAccessedAt?: string;
|
|
25
|
-
updatedAt: string;
|
|
26
|
-
}>,
|
|
27
|
-
decayDays: number,
|
|
28
|
-
): void {
|
|
29
|
-
if (decayDays <= 0 || !Number.isFinite(decayDays)) return;
|
|
30
|
-
const now = Date.now();
|
|
31
|
-
for (const item of items) {
|
|
32
|
-
const lastAccess = item.lastAccessedAt || item.updatedAt;
|
|
33
|
-
const daysSince =
|
|
34
|
-
(now - new Date(lastAccess).getTime()) / (1000 * 60 * 60 * 24);
|
|
35
|
-
if (daysSince > decayDays) {
|
|
36
|
-
const decayPeriods = Math.floor(daysSince / decayDays);
|
|
37
|
-
item.strength = Math.max(
|
|
38
|
-
0.1,
|
|
39
|
-
item.strength * Math.pow(0.9, decayPeriods),
|
|
40
|
-
);
|
|
41
|
-
}
|
|
42
|
-
}
|
|
43
|
-
}
|
|
44
|
-
|
|
45
|
-
export function registerConsolidationPipelineFunction(
|
|
46
|
-
sdk: ISdk,
|
|
47
|
-
kv: StateKV,
|
|
48
|
-
provider: MemoryProvider,
|
|
49
|
-
): void {
|
|
50
|
-
sdk.registerFunction(
|
|
51
|
-
{ id: "mem::consolidate-pipeline" },
|
|
52
|
-
async (data?: { tier?: string; force?: boolean }) => {
|
|
53
|
-
if (!data?.force && !isConsolidationEnabled()) {
|
|
54
|
-
return { success: false, skipped: true, reason: "CONSOLIDATION_ENABLED is not set to true" };
|
|
55
|
-
}
|
|
56
|
-
const ctx = getContext();
|
|
57
|
-
const tier = data?.tier || "all";
|
|
58
|
-
const decayDays = getConsolidationDecayDays();
|
|
59
|
-
const results: Record<string, unknown> = {};
|
|
60
|
-
|
|
61
|
-
if (tier === "all" || tier === "semantic") {
|
|
62
|
-
const summaries = await kv.list<SessionSummary>(KV.summaries);
|
|
63
|
-
const existingSemantic = await kv.list<SemanticMemory>(KV.semantic);
|
|
64
|
-
|
|
65
|
-
if (summaries.length >= 5) {
|
|
66
|
-
const recentSummaries = summaries
|
|
67
|
-
.sort(
|
|
68
|
-
(a, b) =>
|
|
69
|
-
new Date(b.createdAt).getTime() -
|
|
70
|
-
new Date(a.createdAt).getTime(),
|
|
71
|
-
)
|
|
72
|
-
.slice(0, 20);
|
|
73
|
-
|
|
74
|
-
const prompt = buildSemanticMergePrompt(
|
|
75
|
-
recentSummaries.map((s) => ({
|
|
76
|
-
title: s.title,
|
|
77
|
-
narrative: s.narrative,
|
|
78
|
-
concepts: s.concepts,
|
|
79
|
-
})),
|
|
80
|
-
);
|
|
81
|
-
|
|
82
|
-
try {
|
|
83
|
-
const response = await provider.summarize(
|
|
84
|
-
SEMANTIC_MERGE_SYSTEM,
|
|
85
|
-
prompt,
|
|
86
|
-
);
|
|
87
|
-
|
|
88
|
-
const factRegex = /<fact\s+confidence="([^"]+)">([^<]+)<\/fact>/g;
|
|
89
|
-
let match;
|
|
90
|
-
let newFacts = 0;
|
|
91
|
-
const now = new Date().toISOString();
|
|
92
|
-
|
|
93
|
-
while ((match = factRegex.exec(response)) !== null) {
|
|
94
|
-
const parsedConf = parseFloat(match[1]);
|
|
95
|
-
const confidence = Number.isNaN(parsedConf) ? 0.5 : parsedConf;
|
|
96
|
-
const fact = match[2].trim();
|
|
97
|
-
|
|
98
|
-
const existing = existingSemantic.find(
|
|
99
|
-
(s) => s.fact.toLowerCase() === fact.toLowerCase(),
|
|
100
|
-
);
|
|
101
|
-
if (existing) {
|
|
102
|
-
existing.accessCount++;
|
|
103
|
-
existing.lastAccessedAt = now;
|
|
104
|
-
existing.updatedAt = now;
|
|
105
|
-
existing.confidence = Math.max(existing.confidence, confidence);
|
|
106
|
-
await kv.set(KV.semantic, existing.id, existing);
|
|
107
|
-
} else {
|
|
108
|
-
const sem: SemanticMemory = {
|
|
109
|
-
id: generateId("sem"),
|
|
110
|
-
fact,
|
|
111
|
-
confidence,
|
|
112
|
-
sourceSessionIds: recentSummaries.map((s) => s.sessionId),
|
|
113
|
-
sourceMemoryIds: [],
|
|
114
|
-
accessCount: 1,
|
|
115
|
-
lastAccessedAt: now,
|
|
116
|
-
strength: confidence,
|
|
117
|
-
createdAt: now,
|
|
118
|
-
updatedAt: now,
|
|
119
|
-
};
|
|
120
|
-
await kv.set(KV.semantic, sem.id, sem);
|
|
121
|
-
newFacts++;
|
|
122
|
-
}
|
|
123
|
-
}
|
|
124
|
-
results.semantic = { newFacts, totalSummaries: summaries.length };
|
|
125
|
-
} catch (err) {
|
|
126
|
-
const msg = err instanceof Error ? err.message : String(err);
|
|
127
|
-
ctx.logger.error("Semantic consolidation failed", { error: msg });
|
|
128
|
-
results.semantic = { error: msg };
|
|
129
|
-
}
|
|
130
|
-
} else {
|
|
131
|
-
results.semantic = {
|
|
132
|
-
skipped: true,
|
|
133
|
-
reason: "fewer than 5 summaries",
|
|
134
|
-
};
|
|
135
|
-
}
|
|
136
|
-
}
|
|
137
|
-
|
|
138
|
-
if (tier === "all" || tier === "procedural") {
|
|
139
|
-
const memories = await kv.list<Memory>(KV.memories);
|
|
140
|
-
const patterns = memories
|
|
141
|
-
.filter((m) => m.isLatest && m.type === "pattern")
|
|
142
|
-
.map((m) => ({
|
|
143
|
-
content: m.content,
|
|
144
|
-
frequency: m.sessionIds.length || 1,
|
|
145
|
-
}))
|
|
146
|
-
.filter((p) => p.frequency >= 2);
|
|
147
|
-
|
|
148
|
-
if (patterns.length >= 2) {
|
|
149
|
-
const prompt = buildProceduralExtractionPrompt(patterns);
|
|
150
|
-
|
|
151
|
-
try {
|
|
152
|
-
const response = await provider.summarize(
|
|
153
|
-
PROCEDURAL_EXTRACTION_SYSTEM,
|
|
154
|
-
prompt,
|
|
155
|
-
);
|
|
156
|
-
|
|
157
|
-
const procRegex =
|
|
158
|
-
/<procedure\s+name="([^"]+)"\s+trigger="([^"]+)">([\s\S]*?)<\/procedure>/g;
|
|
159
|
-
let match;
|
|
160
|
-
let newProcs = 0;
|
|
161
|
-
const now = new Date().toISOString();
|
|
162
|
-
const existingProcs = await kv.list<ProceduralMemory>(
|
|
163
|
-
KV.procedural,
|
|
164
|
-
);
|
|
165
|
-
|
|
166
|
-
while ((match = procRegex.exec(response)) !== null) {
|
|
167
|
-
const name = match[1];
|
|
168
|
-
const trigger = match[2];
|
|
169
|
-
const stepsBlock = match[3];
|
|
170
|
-
const steps: string[] = [];
|
|
171
|
-
|
|
172
|
-
const stepRegex = /<step>([^<]+)<\/step>/g;
|
|
173
|
-
let stepMatch;
|
|
174
|
-
while ((stepMatch = stepRegex.exec(stepsBlock)) !== null) {
|
|
175
|
-
steps.push(stepMatch[1].trim());
|
|
176
|
-
}
|
|
177
|
-
|
|
178
|
-
const existing = existingProcs.find(
|
|
179
|
-
(p) => p.name.toLowerCase() === name.toLowerCase(),
|
|
180
|
-
);
|
|
181
|
-
if (existing) {
|
|
182
|
-
existing.frequency++;
|
|
183
|
-
existing.updatedAt = now;
|
|
184
|
-
existing.strength = Math.min(1, existing.strength + 0.1);
|
|
185
|
-
await kv.set(KV.procedural, existing.id, existing);
|
|
186
|
-
} else {
|
|
187
|
-
const proc: ProceduralMemory = {
|
|
188
|
-
id: generateId("proc"),
|
|
189
|
-
name,
|
|
190
|
-
steps,
|
|
191
|
-
triggerCondition: trigger,
|
|
192
|
-
frequency: 1,
|
|
193
|
-
sourceSessionIds: [],
|
|
194
|
-
strength: 0.5,
|
|
195
|
-
createdAt: now,
|
|
196
|
-
updatedAt: now,
|
|
197
|
-
};
|
|
198
|
-
await kv.set(KV.procedural, proc.id, proc);
|
|
199
|
-
newProcs++;
|
|
200
|
-
}
|
|
201
|
-
}
|
|
202
|
-
results.procedural = {
|
|
203
|
-
newProcedures: newProcs,
|
|
204
|
-
patternsAnalyzed: patterns.length,
|
|
205
|
-
};
|
|
206
|
-
} catch (err) {
|
|
207
|
-
const msg = err instanceof Error ? err.message : String(err);
|
|
208
|
-
ctx.logger.error("Procedural extraction failed", { error: msg });
|
|
209
|
-
results.procedural = { error: msg };
|
|
210
|
-
}
|
|
211
|
-
} else {
|
|
212
|
-
results.procedural = {
|
|
213
|
-
skipped: true,
|
|
214
|
-
reason: "fewer than 2 recurring patterns",
|
|
215
|
-
};
|
|
216
|
-
}
|
|
217
|
-
}
|
|
218
|
-
|
|
219
|
-
if (tier === "all" || tier === "decay") {
|
|
220
|
-
const semantic = await kv.list<SemanticMemory>(KV.semantic);
|
|
221
|
-
applyDecay(semantic, decayDays);
|
|
222
|
-
for (const s of semantic) {
|
|
223
|
-
await kv.set(KV.semantic, s.id, s);
|
|
224
|
-
}
|
|
225
|
-
|
|
226
|
-
const procedural = await kv.list<ProceduralMemory>(KV.procedural);
|
|
227
|
-
applyDecay(procedural, decayDays);
|
|
228
|
-
for (const p of procedural) {
|
|
229
|
-
await kv.set(KV.procedural, p.id, p);
|
|
230
|
-
}
|
|
231
|
-
|
|
232
|
-
results.decay = {
|
|
233
|
-
semantic: semantic.length,
|
|
234
|
-
procedural: procedural.length,
|
|
235
|
-
};
|
|
236
|
-
}
|
|
237
|
-
|
|
238
|
-
if (process.env["OBSIDIAN_AUTO_EXPORT"] === "true") {
|
|
239
|
-
try {
|
|
240
|
-
await sdk.trigger("mem::obsidian-export", {});
|
|
241
|
-
results.obsidianExport = { success: true };
|
|
242
|
-
} catch (err) {
|
|
243
|
-
const msg = err instanceof Error ? err.message : String(err);
|
|
244
|
-
ctx.logger.warn("Obsidian auto-export failed", { error: msg });
|
|
245
|
-
results.obsidianExport = { success: false, error: msg };
|
|
246
|
-
}
|
|
247
|
-
}
|
|
248
|
-
|
|
249
|
-
await recordAudit(kv, "consolidate", "mem::consolidate-pipeline", [], {
|
|
250
|
-
tier,
|
|
251
|
-
results,
|
|
252
|
-
});
|
|
253
|
-
|
|
254
|
-
ctx.logger.info("Consolidation pipeline complete", { tier, results });
|
|
255
|
-
return { success: true, results };
|
|
256
|
-
},
|
|
257
|
-
);
|
|
258
|
-
}
|