@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
package/src/functions/migrate.ts
DELETED
|
@@ -1,165 +0,0 @@
|
|
|
1
|
-
import type { ISdk } from "iii-sdk";
|
|
2
|
-
import { getContext } from "iii-sdk";
|
|
3
|
-
import { resolve } from "node:path";
|
|
4
|
-
import { homedir } from "node:os";
|
|
5
|
-
import { KV, generateId } from "../state/schema.js";
|
|
6
|
-
import { StateKV } from "../state/kv.js";
|
|
7
|
-
import type {
|
|
8
|
-
Session,
|
|
9
|
-
CompressedObservation,
|
|
10
|
-
SessionSummary,
|
|
11
|
-
} from "../types.js";
|
|
12
|
-
|
|
13
|
-
const ALLOWED_DIRS = [resolve(homedir(), ".agentmemory")];
|
|
14
|
-
|
|
15
|
-
function isAllowedPath(dbPath: string): boolean {
|
|
16
|
-
const resolved = resolve(dbPath);
|
|
17
|
-
return ALLOWED_DIRS.some((dir) => resolved.startsWith(dir + "/"));
|
|
18
|
-
}
|
|
19
|
-
|
|
20
|
-
export function registerMigrateFunction(sdk: ISdk, kv: StateKV): void {
|
|
21
|
-
sdk.registerFunction(
|
|
22
|
-
{
|
|
23
|
-
id: "mem::migrate",
|
|
24
|
-
description: "Import data from SQLite database",
|
|
25
|
-
},
|
|
26
|
-
async (data: { dbPath: string }) => {
|
|
27
|
-
const ctx = getContext();
|
|
28
|
-
ctx.logger.info("Migration started", { dbPath: data.dbPath });
|
|
29
|
-
|
|
30
|
-
if (!isAllowedPath(data.dbPath)) {
|
|
31
|
-
return {
|
|
32
|
-
success: false,
|
|
33
|
-
error: `Path not allowed. Must be under: ${ALLOWED_DIRS.join(", ")}`,
|
|
34
|
-
};
|
|
35
|
-
}
|
|
36
|
-
|
|
37
|
-
let Database: any;
|
|
38
|
-
try {
|
|
39
|
-
// @ts-expect-error optional dependency
|
|
40
|
-
Database = (await import("better-sqlite3")).default;
|
|
41
|
-
} catch {
|
|
42
|
-
return {
|
|
43
|
-
success: false,
|
|
44
|
-
error:
|
|
45
|
-
"better-sqlite3 not installed. Run: npm install better-sqlite3",
|
|
46
|
-
};
|
|
47
|
-
}
|
|
48
|
-
|
|
49
|
-
const fs = await import("node:fs");
|
|
50
|
-
if (!fs.existsSync(data.dbPath)) {
|
|
51
|
-
return { success: false, error: `Database not found: ${data.dbPath}` };
|
|
52
|
-
}
|
|
53
|
-
|
|
54
|
-
try {
|
|
55
|
-
const db = Database(data.dbPath, { readonly: true });
|
|
56
|
-
let sessionCount = 0;
|
|
57
|
-
let obsCount = 0;
|
|
58
|
-
let summaryCount = 0;
|
|
59
|
-
|
|
60
|
-
const sessions = db
|
|
61
|
-
.prepare("SELECT * FROM sessions ORDER BY created_at DESC")
|
|
62
|
-
.all() as any[];
|
|
63
|
-
for (const row of sessions) {
|
|
64
|
-
const session: Session = {
|
|
65
|
-
id: row.session_id || row.id,
|
|
66
|
-
project: row.project_path || row.project || "unknown",
|
|
67
|
-
cwd: row.cwd || row.project_path || "",
|
|
68
|
-
startedAt:
|
|
69
|
-
row.created_at || row.started_at || new Date().toISOString(),
|
|
70
|
-
endedAt: row.ended_at || row.updated_at,
|
|
71
|
-
status: "completed",
|
|
72
|
-
observationCount: 0,
|
|
73
|
-
};
|
|
74
|
-
await kv.set(KV.sessions, session.id, session);
|
|
75
|
-
sessionCount++;
|
|
76
|
-
}
|
|
77
|
-
|
|
78
|
-
let observations: any[] = [];
|
|
79
|
-
try {
|
|
80
|
-
observations = db
|
|
81
|
-
.prepare("SELECT * FROM observations ORDER BY created_at ASC")
|
|
82
|
-
.all() as any[];
|
|
83
|
-
} catch {
|
|
84
|
-
try {
|
|
85
|
-
observations = db
|
|
86
|
-
.prepare(
|
|
87
|
-
"SELECT * FROM compressed_observations ORDER BY created_at ASC",
|
|
88
|
-
)
|
|
89
|
-
.all() as any[];
|
|
90
|
-
} catch {
|
|
91
|
-
ctx.logger.warn("No observation tables found");
|
|
92
|
-
}
|
|
93
|
-
}
|
|
94
|
-
|
|
95
|
-
for (const row of observations) {
|
|
96
|
-
const sessionId = row.session_id || "migrated";
|
|
97
|
-
const obs: CompressedObservation = {
|
|
98
|
-
id: row.id || generateId("mig"),
|
|
99
|
-
sessionId,
|
|
100
|
-
timestamp: row.created_at || new Date().toISOString(),
|
|
101
|
-
type: row.type || "other",
|
|
102
|
-
title: row.title || row.summary || "Migrated observation",
|
|
103
|
-
subtitle: row.subtitle,
|
|
104
|
-
facts: safeJsonParse(row.facts, []),
|
|
105
|
-
narrative: row.narrative || row.content || "",
|
|
106
|
-
concepts: safeJsonParse(row.concepts, []),
|
|
107
|
-
files: safeJsonParse(row.files, []),
|
|
108
|
-
importance: row.importance || 5,
|
|
109
|
-
};
|
|
110
|
-
await kv.set(KV.observations(sessionId), obs.id, obs);
|
|
111
|
-
obsCount++;
|
|
112
|
-
}
|
|
113
|
-
|
|
114
|
-
let summaries: any[] = [];
|
|
115
|
-
try {
|
|
116
|
-
summaries = db
|
|
117
|
-
.prepare("SELECT * FROM session_summaries")
|
|
118
|
-
.all() as any[];
|
|
119
|
-
} catch {
|
|
120
|
-
ctx.logger.warn("No summaries table found");
|
|
121
|
-
}
|
|
122
|
-
|
|
123
|
-
for (const row of summaries) {
|
|
124
|
-
const summary: SessionSummary = {
|
|
125
|
-
sessionId: row.session_id,
|
|
126
|
-
project: row.project || "unknown",
|
|
127
|
-
createdAt: row.created_at || new Date().toISOString(),
|
|
128
|
-
title: row.title || "Migrated session",
|
|
129
|
-
narrative: row.narrative || row.summary || "",
|
|
130
|
-
keyDecisions: safeJsonParse(row.key_decisions, []),
|
|
131
|
-
filesModified: safeJsonParse(row.files_modified, []),
|
|
132
|
-
concepts: safeJsonParse(row.concepts, []),
|
|
133
|
-
observationCount: row.observation_count || 0,
|
|
134
|
-
};
|
|
135
|
-
await kv.set(KV.summaries, row.session_id, summary);
|
|
136
|
-
summaryCount++;
|
|
137
|
-
}
|
|
138
|
-
|
|
139
|
-
db.close();
|
|
140
|
-
ctx.logger.info("Migration complete", {
|
|
141
|
-
sessionCount,
|
|
142
|
-
obsCount,
|
|
143
|
-
summaryCount,
|
|
144
|
-
});
|
|
145
|
-
return { success: true, sessionCount, obsCount, summaryCount };
|
|
146
|
-
} catch (err) {
|
|
147
|
-
const msg = err instanceof Error ? err.message : String(err);
|
|
148
|
-
ctx.logger.error("Migration failed", { error: msg });
|
|
149
|
-
return { success: false, error: "Migration failed" };
|
|
150
|
-
}
|
|
151
|
-
},
|
|
152
|
-
);
|
|
153
|
-
}
|
|
154
|
-
|
|
155
|
-
function safeJsonParse<T>(value: unknown, fallback: T): T {
|
|
156
|
-
if (Array.isArray(value)) return value as T;
|
|
157
|
-
if (typeof value === "string") {
|
|
158
|
-
try {
|
|
159
|
-
return JSON.parse(value) as T;
|
|
160
|
-
} catch {
|
|
161
|
-
return fallback;
|
|
162
|
-
}
|
|
163
|
-
}
|
|
164
|
-
return fallback;
|
|
165
|
-
}
|
package/src/functions/observe.ts
DELETED
|
@@ -1,144 +0,0 @@
|
|
|
1
|
-
import type { ISdk } from "iii-sdk";
|
|
2
|
-
import { getContext } from "iii-sdk";
|
|
3
|
-
import type { RawObservation, HookPayload, Session } from "../types.js";
|
|
4
|
-
import { KV, STREAM, generateId } from "../state/schema.js";
|
|
5
|
-
import { StateKV } from "../state/kv.js";
|
|
6
|
-
import { stripPrivateData } from "./privacy.js";
|
|
7
|
-
import { DedupMap } from "./dedup.js";
|
|
8
|
-
import { withKeyedLock } from "../state/keyed-mutex.js";
|
|
9
|
-
|
|
10
|
-
export function registerObserveFunction(
|
|
11
|
-
sdk: ISdk,
|
|
12
|
-
kv: StateKV,
|
|
13
|
-
dedupMap?: DedupMap,
|
|
14
|
-
maxObservationsPerSession?: number,
|
|
15
|
-
): void {
|
|
16
|
-
sdk.registerFunction(
|
|
17
|
-
{
|
|
18
|
-
id: "mem::observe",
|
|
19
|
-
description: "Capture and store a tool-use observation",
|
|
20
|
-
},
|
|
21
|
-
async (payload: HookPayload) => {
|
|
22
|
-
const ctx = getContext();
|
|
23
|
-
|
|
24
|
-
if (
|
|
25
|
-
!payload?.sessionId ||
|
|
26
|
-
typeof payload.sessionId !== "string" ||
|
|
27
|
-
!payload.hookType ||
|
|
28
|
-
typeof payload.hookType !== "string" ||
|
|
29
|
-
!payload.timestamp ||
|
|
30
|
-
typeof payload.timestamp !== "string"
|
|
31
|
-
) {
|
|
32
|
-
return {
|
|
33
|
-
success: false,
|
|
34
|
-
error:
|
|
35
|
-
"Invalid payload: sessionId, hookType, and timestamp are required",
|
|
36
|
-
};
|
|
37
|
-
}
|
|
38
|
-
|
|
39
|
-
const obsId = generateId("obs");
|
|
40
|
-
|
|
41
|
-
let dedupHash: string | undefined;
|
|
42
|
-
if (dedupMap) {
|
|
43
|
-
const d =
|
|
44
|
-
typeof payload.data === "object" && payload.data !== null
|
|
45
|
-
? (payload.data as Record<string, unknown>)
|
|
46
|
-
: {};
|
|
47
|
-
const toolName = (d["tool_name"] as string) || payload.hookType;
|
|
48
|
-
dedupHash = dedupMap.computeHash(
|
|
49
|
-
payload.sessionId,
|
|
50
|
-
toolName,
|
|
51
|
-
d["tool_input"],
|
|
52
|
-
);
|
|
53
|
-
if (dedupMap.isDuplicate(dedupHash)) {
|
|
54
|
-
return { deduplicated: true, sessionId: payload.sessionId };
|
|
55
|
-
}
|
|
56
|
-
}
|
|
57
|
-
|
|
58
|
-
let sanitizedRaw: unknown = payload.data;
|
|
59
|
-
try {
|
|
60
|
-
const jsonStr = JSON.stringify(payload.data);
|
|
61
|
-
const sanitized = stripPrivateData(jsonStr);
|
|
62
|
-
sanitizedRaw = JSON.parse(sanitized);
|
|
63
|
-
} catch {
|
|
64
|
-
sanitizedRaw = stripPrivateData(String(payload.data));
|
|
65
|
-
}
|
|
66
|
-
|
|
67
|
-
const raw: RawObservation = {
|
|
68
|
-
id: obsId,
|
|
69
|
-
sessionId: payload.sessionId,
|
|
70
|
-
timestamp: payload.timestamp,
|
|
71
|
-
hookType: payload.hookType,
|
|
72
|
-
raw: sanitizedRaw,
|
|
73
|
-
};
|
|
74
|
-
|
|
75
|
-
if (typeof sanitizedRaw === "object" && sanitizedRaw !== null) {
|
|
76
|
-
const d = sanitizedRaw as Record<string, unknown>;
|
|
77
|
-
if (
|
|
78
|
-
payload.hookType === "post_tool_use" ||
|
|
79
|
-
payload.hookType === "post_tool_failure"
|
|
80
|
-
) {
|
|
81
|
-
raw.toolName = d["tool_name"] as string | undefined;
|
|
82
|
-
raw.toolInput = d["tool_input"];
|
|
83
|
-
raw.toolOutput = d["tool_output"] || d["error"];
|
|
84
|
-
}
|
|
85
|
-
if (payload.hookType === "prompt_submit") {
|
|
86
|
-
raw.userPrompt = d["prompt"] as string | undefined;
|
|
87
|
-
}
|
|
88
|
-
}
|
|
89
|
-
|
|
90
|
-
return withKeyedLock(`obs:${payload.sessionId}`, async () => {
|
|
91
|
-
if (maxObservationsPerSession && maxObservationsPerSession > 0) {
|
|
92
|
-
const existing = await kv.list(KV.observations(payload.sessionId));
|
|
93
|
-
if (existing.length >= maxObservationsPerSession) {
|
|
94
|
-
return {
|
|
95
|
-
success: false,
|
|
96
|
-
error: `Session observation limit reached (${maxObservationsPerSession})`,
|
|
97
|
-
};
|
|
98
|
-
}
|
|
99
|
-
}
|
|
100
|
-
|
|
101
|
-
await kv.set(KV.observations(payload.sessionId), obsId, raw);
|
|
102
|
-
|
|
103
|
-
if (dedupMap && dedupHash) {
|
|
104
|
-
dedupMap.record(dedupHash);
|
|
105
|
-
}
|
|
106
|
-
|
|
107
|
-
sdk.triggerVoid("stream::set", {
|
|
108
|
-
stream_name: STREAM.name,
|
|
109
|
-
group_id: STREAM.group(payload.sessionId),
|
|
110
|
-
item_id: obsId,
|
|
111
|
-
data: { type: "raw", observation: raw },
|
|
112
|
-
});
|
|
113
|
-
|
|
114
|
-
sdk.triggerVoid("stream::set", {
|
|
115
|
-
stream_name: STREAM.name,
|
|
116
|
-
group_id: STREAM.viewerGroup,
|
|
117
|
-
item_id: obsId,
|
|
118
|
-
data: { type: "raw", observation: raw, sessionId: payload.sessionId },
|
|
119
|
-
});
|
|
120
|
-
|
|
121
|
-
const session = await kv.get<Session>(KV.sessions, payload.sessionId);
|
|
122
|
-
if (session) {
|
|
123
|
-
await kv.set(KV.sessions, payload.sessionId, {
|
|
124
|
-
...session,
|
|
125
|
-
observationCount: (session.observationCount || 0) + 1,
|
|
126
|
-
});
|
|
127
|
-
}
|
|
128
|
-
|
|
129
|
-
sdk.triggerVoid("mem::compress", {
|
|
130
|
-
observationId: obsId,
|
|
131
|
-
sessionId: payload.sessionId,
|
|
132
|
-
raw,
|
|
133
|
-
});
|
|
134
|
-
|
|
135
|
-
ctx.logger.info("Observation captured", {
|
|
136
|
-
obsId,
|
|
137
|
-
sessionId: payload.sessionId,
|
|
138
|
-
hook: payload.hookType,
|
|
139
|
-
});
|
|
140
|
-
return { observationId: obsId };
|
|
141
|
-
});
|
|
142
|
-
},
|
|
143
|
-
);
|
|
144
|
-
}
|
|
@@ -1,310 +0,0 @@
|
|
|
1
|
-
import { mkdir, writeFile } from "node:fs/promises";
|
|
2
|
-
import { join } from "node:path";
|
|
3
|
-
import { homedir } from "node:os";
|
|
4
|
-
import type { ISdk } from "iii-sdk";
|
|
5
|
-
import type { StateKV } from "../state/kv.js";
|
|
6
|
-
import { KV } from "../state/schema.js";
|
|
7
|
-
import type {
|
|
8
|
-
Memory,
|
|
9
|
-
Lesson,
|
|
10
|
-
Crystal,
|
|
11
|
-
Session,
|
|
12
|
-
} from "../types.js";
|
|
13
|
-
import { recordAudit } from "./audit.js";
|
|
14
|
-
|
|
15
|
-
const DEFAULT_VAULT = join(homedir(), ".agentmemory", "vault");
|
|
16
|
-
|
|
17
|
-
function sanitize(name: string): string {
|
|
18
|
-
return name.replace(/[<>:"/\\|?*\x00-\x1f]/g, "_").slice(0, 100);
|
|
19
|
-
}
|
|
20
|
-
|
|
21
|
-
function toFrontmatter(obj: Record<string, unknown>): string {
|
|
22
|
-
const lines = ["---"];
|
|
23
|
-
for (const [key, value] of Object.entries(obj)) {
|
|
24
|
-
if (value === undefined || value === null) continue;
|
|
25
|
-
if (Array.isArray(value)) {
|
|
26
|
-
lines.push(`${key}: [${value.map((v) => JSON.stringify(String(v))).join(", ")}]`);
|
|
27
|
-
} else {
|
|
28
|
-
lines.push(`${key}: ${JSON.stringify(value)}`);
|
|
29
|
-
}
|
|
30
|
-
}
|
|
31
|
-
lines.push("---");
|
|
32
|
-
return lines.join("\n");
|
|
33
|
-
}
|
|
34
|
-
|
|
35
|
-
function memoryToMd(m: Memory): string {
|
|
36
|
-
const fm = toFrontmatter({
|
|
37
|
-
id: m.id,
|
|
38
|
-
type: m.type,
|
|
39
|
-
created: m.createdAt,
|
|
40
|
-
updated: m.updatedAt,
|
|
41
|
-
strength: m.strength,
|
|
42
|
-
version: m.version,
|
|
43
|
-
concepts: m.concepts,
|
|
44
|
-
files: m.files,
|
|
45
|
-
});
|
|
46
|
-
|
|
47
|
-
const related = (m.relatedIds || [])
|
|
48
|
-
.map((id) => `- [[${id}]]`)
|
|
49
|
-
.join("\n");
|
|
50
|
-
const supersedes = (m.supersedes || [])
|
|
51
|
-
.map((id) => `- [[${id}]] (superseded)`)
|
|
52
|
-
.join("\n");
|
|
53
|
-
|
|
54
|
-
const sections = [
|
|
55
|
-
fm,
|
|
56
|
-
"",
|
|
57
|
-
`# ${m.title}`,
|
|
58
|
-
"",
|
|
59
|
-
m.content,
|
|
60
|
-
];
|
|
61
|
-
|
|
62
|
-
if (m.concepts.length > 0) {
|
|
63
|
-
sections.push("", "## Concepts", m.concepts.map((c) => `#${c.replace(/\s+/g, "-")}`).join(" "));
|
|
64
|
-
}
|
|
65
|
-
if (related) {
|
|
66
|
-
sections.push("", "## Related", related);
|
|
67
|
-
}
|
|
68
|
-
if (supersedes) {
|
|
69
|
-
sections.push("", "## Supersedes", supersedes);
|
|
70
|
-
}
|
|
71
|
-
|
|
72
|
-
return sections.join("\n");
|
|
73
|
-
}
|
|
74
|
-
|
|
75
|
-
function lessonToMd(l: Lesson): string {
|
|
76
|
-
const fm = toFrontmatter({
|
|
77
|
-
id: l.id,
|
|
78
|
-
type: "lesson",
|
|
79
|
-
source: l.source,
|
|
80
|
-
confidence: l.confidence,
|
|
81
|
-
reinforcements: l.reinforcements,
|
|
82
|
-
created: l.createdAt,
|
|
83
|
-
updated: l.updatedAt,
|
|
84
|
-
project: l.project,
|
|
85
|
-
tags: l.tags,
|
|
86
|
-
decayRate: l.decayRate,
|
|
87
|
-
});
|
|
88
|
-
|
|
89
|
-
const sourceLinks = l.sourceIds
|
|
90
|
-
.map((id) => `- [[${id}]]`)
|
|
91
|
-
.join("\n");
|
|
92
|
-
|
|
93
|
-
const sections = [
|
|
94
|
-
fm,
|
|
95
|
-
"",
|
|
96
|
-
`# Lesson: ${l.content.slice(0, 80)}`,
|
|
97
|
-
"",
|
|
98
|
-
l.content,
|
|
99
|
-
];
|
|
100
|
-
|
|
101
|
-
if (l.context) {
|
|
102
|
-
sections.push("", "## Context", l.context);
|
|
103
|
-
}
|
|
104
|
-
if (l.tags.length > 0) {
|
|
105
|
-
sections.push("", "## Tags", l.tags.map((t) => `#${t.replace(/\s+/g, "-")}`).join(" "));
|
|
106
|
-
}
|
|
107
|
-
if (sourceLinks) {
|
|
108
|
-
sections.push("", "## Sources", sourceLinks);
|
|
109
|
-
}
|
|
110
|
-
|
|
111
|
-
return sections.join("\n");
|
|
112
|
-
}
|
|
113
|
-
|
|
114
|
-
function crystalToMd(c: Crystal): string {
|
|
115
|
-
const fm = toFrontmatter({
|
|
116
|
-
id: c.id,
|
|
117
|
-
type: "crystal",
|
|
118
|
-
created: c.createdAt,
|
|
119
|
-
project: c.project,
|
|
120
|
-
sessionId: c.sessionId,
|
|
121
|
-
filesAffected: c.filesAffected,
|
|
122
|
-
});
|
|
123
|
-
|
|
124
|
-
const actionLinks = c.sourceActionIds
|
|
125
|
-
.map((id) => `- [[${id}]]`)
|
|
126
|
-
.join("\n");
|
|
127
|
-
|
|
128
|
-
const sections = [
|
|
129
|
-
fm,
|
|
130
|
-
"",
|
|
131
|
-
`# Crystal: ${c.narrative.slice(0, 80)}`,
|
|
132
|
-
"",
|
|
133
|
-
c.narrative,
|
|
134
|
-
"",
|
|
135
|
-
"## Key Outcomes",
|
|
136
|
-
...c.keyOutcomes.map((o) => `- ${o}`),
|
|
137
|
-
];
|
|
138
|
-
|
|
139
|
-
if (c.lessons.length > 0) {
|
|
140
|
-
sections.push("", "## Lessons", ...c.lessons.map((l) => `- ${l}`));
|
|
141
|
-
}
|
|
142
|
-
if (c.filesAffected.length > 0) {
|
|
143
|
-
sections.push("", "## Files", ...c.filesAffected.map((f) => `- \`${f}\``));
|
|
144
|
-
}
|
|
145
|
-
if (actionLinks) {
|
|
146
|
-
sections.push("", "## Source Actions", actionLinks);
|
|
147
|
-
}
|
|
148
|
-
|
|
149
|
-
return sections.join("\n");
|
|
150
|
-
}
|
|
151
|
-
|
|
152
|
-
function sessionToMd(s: Session): string {
|
|
153
|
-
const fm = toFrontmatter({
|
|
154
|
-
id: s.id,
|
|
155
|
-
type: "session",
|
|
156
|
-
project: s.project,
|
|
157
|
-
status: s.status,
|
|
158
|
-
started: s.startedAt,
|
|
159
|
-
ended: s.endedAt,
|
|
160
|
-
observations: s.observationCount,
|
|
161
|
-
});
|
|
162
|
-
|
|
163
|
-
return [
|
|
164
|
-
fm,
|
|
165
|
-
"",
|
|
166
|
-
`# Session: ${s.project}`,
|
|
167
|
-
"",
|
|
168
|
-
`**Status:** ${s.status}`,
|
|
169
|
-
`**Started:** ${s.startedAt}`,
|
|
170
|
-
s.endedAt ? `**Ended:** ${s.endedAt}` : "",
|
|
171
|
-
`**Observations:** ${s.observationCount}`,
|
|
172
|
-
`**CWD:** \`${s.cwd}\``,
|
|
173
|
-
]
|
|
174
|
-
.filter(Boolean)
|
|
175
|
-
.join("\n");
|
|
176
|
-
}
|
|
177
|
-
|
|
178
|
-
interface ExportError {
|
|
179
|
-
id: string;
|
|
180
|
-
path: string;
|
|
181
|
-
error: string;
|
|
182
|
-
}
|
|
183
|
-
|
|
184
|
-
export function registerObsidianExportFunction(
|
|
185
|
-
sdk: ISdk,
|
|
186
|
-
kv: StateKV,
|
|
187
|
-
): void {
|
|
188
|
-
sdk.registerFunction(
|
|
189
|
-
{ id: "mem::obsidian-export" },
|
|
190
|
-
async (data: { vaultDir?: string; types?: string[] }) => {
|
|
191
|
-
const vaultDir = data.vaultDir || DEFAULT_VAULT;
|
|
192
|
-
const exportTypes = new Set(
|
|
193
|
-
data.types || ["memories", "lessons", "crystals", "sessions"],
|
|
194
|
-
);
|
|
195
|
-
|
|
196
|
-
const dirs = {
|
|
197
|
-
memories: join(vaultDir, "memories"),
|
|
198
|
-
lessons: join(vaultDir, "lessons"),
|
|
199
|
-
crystals: join(vaultDir, "crystals"),
|
|
200
|
-
sessions: join(vaultDir, "sessions"),
|
|
201
|
-
};
|
|
202
|
-
|
|
203
|
-
await Promise.all(
|
|
204
|
-
Object.values(dirs).map((dir) => mkdir(dir, { recursive: true })),
|
|
205
|
-
);
|
|
206
|
-
|
|
207
|
-
const stats = { memories: 0, lessons: 0, crystals: 0, sessions: 0 };
|
|
208
|
-
const errors: ExportError[] = [];
|
|
209
|
-
const memoryMoc: string[] = [];
|
|
210
|
-
const lessonMoc: string[] = [];
|
|
211
|
-
const crystalMoc: string[] = [];
|
|
212
|
-
const sessionMoc: string[] = [];
|
|
213
|
-
|
|
214
|
-
const [memories, lessons, crystals, sessions] = await Promise.all([
|
|
215
|
-
exportTypes.has("memories") ? kv.list<Memory>(KV.memories) : Promise.resolve([] as Memory[]),
|
|
216
|
-
exportTypes.has("lessons") ? kv.list<Lesson>(KV.lessons) : Promise.resolve([] as Lesson[]),
|
|
217
|
-
exportTypes.has("crystals") ? kv.list<Crystal>(KV.crystals) : Promise.resolve([] as Crystal[]),
|
|
218
|
-
exportTypes.has("sessions") ? kv.list<Session>(KV.sessions) : Promise.resolve([] as Session[]),
|
|
219
|
-
]);
|
|
220
|
-
|
|
221
|
-
for (const m of memories.filter((m) => m.isLatest)) {
|
|
222
|
-
const filename = `${sanitize(m.id)}.md`;
|
|
223
|
-
const filepath = join(dirs.memories, filename);
|
|
224
|
-
try {
|
|
225
|
-
await writeFile(filepath, memoryToMd(m));
|
|
226
|
-
stats.memories++;
|
|
227
|
-
memoryMoc.push(`- [[memories/${sanitize(m.id)}|${m.title}]] (${m.type}, strength: ${m.strength})`);
|
|
228
|
-
} catch (err) {
|
|
229
|
-
errors.push({ id: m.id, path: filepath, error: err instanceof Error ? err.message : String(err) });
|
|
230
|
-
}
|
|
231
|
-
}
|
|
232
|
-
|
|
233
|
-
for (const l of lessons.filter((l) => !l.deleted)) {
|
|
234
|
-
const filename = `${sanitize(l.id)}.md`;
|
|
235
|
-
const filepath = join(dirs.lessons, filename);
|
|
236
|
-
try {
|
|
237
|
-
await writeFile(filepath, lessonToMd(l));
|
|
238
|
-
stats.lessons++;
|
|
239
|
-
lessonMoc.push(`- [[lessons/${sanitize(l.id)}|${l.content.slice(0, 60)}]] (confidence: ${l.confidence})`);
|
|
240
|
-
} catch (err) {
|
|
241
|
-
errors.push({ id: l.id, path: filepath, error: err instanceof Error ? err.message : String(err) });
|
|
242
|
-
}
|
|
243
|
-
}
|
|
244
|
-
|
|
245
|
-
for (const c of crystals) {
|
|
246
|
-
const filename = `${sanitize(c.id)}.md`;
|
|
247
|
-
const filepath = join(dirs.crystals, filename);
|
|
248
|
-
try {
|
|
249
|
-
await writeFile(filepath, crystalToMd(c));
|
|
250
|
-
stats.crystals++;
|
|
251
|
-
crystalMoc.push(`- [[crystals/${sanitize(c.id)}|${c.narrative.slice(0, 60)}]]`);
|
|
252
|
-
} catch (err) {
|
|
253
|
-
errors.push({ id: c.id, path: filepath, error: err instanceof Error ? err.message : String(err) });
|
|
254
|
-
}
|
|
255
|
-
}
|
|
256
|
-
|
|
257
|
-
const recent = sessions
|
|
258
|
-
.sort(
|
|
259
|
-
(a, b) =>
|
|
260
|
-
new Date(b.startedAt).getTime() -
|
|
261
|
-
new Date(a.startedAt).getTime(),
|
|
262
|
-
)
|
|
263
|
-
.slice(0, 50);
|
|
264
|
-
for (const s of recent) {
|
|
265
|
-
const filename = `${sanitize(s.id)}.md`;
|
|
266
|
-
const filepath = join(dirs.sessions, filename);
|
|
267
|
-
try {
|
|
268
|
-
await writeFile(filepath, sessionToMd(s));
|
|
269
|
-
stats.sessions++;
|
|
270
|
-
sessionMoc.push(`- [[sessions/${sanitize(s.id)}|${s.project} (${s.status})]]`);
|
|
271
|
-
} catch (err) {
|
|
272
|
-
errors.push({ id: s.id, path: filepath, error: err instanceof Error ? err.message : String(err) });
|
|
273
|
-
}
|
|
274
|
-
}
|
|
275
|
-
|
|
276
|
-
const exportedAt = new Date().toISOString();
|
|
277
|
-
const moc = [
|
|
278
|
-
"---",
|
|
279
|
-
"type: moc",
|
|
280
|
-
`exported: ${exportedAt}`,
|
|
281
|
-
"---",
|
|
282
|
-
"",
|
|
283
|
-
"# agentmemory vault",
|
|
284
|
-
"",
|
|
285
|
-
`Exported: ${exportedAt}`,
|
|
286
|
-
"",
|
|
287
|
-
`## Memories (${stats.memories})`,
|
|
288
|
-
...memoryMoc,
|
|
289
|
-
"",
|
|
290
|
-
`## Lessons (${stats.lessons})`,
|
|
291
|
-
...lessonMoc,
|
|
292
|
-
"",
|
|
293
|
-
`## Crystals (${stats.crystals})`,
|
|
294
|
-
...crystalMoc,
|
|
295
|
-
"",
|
|
296
|
-
`## Sessions (${stats.sessions})`,
|
|
297
|
-
...sessionMoc,
|
|
298
|
-
].join("\n");
|
|
299
|
-
|
|
300
|
-
await writeFile(join(vaultDir, "MOC.md"), moc);
|
|
301
|
-
|
|
302
|
-
await recordAudit(kv, "obsidian_export", "mem::obsidian-export", [], {
|
|
303
|
-
vaultDir,
|
|
304
|
-
stats,
|
|
305
|
-
});
|
|
306
|
-
|
|
307
|
-
return { success: true, exported: stats, errors: errors.length > 0 ? errors : undefined, vaultDir };
|
|
308
|
-
},
|
|
309
|
-
);
|
|
310
|
-
}
|