@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,476 @@
|
|
|
1
|
+
import type { ISdk } from "iii-sdk";
|
|
2
|
+
import { getContext } from "iii-sdk";
|
|
3
|
+
import type {
|
|
4
|
+
GraphNode,
|
|
5
|
+
GraphEdge,
|
|
6
|
+
GraphEdgeType,
|
|
7
|
+
EdgeContext,
|
|
8
|
+
TemporalState,
|
|
9
|
+
MemoryProvider,
|
|
10
|
+
} from "../types.js";
|
|
11
|
+
import { KV, generateId } from "../state/schema.js";
|
|
12
|
+
import type { StateKV } from "../state/kv.js";
|
|
13
|
+
|
|
14
|
+
const TEMPORAL_EXTRACTION_SYSTEM = `You are a temporal knowledge extraction engine. Given observations, extract entities AND their temporal relationships with full context metadata.
|
|
15
|
+
|
|
16
|
+
For each relationship, you MUST provide:
|
|
17
|
+
1. Semantic relation type
|
|
18
|
+
2. Temporal validity (when this fact became true in the real world)
|
|
19
|
+
3. Context metadata: WHY this relationship exists, what reasoning led to it, what alternatives were considered
|
|
20
|
+
|
|
21
|
+
Output EXACTLY this XML:
|
|
22
|
+
<temporal_graph>
|
|
23
|
+
<entities>
|
|
24
|
+
<entity type="file|function|concept|error|decision|pattern|library|person|project|preference|location|organization|event" name="exact name">
|
|
25
|
+
<property key="key">value</property>
|
|
26
|
+
<alias>alternate name</alias>
|
|
27
|
+
</entity>
|
|
28
|
+
</entities>
|
|
29
|
+
<relationships>
|
|
30
|
+
<relationship type="uses|imports|modifies|causes|fixes|depends_on|related_to|works_at|prefers|blocked_by|caused_by|optimizes_for|rejected|avoids|located_in|succeeded_by"
|
|
31
|
+
source="entity name" target="entity name" weight="0.1-1.0"
|
|
32
|
+
valid_from="ISO date or 'unknown'" valid_to="ISO date or 'current'">
|
|
33
|
+
<reasoning>WHY this relationship exists</reasoning>
|
|
34
|
+
<sentiment>positive|negative|neutral</sentiment>
|
|
35
|
+
<alternatives>
|
|
36
|
+
<alt>alternative that was considered</alt>
|
|
37
|
+
</alternatives>
|
|
38
|
+
</relationship>
|
|
39
|
+
</relationships>
|
|
40
|
+
</temporal_graph>
|
|
41
|
+
|
|
42
|
+
Rules:
|
|
43
|
+
- NEVER overwrite existing relationships — always create new versioned edges
|
|
44
|
+
- Extract temporal validity from context clues ("since last month", "in 2024", "currently")
|
|
45
|
+
- Capture reasoning/motivation behind each relationship
|
|
46
|
+
- Weight relationships by directness: 1.0 = explicit statement, 0.5 = inferred, 0.1 = speculative`;
|
|
47
|
+
|
|
48
|
+
function parseTemporalGraphXml(
|
|
49
|
+
xml: string,
|
|
50
|
+
observationIds: string[],
|
|
51
|
+
): { nodes: GraphNode[]; edges: GraphEdge[] } {
|
|
52
|
+
const nodes: GraphNode[] = [];
|
|
53
|
+
const edges: GraphEdge[] = [];
|
|
54
|
+
const now = new Date().toISOString();
|
|
55
|
+
|
|
56
|
+
const entityRegex =
|
|
57
|
+
/<entity\s+type="([^"]+)"\s+name="([^"]+)"[^>]*>([\s\S]*?)<\/entity>/g;
|
|
58
|
+
let match;
|
|
59
|
+
while ((match = entityRegex.exec(xml)) !== null) {
|
|
60
|
+
const type = match[1] as GraphNode["type"];
|
|
61
|
+
const name = match[2];
|
|
62
|
+
const propsBlock = match[3];
|
|
63
|
+
const properties: Record<string, string> = {};
|
|
64
|
+
const aliases: string[] = [];
|
|
65
|
+
|
|
66
|
+
const propRegex = /<property\s+key="([^"]+)">([^<]*)<\/property>/g;
|
|
67
|
+
let propMatch;
|
|
68
|
+
while ((propMatch = propRegex.exec(propsBlock)) !== null) {
|
|
69
|
+
properties[propMatch[1]] = propMatch[2];
|
|
70
|
+
}
|
|
71
|
+
|
|
72
|
+
const aliasRegex = /<alias>([^<]+)<\/alias>/g;
|
|
73
|
+
while ((propMatch = aliasRegex.exec(propsBlock)) !== null) {
|
|
74
|
+
aliases.push(propMatch[1]);
|
|
75
|
+
}
|
|
76
|
+
|
|
77
|
+
nodes.push({
|
|
78
|
+
id: generateId("gn"),
|
|
79
|
+
type,
|
|
80
|
+
name,
|
|
81
|
+
properties,
|
|
82
|
+
sourceObservationIds: observationIds,
|
|
83
|
+
createdAt: now,
|
|
84
|
+
aliases: aliases.length > 0 ? aliases : undefined,
|
|
85
|
+
});
|
|
86
|
+
}
|
|
87
|
+
|
|
88
|
+
const relRegex =
|
|
89
|
+
/<relationship\s+type="([^"]+)"\s+source="([^"]+)"\s+target="([^"]+)"\s+weight="([^"]+)"(?:\s+valid_from="([^"]*)")?(?:\s+valid_to="([^"]*)")?[^>]*>([\s\S]*?)<\/relationship>/g;
|
|
90
|
+
while ((match = relRegex.exec(xml)) !== null) {
|
|
91
|
+
const type = match[1] as GraphEdgeType;
|
|
92
|
+
const sourceName = match[2];
|
|
93
|
+
const targetName = match[3];
|
|
94
|
+
const parsedWeight = parseFloat(match[4]);
|
|
95
|
+
const weight = Number.isNaN(parsedWeight) ? 0.5 : parsedWeight;
|
|
96
|
+
const validFrom = match[5] || undefined;
|
|
97
|
+
const validTo = match[6] || undefined;
|
|
98
|
+
const metaBlock = match[7] || "";
|
|
99
|
+
|
|
100
|
+
const sourceNode = nodes.find(
|
|
101
|
+
(n) =>
|
|
102
|
+
n.name === sourceName ||
|
|
103
|
+
(n.aliases && n.aliases.includes(sourceName)),
|
|
104
|
+
);
|
|
105
|
+
const targetNode = nodes.find(
|
|
106
|
+
(n) =>
|
|
107
|
+
n.name === targetName ||
|
|
108
|
+
(n.aliases && n.aliases.includes(targetName)),
|
|
109
|
+
);
|
|
110
|
+
|
|
111
|
+
if (sourceNode && targetNode) {
|
|
112
|
+
const reasoning =
|
|
113
|
+
metaBlock.match(/<reasoning>([^<]*)<\/reasoning>/)?.[1] || undefined;
|
|
114
|
+
const sentiment =
|
|
115
|
+
metaBlock.match(/<sentiment>([^<]*)<\/sentiment>/)?.[1] || undefined;
|
|
116
|
+
const alternatives: string[] = [];
|
|
117
|
+
const altRegex = /<alt>([^<]+)<\/alt>/g;
|
|
118
|
+
let altMatch;
|
|
119
|
+
while ((altMatch = altRegex.exec(metaBlock)) !== null) {
|
|
120
|
+
alternatives.push(altMatch[1]);
|
|
121
|
+
}
|
|
122
|
+
|
|
123
|
+
const context: EdgeContext = {};
|
|
124
|
+
if (reasoning) context.reasoning = reasoning;
|
|
125
|
+
if (sentiment) context.sentiment = sentiment;
|
|
126
|
+
if (alternatives.length > 0) context.alternatives = alternatives;
|
|
127
|
+
context.confidence = Math.max(0, Math.min(1, weight));
|
|
128
|
+
|
|
129
|
+
edges.push({
|
|
130
|
+
id: generateId("ge"),
|
|
131
|
+
type,
|
|
132
|
+
sourceNodeId: sourceNode.id,
|
|
133
|
+
targetNodeId: targetNode.id,
|
|
134
|
+
weight: Math.max(0, Math.min(1, weight)),
|
|
135
|
+
sourceObservationIds: observationIds,
|
|
136
|
+
createdAt: now,
|
|
137
|
+
tcommit: now,
|
|
138
|
+
tvalid:
|
|
139
|
+
validFrom && validFrom !== "unknown" ? validFrom : undefined,
|
|
140
|
+
tvalidEnd:
|
|
141
|
+
validTo && validTo !== "current" ? validTo : undefined,
|
|
142
|
+
context: Object.keys(context).length > 0 ? context : undefined,
|
|
143
|
+
version: 1,
|
|
144
|
+
isLatest: true,
|
|
145
|
+
});
|
|
146
|
+
}
|
|
147
|
+
}
|
|
148
|
+
|
|
149
|
+
return { nodes, edges };
|
|
150
|
+
}
|
|
151
|
+
|
|
152
|
+
export function registerTemporalGraphFunctions(
|
|
153
|
+
sdk: ISdk,
|
|
154
|
+
kv: StateKV,
|
|
155
|
+
provider: MemoryProvider,
|
|
156
|
+
): void {
|
|
157
|
+
sdk.registerFunction(
|
|
158
|
+
{
|
|
159
|
+
id: "mem::temporal-graph-extract",
|
|
160
|
+
description:
|
|
161
|
+
"Extract temporal knowledge graph with context metadata from observations",
|
|
162
|
+
},
|
|
163
|
+
async (data: {
|
|
164
|
+
observations: Array<{
|
|
165
|
+
id: string;
|
|
166
|
+
title: string;
|
|
167
|
+
narrative: string;
|
|
168
|
+
concepts: string[];
|
|
169
|
+
files: string[];
|
|
170
|
+
type: string;
|
|
171
|
+
timestamp: string;
|
|
172
|
+
}>;
|
|
173
|
+
}) => {
|
|
174
|
+
const ctx = getContext();
|
|
175
|
+
if (!data.observations || data.observations.length === 0) {
|
|
176
|
+
return { success: false, error: "No observations provided" };
|
|
177
|
+
}
|
|
178
|
+
|
|
179
|
+
const items = data.observations
|
|
180
|
+
.map(
|
|
181
|
+
(o, i) =>
|
|
182
|
+
`[${i + 1}] Type: ${o.type}\nTimestamp: ${o.timestamp}\nTitle: ${o.title}\nNarrative: ${o.narrative}\nConcepts: ${(o.concepts ?? []).join(", ")}\nFiles: ${(o.files ?? []).join(", ")}`,
|
|
183
|
+
)
|
|
184
|
+
.join("\n\n");
|
|
185
|
+
|
|
186
|
+
try {
|
|
187
|
+
const response = await provider.compress(
|
|
188
|
+
TEMPORAL_EXTRACTION_SYSTEM,
|
|
189
|
+
`Extract temporal knowledge graph from:\n\n${items}`,
|
|
190
|
+
);
|
|
191
|
+
|
|
192
|
+
const obsIds = data.observations.map((o) => o.id);
|
|
193
|
+
const { nodes, edges } = parseTemporalGraphXml(response, obsIds);
|
|
194
|
+
|
|
195
|
+
const existingNodes = await kv.list<GraphNode>(KV.graphNodes);
|
|
196
|
+
const existingEdges = await kv.list<GraphEdge>(KV.graphEdges);
|
|
197
|
+
|
|
198
|
+
const idRemap = new Map<string, string>();
|
|
199
|
+
for (const node of nodes) {
|
|
200
|
+
const existing = existingNodes.find(
|
|
201
|
+
(n) =>
|
|
202
|
+
n.name === node.name && n.type === node.type,
|
|
203
|
+
);
|
|
204
|
+
if (existing) {
|
|
205
|
+
const oldId = node.id;
|
|
206
|
+
const merged = {
|
|
207
|
+
...existing,
|
|
208
|
+
sourceObservationIds: [
|
|
209
|
+
...new Set([
|
|
210
|
+
...existing.sourceObservationIds,
|
|
211
|
+
...obsIds,
|
|
212
|
+
]),
|
|
213
|
+
],
|
|
214
|
+
properties: { ...existing.properties, ...node.properties },
|
|
215
|
+
updatedAt: new Date().toISOString(),
|
|
216
|
+
aliases: [
|
|
217
|
+
...new Set([
|
|
218
|
+
...(existing.aliases || []),
|
|
219
|
+
...(node.aliases || []),
|
|
220
|
+
]),
|
|
221
|
+
],
|
|
222
|
+
};
|
|
223
|
+
if (merged.aliases.length === 0) delete (merged as any).aliases;
|
|
224
|
+
await kv.set(KV.graphNodes, existing.id, merged);
|
|
225
|
+
node.id = existing.id;
|
|
226
|
+
idRemap.set(oldId, existing.id);
|
|
227
|
+
} else {
|
|
228
|
+
await kv.set(KV.graphNodes, node.id, node);
|
|
229
|
+
existingNodes.push(node);
|
|
230
|
+
}
|
|
231
|
+
}
|
|
232
|
+
|
|
233
|
+
for (const edge of edges) {
|
|
234
|
+
if (idRemap.has(edge.sourceNodeId)) {
|
|
235
|
+
edge.sourceNodeId = idRemap.get(edge.sourceNodeId)!;
|
|
236
|
+
}
|
|
237
|
+
if (idRemap.has(edge.targetNodeId)) {
|
|
238
|
+
edge.targetNodeId = idRemap.get(edge.targetNodeId)!;
|
|
239
|
+
}
|
|
240
|
+
const existingKey = `${edge.sourceNodeId}|${edge.targetNodeId}|${edge.type}`;
|
|
241
|
+
const existingEdge = existingEdges.find(
|
|
242
|
+
(e) =>
|
|
243
|
+
`${e.sourceNodeId}|${e.targetNodeId}|${e.type}` ===
|
|
244
|
+
existingKey,
|
|
245
|
+
);
|
|
246
|
+
|
|
247
|
+
if (existingEdge) {
|
|
248
|
+
const updatedOld = {
|
|
249
|
+
...existingEdge,
|
|
250
|
+
isLatest: false,
|
|
251
|
+
tvalidEnd:
|
|
252
|
+
existingEdge.tvalidEnd || new Date().toISOString(),
|
|
253
|
+
supersededBy: edge.id,
|
|
254
|
+
};
|
|
255
|
+
await kv.set(KV.graphEdges, existingEdge.id, updatedOld);
|
|
256
|
+
|
|
257
|
+
await kv.set(KV.graphEdgeHistory, existingEdge.id, updatedOld);
|
|
258
|
+
|
|
259
|
+
edge.version = (existingEdge.version || 1) + 1;
|
|
260
|
+
}
|
|
261
|
+
|
|
262
|
+
await kv.set(KV.graphEdges, edge.id, edge);
|
|
263
|
+
existingEdges.push(edge);
|
|
264
|
+
}
|
|
265
|
+
|
|
266
|
+
ctx.logger.info("Temporal graph extraction complete", {
|
|
267
|
+
nodes: nodes.length,
|
|
268
|
+
edges: edges.length,
|
|
269
|
+
});
|
|
270
|
+
return {
|
|
271
|
+
success: true,
|
|
272
|
+
nodesAdded: nodes.length,
|
|
273
|
+
edgesAdded: edges.length,
|
|
274
|
+
};
|
|
275
|
+
} catch (err) {
|
|
276
|
+
const msg = err instanceof Error ? err.message : String(err);
|
|
277
|
+
ctx.logger.error("Temporal graph extraction failed", { error: msg });
|
|
278
|
+
return { success: false, error: msg };
|
|
279
|
+
}
|
|
280
|
+
},
|
|
281
|
+
);
|
|
282
|
+
|
|
283
|
+
sdk.registerFunction(
|
|
284
|
+
{
|
|
285
|
+
id: "mem::temporal-query",
|
|
286
|
+
description:
|
|
287
|
+
"Query entity state at a specific point in time with full history",
|
|
288
|
+
},
|
|
289
|
+
async (data: {
|
|
290
|
+
entityName: string;
|
|
291
|
+
asOf?: string;
|
|
292
|
+
includeHistory?: boolean;
|
|
293
|
+
}): Promise<TemporalState | { error: string }> => {
|
|
294
|
+
const allNodes = await kv.list<GraphNode>(KV.graphNodes);
|
|
295
|
+
const allEdges = await kv.list<GraphEdge>(KV.graphEdges);
|
|
296
|
+
|
|
297
|
+
const entity = allNodes.find(
|
|
298
|
+
(n) =>
|
|
299
|
+
n.name.toLowerCase() === data.entityName.toLowerCase() ||
|
|
300
|
+
(n.aliases &&
|
|
301
|
+
n.aliases.some(
|
|
302
|
+
(a) =>
|
|
303
|
+
a.toLowerCase() === data.entityName.toLowerCase(),
|
|
304
|
+
)),
|
|
305
|
+
);
|
|
306
|
+
|
|
307
|
+
if (!entity) {
|
|
308
|
+
return { error: `Entity "${data.entityName}" not found` } as any;
|
|
309
|
+
}
|
|
310
|
+
|
|
311
|
+
const relatedEdges = allEdges.filter(
|
|
312
|
+
(e) => e.sourceNodeId === entity.id || e.targetNodeId === entity.id,
|
|
313
|
+
);
|
|
314
|
+
|
|
315
|
+
const historicalEdges = await kv
|
|
316
|
+
.list<GraphEdge>(KV.graphEdgeHistory)
|
|
317
|
+
.catch(() => [] as GraphEdge[]);
|
|
318
|
+
const entityHistory = historicalEdges.filter(
|
|
319
|
+
(e) => e.sourceNodeId === entity.id || e.targetNodeId === entity.id,
|
|
320
|
+
);
|
|
321
|
+
|
|
322
|
+
const allEntityEdges = [...relatedEdges, ...entityHistory];
|
|
323
|
+
|
|
324
|
+
if (data.asOf) {
|
|
325
|
+
const asOfTime = new Date(data.asOf).getTime();
|
|
326
|
+
const validEdges = allEntityEdges.filter((e) => {
|
|
327
|
+
const commitTime = new Date(
|
|
328
|
+
e.tcommit || e.createdAt,
|
|
329
|
+
).getTime();
|
|
330
|
+
if (commitTime > asOfTime) return false;
|
|
331
|
+
if (e.tvalid) {
|
|
332
|
+
const validTime = new Date(e.tvalid).getTime();
|
|
333
|
+
if (validTime > asOfTime) return false;
|
|
334
|
+
}
|
|
335
|
+
if (e.tvalidEnd) {
|
|
336
|
+
const endTime = new Date(e.tvalidEnd).getTime();
|
|
337
|
+
if (endTime < asOfTime) return false;
|
|
338
|
+
}
|
|
339
|
+
return true;
|
|
340
|
+
});
|
|
341
|
+
|
|
342
|
+
const currentEdges = getLatestByKey(validEdges);
|
|
343
|
+
const historical = data.includeHistory ? validEdges : [];
|
|
344
|
+
|
|
345
|
+
return {
|
|
346
|
+
entity,
|
|
347
|
+
currentEdges,
|
|
348
|
+
historicalEdges: historical,
|
|
349
|
+
timeline: buildTimeline(allEntityEdges),
|
|
350
|
+
};
|
|
351
|
+
}
|
|
352
|
+
|
|
353
|
+
const currentEdges = relatedEdges.filter(
|
|
354
|
+
(e) => e.isLatest !== false,
|
|
355
|
+
);
|
|
356
|
+
|
|
357
|
+
return {
|
|
358
|
+
entity,
|
|
359
|
+
currentEdges,
|
|
360
|
+
historicalEdges: data.includeHistory ? entityHistory : [],
|
|
361
|
+
timeline: buildTimeline(allEntityEdges),
|
|
362
|
+
};
|
|
363
|
+
},
|
|
364
|
+
);
|
|
365
|
+
|
|
366
|
+
sdk.registerFunction(
|
|
367
|
+
{
|
|
368
|
+
id: "mem::differential-state",
|
|
369
|
+
description:
|
|
370
|
+
"Compute state changes between two entities over time",
|
|
371
|
+
},
|
|
372
|
+
async (data: {
|
|
373
|
+
entityName: string;
|
|
374
|
+
from?: string;
|
|
375
|
+
to?: string;
|
|
376
|
+
}) => {
|
|
377
|
+
const allNodes = await kv.list<GraphNode>(KV.graphNodes);
|
|
378
|
+
const allEdges = await kv.list<GraphEdge>(KV.graphEdges);
|
|
379
|
+
const historicalEdges = await kv
|
|
380
|
+
.list<GraphEdge>(KV.graphEdgeHistory)
|
|
381
|
+
.catch(() => [] as GraphEdge[]);
|
|
382
|
+
|
|
383
|
+
const entity = allNodes.find(
|
|
384
|
+
(n) => n.name.toLowerCase() === data.entityName.toLowerCase(),
|
|
385
|
+
);
|
|
386
|
+
if (!entity) return { error: "Entity not found" };
|
|
387
|
+
|
|
388
|
+
const allEntityEdges = [
|
|
389
|
+
...allEdges.filter(
|
|
390
|
+
(e) =>
|
|
391
|
+
e.sourceNodeId === entity.id || e.targetNodeId === entity.id,
|
|
392
|
+
),
|
|
393
|
+
...historicalEdges.filter(
|
|
394
|
+
(e) =>
|
|
395
|
+
e.sourceNodeId === entity.id || e.targetNodeId === entity.id,
|
|
396
|
+
),
|
|
397
|
+
];
|
|
398
|
+
|
|
399
|
+
allEntityEdges.sort(
|
|
400
|
+
(a, b) =>
|
|
401
|
+
new Date(a.tcommit || a.createdAt).getTime() -
|
|
402
|
+
new Date(b.tcommit || b.createdAt).getTime(),
|
|
403
|
+
);
|
|
404
|
+
|
|
405
|
+
const fromTime = data.from
|
|
406
|
+
? new Date(data.from).getTime()
|
|
407
|
+
: 0;
|
|
408
|
+
const toTime = data.to
|
|
409
|
+
? new Date(data.to).getTime()
|
|
410
|
+
: Date.now();
|
|
411
|
+
|
|
412
|
+
const filtered = allEntityEdges.filter((e) => {
|
|
413
|
+
const t = new Date(e.tcommit || e.createdAt).getTime();
|
|
414
|
+
return t >= fromTime && t <= toTime;
|
|
415
|
+
});
|
|
416
|
+
|
|
417
|
+
const changes = filtered.map((e) => ({
|
|
418
|
+
type: e.type,
|
|
419
|
+
target:
|
|
420
|
+
e.sourceNodeId === entity.id
|
|
421
|
+
? e.targetNodeId
|
|
422
|
+
: e.sourceNodeId,
|
|
423
|
+
validFrom: e.tvalid || e.createdAt,
|
|
424
|
+
validTo: e.tvalidEnd,
|
|
425
|
+
reasoning: e.context?.reasoning,
|
|
426
|
+
sentiment: e.context?.sentiment,
|
|
427
|
+
version: e.version || 1,
|
|
428
|
+
isLatest: e.isLatest !== false,
|
|
429
|
+
}));
|
|
430
|
+
|
|
431
|
+
return {
|
|
432
|
+
entity: entity.name,
|
|
433
|
+
totalChanges: changes.length,
|
|
434
|
+
changes,
|
|
435
|
+
};
|
|
436
|
+
},
|
|
437
|
+
);
|
|
438
|
+
}
|
|
439
|
+
|
|
440
|
+
function getLatestByKey(edges: GraphEdge[]): GraphEdge[] {
|
|
441
|
+
const byKey = new Map<string, GraphEdge>();
|
|
442
|
+
for (const e of edges) {
|
|
443
|
+
const key = `${e.sourceNodeId}|${e.targetNodeId}|${e.type}`;
|
|
444
|
+
const existing = byKey.get(key);
|
|
445
|
+
if (
|
|
446
|
+
!existing ||
|
|
447
|
+
new Date(e.tcommit || e.createdAt).getTime() >
|
|
448
|
+
new Date(existing.tcommit || existing.createdAt).getTime()
|
|
449
|
+
) {
|
|
450
|
+
byKey.set(key, e);
|
|
451
|
+
}
|
|
452
|
+
}
|
|
453
|
+
return Array.from(byKey.values());
|
|
454
|
+
}
|
|
455
|
+
|
|
456
|
+
function buildTimeline(
|
|
457
|
+
edges: GraphEdge[],
|
|
458
|
+
): Array<{
|
|
459
|
+
edge: GraphEdge;
|
|
460
|
+
validFrom: string;
|
|
461
|
+
validTo?: string;
|
|
462
|
+
context?: EdgeContext;
|
|
463
|
+
}> {
|
|
464
|
+
const sorted = [...edges].sort(
|
|
465
|
+
(a, b) =>
|
|
466
|
+
new Date(a.tcommit || a.createdAt).getTime() -
|
|
467
|
+
new Date(b.tcommit || b.createdAt).getTime(),
|
|
468
|
+
);
|
|
469
|
+
|
|
470
|
+
return sorted.map((e) => ({
|
|
471
|
+
edge: e,
|
|
472
|
+
validFrom: e.tvalid || e.createdAt,
|
|
473
|
+
validTo: e.tvalidEnd,
|
|
474
|
+
context: e.context,
|
|
475
|
+
}));
|
|
476
|
+
}
|
|
@@ -0,0 +1,138 @@
|
|
|
1
|
+
import type { ISdk } from "iii-sdk";
|
|
2
|
+
import { getContext } from "iii-sdk";
|
|
3
|
+
import type {
|
|
4
|
+
CompressedObservation,
|
|
5
|
+
Session,
|
|
6
|
+
TimelineEntry,
|
|
7
|
+
} from "../types.js";
|
|
8
|
+
import { KV } from "../state/schema.js";
|
|
9
|
+
import { StateKV } from "../state/kv.js";
|
|
10
|
+
|
|
11
|
+
export function registerTimelineFunction(sdk: ISdk, kv: StateKV): void {
|
|
12
|
+
sdk.registerFunction(
|
|
13
|
+
{
|
|
14
|
+
id: "mem::timeline",
|
|
15
|
+
description: "Get chronological observations around an anchor point",
|
|
16
|
+
},
|
|
17
|
+
async (data: {
|
|
18
|
+
anchor: string;
|
|
19
|
+
project?: string;
|
|
20
|
+
before?: number;
|
|
21
|
+
after?: number;
|
|
22
|
+
}) => {
|
|
23
|
+
const ctx = getContext();
|
|
24
|
+
const before = Math.max(0, Math.floor(data.before ?? 5));
|
|
25
|
+
const after = Math.max(0, Math.floor(data.after ?? 5));
|
|
26
|
+
|
|
27
|
+
if (!data.anchor || typeof data.anchor !== "string") {
|
|
28
|
+
return { entries: [], anchor: data.anchor, reason: "invalid_anchor" };
|
|
29
|
+
}
|
|
30
|
+
|
|
31
|
+
let anchorTime: number;
|
|
32
|
+
const isoPattern = /^\d{4}-\d{2}-\d{2}/;
|
|
33
|
+
if (isoPattern.test(data.anchor)) {
|
|
34
|
+
anchorTime = new Date(data.anchor).getTime();
|
|
35
|
+
if (isNaN(anchorTime)) {
|
|
36
|
+
return { entries: [], anchor: data.anchor, reason: "invalid_date" };
|
|
37
|
+
}
|
|
38
|
+
} else {
|
|
39
|
+
const searchResults = await findByKeyword(
|
|
40
|
+
kv,
|
|
41
|
+
data.anchor,
|
|
42
|
+
data.project,
|
|
43
|
+
);
|
|
44
|
+
if (searchResults.length === 0) {
|
|
45
|
+
return { entries: [], anchor: data.anchor, reason: "no_match" };
|
|
46
|
+
}
|
|
47
|
+
anchorTime = new Date(searchResults[0].timestamp).getTime();
|
|
48
|
+
}
|
|
49
|
+
|
|
50
|
+
const sessions = await kv.list<Session>(KV.sessions);
|
|
51
|
+
const filtered = data.project
|
|
52
|
+
? sessions.filter((s) => s.project === data.project)
|
|
53
|
+
: sessions;
|
|
54
|
+
|
|
55
|
+
const allObs: Array<CompressedObservation & { sid: string }> = [];
|
|
56
|
+
for (const session of filtered) {
|
|
57
|
+
const observations = await kv.list<CompressedObservation>(
|
|
58
|
+
KV.observations(session.id),
|
|
59
|
+
);
|
|
60
|
+
for (const obs of observations) {
|
|
61
|
+
if (obs.title && obs.timestamp) {
|
|
62
|
+
allObs.push({ ...obs, sid: session.id });
|
|
63
|
+
}
|
|
64
|
+
}
|
|
65
|
+
}
|
|
66
|
+
|
|
67
|
+
allObs.sort(
|
|
68
|
+
(a, b) =>
|
|
69
|
+
new Date(a.timestamp).getTime() - new Date(b.timestamp).getTime(),
|
|
70
|
+
);
|
|
71
|
+
|
|
72
|
+
let anchorIdx = 0;
|
|
73
|
+
let minDist = Infinity;
|
|
74
|
+
for (let i = 0; i < allObs.length; i++) {
|
|
75
|
+
const dist = Math.abs(
|
|
76
|
+
new Date(allObs[i].timestamp).getTime() - anchorTime,
|
|
77
|
+
);
|
|
78
|
+
if (dist < minDist) {
|
|
79
|
+
minDist = dist;
|
|
80
|
+
anchorIdx = i;
|
|
81
|
+
}
|
|
82
|
+
}
|
|
83
|
+
|
|
84
|
+
const startIdx = Math.max(0, anchorIdx - before);
|
|
85
|
+
const endIdx = Math.min(allObs.length - 1, anchorIdx + after);
|
|
86
|
+
const entries: TimelineEntry[] = [];
|
|
87
|
+
|
|
88
|
+
for (let i = startIdx; i <= endIdx; i++) {
|
|
89
|
+
const obs = allObs[i];
|
|
90
|
+
const { sid, ...observation } = obs;
|
|
91
|
+
entries.push({
|
|
92
|
+
observation,
|
|
93
|
+
sessionId: sid,
|
|
94
|
+
relativePosition: i - anchorIdx,
|
|
95
|
+
});
|
|
96
|
+
}
|
|
97
|
+
|
|
98
|
+
ctx.logger.info("Timeline retrieved", {
|
|
99
|
+
anchor: data.anchor,
|
|
100
|
+
entries: entries.length,
|
|
101
|
+
});
|
|
102
|
+
return { entries, anchorIndex: anchorIdx - startIdx };
|
|
103
|
+
},
|
|
104
|
+
);
|
|
105
|
+
}
|
|
106
|
+
|
|
107
|
+
async function findByKeyword(
|
|
108
|
+
kv: StateKV,
|
|
109
|
+
keyword: string,
|
|
110
|
+
project?: string,
|
|
111
|
+
): Promise<CompressedObservation[]> {
|
|
112
|
+
const sessions = await kv.list<Session>(KV.sessions);
|
|
113
|
+
const filtered = project
|
|
114
|
+
? sessions.filter((s) => s.project === project)
|
|
115
|
+
: sessions;
|
|
116
|
+
|
|
117
|
+
const lower = keyword.toLowerCase();
|
|
118
|
+
const matches: CompressedObservation[] = [];
|
|
119
|
+
|
|
120
|
+
for (const session of filtered) {
|
|
121
|
+
const observations = await kv.list<CompressedObservation>(
|
|
122
|
+
KV.observations(session.id),
|
|
123
|
+
);
|
|
124
|
+
for (const obs of observations) {
|
|
125
|
+
if (
|
|
126
|
+
obs.title?.toLowerCase().includes(lower) ||
|
|
127
|
+
obs.narrative?.toLowerCase().includes(lower) ||
|
|
128
|
+
obs.concepts?.some((c) => c.toLowerCase().includes(lower))
|
|
129
|
+
) {
|
|
130
|
+
matches.push(obs);
|
|
131
|
+
}
|
|
132
|
+
}
|
|
133
|
+
}
|
|
134
|
+
|
|
135
|
+
return matches.sort(
|
|
136
|
+
(a, b) => new Date(b.timestamp).getTime() - new Date(a.timestamp).getTime(),
|
|
137
|
+
);
|
|
138
|
+
}
|