@agentmemory/agentmemory 0.7.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/.claude-plugin/marketplace.json +14 -0
- package/.github/workflows/ci.yml +22 -0
- package/.github/workflows/publish.yml +28 -0
- package/AGENTS.md +113 -0
- package/LICENSE +190 -0
- package/README.md +828 -0
- package/assets/banner.png +0 -0
- package/assets/demo.gif +0 -0
- package/assets/demo.mp4 +0 -0
- package/benchmark/QUALITY.md +73 -0
- package/benchmark/REAL-EMBEDDINGS.md +67 -0
- package/benchmark/SCALE.md +110 -0
- package/benchmark/dataset.ts +293 -0
- package/benchmark/quality-eval.ts +643 -0
- package/benchmark/real-embeddings-eval.ts +405 -0
- package/benchmark/scale-eval.ts +398 -0
- package/dist/cli.d.mts +1 -0
- package/dist/cli.mjs +137 -0
- package/dist/cli.mjs.map +1 -0
- package/dist/docker-compose.yml +14 -0
- package/dist/hooks/notification.d.mts +1 -0
- package/dist/hooks/notification.mjs +45 -0
- package/dist/hooks/notification.mjs.map +1 -0
- package/dist/hooks/post-tool-failure.d.mts +1 -0
- package/dist/hooks/post-tool-failure.mjs +45 -0
- package/dist/hooks/post-tool-failure.mjs.map +1 -0
- package/dist/hooks/post-tool-use.d.mts +1 -0
- package/dist/hooks/post-tool-use.mjs +53 -0
- package/dist/hooks/post-tool-use.mjs.map +1 -0
- package/dist/hooks/pre-compact.d.mts +1 -0
- package/dist/hooks/pre-compact.mjs +50 -0
- package/dist/hooks/pre-compact.mjs.map +1 -0
- package/dist/hooks/pre-tool-use.d.mts +1 -0
- package/dist/hooks/pre-tool-use.mjs +69 -0
- package/dist/hooks/pre-tool-use.mjs.map +1 -0
- package/dist/hooks/prompt-submit.d.mts +1 -0
- package/dist/hooks/prompt-submit.mjs +40 -0
- package/dist/hooks/prompt-submit.mjs.map +1 -0
- package/dist/hooks/session-end.d.mts +1 -0
- package/dist/hooks/session-end.mjs +61 -0
- package/dist/hooks/session-end.mjs.map +1 -0
- package/dist/hooks/session-start.d.mts +1 -0
- package/dist/hooks/session-start.mjs +42 -0
- package/dist/hooks/session-start.mjs.map +1 -0
- package/dist/hooks/stop.d.mts +1 -0
- package/dist/hooks/stop.mjs +33 -0
- package/dist/hooks/stop.mjs.map +1 -0
- package/dist/hooks/subagent-start.d.mts +1 -0
- package/dist/hooks/subagent-start.mjs +43 -0
- package/dist/hooks/subagent-start.mjs.map +1 -0
- package/dist/hooks/subagent-stop.d.mts +1 -0
- package/dist/hooks/subagent-stop.mjs +45 -0
- package/dist/hooks/subagent-stop.mjs.map +1 -0
- package/dist/hooks/task-completed.d.mts +1 -0
- package/dist/hooks/task-completed.mjs +46 -0
- package/dist/hooks/task-completed.mjs.map +1 -0
- package/dist/iii-config.yaml +51 -0
- package/dist/index.d.mts +2 -0
- package/dist/index.mjs +13776 -0
- package/dist/index.mjs.map +1 -0
- package/dist/src-QxitMPfJ.mjs +13775 -0
- package/dist/src-QxitMPfJ.mjs.map +1 -0
- package/dist/standalone.d.mts +1 -0
- package/dist/standalone.mjs +1155 -0
- package/dist/standalone.mjs.map +1 -0
- package/dist/transformers-BX_tgxdO.mjs +38684 -0
- package/dist/transformers-BX_tgxdO.mjs.map +1 -0
- package/dist/transformers-KMm1i9no.mjs +38683 -0
- package/dist/transformers-KMm1i9no.mjs.map +1 -0
- package/docker-compose.yml +14 -0
- package/iii-config.yaml +51 -0
- package/package.json +59 -0
- package/plugin/.claude-plugin/plugin.json +10 -0
- package/plugin/hooks/hooks.json +77 -0
- package/plugin/scripts/diagnostics.mjs +551 -0
- package/plugin/scripts/notification.mjs +45 -0
- package/plugin/scripts/post-tool-failure.mjs +45 -0
- package/plugin/scripts/post-tool-use.mjs +53 -0
- package/plugin/scripts/pre-compact.mjs +50 -0
- package/plugin/scripts/pre-tool-use.mjs +69 -0
- package/plugin/scripts/prompt-submit.mjs +40 -0
- package/plugin/scripts/session-end.mjs +61 -0
- package/plugin/scripts/session-start.mjs +42 -0
- package/plugin/scripts/stop.mjs +33 -0
- package/plugin/scripts/subagent-start.mjs +43 -0
- package/plugin/scripts/subagent-stop.mjs +45 -0
- package/plugin/scripts/task-completed.mjs +46 -0
- package/plugin/skills/forget/SKILL.md +32 -0
- package/plugin/skills/recall/SKILL.md +18 -0
- package/plugin/skills/remember/SKILL.md +25 -0
- package/plugin/skills/session-history/SKILL.md +17 -0
- package/src/auth.ts +12 -0
- package/src/cli.ts +159 -0
- package/src/config.ts +221 -0
- package/src/eval/metrics-store.ts +65 -0
- package/src/eval/quality.ts +51 -0
- package/src/eval/schemas.ts +124 -0
- package/src/eval/self-correct.ts +28 -0
- package/src/eval/validator.ts +31 -0
- package/src/functions/actions.ts +288 -0
- package/src/functions/audit.ts +61 -0
- package/src/functions/auto-forget.ts +169 -0
- package/src/functions/branch-aware.ts +169 -0
- package/src/functions/cascade.ts +80 -0
- package/src/functions/checkpoints.ts +209 -0
- package/src/functions/claude-bridge.ts +161 -0
- package/src/functions/compress.ts +194 -0
- package/src/functions/consolidate.ts +212 -0
- package/src/functions/consolidation-pipeline.ts +258 -0
- package/src/functions/context.ts +169 -0
- package/src/functions/crystallize.ts +293 -0
- package/src/functions/dedup.ts +57 -0
- package/src/functions/diagnostics.ts +785 -0
- package/src/functions/enrich.ts +132 -0
- package/src/functions/evict.ts +163 -0
- package/src/functions/export-import.ts +508 -0
- package/src/functions/facets.ts +248 -0
- package/src/functions/file-index.ts +106 -0
- package/src/functions/flow-compress.ts +214 -0
- package/src/functions/frontier.ts +196 -0
- package/src/functions/governance.ts +131 -0
- package/src/functions/graph-retrieval.ts +277 -0
- package/src/functions/graph.ts +275 -0
- package/src/functions/leases.ts +216 -0
- package/src/functions/lessons.ts +253 -0
- package/src/functions/mesh.ts +434 -0
- package/src/functions/migrate.ts +165 -0
- package/src/functions/observe.ts +144 -0
- package/src/functions/obsidian-export.ts +310 -0
- package/src/functions/patterns.ts +138 -0
- package/src/functions/privacy.ts +39 -0
- package/src/functions/profile.ts +155 -0
- package/src/functions/query-expansion.ts +186 -0
- package/src/functions/relations.ts +237 -0
- package/src/functions/remember.ts +162 -0
- package/src/functions/retention.ts +235 -0
- package/src/functions/routines.ts +289 -0
- package/src/functions/search.ts +80 -0
- package/src/functions/sentinels.ts +417 -0
- package/src/functions/signals.ts +186 -0
- package/src/functions/sketches.ts +274 -0
- package/src/functions/sliding-window.ts +257 -0
- package/src/functions/smart-search.ts +115 -0
- package/src/functions/snapshot.ts +219 -0
- package/src/functions/summarize.ts +155 -0
- package/src/functions/team.ts +147 -0
- package/src/functions/temporal-graph.ts +476 -0
- package/src/functions/timeline.ts +138 -0
- package/src/functions/verify.ts +117 -0
- package/src/health/monitor.ts +110 -0
- package/src/health/thresholds.ts +73 -0
- package/src/hooks/notification.ts +52 -0
- package/src/hooks/post-tool-failure.ts +58 -0
- package/src/hooks/post-tool-use.ts +62 -0
- package/src/hooks/pre-compact.ts +60 -0
- package/src/hooks/pre-tool-use.ts +72 -0
- package/src/hooks/prompt-submit.ts +46 -0
- package/src/hooks/session-end.ts +71 -0
- package/src/hooks/session-start.ts +48 -0
- package/src/hooks/stop.ts +39 -0
- package/src/hooks/subagent-start.ts +49 -0
- package/src/hooks/subagent-stop.ts +54 -0
- package/src/hooks/task-completed.ts +54 -0
- package/src/index.ts +342 -0
- package/src/mcp/in-memory-kv.ts +61 -0
- package/src/mcp/server.ts +1455 -0
- package/src/mcp/standalone.ts +177 -0
- package/src/mcp/tools-registry.ts +769 -0
- package/src/mcp/transport.ts +91 -0
- package/src/prompts/compression.ts +67 -0
- package/src/prompts/consolidation.ts +48 -0
- package/src/prompts/graph-extraction.ts +35 -0
- package/src/prompts/summary.ts +38 -0
- package/src/prompts/xml.ts +26 -0
- package/src/providers/agent-sdk.ts +34 -0
- package/src/providers/anthropic.ts +35 -0
- package/src/providers/circuit-breaker.ts +82 -0
- package/src/providers/embedding/cohere.ts +46 -0
- package/src/providers/embedding/gemini.ts +54 -0
- package/src/providers/embedding/index.ts +39 -0
- package/src/providers/embedding/local.ts +52 -0
- package/src/providers/embedding/openai.ts +45 -0
- package/src/providers/embedding/openrouter.ts +51 -0
- package/src/providers/embedding/voyage.ts +46 -0
- package/src/providers/fallback-chain.ts +31 -0
- package/src/providers/index.ts +84 -0
- package/src/providers/openrouter.ts +71 -0
- package/src/providers/resilient.ts +37 -0
- package/src/state/hybrid-search.ts +295 -0
- package/src/state/index-persistence.ts +63 -0
- package/src/state/keyed-mutex.ts +18 -0
- package/src/state/kv.ts +33 -0
- package/src/state/schema.ts +71 -0
- package/src/state/search-index.ts +245 -0
- package/src/state/stemmer.ts +104 -0
- package/src/state/synonyms.ts +63 -0
- package/src/state/vector-index.ts +130 -0
- package/src/telemetry/setup.ts +116 -0
- package/src/triggers/api.ts +1904 -0
- package/src/triggers/events.ts +71 -0
- package/src/types.ts +769 -0
- package/src/version.ts +1 -0
- package/src/viewer/index.html +2497 -0
- package/src/viewer/server.ts +207 -0
- package/src/xenova.d.ts +3 -0
- package/test/actions.test.ts +490 -0
- package/test/audit.test.ts +108 -0
- package/test/auto-forget.test.ts +188 -0
- package/test/cascade.test.ts +277 -0
- package/test/checkpoints.test.ts +493 -0
- package/test/circuit-breaker.test.ts +107 -0
- package/test/claude-bridge.test.ts +178 -0
- package/test/confidence.test.ts +247 -0
- package/test/consistency.test.ts +61 -0
- package/test/consolidation-pipeline.test.ts +251 -0
- package/test/crystallize.test.ts +521 -0
- package/test/diagnostics.test.ts +638 -0
- package/test/embedding-provider.test.ts +49 -0
- package/test/enrich.test.ts +209 -0
- package/test/eval.test.ts +300 -0
- package/test/export-import.test.ts +251 -0
- package/test/facets.test.ts +448 -0
- package/test/fallback-chain.test.ts +93 -0
- package/test/frontier.test.ts +485 -0
- package/test/governance.test.ts +147 -0
- package/test/graph-retrieval.test.ts +186 -0
- package/test/graph.test.ts +160 -0
- package/test/helpers/mocks.ts +40 -0
- package/test/hybrid-search.test.ts +145 -0
- package/test/index-persistence.test.ts +124 -0
- package/test/integration.test.ts +265 -0
- package/test/leases.test.ts +399 -0
- package/test/mcp-prompts.test.ts +218 -0
- package/test/mcp-resources.test.ts +286 -0
- package/test/mcp-standalone.test.ts +113 -0
- package/test/mesh.test.ts +700 -0
- package/test/privacy.test.ts +87 -0
- package/test/profile.test.ts +161 -0
- package/test/query-expansion.test.ts +154 -0
- package/test/relations.test.ts +198 -0
- package/test/retention.test.ts +245 -0
- package/test/routines.test.ts +497 -0
- package/test/schema-fingerprint.test.ts +81 -0
- package/test/schema.test.ts +42 -0
- package/test/search-index.test.ts +128 -0
- package/test/sentinels.test.ts +626 -0
- package/test/signals.test.ts +410 -0
- package/test/sketches.test.ts +549 -0
- package/test/sliding-window.test.ts +199 -0
- package/test/smart-search.test.ts +169 -0
- package/test/snapshot.test.ts +165 -0
- package/test/team.test.ts +156 -0
- package/test/temporal-graph.test.ts +378 -0
- package/test/timeline.test.ts +148 -0
- package/test/vector-index.test.ts +79 -0
- package/test/verify.test.ts +209 -0
- package/test/xml.test.ts +65 -0
- package/tsconfig.json +22 -0
- package/tsdown.config.ts +62 -0
|
@@ -0,0 +1,165 @@
|
|
|
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
|
+
}
|
|
@@ -0,0 +1,144 @@
|
|
|
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
|
+
}
|
|
@@ -0,0 +1,310 @@
|
|
|
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
|
+
}
|